@airgap/crypto
Version:
The @airgap/crypto packages provides common crypto functionalities.
69 lines • 2.81 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.deriveSecp256K1 = void 0;
var sha512_1 = require("@airgap/coinlib-core/dependencies/src/@stablelib/sha512-1.0.1/packages/sha512/sha512");
// @ts-ignore
var elliptic_1 = __importDefault(require("@airgap/coinlib-core/dependencies/src/secp256k1-4.0.2/elliptic"));
var hmac_1 = require("@stablelib/hmac");
var derivation_1 = require("../utils/derivation");
var hash_1 = require("../utils/hash");
var BITCOIN_KEY = 'Bitcoin seed';
function deriveSecp256K1(seed, derivationPath, key) {
if (key === void 0) { key = BITCOIN_KEY; }
var masterNode = masterNodeFromSeed(seed, key);
return derivationPath !== undefined ? derive(masterNode, derivationPath) : masterNode;
}
exports.deriveSecp256K1 = deriveSecp256K1;
function masterNodeFromSeed(seed, key) {
var _a = getKey(seed, Buffer.from(key, 'utf-8')), secretKey = _a.key, chainCode = _a.chainCode;
return {
depth: 0,
parentFingerprint: 0x00000000,
index: 0,
chainCode: chainCode,
secretKey: secretKey,
publicKey: getPublicKey(secretKey)
};
}
function derive(masterNode, derivationPath) {
var derivationIndices = (0, derivation_1.splitDerivationPath)(derivationPath);
return derivationIndices.reduce(deriveChild, masterNode);
}
function deriveChild(node, derivationIndex) {
var parentFingerprint = (0, hash_1.hash160)(node.publicKey).readUInt32BE(0);
var index = derivationIndex.masked;
var indexBuffer = Buffer.alloc(4);
indexBuffer.writeUInt32BE(index);
var data = derivationIndex.isHardened
? Buffer.concat([Buffer.alloc(1, 0), node.secretKey, indexBuffer])
: Buffer.concat([node.publicKey, indexBuffer]);
var _a = getKey(data, node.chainCode), key = _a.key, chainCode = _a.chainCode;
try {
var ki = Buffer.from(elliptic_1.default.privateKeyTweakAdd(Buffer.from(node.secretKey), key));
return {
depth: node.depth + 1,
parentFingerprint: parentFingerprint,
index: index,
chainCode: chainCode,
secretKey: ki,
publicKey: getPublicKey(ki)
};
}
catch (_b) {
return deriveChild(node, (0, derivation_1.incIndex)(derivationIndex));
}
}
function getKey(data, key) {
var I = Buffer.from((0, hmac_1.hmac)(sha512_1.SHA512, key, data));
var IL = I.slice(0, 32);
var IR = I.slice(32);
return { key: IL, chainCode: IR };
}
function getPublicKey(privateKey) {
var publicKey = elliptic_1.default.publicKeyCreate(privateKey, true);
return Buffer.from(publicKey);
}
//# sourceMappingURL=derive.js.map