-
Notifications
You must be signed in to change notification settings - Fork 2
/
legacy-wallet.js
489 lines (436 loc) · 14.1 KB
/
legacy-wallet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
import { AbstractWallet } from './abstract-wallet';
import { SegwitBech32Wallet } from './';
import { useBlockcypherTokens } from './constants';
import Frisbee from 'frisbee';
import { NativeModules } from 'react-native';
const bitcoin = require('bitcoinjs-lib');
const { RNRandomBytes } = NativeModules;
const BigNumber = require('bignumber.js');
const signer = require('../models/signer');
const BlueElectrum = require('../BlueElectrum');
/**
* Has private key and single address like "1ABCD....."
* (legacy P2PKH compressed)
*/
export class LegacyWallet extends AbstractWallet {
static type = 'legacy';
static typeReadable = 'Legacy (P2PKH)';
/**
* Simple function which says that we havent tried to fetch balance
* for a long time
*
* @return {boolean}
*/
timeToRefreshBalance() {
if (+new Date() - this._lastBalanceFetch >= 5 * 60 * 1000) {
return true;
}
return false;
}
/**
* Simple function which says if we hve some low-confirmed transactions
* and we better fetch them
*
* @return {boolean}
*/
timeToRefreshTransaction() {
for (let tx of this.transactions) {
if (tx.confirmations < 7) {
return true;
}
}
return false;
}
async generate() {
let that = this;
return new Promise(function(resolve) {
if (typeof RNRandomBytes === 'undefined') {
// CLI/CI environment
// crypto should be provided globally by test launcher
return crypto.randomBytes(32, (err, buf) => { // eslint-disable-line
if (err) throw err;
that.secret = bitcoin.ECPair.makeRandom({
rng: function(length) {
return buf;
},
}).toWIF();
resolve();
});
}
// RN environment
RNRandomBytes.randomBytes(32, (err, bytes) => {
if (err) throw new Error(err);
that.secret = bitcoin.ECPair.makeRandom({
rng: function(length) {
let b = Buffer.from(bytes, 'base64');
return b;
},
}).toWIF();
resolve();
});
});
}
/**
*
* @returns {string}
*/
getAddress() {
if (this._address) return this._address;
let address;
try {
let keyPair = bitcoin.ECPair.fromWIF(this.secret);
address = bitcoin.payments.p2pkh({
pubkey: keyPair.publicKey,
}).address;
} catch (err) {
return false;
}
this._address = address;
return this._address;
}
/**
* Fetches balance of the Wallet via API.
* Returns VOID. Get the actual balance via getter.
*
* @returns {Promise.<void>}
*/
async fetchBalance() {
try {
const api = new Frisbee({
baseURI: 'https://api.blockcypher.com/v1/btc/main/addrs/',
});
let response = await api.get(
this.getAddress() + '/balance' + ((useBlockcypherTokens && '?token=' + this.getRandomBlockcypherToken()) || ''),
);
let json = response.body;
if (typeof json === 'undefined' || typeof json.final_balance === 'undefined') {
throw new Error('Could not fetch balance from API: ' + response.err + ' ' + JSON.stringify(response.body));
}
this.balance = Number(json.final_balance);
this.unconfirmed_balance = new BigNumber(json.unconfirmed_balance);
this.unconfirmed_balance = this.unconfirmed_balance.dividedBy(100000000).toString() * 1;
this._lastBalanceFetch = +new Date();
} catch (err) {
console.warn(err);
}
}
/**
* Fetches UTXO from API. Returns VOID.
*
* @return {Promise.<void>}
*/
async fetchUtxo() {
const api = new Frisbee({
baseURI: 'https://api.blockcypher.com/v1/btc/main/addrs/',
});
let response;
try {
let maxHeight = 0;
this.utxo = [];
let json;
do {
response = await api.get(
this.getAddress() +
'?limit=2000&after=' +
maxHeight +
((useBlockcypherTokens && '&token=' + this.getRandomBlockcypherToken()) || ''),
);
json = response.body;
if (typeof json === 'undefined' || typeof json.final_balance === 'undefined') {
throw new Error('Could not fetch UTXO from API' + response.err);
}
json.txrefs = json.txrefs || []; // case when source address is empty (or maxheight too high, no txs)
for (let txref of json.txrefs) {
maxHeight = Math.max(maxHeight, txref.block_height) + 1;
if (typeof txref.spent !== 'undefined' && txref.spent === false) {
this.utxo.push(txref);
}
}
} while (json.txrefs.length);
json.unconfirmed_txrefs = json.unconfirmed_txrefs || [];
this.utxo = this.utxo.concat(json.unconfirmed_txrefs);
} catch (err) {
console.warn(err);
}
}
/**
* Fetches transactions via API. Returns VOID.
* Use getter to get the actual list.
*
* @return {Promise.<void>}
*/
async fetchTransactions() {
try {
const api = new Frisbee({
baseURI: 'https://api.blockcypher.com/',
});
let after = 0;
let before = 100500100;
for (let oldTx of this.getTransactions()) {
if (oldTx.block_height && oldTx.confirmations < 7) {
after = Math.max(after, oldTx.block_height);
}
}
while (1) {
let response = await api.get(
'v1/btc/main/addrs/' +
this.getAddress() +
'/full?after=' +
after +
'&before=' +
before +
'&limit=50' +
((useBlockcypherTokens && '&token=' + this.getRandomBlockcypherToken()) || ''),
);
let json = response.body;
if (typeof json === 'undefined' || !json.txs) {
throw new Error('Could not fetch transactions from API:' + response.err);
}
let alreadyFetchedTransactions = this.transactions;
this.transactions = json.txs;
this._lastTxFetch = +new Date();
// now, calculating value per each transaction...
for (let tx of this.transactions) {
if (tx.block_height) {
before = Math.min(before, tx.block_height); // so next time we fetch older TXs
}
// now, if we dont have enough outputs or inputs in response we should collect them from API:
if (tx.next_outputs) {
let newOutputs = await this._fetchAdditionalOutputs(tx.next_outputs);
tx.outputs = tx.outputs.concat(newOutputs);
}
if (tx.next_inputs) {
let newInputs = await this._fetchAdditionalInputs(tx.next_inputs);
tx.inputs = tx.inputs.concat(newInputs);
}
// how much came in...
let value = 0;
for (let out of tx.outputs) {
if (out && out.addresses && out.addresses.indexOf(this.getAddress()) !== -1) {
// found our address in outs of this TX
value += out.value;
}
}
tx.value = value;
// end
// how much came out
value = 0;
for (let inp of tx.inputs) {
if (!inp.addresses) {
// console.log('inp.addresses empty');
// console.log('got witness', inp.witness); // TODO
inp.addresses = [];
if (inp.witness && inp.witness[1]) {
let address = SegwitBech32Wallet.witnessToAddress(inp.witness[1]);
inp.addresses.push(address);
} else {
inp.addresses.push('???');
}
}
if (inp && inp.addresses && inp.addresses.indexOf(this.getAddress()) !== -1) {
// found our address in outs of this TX
value -= inp.output_value;
}
}
tx.value += value;
// end
}
this.transactions = alreadyFetchedTransactions.concat(this.transactions);
let txsUnconf = [];
let txs = [];
let hashPresent = {};
// now, rearranging TXs. unconfirmed go first:
for (let tx of this.transactions.reverse()) {
if (hashPresent[tx.hash]) continue;
hashPresent[tx.hash] = 1;
if (tx.block_height && tx.block_height === -1) {
// unconfirmed
console.log(tx);
if (+new Date(tx.received) < +new Date() - 3600 * 24 * 1000) {
// nop, too old unconfirmed tx - skipping it
} else {
txsUnconf.push(tx);
}
} else {
txs.push(tx);
}
}
this.transactions = txsUnconf.reverse().concat(txs.reverse());
// all reverses needed so freshly fetched TXs replace same old TXs
this.transactions = this.transactions.sort((a, b) => {
return a.received < b.received;
});
if (json.txs.length < 50) {
// final batch, so it has les than max txs
break;
}
}
} catch (err) {
console.warn(err);
}
}
async _fetchAdditionalOutputs(nextOutputs) {
let outputs = [];
let baseURI = nextOutputs.split('/');
baseURI = baseURI[0] + '/' + baseURI[1] + '/' + baseURI[2] + '/';
const api = new Frisbee({
baseURI: baseURI,
});
do {
await (() => new Promise(resolve => setTimeout(resolve, 1000)))();
nextOutputs = nextOutputs.replace(baseURI, '');
let response = await api.get(nextOutputs + ((useBlockcypherTokens && '&token=' + this.getRandomBlockcypherToken()) || ''));
let json = response.body;
if (typeof json === 'undefined') {
throw new Error('Could not fetch transactions from API:' + response.err);
}
if (json.outputs && json.outputs.length) {
outputs = outputs.concat(json.outputs);
nextOutputs = json.next_outputs;
} else {
break;
}
} while (1);
return outputs;
}
async _fetchAdditionalInputs(nextInputs) {
let inputs = [];
let baseURI = nextInputs.split('/');
baseURI = baseURI[0] + '/' + baseURI[1] + '/' + baseURI[2] + '/';
const api = new Frisbee({
baseURI: baseURI,
});
do {
await (() => new Promise(resolve => setTimeout(resolve, 1000)))();
nextInputs = nextInputs.replace(baseURI, '');
let response = await api.get(nextInputs + ((useBlockcypherTokens && '&token=' + this.getRandomBlockcypherToken()) || ''));
let json = response.body;
if (typeof json === 'undefined') {
throw new Error('Could not fetch transactions from API:' + response.err);
}
if (json.inputs && json.inputs.length) {
inputs = inputs.concat(json.inputs);
nextInputs = json.next_inputs;
} else {
break;
}
} while (1);
return inputs;
}
async broadcastTx(txhex) {
try {
const broadcast = await BlueElectrum.broadcast(txhex);
return broadcast;
} catch (error) {
return error;
}
}
async _broadcastTxBtczen(txhex) {
const api = new Frisbee({
baseURI: 'https://btczen.com',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
let res = await api.get('/broadcast/' + txhex);
console.log('response btczen', res.body);
return res.body;
}
async _broadcastTxChainso(txhex) {
const api = new Frisbee({
baseURI: 'https://chain.so',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
let res = await api.post('/api/v2/send_tx/BTC', {
body: { tx_hex: txhex },
});
return res.body;
}
async _broadcastTxSmartbit(txhex) {
const api = new Frisbee({
baseURI: 'https://api.smartbit.com.au',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
let res = await api.post('/v1/blockchain/pushtx', {
body: { hex: txhex },
});
return res.body;
}
async _broadcastTxBlockcypher(txhex) {
const api = new Frisbee({
baseURI: 'https://api.blockcypher.com',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
let res = await api.post('/v1/btc/main/txs/push', { body: { tx: txhex } });
// console.log('blockcypher response', res);
return res.body;
}
/**
* Takes UTXOs (as presented by blockcypher api), transforms them into
* format expected by signer module, creates tx and returns signed string txhex.
*
* @param utxos Unspent outputs, expects blockcypher format
* @param amount
* @param fee
* @param toAddress
* @param memo
* @return string Signed txhex ready for broadcast
*/
createTx(utxos, amount, fee, toAddress, memo) {
// transforming UTXOs fields to how module expects it
for (let u of utxos) {
u.confirmations = 6; // hack to make module accept 0 confirmations
u.txid = u.tx_hash;
u.vout = u.tx_output_n;
u.amount = new BigNumber(u.value);
u.amount = u.amount.dividedBy(100000000);
u.amount = u.amount.toString(10);
}
// console.log('creating legacy tx ', amount, ' with fee ', fee, 'secret=', this.getSecret(), 'from address', this.getAddress());
let amountPlusFee = parseFloat(new BigNumber(amount).plus(fee).toString(10));
return signer.createTransaction(utxos, toAddress, amountPlusFee, fee, this.getSecret(), this.getAddress());
}
getLatestTransactionTime() {
if (this.getTransactions().length === 0) {
return 0;
}
let max = 0;
for (let tx of this.getTransactions()) {
max = Math.max(new Date(tx.received) * 1, max);
}
return new Date(max).toString();
}
getRandomBlockcypherToken() {
return (array => {
for (let i = array.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array[0];
})([
'0326b7107b4149559d18ce80612ef812',
'a133eb7ccacd4accb80cb1225de4b155',
'7c2b1628d27b4bd3bf8eaee7149c577f',
'f1e5a02b9ec84ec4bc8db2349022e5f5',
'e5926dbeb57145979153adc41305b183',
]);
}
isAddressValid(address) {
try {
bitcoin.address.toOutputScript(address);
return true;
} catch (e) {
return false;
}
}
}