BlueWallet/class/hd-legacy-p2pkh-wallet.js

101 lines
2.7 KiB
JavaScript
Raw Normal View History

import bip39 from 'bip39';
import BigNumber from 'bignumber.js';
import signer from '../models/signer';
2020-03-08 22:46:43 +01:00
import { AbstractHDElectrumWallet } from './abstract-hd-electrum-wallet';
2019-09-14 02:48:37 +02:00
const bitcoin = require('bitcoinjs-lib');
const HDNode = require('bip32');
/**
* HD Wallet (BIP39).
* In particular, BIP44 (P2PKH legacy addressess)
* @see https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
*/
2020-03-08 22:46:43 +01:00
export class HDLegacyP2PKHWallet extends AbstractHDElectrumWallet {
static type = 'HDlegacyP2PKH';
static typeReadable = 'HD Legacy (BIP44 P2PKH)';
2018-12-19 12:22:57 +01:00
allowSend() {
return true;
}
getXpub() {
if (this._xpub) {
return this._xpub; // cache hit
}
const mnemonic = this.secret;
const seed = bip39.mnemonicToSeed(mnemonic);
2019-09-14 00:15:59 +02:00
const root = bitcoin.bip32.fromSeed(seed);
const path = "m/44'/0'/0'";
const child = root.derivePath(path).neutered();
this._xpub = child.toBase58();
return this._xpub;
}
_getExternalWIFByIndex(index) {
2019-01-02 17:08:54 +01:00
return this._getWIFByIndex(false, index);
}
_getInternalWIFByIndex(index) {
2019-01-02 17:08:54 +01:00
return this._getWIFByIndex(true, index);
}
/**
* Get internal/external WIF by wallet index
* @param {Boolean} internal
* @param {Number} index
* @returns {*}
* @private
*/
_getWIFByIndex(internal, index) {
const mnemonic = this.secret;
const seed = bip39.mnemonicToSeed(mnemonic);
const root = HDNode.fromSeed(seed);
const path = `m/44'/0'/0'/${internal ? 1 : 0}/${index}`;
const child = root.derivePath(path);
2019-01-02 17:08:54 +01:00
return child.toWIF();
}
_getExternalAddressByIndex(index) {
index = index * 1; // cast to int
if (this.external_addresses_cache[index]) return this.external_addresses_cache[index]; // cache hit
2019-09-14 00:15:59 +02:00
const node = bitcoin.bip32.fromBase58(this.getXpub());
const address = bitcoin.payments.p2pkh({
pubkey: node.derive(0).derive(index).publicKey,
}).address;
return (this.external_addresses_cache[index] = address);
}
_getInternalAddressByIndex(index) {
index = index * 1; // cast to int
if (this.internal_addresses_cache[index]) return this.internal_addresses_cache[index]; // cache hit
2019-09-14 00:15:59 +02:00
const node = bitcoin.bip32.fromBase58(this.getXpub());
const address = bitcoin.payments.p2pkh({
pubkey: node.derive(1).derive(index).publicKey,
}).address;
return (this.internal_addresses_cache[index] = address);
}
2018-12-19 12:22:57 +01:00
createTx(utxos, amount, fee, address) {
for (let utxo of utxos) {
utxo.wif = this._getWifForAddress(utxo.address);
}
let amountPlusFee = parseFloat(new BigNumber(amount).plus(fee).toString(10));
return signer.createHDTransaction(
utxos,
address,
amountPlusFee,
fee,
this._getInternalAddressByIndex(this.next_free_change_address_index),
);
}
}