UNPKG

@taquito/signer

Version:

Provide signing functionality to be with taquito

76 lines (75 loc) 2.81 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PrivateKey = void 0; /* eslint-disable @typescript-eslint/no-this-alias */ const hmac_1 = require("@stablelib/hmac"); const sha512_1 = require("@stablelib/sha512"); const ed25519_1 = require("@stablelib/ed25519"); const index_1 = require("./index"); const utils_1 = require("./utils"); const errors_1 = require("../errors"); const core_1 = require("@taquito/core"); // MinSeedSize is the minimal allowed seed byte length const minSeedSize = 16; // MaxSeedSize is the maximal allowed seed byte length const maxSeedSize = 64; const ed25519Key = 'ed25519 seed'; class PrivateKey { /** * * @param priv generated keypair 0->32 private key 32->n public key * @param chainCode new HMAC hash with new key */ constructor(priv, chainCode) { this.priv = priv; this.chainCode = chainCode; } /** * * @param seedSrc result of Bip39.mnemonicToSeed * @returns instance of PrivateKey * @throws {@link InvalidSeedLengthError} */ static fromSeed(seedSrc) { const seed = typeof seedSrc === 'string' ? (0, utils_1.parseHex)(seedSrc) : seedSrc; if (seed.length < minSeedSize || seed.length > maxSeedSize) { throw new errors_1.InvalidSeedLengthError(seed.length); } const key = new TextEncoder().encode(ed25519Key); const sum = new hmac_1.HMAC(sha512_1.SHA512, key).update(seed).digest(); return new PrivateKey((0, ed25519_1.generateKeyPairFromSeed)(sum.subarray(0, 32)).secretKey, sum.subarray(32)); } /** * * @returns slice(0, 32) of current priv for new seed for next derived priv */ seed() { return this.priv.subarray(0, 32); } /** * @index current derivation path item ie: 1729' * @returns derivation path child of original private key pair */ derive(index) { if ((index & index_1.Hard) === 0) { throw new core_1.InvalidDerivationPathError(index.toString(), ': Non-hardened derivation path.'); } const data = new Uint8Array(37); data.set(this.seed(), 1); new DataView(data.buffer).setUint32(33, index); const sum = new hmac_1.HMAC(sha512_1.SHA512, this.chainCode).update(data).digest(); return new PrivateKey((0, ed25519_1.generateKeyPairFromSeed)(sum.subarray(0, 32)).secretKey, sum.subarray(32)); } /** * @param path array of numbers pre adjusted for hardened paths ie: 44' -> 2^31 + 44 * @returns final child of full derivation path private key pair */ derivePath(path) { let key = this; for (const index of path) { key = key.derive(index); } return key; } } exports.PrivateKey = PrivateKey;