-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathabstract-hd-electrum-wallet.ts
More file actions
1565 lines (1372 loc) · 58.3 KB
/
Copy pathabstract-hd-electrum-wallet.ts
File metadata and controls
1565 lines (1372 loc) · 58.3 KB
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint react/prop-types: "off", @typescript-eslint/ban-ts-comment: "off", camelcase: "off" */
import * as bip39 from 'bip39';
import BigNumber from 'bignumber.js';
import b58 from 'bs58check';
import BIP32Factory, { BIP32Interface } from 'bip32';
import { ECPairInterface } from 'ecpair/src/ecpair';
import { Psbt, Transaction as BTransaction } from 'bitcoinjs-lib';
import { CoinSelectReturnInput, CoinSelectTarget } from 'coinselect';
import ecc from '../../blue_modules/noble_ecc';
import BIP47Factory, { BIP47Interface } from '@spsina/bip47';
import { ECPairFactory } from 'ecpair';
import { randomBytes } from '../rng';
import { AbstractHDWallet } from './abstract-hd-wallet';
import { CreateTransactionResult, CreateTransactionUtxo, Transaction, Utxo } from './types';
import { ElectrumHistory } from '../../blue_modules/BlueElectrum';
import type BlueElectrumNs from '../../blue_modules/BlueElectrum';
const ECPair = ECPairFactory(ecc);
const bitcoin = require('bitcoinjs-lib');
const BlueElectrum: typeof BlueElectrumNs = require('../../blue_modules/BlueElectrum');
const reverse = require('buffer-reverse');
const bip32 = BIP32Factory(ecc);
const bip47 = BIP47Factory(ecc);
type BalanceByIndex = {
c: number;
u: number;
};
/**
* Electrum - means that it utilizes Electrum protocol for blockchain data
*/
export class AbstractHDElectrumWallet extends AbstractHDWallet {
static type = 'abstract';
static typeReadable = 'abstract';
static defaultRBFSequence = 2147483648; // 1 << 31, minimum for replaceable transactions as per BIP68
static finalRBFSequence = 4294967295; // 0xFFFFFFFF
_balances_by_external_index: Record<number, BalanceByIndex>;
_balances_by_internal_index: Record<number, BalanceByIndex>;
// @ts-ignore
_txs_by_external_index: Record<number, Transaction[]>;
// @ts-ignore
_txs_by_internal_index: Record<number, Transaction[]>;
_utxo: any[];
// BIP47
_enable_BIP47: boolean;
_payment_code: string;
_sender_payment_codes: string[];
_addresses_by_payment_code: Record<string, string[]>;
_next_free_payment_code_address_index: Record<string, number>;
_txs_by_payment_code_index: Record<string, Transaction[][]>;
_balances_by_payment_code_index: Record<string, BalanceByIndex>;
_bip47_instance?: BIP47Interface;
constructor() {
super();
this._balances_by_external_index = {}; // 0 => { c: 0, u: 0 } // confirmed/unconfirmed
this._balances_by_internal_index = {};
this._txs_by_external_index = {};
this._txs_by_internal_index = {};
this._utxo = [];
// BIP47
this._enable_BIP47 = false;
this._payment_code = '';
this._sender_payment_codes = [];
this._next_free_payment_code_address_index = {};
this._txs_by_payment_code_index = {};
this._balances_by_payment_code_index = {};
this._addresses_by_payment_code = {};
}
/**
* @inheritDoc
*/
getBalance() {
let ret = 0;
for (const bal of Object.values(this._balances_by_external_index)) {
ret += bal.c;
}
for (const bal of Object.values(this._balances_by_internal_index)) {
ret += bal.c;
}
for (const pc of this._sender_payment_codes) {
ret += this._getBalancesByPaymentCodeIndex(pc).c;
}
return ret + (this.getUnconfirmedBalance() < 0 ? this.getUnconfirmedBalance() : 0);
}
/**
*
* @inheritDoc
*/
getUnconfirmedBalance() {
let ret = 0;
for (const bal of Object.values(this._balances_by_external_index)) {
ret += bal.u;
}
for (const bal of Object.values(this._balances_by_internal_index)) {
ret += bal.u;
}
for (const pc of this._sender_payment_codes) {
ret += this._getBalancesByPaymentCodeIndex(pc).u;
}
return ret;
}
async generate() {
const buf = await randomBytes(16);
this.secret = bip39.entropyToMnemonic(buf.toString('hex'));
}
async generateFromEntropy(user: Buffer) {
const random = await randomBytes(user.length < 32 ? 32 - user.length : 0);
const buf = Buffer.concat([user, random], 32);
this.secret = bip39.entropyToMnemonic(buf.toString('hex'));
}
_getExternalWIFByIndex(index: number): string | false {
return this._getWIFByIndex(false, index);
}
_getInternalWIFByIndex(index: number): string | false {
return this._getWIFByIndex(true, index);
}
/**
* Get internal/external WIF by wallet index
* @param {Boolean} internal
* @param {Number} index
* @returns {string|false} Either string WIF or FALSE if error happened
* @private
*/
_getWIFByIndex(internal: boolean, index: number): string | false {
if (!this.secret) return false;
const seed = this._getSeed();
const root = bip32.fromSeed(seed);
const path = `${this.getDerivationPath()}/${internal ? 1 : 0}/${index}`;
const child = root.derivePath(path);
return child.toWIF();
}
_getNodeAddressByIndex(node: number, index: number): string {
index = index * 1; // cast to int
if (node === 0) {
if (this.external_addresses_cache[index]) return this.external_addresses_cache[index]; // cache hit
}
if (node === 1) {
if (this.internal_addresses_cache[index]) return this.internal_addresses_cache[index]; // cache hit
}
if (node === 0 && !this._node0) {
const xpub = this._zpubToXpub(this.getXpub());
const hdNode = bip32.fromBase58(xpub);
this._node0 = hdNode.derive(node);
}
if (node === 1 && !this._node1) {
const xpub = this._zpubToXpub(this.getXpub());
const hdNode = bip32.fromBase58(xpub);
this._node1 = hdNode.derive(node);
}
let address: string;
if (node === 0) {
// @ts-ignore
address = this._hdNodeToAddress(this._node0.derive(index));
} else {
// tbh the only possible else is node === 1
// @ts-ignore
address = this._hdNodeToAddress(this._node1.derive(index));
}
if (node === 0) {
return (this.external_addresses_cache[index] = address);
} else {
// tbh the only possible else option is node === 1
return (this.internal_addresses_cache[index] = address);
}
}
_getNodePubkeyByIndex(node: number, index: number) {
index = index * 1; // cast to int
if (node === 0 && !this._node0) {
const xpub = this._zpubToXpub(this.getXpub());
const hdNode = bip32.fromBase58(xpub);
this._node0 = hdNode.derive(node);
}
if (node === 1 && !this._node1) {
const xpub = this._zpubToXpub(this.getXpub());
const hdNode = bip32.fromBase58(xpub);
this._node1 = hdNode.derive(node);
}
if (node === 0 && this._node0) {
return this._node0.derive(index).publicKey;
}
if (node === 1 && this._node1) {
return this._node1.derive(index).publicKey;
}
throw new Error('Internal error: this._node0 or this._node1 is undefined');
}
_getExternalAddressByIndex(index: number): string {
return this._getNodeAddressByIndex(0, index);
}
_getInternalAddressByIndex(index: number) {
return this._getNodeAddressByIndex(1, index);
}
/**
* Returning zpub actually, not xpub. Keeping same method name
* for compatibility.
*
* @return {String} zpub
*/
getXpub() {
if (this._xpub) {
return this._xpub; // cache hit
}
// first, getting xpub
const seed = this._getSeed();
const root = bip32.fromSeed(seed);
const path = this.getDerivationPath();
if (!path) {
throw new Error('Internal error: no path');
}
const child = root.derivePath(path).neutered();
const xpub = child.toBase58();
// bitcoinjs does not support zpub yet, so we just convert it from xpub
let data = b58.decode(xpub);
data = data.slice(4);
data = Buffer.concat([Buffer.from('04b24746', 'hex'), data]);
this._xpub = b58.encode(data);
return this._xpub;
}
/**
* @inheritDoc
*/
async fetchTransactions() {
// if txs are absent for some internal address in hierarchy - this is a sign
// we should fetch txs for that address
// OR if some address has unconfirmed balance - should fetch it's txs
// OR some tx for address is unconfirmed
// OR some tx has < 7 confirmations
// fetching transactions in batch: first, getting batch history for all addresses,
// then batch fetching all involved txids
// finally, batch fetching txids of all inputs (needed to see amounts & addresses of those inputs)
// then we combine it all together
const addresses2fetch = [];
for (let c = 0; c < this.next_free_address_index + this.gap_limit; c++) {
// external addresses first
let hasUnconfirmed = false;
this._txs_by_external_index[c] = this._txs_by_external_index[c] || [];
for (const tx of this._txs_by_external_index[c]) hasUnconfirmed = hasUnconfirmed || !tx.confirmations || tx.confirmations < 7;
if (hasUnconfirmed || this._txs_by_external_index[c].length === 0 || this._balances_by_external_index[c].u !== 0) {
addresses2fetch.push(this._getExternalAddressByIndex(c));
}
}
for (let c = 0; c < this.next_free_change_address_index + this.gap_limit; c++) {
// next, internal addresses
let hasUnconfirmed = false;
this._txs_by_internal_index[c] = this._txs_by_internal_index[c] || [];
for (const tx of this._txs_by_internal_index[c]) hasUnconfirmed = hasUnconfirmed || !tx.confirmations || tx.confirmations < 7;
if (hasUnconfirmed || this._txs_by_internal_index[c].length === 0 || this._balances_by_internal_index[c].u !== 0) {
addresses2fetch.push(this._getInternalAddressByIndex(c));
}
}
// next, bip47 addresses
for (const pc of this._sender_payment_codes) {
for (let c = 0; c < this._getNextFreePaymentCodeAddress(pc) + this.gap_limit; c++) {
let hasUnconfirmed = false;
this._txs_by_payment_code_index[pc] = this._txs_by_payment_code_index[pc] || {};
this._txs_by_payment_code_index[pc][c] = this._txs_by_payment_code_index[pc][c] || [];
for (const tx of this._txs_by_payment_code_index[pc][c])
hasUnconfirmed = hasUnconfirmed || !tx.confirmations || tx.confirmations < 7;
if (hasUnconfirmed || this._txs_by_payment_code_index[pc][c].length === 0 || this._balances_by_payment_code_index[pc].u !== 0) {
addresses2fetch.push(this._getBIP47Address(pc, c));
}
}
}
// first: batch fetch for all addresses histories
const histories = await BlueElectrum.multiGetHistoryByAddress(addresses2fetch);
const txs: Record<string, ElectrumHistory> = {};
for (const history of Object.values(histories)) {
for (const tx of history as ElectrumHistory[]) {
txs[tx.tx_hash] = tx;
}
}
// next, batch fetching each txid we got
const txdatas = await BlueElectrum.multiGetTransactionByTxid(Object.keys(txs));
// now, tricky part. we collect all transactions from inputs (vin), and batch fetch them too.
// then we combine all this data (we need inputs to see source addresses and amounts)
const vinTxids = [];
for (const txdata of Object.values(txdatas)) {
for (const vin of txdata.vin) {
vinTxids.push(vin.txid);
}
}
const vintxdatas = await BlueElectrum.multiGetTransactionByTxid(vinTxids);
// fetched all transactions from our inputs. now we need to combine it.
// iterating all _our_ transactions:
for (const txid of Object.keys(txdatas)) {
// iterating all inputs our our single transaction:
for (let inpNum = 0; inpNum < txdatas[txid].vin.length; inpNum++) {
const inpTxid = txdatas[txid].vin[inpNum].txid;
const inpVout = txdatas[txid].vin[inpNum].vout;
// got txid and output number of _previous_ transaction we shoud look into
if (vintxdatas[inpTxid]?.vout[inpVout]) {
// extracting amount & addresses from previous output and adding it to _our_ input:
txdatas[txid].vin[inpNum].addresses = vintxdatas[inpTxid].vout[inpVout].scriptPubKey.addresses;
txdatas[txid].vin[inpNum].value = vintxdatas[inpTxid].vout[inpVout].value;
}
}
}
// now purge all unconfirmed txs from internal hashmaps, since some may be evicted from mempool because they became invalid
// or replaced. hashmaps are going to be re-populated anyways, since we fetched TXs for addresses with unconfirmed TXs
for (let c = 0; c < this.next_free_address_index + this.gap_limit; c++) {
this._txs_by_external_index[c] = this._txs_by_external_index[c].filter(tx => !!tx.confirmations);
}
for (let c = 0; c < this.next_free_change_address_index + this.gap_limit; c++) {
this._txs_by_internal_index[c] = this._txs_by_internal_index[c].filter(tx => !!tx.confirmations);
}
for (const pc of this._sender_payment_codes) {
for (let c = 0; c < this._getNextFreePaymentCodeAddress(pc) + this.gap_limit; c++) {
this._txs_by_payment_code_index[pc][c] = this._txs_by_payment_code_index[pc][c].filter(tx => !!tx.confirmations);
}
}
// now, we need to put transactions in all relevant `cells` of internal hashmaps: this._txs_by_internal_index && this._txs_by_external_index
for (let c = 0; c < this.next_free_address_index + this.gap_limit; c++) {
for (const tx of Object.values(txdatas)) {
for (const vin of tx.vin) {
if (vin.addresses && vin.addresses.indexOf(this._getExternalAddressByIndex(c)) !== -1) {
// this TX is related to our address
this._txs_by_external_index[c] = this._txs_by_external_index[c] || [];
const { vin: txVin, vout: txVout, ...txRest } = tx;
const clonedTx = { ...txRest, inputs: txVin.slice(0), outputs: txVout.slice(0) };
// trying to replace tx if it exists already (because it has lower confirmations, for example)
let replaced = false;
for (let cc = 0; cc < this._txs_by_external_index[c].length; cc++) {
if (this._txs_by_external_index[c][cc].txid === clonedTx.txid) {
replaced = true;
this._txs_by_external_index[c][cc] = clonedTx;
}
}
if (!replaced) this._txs_by_external_index[c].push(clonedTx);
}
}
for (const vout of tx.vout) {
if (vout.scriptPubKey.addresses && vout.scriptPubKey.addresses.indexOf(this._getExternalAddressByIndex(c)) !== -1) {
// this TX is related to our address
this._txs_by_external_index[c] = this._txs_by_external_index[c] || [];
const { vin: txVin, vout: txVout, ...txRest } = tx;
const clonedTx = { ...txRest, inputs: txVin.slice(0), outputs: txVout.slice(0) };
// trying to replace tx if it exists already (because it has lower confirmations, for example)
let replaced = false;
for (let cc = 0; cc < this._txs_by_external_index[c].length; cc++) {
if (this._txs_by_external_index[c][cc].txid === clonedTx.txid) {
replaced = true;
this._txs_by_external_index[c][cc] = clonedTx;
}
}
if (!replaced) this._txs_by_external_index[c].push(clonedTx);
}
}
}
}
for (let c = 0; c < this.next_free_change_address_index + this.gap_limit; c++) {
for (const tx of Object.values(txdatas)) {
for (const vin of tx.vin) {
if (vin.addresses && vin.addresses.indexOf(this._getInternalAddressByIndex(c)) !== -1) {
// this TX is related to our address
this._txs_by_internal_index[c] = this._txs_by_internal_index[c] || [];
const { vin: txVin, vout: txVout, ...txRest } = tx;
const clonedTx = { ...txRest, inputs: txVin.slice(0), outputs: txVout.slice(0) };
// trying to replace tx if it exists already (because it has lower confirmations, for example)
let replaced = false;
for (let cc = 0; cc < this._txs_by_internal_index[c].length; cc++) {
if (this._txs_by_internal_index[c][cc].txid === clonedTx.txid) {
replaced = true;
this._txs_by_internal_index[c][cc] = clonedTx;
}
}
if (!replaced) this._txs_by_internal_index[c].push(clonedTx);
}
}
for (const vout of tx.vout) {
if (vout.scriptPubKey.addresses && vout.scriptPubKey.addresses.indexOf(this._getInternalAddressByIndex(c)) !== -1) {
// this TX is related to our address
this._txs_by_internal_index[c] = this._txs_by_internal_index[c] || [];
const { vin: txVin, vout: txVout, ...txRest } = tx;
const clonedTx = { ...txRest, inputs: txVin.slice(0), outputs: txVout.slice(0) };
// trying to replace tx if it exists already (because it has lower confirmations, for example)
let replaced = false;
for (let cc = 0; cc < this._txs_by_internal_index[c].length; cc++) {
if (this._txs_by_internal_index[c][cc].txid === clonedTx.txid) {
replaced = true;
this._txs_by_internal_index[c][cc] = clonedTx;
}
}
if (!replaced) this._txs_by_internal_index[c].push(clonedTx);
}
}
}
}
for (const pc of this._sender_payment_codes) {
for (let c = 0; c < this._getNextFreePaymentCodeAddress(pc) + this.gap_limit; c++) {
for (const tx of Object.values(txdatas)) {
for (const vin of tx.vin) {
if (vin.addresses && vin.addresses.indexOf(this._getBIP47Address(pc, c)) !== -1) {
// this TX is related to our address
this._txs_by_payment_code_index[pc] = this._txs_by_payment_code_index[pc] || {};
this._txs_by_payment_code_index[pc][c] = this._txs_by_payment_code_index[pc][c] || [];
const { vin: txVin, vout: txVout, ...txRest } = tx;
const clonedTx = { ...txRest, inputs: txVin.slice(0), outputs: txVout.slice(0) };
// trying to replace tx if it exists already (because it has lower confirmations, for example)
let replaced = false;
for (let cc = 0; cc < this._txs_by_payment_code_index[pc][c].length; cc++) {
if (this._txs_by_payment_code_index[pc][c][cc].txid === clonedTx.txid) {
replaced = true;
this._txs_by_payment_code_index[pc][c][cc] = clonedTx;
}
}
if (!replaced) this._txs_by_payment_code_index[pc][c].push(clonedTx);
}
}
for (const vout of tx.vout) {
if (vout.scriptPubKey.addresses && vout.scriptPubKey.addresses.indexOf(this._getBIP47Address(pc, c)) !== -1) {
// this TX is related to our address
this._txs_by_payment_code_index[pc] = this._txs_by_payment_code_index[pc] || {};
this._txs_by_payment_code_index[pc][c] = this._txs_by_payment_code_index[pc][c] || [];
const { vin: txVin, vout: txVout, ...txRest } = tx;
const clonedTx = { ...txRest, inputs: txVin.slice(0), outputs: txVout.slice(0) };
// trying to replace tx if it exists already (because it has lower confirmations, for example)
let replaced = false;
for (let cc = 0; cc < this._txs_by_internal_index[c].length; cc++) {
if (this._txs_by_internal_index[c][cc].txid === clonedTx.txid) {
replaced = true;
this._txs_by_internal_index[c][cc] = clonedTx;
}
}
if (!replaced) this._txs_by_internal_index[c].push(clonedTx);
}
}
}
}
}
this._lastTxFetch = +new Date();
}
getTransactions() {
let txs: Transaction[] = [];
for (const addressTxs of Object.values(this._txs_by_external_index)) {
txs = txs.concat(addressTxs);
}
for (const addressTxs of Object.values(this._txs_by_internal_index)) {
txs = txs.concat(addressTxs);
}
if (this._sender_payment_codes) {
for (const pc of this._sender_payment_codes) {
if (this._txs_by_payment_code_index[pc])
for (const addressTxs of Object.values(this._txs_by_payment_code_index[pc])) {
txs = txs.concat(addressTxs);
}
}
}
if (txs.length === 0) return []; // guard clause; so we wont spend time calculating addresses
// its faster to pre-build hashmap of owned addresses than to query `this.weOwnAddress()`, which in turn
// iterates over all addresses in hierarchy
const ownedAddressesHashmap: Record<string, boolean> = {};
for (let c = 0; c < this.next_free_address_index + 1; c++) {
ownedAddressesHashmap[this._getExternalAddressByIndex(c)] = true;
}
for (let c = 0; c < this.next_free_change_address_index + 1; c++) {
ownedAddressesHashmap[this._getInternalAddressByIndex(c)] = true;
}
if (this._sender_payment_codes)
for (const pc of this._sender_payment_codes) {
for (let c = 0; c < this._getNextFreePaymentCodeAddress(pc) + 1; c++) {
ownedAddressesHashmap[this._getBIP47Address(pc, c)] = true;
}
}
// hack: in case this code is called from LegacyWallet:
if (this.getAddress()) ownedAddressesHashmap[String(this.getAddress())] = true;
const ret: Transaction[] = [];
for (const tx of txs) {
tx.received = tx.blocktime * 1000;
if (!tx.blocktime) tx.received = +new Date() - 30 * 1000; // unconfirmed
tx.confirmations = tx.confirmations || 0; // unconfirmed
tx.hash = tx.txid;
tx.value = 0;
for (const vin of tx.inputs) {
// if input (spending) goes from our address - we are loosing!
if ((vin.address && ownedAddressesHashmap[vin.address]) || (vin.addresses?.[0] && ownedAddressesHashmap[vin.addresses[0]])) {
tx.value -= new BigNumber(vin.value ?? 0).multipliedBy(100000000).toNumber();
}
}
for (const vout of tx.outputs) {
// when output goes to our address - this means we are gaining!
if (vout.scriptPubKey.addresses?.[0] && ownedAddressesHashmap[vout.scriptPubKey.addresses[0]]) {
tx.value += new BigNumber(vout.value).multipliedBy(100000000).toNumber();
}
}
ret.push(tx);
}
// now, deduplication:
const usedTxIds: Record<string, number> = {};
const ret2 = [];
for (const tx of ret) {
if (!usedTxIds[tx.txid]) ret2.push(tx);
usedTxIds[tx.txid] = 1;
}
return ret2.sort(function (a, b) {
return Number(b.received) - Number(a.received);
});
}
async _binarySearchIterationForInternalAddress(index: number) {
const gerenateChunkAddresses = (chunkNum: number) => {
const ret = [];
for (let c = this.gap_limit * chunkNum; c < this.gap_limit * (chunkNum + 1); c++) {
ret.push(this._getInternalAddressByIndex(c));
}
return ret;
};
let lastChunkWithUsedAddressesNum = null;
let lastHistoriesWithUsedAddresses = null;
for (let c = 0; c < Math.round(index / this.gap_limit); c++) {
const histories = await BlueElectrum.multiGetHistoryByAddress(gerenateChunkAddresses(c));
// @ts-ignore
if (this.constructor._getTransactionsFromHistories(histories).length > 0) {
// in this particular chunk we have used addresses
lastChunkWithUsedAddressesNum = c;
lastHistoriesWithUsedAddresses = histories;
} else {
// empty chunk. no sense searching more chunks
break;
}
}
let lastUsedIndex = 0;
if (lastHistoriesWithUsedAddresses) {
// now searching for last used address in batch lastChunkWithUsedAddressesNum
for (
let c = Number(lastChunkWithUsedAddressesNum) * this.gap_limit;
c < Number(lastChunkWithUsedAddressesNum) * this.gap_limit + this.gap_limit;
c++
) {
const address = this._getInternalAddressByIndex(c);
if (lastHistoriesWithUsedAddresses[address] && lastHistoriesWithUsedAddresses[address].length > 0) {
lastUsedIndex = Math.max(c, lastUsedIndex) + 1; // point to next, which is supposed to be unused
}
}
}
return lastUsedIndex;
}
async _binarySearchIterationForExternalAddress(index: number) {
const gerenateChunkAddresses = (chunkNum: number) => {
const ret = [];
for (let c = this.gap_limit * chunkNum; c < this.gap_limit * (chunkNum + 1); c++) {
ret.push(this._getExternalAddressByIndex(c));
}
return ret;
};
let lastChunkWithUsedAddressesNum = null;
let lastHistoriesWithUsedAddresses = null;
for (let c = 0; c < Math.round(index / this.gap_limit); c++) {
const histories = await BlueElectrum.multiGetHistoryByAddress(gerenateChunkAddresses(c));
// @ts-ignore
if (this.constructor._getTransactionsFromHistories(histories).length > 0) {
// in this particular chunk we have used addresses
lastChunkWithUsedAddressesNum = c;
lastHistoriesWithUsedAddresses = histories;
} else {
// empty chunk. no sense searching more chunks
break;
}
}
let lastUsedIndex = 0;
if (lastHistoriesWithUsedAddresses) {
// now searching for last used address in batch lastChunkWithUsedAddressesNum
for (
let c = Number(lastChunkWithUsedAddressesNum) * this.gap_limit;
c < Number(lastChunkWithUsedAddressesNum) * this.gap_limit + this.gap_limit;
c++
) {
const address = this._getExternalAddressByIndex(c);
if (lastHistoriesWithUsedAddresses[address] && lastHistoriesWithUsedAddresses[address].length > 0) {
lastUsedIndex = Math.max(c, lastUsedIndex) + 1; // point to next, which is supposed to be unused
}
}
}
return lastUsedIndex;
}
async _binarySearchIterationForBIP47Address(paymentCode: string, index: number) {
const generateChunkAddresses = (chunkNum: number) => {
const ret = [];
for (let c = this.gap_limit * chunkNum; c < this.gap_limit * (chunkNum + 1); c++) {
ret.push(this._getBIP47Address(paymentCode, c));
}
return ret;
};
let lastChunkWithUsedAddressesNum = null;
let lastHistoriesWithUsedAddresses = null;
for (let c = 0; c < Math.round(index / this.gap_limit); c++) {
const histories = await BlueElectrum.multiGetHistoryByAddress(generateChunkAddresses(c));
// @ts-ignore
if (this.constructor._getTransactionsFromHistories(histories).length > 0) {
// in this particular chunk we have used addresses
lastChunkWithUsedAddressesNum = c;
lastHistoriesWithUsedAddresses = histories;
} else {
// empty chunk. no sense searching more chunks
break;
}
}
let lastUsedIndex = 0;
if (lastHistoriesWithUsedAddresses) {
// now searching for last used address in batch lastChunkWithUsedAddressesNum
for (
let c = Number(lastChunkWithUsedAddressesNum) * this.gap_limit;
c < Number(lastChunkWithUsedAddressesNum) * this.gap_limit + this.gap_limit;
c++
) {
const address = this._getBIP47Address(paymentCode, c);
if (lastHistoriesWithUsedAddresses[address] && lastHistoriesWithUsedAddresses[address].length > 0) {
lastUsedIndex = Math.max(c, lastUsedIndex) + 1; // point to next, which is supposed to be unused
}
}
}
return lastUsedIndex;
}
async fetchBalance() {
try {
if (this.next_free_change_address_index === 0 && this.next_free_address_index === 0) {
// doing binary search for last used address:
this.next_free_change_address_index = await this._binarySearchIterationForInternalAddress(1000);
this.next_free_address_index = await this._binarySearchIterationForExternalAddress(1000);
if (this._sender_payment_codes) {
for (const pc of this._sender_payment_codes) {
this._next_free_payment_code_address_index[pc] = await this._binarySearchIterationForBIP47Address(pc, 1000);
}
}
} // end rescanning fresh wallet
// finally fetching balance
await this._fetchBalance();
} catch (err) {
console.warn(err);
}
}
async _fetchBalance() {
// probing future addressess in hierarchy whether they have any transactions, in case
// our 'next free addr' pointers are lagging behind
// for that we are gona batch fetch history for all addresses between last used and last used + gap_limit
const lagAddressesToFetch = [];
for (let c = this.next_free_address_index; c < this.next_free_address_index + this.gap_limit; c++) {
lagAddressesToFetch.push(this._getExternalAddressByIndex(c));
}
for (let c = this.next_free_change_address_index; c < this.next_free_change_address_index + this.gap_limit; c++) {
lagAddressesToFetch.push(this._getInternalAddressByIndex(c));
}
for (const pc of this._sender_payment_codes) {
for (
let c = this._next_free_payment_code_address_index[pc];
c < this._next_free_payment_code_address_index[pc] + this.gap_limit;
c++
) {
lagAddressesToFetch.push(this._getBIP47Address(pc, c));
}
}
const txs = await BlueElectrum.multiGetHistoryByAddress(lagAddressesToFetch); // <------ electrum call
for (let c = this.next_free_address_index; c < this.next_free_address_index + this.gap_limit; c++) {
const address = this._getExternalAddressByIndex(c);
if (txs[address] && Array.isArray(txs[address]) && txs[address].length > 0) {
// whoa, someone uses our wallet outside! better catch up
this.next_free_address_index = c + 1;
}
}
for (let c = this.next_free_change_address_index; c < this.next_free_change_address_index + this.gap_limit; c++) {
const address = this._getInternalAddressByIndex(c);
if (txs[address] && Array.isArray(txs[address]) && txs[address].length > 0) {
// whoa, someone uses our wallet outside! better catch up
this.next_free_change_address_index = c + 1;
}
}
for (const pc of this._sender_payment_codes) {
for (
let c = this._next_free_payment_code_address_index[pc];
c < this._next_free_payment_code_address_index[pc] + this.gap_limit;
c++
) {
const address = this._getBIP47Address(pc, c);
if (txs[address] && Array.isArray(txs[address]) && txs[address].length > 0) {
// whoa, someone uses our wallet outside! better catch up
this._next_free_payment_code_address_index[pc] = c + 1;
}
}
}
// next, business as usuall. fetch balances
const addresses2fetch = [];
// generating all involved addresses.
// basically, refetch all from index zero to maximum. doesnt matter
// since we batch them 100 per call
// external
for (let c = 0; c < this.next_free_address_index + this.gap_limit; c++) {
addresses2fetch.push(this._getExternalAddressByIndex(c));
}
// internal
for (let c = 0; c < this.next_free_change_address_index + this.gap_limit; c++) {
addresses2fetch.push(this._getInternalAddressByIndex(c));
}
for (const pc of this._sender_payment_codes) {
for (let c = 0; c < this._next_free_payment_code_address_index[pc] + this.gap_limit; c++) {
addresses2fetch.push(this._getBIP47Address(pc, c));
}
}
const balances = await BlueElectrum.multiGetBalanceByAddress(addresses2fetch);
// converting to a more compact internal format
for (let c = 0; c < this.next_free_address_index + this.gap_limit; c++) {
const addr = this._getExternalAddressByIndex(c);
if (balances.addresses[addr]) {
// first, if balances differ from what we store - we delete transactions for that
// address so next fetchTransactions() will refetch everything
if (this._balances_by_external_index[c]) {
if (
this._balances_by_external_index[c].c !== balances.addresses[addr].confirmed ||
this._balances_by_external_index[c].u !== balances.addresses[addr].unconfirmed
) {
delete this._txs_by_external_index[c];
}
}
// update local representation of balances on that address:
this._balances_by_external_index[c] = {
c: balances.addresses[addr].confirmed,
u: balances.addresses[addr].unconfirmed,
};
}
}
for (let c = 0; c < this.next_free_change_address_index + this.gap_limit; c++) {
const addr = this._getInternalAddressByIndex(c);
if (balances.addresses[addr]) {
// first, if balances differ from what we store - we delete transactions for that
// address so next fetchTransactions() will refetch everything
if (this._balances_by_internal_index[c]) {
if (
this._balances_by_internal_index[c].c !== balances.addresses[addr].confirmed ||
this._balances_by_internal_index[c].u !== balances.addresses[addr].unconfirmed
) {
delete this._txs_by_internal_index[c];
}
}
// update local representation of balances on that address:
this._balances_by_internal_index[c] = {
c: balances.addresses[addr].confirmed,
u: balances.addresses[addr].unconfirmed,
};
}
}
for (const pc of this._sender_payment_codes) {
let confirmed = 0;
let unconfirmed = 0;
for (let c = 0; c < this._getNextFreePaymentCodeAddress(pc) + this.gap_limit; c++) {
const addr = this._getBIP47Address(pc, c);
if (balances.addresses[addr].confirmed || balances.addresses[addr].unconfirmed) {
confirmed = confirmed + balances.addresses[addr].confirmed;
unconfirmed = unconfirmed + balances.addresses[addr].unconfirmed;
}
}
this._balances_by_payment_code_index[pc] = {
c: confirmed,
u: unconfirmed,
};
}
this._lastBalanceFetch = +new Date();
}
async fetchUtxo() {
// fetching utxo of addresses that only have some balance
let addressess = [];
// considering confirmed balance:
for (let c = 0; c < this.next_free_address_index + this.gap_limit; c++) {
if (this._balances_by_external_index?.[c]?.c > 0) {
addressess.push(this._getExternalAddressByIndex(c));
}
}
for (let c = 0; c < this.next_free_change_address_index + this.gap_limit; c++) {
if (this._balances_by_internal_index?.[c]?.c > 0) {
addressess.push(this._getInternalAddressByIndex(c));
}
}
for (const pc of this._sender_payment_codes) {
for (let c = 0; c < this._next_free_payment_code_address_index[pc] + this.gap_limit; c++) {
if (this._balances_by_payment_code_index?.[pc]?.c > 0) {
addressess.push(this._getBIP47Address(pc, c));
}
}
}
// considering UNconfirmed balance:
for (let c = 0; c < this.next_free_address_index + this.gap_limit; c++) {
if (this._balances_by_external_index?.[c]?.u > 0) {
addressess.push(this._getExternalAddressByIndex(c));
}
}
for (let c = 0; c < this.next_free_change_address_index + this.gap_limit; c++) {
if (this._balances_by_internal_index?.[c]?.u > 0) {
addressess.push(this._getInternalAddressByIndex(c));
}
}
for (const pc of this._sender_payment_codes) {
for (let c = 0; c < this._next_free_payment_code_address_index[pc] + this.gap_limit; c++) {
if (this._balances_by_payment_code_index?.[pc]?.u > 0) {
addressess.push(this._getBIP47Address(pc, c));
}
}
}
// note: we could remove checks `.c` and `.u` to simplify code, but the resulting `addressess` array would be bigger, thus bigger batch
// to fetch (or maybe even several fetches), which is not critical but undesirable.
// anyway, result has `.confirmations` property for each utxo, so outside caller can easily filter out unconfirmed if he wants to
addressess = [...new Set(addressess)]; // deduplicate just for any case
const fetchedUtxo = await BlueElectrum.multiGetUtxoByAddress(addressess);
this._utxo = [];
for (const arr of Object.values(fetchedUtxo)) {
this._utxo = this._utxo.concat(arr);
}
// backward compatibility TODO: remove when we make sure `.utxo` is not used
this.utxo = this._utxo;
// this belongs in `.getUtxo()`
for (const u of this.utxo) {
u.txid = u.txId;
u.amount = u.value;
u.wif = this._getWifForAddress(u.address);
if (!u.confirmations && u.height) u.confirmations = BlueElectrum.estimateCurrentBlockheight() - u.height;
}
this.utxo = this.utxo.sort((a, b) => Number(a.amount) - Number(b.amount));
// more consistent, so txhex in unit tests wont change
}
/**
* Getter for previously fetched UTXO. For example:
* [ { height: 0,
* value: 666,
* address: 'string',
* txId: 'string',
* vout: 1,
* txid: 'string',
* amount: 666,
* wif: 'string',
* confirmations: 0 } ]
*
* @param respectFrozen {boolean} Add Frozen outputs
* @returns {[]}
*/
getUtxo(respectFrozen = false) {
let ret = [];
if (this._utxo.length === 0) {
ret = this.getDerivedUtxoFromOurTransaction(); // oy vey, no stored utxo. lets attempt to derive it from stored transactions
} else {
ret = this._utxo;
}
if (!respectFrozen) {
ret = ret.filter(({ txid, vout }) => !this.getUTXOMetadata(txid, vout).frozen);
}
return ret;
}
getDerivedUtxoFromOurTransaction(returnSpentUtxoAsWell = false): Utxo[] {
const utxos: Utxo[] = [];
// its faster to pre-build hashmap of owned addresses than to query `this.weOwnAddress()`, which in turn
// iterates over all addresses in hierarchy
const ownedAddressesHashmap: Record<string, boolean> = {};
for (let c = 0; c < this.next_free_address_index + 1; c++) {
ownedAddressesHashmap[this._getExternalAddressByIndex(c)] = true;
}
for (let c = 0; c < this.next_free_change_address_index + 1; c++) {
ownedAddressesHashmap[this._getInternalAddressByIndex(c)] = true;
}
for (const pc of this._sender_payment_codes) {
for (let c = 0; c < this._getNextFreePaymentCodeAddress(pc) + 1; c++) {
ownedAddressesHashmap[this._getBIP47Address(pc, c)] = true;
}
}
for (const tx of this.getTransactions()) {
for (const output of tx.outputs) {
let address: string | false = false;
if (output.scriptPubKey && output.scriptPubKey.addresses && output.scriptPubKey.addresses[0]) {
address = output.scriptPubKey.addresses[0];
}
if (ownedAddressesHashmap[String(address)]) {
const value = new BigNumber(output.value).multipliedBy(100000000).toNumber();
utxos.push({
txid: tx.txid,
txId: tx.txid,
vout: output.n,
address: String(address),
value,
amount: value,
confirmations: tx.confirmations,
wif: false,
height: BlueElectrum.estimateCurrentBlockheight() - (tx.confirmations ?? 0),
});
}
}
}
if (returnSpentUtxoAsWell) return utxos;