@stricahq/bip32ed25519
Version:
Pure javascript implementation of Bip32Ed25519, used for Cardano blockchain key pair.
54 lines (53 loc) • 1.9 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/* eslint-disable no-bitwise */
const buffer_1 = require("buffer");
const bn_js_1 = __importDefault(require("bn.js"));
const PublicKey_1 = __importDefault(require("./PublicKey"));
const utils_1 = require("./utils");
const EDDSA = require("./ed25519e");
const eddsa = new EDDSA();
class Bip32PublicKey {
constructor(xpub) {
this.xpub = xpub;
}
derive(index) {
const pk = this.xpub.slice(0, 32);
const cc = this.xpub.slice(32, 64);
const data = buffer_1.Buffer.allocUnsafe(1 + 32 + 4);
data.writeUInt32LE(index, 1 + 32);
let z;
let i;
if (index < utils_1.HARDENED_OFFSET) {
pk.copy(data, 1);
data[0] = 0x02;
z = utils_1.hmac512(cc, data);
data[0] = 0x03;
i = utils_1.hmac512(cc, data);
}
else {
throw new Error("can not derive hardened public key");
}
const chainCode = i.slice(32, 64);
const zl = z.slice(0, 32);
const left = new bn_js_1.default(zl.slice(0, 28), 16, "le").mul(new bn_js_1.default(8));
const p = eddsa.g.mul(left);
const pp = eddsa.decodePoint(pk.toString("hex"));
const point = pp.add(p);
return new Bip32PublicKey(buffer_1.Buffer.concat([buffer_1.Buffer.from(eddsa.encodePoint(point)), chainCode]));
}
toPublicKey() {
const key = eddsa.keyFromPublic(this.xpub.slice(0, 32));
return new PublicKey_1.default(buffer_1.Buffer.from(key.pubBytes()));
}
toBytes() {
return this.xpub;
}
static fromBytes(xpub) {
return new Bip32PublicKey(xpub);
}
}
exports.default = Bip32PublicKey;