UNPKG

@arcblock/did

Version:

Javascript lib to work with ArcBlock DID

40 lines (38 loc) 1.21 kB
import { fromBase58, isHexStrict, stripHexPrefix, toBN } from "@ocap/util"; import padStart from "lodash/padStart.js"; //#region src/util.ts const DID_PREFIX = "did:abt:"; /** * Convert did to bytes with length of 26 * * @param {string} did * @returns {Buffer} */ const toBytes = (did) => { try { if (isHexStrict(did)) return Buffer.from(stripHexPrefix(did), "hex"); let bytes = fromBase58(did.replace(/^did:[a-z0-9]+:/, "")); while (bytes.length < 26) bytes = Buffer.concat([Uint8Array.from([0]), Uint8Array.from(bytes)]); return bytes; } catch (err) { throw new Error(`Cannot convert DID string to byte array: ${err.message}`); } }; /** * Convert number to bit string with predefined length */ const toBits = (number, length) => padStart(toBN(number).toString(2), length, "0"); /** * Ensure the hex length is even number, 2, 4, 6, 8 * * @param {string} hex * @param {number} length * @returns {string} hex */ const toStrictHex = (hex, length) => { const str = hex.replace(/^0x/i, ""); if (typeof length === "number" && length % 2 === 0) return padStart(hex, length, "0"); return str.length % 2 === 0 ? str : `0${str}`; }; //#endregion export { DID_PREFIX, toBits, toBytes, toStrictHex };