crypto-wallet-core
Version:
A multi-currency support library for address derivation, private key creation, and transaction creation
60 lines • 2.67 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.EthDeriver = void 0;
const web3_utils_1 = __importDefault(require("web3-utils"));
const BitcoreLib = require('bitcore-lib');
class EthDeriver {
padTo32(msg) {
while (msg.length < 32) {
msg = Buffer.concat([new Buffer([0]), msg]);
}
if (msg.length !== 32) {
throw new Error(`invalid key length: ${msg.length}`);
}
return msg;
}
deriveAddress(network, xpubkey, addressIndex, isChange) {
const xpub = new BitcoreLib.HDPublicKey(xpubkey, network);
const changeNum = isChange ? 1 : 0;
const path = `m/${changeNum}/${addressIndex}`;
const derived = xpub.derive(path).publicKey;
return this.deriveAddressWithPath(network, xpubkey, path);
}
addressFromPublicKeyBuffer(pubKey) {
const ecPoint = new BitcoreLib.PublicKey.fromBuffer(pubKey).point;
const x = ecPoint.getX().toBuffer({ size: 32 });
const y = ecPoint.getY().toBuffer({ size: 32 });
const paddedBuffer = Buffer.concat([x, y]);
const address = web3_utils_1.default.keccak256(`0x${paddedBuffer.toString('hex')}`).slice(26);
return web3_utils_1.default.toChecksumAddress(address);
}
derivePrivateKey(network, xPriv, addressIndex, isChange) {
const changeNum = isChange ? 1 : 0;
const path = `m/${changeNum}/${addressIndex}`;
return this.derivePrivateKeyWithPath(network, xPriv, path);
}
deriveAddressWithPath(network, xpubKey, path) {
const xpub = new BitcoreLib.HDPublicKey(xpubKey, network);
const derived = xpub.derive(path).publicKey;
return this.addressFromPublicKeyBuffer(derived.toBuffer());
}
derivePrivateKeyWithPath(network, xprivKey, path) {
const xpriv = new BitcoreLib.HDPrivateKey(xprivKey, network);
const derivedPrivKey = xpriv.derive(path);
const privKey = derivedPrivKey.privateKey.toString('hex');
const pubKeyObj = derivedPrivKey.publicKey;
const pubKey = pubKeyObj.toString('hex');
const pubKeyBuffer = pubKeyObj.toBuffer();
const address = this.addressFromPublicKeyBuffer(pubKeyBuffer);
return { address, privKey, pubKey, path };
}
getAddress(network, pubKey) {
pubKey = new BitcoreLib.PublicKey(pubKey, network);
return this.addressFromPublicKeyBuffer(pubKey.toBuffer());
}
}
exports.EthDeriver = EthDeriver;
//# sourceMappingURL=index.js.map