@arcblock/did
Version:
Javascript lib to work with ArcBlock DID
55 lines (54 loc) • 1.78 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.toStrictHex = exports.toBytes = exports.toBits = exports.DID_PREFIX = void 0;
/* eslint-disable @typescript-eslint/ban-ts-comment */
const padStart_1 = __importDefault(require("lodash/padStart"));
const util_1 = require("@ocap/util");
const DID_PREFIX = 'did:abt:';
exports.DID_PREFIX = DID_PREFIX;
/**
* Convert did to bytes with length of 26
*
* @param {string} did
* @returns {Buffer}
*/
const toBytes = (did) => {
try {
if ((0, util_1.isHexStrict)(did)) {
return Buffer.from((0, util_1.stripHexPrefix)(did), 'hex');
}
let bytes = (0, util_1.fromBase58)(did.replace(DID_PREFIX, ''));
while (bytes.length < 26) {
bytes = Buffer.concat([Buffer.from([0]), bytes]);
}
return bytes;
}
catch (err) {
// @ts-ignore
throw new Error(`Cannot convert DID string to byte array: ${err.message}`);
}
};
exports.toBytes = toBytes;
/**
* Convert number to bit string with predefined length
*/
const toBits = (number, length) => (0, padStart_1.default)((0, util_1.toBN)(number).toString(2), length, '0');
exports.toBits = toBits;
/**
* 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 (0, padStart_1.default)(hex, length, '0');
}
return str.length % 2 === 0 ? str : `0${str}`;
};
exports.toStrictHex = toStrictHex;