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

101 lines
2.7 KiB
JavaScript
Raw Normal View History

2018-07-21 14:52:54 +02:00
import { AbstractHDWallet } from './abstract-hd-wallet';
import bitcoin from 'bitcoinjs-lib';
import bip39 from 'bip39';
import BigNumber from 'bignumber.js';
import signer from '../models/signer';
/**
* HD Wallet (BIP39).
* In particular, BIP44 (P2PKH legacy addressess)
* @see https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
*/
2018-07-21 14:52:54 +02:00
export class HDLegacyP2PKHWallet extends AbstractHDWallet {
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);
const root = bitcoin.HDNode.fromSeedBuffer(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 = bitcoin.HDNode.fromSeedBuffer(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.keyPair.toWIF();
}
_getExternalAddressByIndex(index) {
index = index * 1; // cast to int
if (this.external_addresses_cache[index]) return this.external_addresses_cache[index]; // cache hit
const node = bitcoin.HDNode.fromBase58(this.getXpub());
const address = node
.derive(0)
.derive(index)
.getAddress();
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
const node = bitcoin.HDNode.fromBase58(this.getXpub());
const address = node
.derive(1)
.derive(index)
.getAddress();
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),
);
}
}