UNPKG

tnb-hd-wallet

Version:

A hd wallet that derives public and private keys from a 12 word mnemonic phrase with support

103 lines (102 loc) 3.34 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Slip10Derivation = void 0; const ed25519_hd_key_1 = require("ed25519-hd-key"); const bip32_1 = require("bip32"); const models_1 = require("./models"); class Derivation { constructor(_curve, _seed) { this.curve = _curve; if (typeof _seed === "string") { this.seedBuffer = Buffer.from(_seed, "hex"); } else { this.seedBuffer = _seed; } if (!(this.seedBuffer.length >= 16 && this.seedBuffer.length <= 64)) { throw new Error(`Invalid seed: Seed has to be between 128 and 516 bits \nSeed: ${this.seed} \nSeedLength: ${this.seedBuffer.length}`); } } derivePath(path) { if (path === "m") { return this.masterKey; } return this.curveSpecificDerivation(path); } get seed() { return this.seedBuffer.toString("hex"); } } class Ed25519 extends Derivation { constructor(seed) { super("ed25519", seed); } formatKeys({ key, chainCode }, path) { return { path, publicKey: this.computePublicKey(key), chainCode: chainCode.toString("hex"), privateKey: key.toString("hex") }; } curveSpecificDerivation(path) { const addressKeys = ed25519_hd_key_1.derivePath(path, this.seed); return this.formatKeys(addressKeys, path); } get masterKey() { const masterKeys = ed25519_hd_key_1.getMasterKeyFromSeed(this.seed); return this.formatKeys(masterKeys, "m"); } computePublicKey(privateKey, withZeroByte = true) { if (typeof privateKey === "string") { privateKey = Buffer.from(privateKey, "hex"); } return ed25519_hd_key_1.getPublicKey(privateKey, withZeroByte).toString("hex"); } } class Secp256k1 extends Derivation { constructor(seed) { super("secp256k1", seed); this.bip32 = bip32_1.fromSeed(this.seedBuffer); } formatKeys(bip32Address, path) { if (!bip32Address.privateKey) throw new Error("Private Key is Invalid"); return { path, publicKey: bip32Address.publicKey.toString("hex"), chainCode: bip32Address.chainCode.toString("hex"), privateKey: bip32Address.privateKey.toString("hex") }; } curveSpecificDerivation(path) { const bip32address = this.bip32.derivePath(path); return this.formatKeys(bip32address, path); } get masterKey() { return this.formatKeys(this.bip32, "m"); } } class Slip10Derivation { constructor(_curve, _seed) { this.curve = _curve; this.seed = _seed; switch (_curve) { case models_1.Curve.ed25519: this.derivationScheme = new Ed25519(_seed); break; case models_1.Curve.secp256k1: this.derivationScheme = new Secp256k1(_seed); break; default: throw new Error(`Curve '${_curve}' not supported`); } } derivePath(path) { return this.derivationScheme.derivePath(path); } get masterKey() { return this.derivationScheme.masterKey; } } exports.Slip10Derivation = Slip10Derivation;