BlueWallet/class/wallets/abstract-hd-wallet.js

347 lines
11 KiB
JavaScript
Raw Normal View History

2018-07-21 14:52:54 +02:00
import { LegacyWallet } from './legacy-wallet';
import Frisbee from 'frisbee';
2019-09-14 00:15:59 +02:00
const bip39 = require('bip39');
const BlueElectrum = require('../../blue_modules/BlueElectrum');
2018-07-21 14:52:54 +02:00
2020-03-09 19:44:42 +01:00
/**
* @deprecated
*/
2018-07-21 14:52:54 +02:00
export class AbstractHDWallet extends LegacyWallet {
static type = 'abstract';
static typeReadable = 'abstract';
2018-07-21 14:52:54 +02:00
constructor() {
super();
this.next_free_address_index = 0;
this.next_free_change_address_index = 0;
this.internal_addresses_cache = {}; // index => address
this.external_addresses_cache = {}; // index => address
this._xpub = ''; // cache
2018-08-08 02:05:34 +02:00
this.usedAddresses = [];
this._address_to_wif_cache = {};
this.gap_limit = 20;
2018-07-21 14:52:54 +02:00
}
getNextFreeAddressIndex() {
return this.next_free_address_index;
}
getNextFreeChangeAddressIndex() {
return this.next_free_change_address_index;
}
prepareForSerialization() {
// deleting structures that cant be serialized
delete this._node0;
delete this._node1;
}
generate() {
throw new Error('Not implemented');
}
2018-07-21 14:52:54 +02:00
allowSend() {
2018-08-08 02:05:34 +02:00
return false;
2018-07-21 14:52:54 +02:00
}
getTransactions() {
throw new Error('Not implemented');
}
2018-07-21 14:52:54 +02:00
setSecret(newSecret) {
this.secret = newSecret.trim().toLowerCase();
2018-07-21 14:52:54 +02:00
this.secret = this.secret.replace(/[^a-zA-Z0-9]/g, ' ').replace(/\s+/g, ' ');
return this;
}
/**
* @return {Boolean} is mnemonic in `this.secret` valid
*/
2018-07-21 14:52:54 +02:00
validateMnemonic() {
return bip39.validateMnemonic(this.secret);
}
getMnemonicToSeedHex() {
return bip39.mnemonicToSeedHex(this.secret);
}
/**
* Derives from hierarchy, returns next free address
* (the one that has no transactions). Looks for several,
* gives up if none found, and returns the used one
*
* @return {Promise.<string>}
*/
async getAddressAsync() {
// looking for free external address
let freeAddress = '';
let c;
for (c = 0; c < this.gap_limit + 1; c++) {
if (this.next_free_address_index + c < 0) continue;
const address = this._getExternalAddressByIndex(this.next_free_address_index + c);
2018-08-01 00:37:35 +02:00
this.external_addresses_cache[this.next_free_address_index + c] = address; // updating cache just for any case
2019-05-03 15:24:08 +02:00
let txs = [];
try {
txs = await BlueElectrum.getTransactionsByAddress(address);
} catch (Err) {
console.warn('BlueElectrum.getTransactionsByAddress()', Err.message);
}
2019-03-31 01:20:18 +01:00
if (txs.length === 0) {
// found free address
2019-03-31 01:20:18 +01:00
freeAddress = address;
this.next_free_address_index += c; // now points to _this one_
break;
}
}
if (!freeAddress) {
// could not find in cycle above, give up
freeAddress = this._getExternalAddressByIndex(this.next_free_address_index + c); // we didnt check this one, maybe its free
this.next_free_address_index += c; // now points to this one
}
this._address = freeAddress;
return freeAddress;
}
2018-08-01 00:37:35 +02:00
/**
* Derives from hierarchy, returns next free CHANGE address
* (the one that has no transactions). Looks for several,
* gives up if none found, and returns the used one
*
* @return {Promise.<string>}
*/
async getChangeAddressAsync() {
// looking for free internal address
let freeAddress = '';
let c;
for (c = 0; c < this.gap_limit + 1; c++) {
2018-08-01 00:37:35 +02:00
if (this.next_free_change_address_index + c < 0) continue;
const address = this._getInternalAddressByIndex(this.next_free_change_address_index + c);
2018-08-01 00:37:35 +02:00
this.internal_addresses_cache[this.next_free_change_address_index + c] = address; // updating cache just for any case
2019-05-03 15:24:08 +02:00
let txs = [];
try {
txs = await BlueElectrum.getTransactionsByAddress(address);
} catch (Err) {
console.warn('BlueElectrum.getTransactionsByAddress()', Err.message);
}
2019-03-31 01:20:18 +01:00
if (txs.length === 0) {
2018-08-01 00:37:35 +02:00
// found free address
2019-03-31 01:20:18 +01:00
freeAddress = address;
2018-08-01 00:37:35 +02:00
this.next_free_change_address_index += c; // now points to _this one_
break;
}
}
if (!freeAddress) {
// could not find in cycle above, give up
freeAddress = this._getInternalAddressByIndex(this.next_free_change_address_index + c); // we didnt check this one, maybe its free
this.next_free_change_address_index += c; // now points to this one
2018-08-01 00:37:35 +02:00
}
this._address = freeAddress;
2018-08-01 00:37:35 +02:00
return freeAddress;
}
/**
* Should not be used in HD wallets
*
* @deprecated
* @return {string}
*/
getAddress() {
return this._address;
2018-07-21 14:52:54 +02:00
}
_getExternalWIFByIndex(index) {
throw new Error('Not implemented');
}
_getInternalWIFByIndex(index) {
throw new Error('Not implemented');
}
_getExternalAddressByIndex(index) {
throw new Error('Not implemented');
}
_getInternalAddressByIndex(index) {
throw new Error('Not implemented');
}
getXpub() {
throw new Error('Not implemented');
}
/**
* Async function to fetch all transactions. Use getter to get actual txs.
* Also, sets internals:
* `this.internal_addresses_cache`
* `this.external_addresses_cache`
*
* @returns {Promise<void>}
*/
async fetchTransactions() {
try {
const api = new Frisbee({ baseURI: 'https://blockchain.info' });
this.transactions = [];
let offset = 0;
2018-07-21 14:52:54 +02:00
while (1) {
const response = await api.get('/multiaddr?active=' + this.getXpub() + '&n=100&offset=' + offset);
2018-07-21 14:52:54 +02:00
if (response && response.body) {
if (response.body.txs && response.body.txs.length === 0) {
break;
}
2018-07-21 14:52:54 +02:00
let latestBlock = false;
if (response.body.info && response.body.info.latest_block) {
latestBlock = response.body.info.latest_block.height;
}
this._lastTxFetch = +new Date();
// processing TXs and adding to internal memory
if (response.body.txs) {
for (const tx of response.body.txs) {
let value = 0;
for (const input of tx.inputs) {
// ----- INPUTS
if (input.prev_out.xpub) {
// sent FROM US
value -= input.prev_out.value;
// setting internal caches to help ourselves in future...
const path = input.prev_out.xpub.path.split('/');
if (path[path.length - 2] === '1') {
// change address
this.next_free_change_address_index = Math.max(path[path.length - 1] * 1 + 1, this.next_free_change_address_index);
// setting to point to last maximum known change address + 1
}
if (path[path.length - 2] === '0') {
// main (aka external) address
this.next_free_address_index = Math.max(path[path.length - 1] * 1 + 1, this.next_free_address_index);
// setting to point to last maximum known main address + 1
}
// done with cache
2018-07-21 14:52:54 +02:00
}
}
for (const output of tx.out) {
// ----- OUTPUTS
if (output.xpub) {
// sent TO US (change)
value += output.value;
// setting internal caches to help ourselves in future...
const path = output.xpub.path.split('/');
if (path[path.length - 2] === '1') {
// change address
this.next_free_change_address_index = Math.max(path[path.length - 1] * 1 + 1, this.next_free_change_address_index);
// setting to point to last maximum known change address + 1
}
if (path[path.length - 2] === '0') {
// main (aka external) address
this.next_free_address_index = Math.max(path[path.length - 1] * 1 + 1, this.next_free_address_index);
// setting to point to last maximum known main address + 1
}
// done with cache
2018-07-21 14:52:54 +02:00
}
}
tx.value = value; // new BigNumber(value).div(100000000).toString() * 1;
if (!tx.confirmations && latestBlock) {
tx.confirmations = latestBlock - tx.block_height + 1;
}
2018-07-21 14:52:54 +02:00
this.transactions.push(tx);
}
if (response.body.txs.length < 100) {
// this fetch yilded less than page size, thus requesting next batch makes no sense
break;
}
} else {
break; // error ?
2018-07-21 14:52:54 +02:00
}
} else {
throw new Error('Could not fetch transactions from API: ' + response.err); // breaks here
2018-07-21 14:52:54 +02:00
}
offset += 100;
}
} catch (err) {
console.warn(err);
2018-07-21 14:52:54 +02:00
}
}
2018-08-08 02:05:34 +02:00
/**
* Given that `address` is in our HD hierarchy, try to find
* corresponding WIF
*
* @param address {String} In our HD hierarchy
* @return {String} WIF if found
*/
_getWifForAddress(address) {
if (this._address_to_wif_cache[address]) return this._address_to_wif_cache[address]; // cache hit
// fast approach, first lets iterate over all addressess we have in cache
for (const index of Object.keys(this.internal_addresses_cache)) {
2018-08-08 02:05:34 +02:00
if (this._getInternalAddressByIndex(index) === address) {
return (this._address_to_wif_cache[address] = this._getInternalWIFByIndex(index));
}
}
for (const index of Object.keys(this.external_addresses_cache)) {
2018-08-08 02:05:34 +02:00
if (this._getExternalAddressByIndex(index) === address) {
return (this._address_to_wif_cache[address] = this._getExternalWIFByIndex(index));
}
}
2018-12-23 06:43:50 +01:00
// no luck - lets iterate over all addresses we have up to first unused address index
2019-05-28 22:30:03 +02:00
for (let c = 0; c <= this.next_free_change_address_index + this.gap_limit; c++) {
const possibleAddress = this._getInternalAddressByIndex(c);
2018-08-08 02:05:34 +02:00
if (possibleAddress === address) {
return (this._address_to_wif_cache[address] = this._getInternalWIFByIndex(c));
}
}
2019-05-28 22:30:03 +02:00
for (let c = 0; c <= this.next_free_address_index + this.gap_limit; c++) {
const possibleAddress = this._getExternalAddressByIndex(c);
2018-08-08 02:05:34 +02:00
if (possibleAddress === address) {
return (this._address_to_wif_cache[address] = this._getExternalWIFByIndex(c));
}
}
throw new Error('Could not find WIF for ' + address);
}
2018-12-22 03:46:35 +01:00
async fetchBalance() {
throw new Error('Not implemented');
2019-04-14 00:21:41 +02:00
}
/**
* @inheritDoc
*/
async fetchUtxo() {
throw new Error('Not implemented');
2018-12-22 03:46:35 +01:00
}
weOwnAddress(addr) {
const hashmap = {};
for (const a of this.usedAddresses) {
2018-12-22 03:46:35 +01:00
hashmap[a] = 1;
}
return hashmap[addr] === 1;
}
2019-09-27 16:49:56 +02:00
_getDerivationPathByAddress(address) {
throw new Error('Not implemented');
}
_getNodePubkeyByIndex(address) {
throw new Error('Not implemented');
}
2018-07-21 14:52:54 +02:00
}