forked from JSKitty/scc-web3
-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathwallet.js
More file actions
1687 lines (1554 loc) · 55.6 KB
/
wallet.js
File metadata and controls
1687 lines (1554 loc) · 55.6 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
import { validateMnemonic } from 'bip39';
import { parseWIF } from './encoding.js';
import { beforeUnloadListener, blockCount } from './global.js';
import { getNetwork } from './network/network_manager.js';
import { MAX_ACCOUNT_GAP } from './chain_params.js';
import { HistoricalTx, HistoricalTxType } from './historical_tx.js';
import { COutpoint, Transaction } from './transaction.js';
import { confirmPopup, isShieldAddress } from './misc.js';
import { cChainParams } from './chain_params.js';
import { COIN } from './chain_params.js';
import { ALERTS, translation } from './i18n.js';
import { encrypt } from './aes-gcm.js';
import { Database } from './database.js';
import { RECEIVE_TYPES } from './contacts-book.js';
import { Account } from './accounts.js';
import { fAdvancedMode } from './settings.js';
import {
bytesToHex,
hexToBytes,
reverseAndSwapEndianess,
sleep,
} from './utils.js';
import { LedgerController } from './ledger.js';
import { OutpointState, Mempool } from './mempool.js';
import { EventEmitterWrapper, getEventEmitter } from './event_bus.js';
import { lockableFunction } from './lock.js';
import {
isP2CS,
isP2PKH,
isP2EXC,
getAddressFromHash,
COLD_START_INDEX,
P2PK_START_INDEX,
OWNER_START_INDEX,
} from './script.js';
import { PIVXShield } from 'pivx-shield';
import { guiToggleReceiveType } from './contacts-book.js';
import { TransactionBuilder } from './transaction_builder.js';
import { createAlert } from './alerts/alert.js';
import { AsyncInterval } from './async_interval.js';
import {
debugError,
debugLog,
debugTimerEnd,
debugTimerStart,
DebugTopics,
} from './debug.js';
import { OrderedArray } from './ordered_array.js';
import { SaplingParams } from './sapling_params.js';
import { HdMasterKey } from './masterkey.js';
import { BinaryShieldSyncer } from './shield_syncer.js';
import { useWallets } from './composables/use_wallet.js';
/**
* Class Wallet, at the moment it is just a "realization" of Masterkey with a given nAccount
* it also remembers which addresses we generated.
* in future PRs this class will manage balance, UTXOs, masternode etc...
*/
export class Wallet {
/**
* We are using two chains: The external chain, and the internal one (i.e. change addresses)
* See https://github.com/bitcoin/bips/blob/master/bip-0048.mediawiki for more info
* (Change paragraph)
*/
static Chains = {
EXTERNAL: 0,
INTERNAL: 1,
};
/**
* @param {(x: number) => void} fn
*/
#iterChains(fn) {
for (let i in Wallet.Chains) {
let chain = Wallet.Chains[i];
fn(chain);
}
}
/**
* @type {import('./masterkey.js').MasterKey?}
*/
#masterKey;
/**
* @type {import('pivx-shield').PIVXShield?}
*/
#shield = null;
/**
* @type {number}
*/
#nAccount;
/**
* Map bip48 change -> Loaded index
* Number of loaded indexes, loaded means that they are in the ownAddresses map
* @type {Map<number, number>}
*/
#loadedIndexes = new Map();
/**
* Map bip48 change -> Highest used index
* Highest index used, where used means that the corresponding address is on chain (for example in a tx)
* @type {Map<number, number>}
*/
#highestUsedIndices = new Map();
/**
* @type {Map<number, number>}
*/
#addressIndices = new Map();
/**
* Map our own address -> Path
* @type {Map<String, String?>}
*/
#ownAddresses = new Map();
/**
* Map public key hash -> Address
* @type {Map<String,String>}
*/
#knownPKH = new Map();
/**
* @type {Mempool}
*/
#mempool;
#isSynced = false;
/**
* The height of the last processed block in the wallet
* @type {number}
*/
#lastProcessedBlock = 0;
#eventEmitter = new EventEmitterWrapper();
/**
* Array of historical txs, ordered by block height
* @type OrderedArray<HistoricalTx>
*/
#historicalTxs = new OrderedArray((hTx1, hTx2) => {
if (hTx1.blockHeight === -1) {
return hTx1;
}
if (hTx2.blockHeight === -1) {
return hTx2;
}
return hTx1.blockHeight >= hTx2.blockHeight;
});
constructor({
nAccount = 0,
masterKey,
shield,
mempool = new Mempool(),
} = {}) {
this.#nAccount = nAccount;
this.#mempool = mempool;
this.#mempool.setEmitter(() => {
this.#eventEmitter.emit('balance-update');
});
this.setMasterKey({ mk: masterKey, nAccount });
this.#shield = shield;
this.#iterChains((chain) => {
this.#highestUsedIndices.set(chain, 0);
this.#loadedIndexes.set(chain, 0);
this.#addressIndices.set(chain, 0);
});
this.#subscribeToNetworkEvents();
}
/**
* Check whether a given outpoint is locked
* @param {import('./transaction.js').COutpoint} opt
* @return {boolean} true if opt is locked, false otherwise
*/
isCoinLocked(opt) {
return !!(this.#mempool.getOutpointStatus(opt) & OutpointState.LOCKED);
}
/**
* Lock a given Outpoint
* @param {import('./transaction.js').COutpoint} opt
*/
lockCoin(opt) {
this.#mempool.addOutpointStatus(opt, OutpointState.LOCKED);
}
/**
* Unlock a given Outpoint
* @param {import('./transaction.js').COutpoint} opt
*/
unlockCoin(opt) {
this.#mempool.removeOutpointStatus(opt, OutpointState.LOCKED);
}
/**
* Get master key
* @deprecated use the wallet functions instead
*/
getMasterKey() {
return this.#masterKey;
}
/**
* Gets the Cold Staking Address for the current wallet, while considering user settings and network automatically.
* @return {Promise<String>} Cold Address
*/
async getColdStakingAddress() {
// Check if we have an Account with custom Cold Staking settings
const cDB = await Database.getInstance();
const settings = await cDB.getSettings();
// If there's an account with a Cold Address, return it, otherwise return the default
return (
settings?.coldAddress ||
cChainParams.current.defaultColdStakingAddress
);
}
get nAccount() {
return this.#nAccount;
}
get isSynced() {
return this.#isSynced;
}
get isSyncing() {
return this.sync.isLocked();
}
wipePrivateData() {
this.#masterKey.wipePrivateData(this.#nAccount);
if (this.#shield) {
this.#shield.extsk = null;
}
}
isViewOnly() {
if (!this.#masterKey) return false;
return this.#masterKey.isViewOnly;
}
isHD() {
if (!this.#masterKey) return false;
return this.#masterKey.isHD;
}
/**
* Set or replace the active Master Key with a new Master Key
* @param {object} o - Object to be destructured
* @param {import('./masterkey.js').MasterKey} o.mk - The new Master Key
* @param {number} [o.nAccount] - The account number
* @param {string} [o.extsk] - The extended spending key
* @returns {Promise<void> | void} Only a promise is extsk is set
*/
setMasterKey({ mk, nAccount = 0, extsk }) {
const isNewAcc =
mk?.getKeyToExport(nAccount) !==
this.#masterKey?.getKeyToExport(this.#nAccount);
this.#masterKey = mk;
this.#nAccount = nAccount;
if (extsk) return this.setExtsk(extsk);
if (isNewAcc) {
this.reset();
this.#iterChains((chain) => {
this.#loadAddresses(chain);
});
}
}
async loadSeed(seed, coinType = cChainParams.current.BIP44_TYPE) {
await this.setMasterKey({
mk: new HdMasterKey({
seed,
}),
nAccount: this.nAccount,
});
await this.#shield?.loadSeed(seed, coinType, this.nAccount);
}
/**
* Set the extended spending key of a shield object
* @param {String} extsk encoded extended spending key
*/
async setExtsk(extsk) {
await this.#shield.loadExtendedSpendingKey(extsk);
}
/**
* This should really be provided with the constructor,
* This will be done once `Dashboard.vue` is the owner of the wallet
* @param {import('pivx-shield').PIVXShield} shield object to set
*/
setShield(shield) {
this.#shield = shield;
}
hasShield() {
return !!this.#shield;
}
/**
* Reset the wallet, indexes address map and so on
*/
reset() {
this.#highestUsedIndices = new Map();
this.#loadedIndexes = new Map();
this.#ownAddresses = new Map();
this.#isSynced = false;
this.#shield = null;
this.#addressIndices = new Map();
this.#iterChains((chain) => {
this.#highestUsedIndices.set(chain, 0);
this.#loadedIndexes.set(chain, 0);
this.#addressIndices.set(chain, 0);
});
this.#mempool = new Mempool();
this.#lastProcessedBlock = 0;
this.#historicalTxs.clear();
}
/**
* Derive the current external address
* @return {string} Address
*
*/
getCurrentAddress() {
const ext = Wallet.Chains.EXTERNAL;
return this.#getAddress(ext, this.#addressIndices.get(ext));
}
/**
* Update the current address.
*/
#updateCurrentAddress() {
// No need to update the change address, as it is only handled internally by the wallet.
const last = this.#highestUsedIndices.get(Wallet.Chains.EXTERNAL);
const curr = this.#addressIndices.get(Wallet.Chains.EXTERNAL);
if (curr <= last) {
this.#addressIndices.set(Wallet.Chains.EXTERNAL, last + 1);
}
}
/**
* Derive a generic address (given nReceiving and nIndex)
* @return {string} Address
*/
#getAddress(nReceiving, nIndex) {
const path = this.#getDerivationPath(nReceiving, nIndex);
return this.#masterKey.getAddress(path);
}
/**
* Derive a generic address (given the full path)
* @return {string} Address
*/
getAddressFromPath(path) {
return this.#masterKey.getAddress(path);
}
/**
* Derive xpub (given nReceiving and nIndex)
* @return {string} Address
*/
getXPub(nReceiving = Wallet.Chains.EXTERNAL, nIndex = 0) {
// Get our current wallet XPub
const derivationPath = this.#getDerivationPath(nReceiving, nIndex)
.split('/')
.slice(0, 4)
.join('/');
return this.#masterKey.getxpub(derivationPath);
}
/**
* Check if the wallet (masterKey) is loaded in memory
* @return {boolean} Return `true` if a masterKey has been loaded in the wallet
*/
isLoaded() {
return !!this.#masterKey;
}
async save(encWif) {
const database = await Database.getInstance();
let shieldData = '';
if (this.#shield) {
shieldData = this.#shield.save();
}
const oldAccount = await database.getAccount(this.getKeyToExport());
// Prepare to Add/Update an account in the DB
const cAccount = new Account({
publicKey: this.getKeyToExport(),
shieldData: shieldData,
encWif: encWif || oldAccount?.encWif || '',
});
// Incase of a "Change Password", we check if an Account already exists
if (oldAccount) {
// Update the existing Account (new encWif) in the DB
await database.updateAccount(cAccount);
} else {
// Add the new Account to the DB
await database.addAccount(cAccount);
}
}
/**
* Encrypt the keyToBackup with a given password
* @param {string} strPassword
* @returns {Promise<boolean>}
*/
async encrypt(strPassword) {
// Encrypt the wallet WIF with AES-GCM and a user-chosen password - suitable for browser storage
let strEncWIF = await encrypt(this.getKeyToEncrypt(), strPassword);
let strEncExtsk = '';
let shieldData = '';
if (this.#shield) {
strEncExtsk = await encrypt(this.#shield.extsk, strPassword);
shieldData = this.#shield.save();
}
if (!strEncWIF) return false;
// Prepare to Add/Update an account in the DB
const cAccount = new Account({
publicKey: this.getKeyToExport(),
encWif: strEncWIF,
encExtsk: strEncExtsk,
shieldData: shieldData,
});
// Incase of a "Change Password", we check if an Account already exists
const database = await Database.getInstance();
if (await database.getAccount(this.getKeyToExport())) {
// Update the existing Account (new encWif) in the DB
await database.updateAccount(cAccount);
} else {
// Add the new Account to the DB
await database.addAccount(cAccount);
}
// Remove the exit blocker, we can annoy the user less knowing the key is safe in their database!
removeEventListener('beforeunload', beforeUnloadListener, {
capture: true,
});
return true;
}
/**
* @return {[string, string]} Address and its BIP32 derivation path
*/
getNewAddress(nReceiving = Wallet.Chains.EXTERNAL) {
const last = this.#highestUsedIndices.get(nReceiving);
const curr = this.#addressIndices.get(nReceiving);
this.#addressIndices.set(nReceiving, Math.max(curr, last) + 1);
if (this.#addressIndices.get(nReceiving) - last > MAX_ACCOUNT_GAP) {
// If the user creates more than ${MAX_ACCOUNT_GAP} empty wallets we will not be able to sync them!
this.#addressIndices.set(nReceiving, last);
}
const path = this.#getDerivationPath(
nReceiving,
this.#addressIndices.get(nReceiving)
);
const address = this.#getAddress(
nReceiving,
this.#addressIndices.get(nReceiving)
);
return [address, path];
}
/**
* Generates a new change address
* @returns {string}
*/
getNewChangeAddress() {
return this.getNewAddress(Wallet.Chains.INTERNAL)[0];
}
/**
* @returns {Promise<string>} new shield address
*/
async getNewShieldAddress() {
return await this.#shield.getNewAddress();
}
isHardwareWallet() {
return this.#masterKey?.isHardwareWallet === true;
}
/**
* Check if the vout is owned and in case update highestUsedIdex
* @param {CTxOut} vout
*/
#updateHighestUsedIndex(vout) {
const dataBytes = hexToBytes(vout.script);
const iStart = isP2PKH(dataBytes) ? P2PK_START_INDEX : COLD_START_INDEX;
const address = this.#getAddressFromHashCache(
bytesToHex(dataBytes.slice(iStart, iStart + 20))
);
const path = this.isOwnAddress(address);
if (path) {
const nReceiving = parseInt(path.split('/')[4]);
this.#highestUsedIndices.set(
nReceiving,
Math.max(
parseInt(path.split('/')[5]),
this.#highestUsedIndices.get(nReceiving)
)
);
if (
this.#highestUsedIndices.get(nReceiving) + MAX_ACCOUNT_GAP >=
this.#loadedIndexes.get(nReceiving)
) {
this.#loadAddresses(nReceiving);
}
}
}
/**
* Load MAX_ACCOUNT_GAP inside #ownAddresses map.
* @param {number} chain - Chain to load
*/
#loadAddresses(chain) {
if (this.isHD()) {
const start = this.#loadedIndexes.get(chain);
const end = start + MAX_ACCOUNT_GAP;
for (let i = start; i <= end; i++) {
const path = this.#getDerivationPath(chain, i);
const address = this.#masterKey.getAddress(path);
this.#ownAddresses.set(address, path);
}
this.#loadedIndexes.set(chain, end);
} else {
this.#ownAddresses.set(this.getKeyToExport(), ':)');
}
}
/**
* @param {string} address - address to check
* @return {string?} BIP32 path or null if it's not your address
*/
isOwnAddress(address) {
const path = this.#ownAddresses.get(address) ?? null;
return path;
}
/**
* @return {String} BIP32 path or null if it's not your address
*/
#getDerivationPath(nReceiving, nIndex) {
return this.#masterKey.getDerivationPath(
this.#nAccount,
nReceiving,
nIndex
);
}
getKeyToExport() {
return this.#masterKey?.getKeyToExport(this.#nAccount);
}
/**
* @returns key to backup. May be encrypted
*/
async getKeyToBackup() {
if (await hasEncryptedWallet()) {
const account = await (
await Database.getInstance()
).getAccount(this.getKeyToExport());
return account.encWif;
}
return this.getKeyToEncrypt();
}
/**
* @returns key to encrypt
*/
getKeyToEncrypt() {
return JSON.stringify({
mk: this.getMasterKey()?.keyToBackup,
shield: this.#shield?.extsk,
});
}
//Get path from a script
getPath(script) {
const dataBytes = hexToBytes(script);
// At the moment we support only P2PKH and P2CS
const iStart = isP2PKH(dataBytes) ? P2PK_START_INDEX : COLD_START_INDEX;
const address = this.#getAddressFromHashCache(
bytesToHex(dataBytes.slice(iStart, iStart + 20))
);
return this.isOwnAddress(address);
}
/**
* Get the outpoint state based on the script.
* This functions only tells us the type of the script and if it's ours
* It doesn't know about LOCK, IMMATURE or SPENT statuses, for that
* it's necessary to interrogate the mempool
*/
#getScriptType(script) {
const { type, addresses } = this.getAddressesFromScript(script);
let status = 0;
const isOurs = addresses.some((s) => this.isOwnAddress(s));
if (isOurs) status |= OutpointState.OURS;
if (type === 'p2pkh') status |= OutpointState.P2PKH;
if (type === 'p2cs') {
status |= OutpointState.P2CS;
}
return status;
}
/**
* Get addresses from a script
* @returns {{ type: 'p2pkh'|'p2cs'|'unknown', addresses: string[] }}
*/
getAddressesFromScript(script) {
const dataBytes = hexToBytes(script);
if (isP2PKH(dataBytes)) {
const address = this.#getAddressFromHashCache(
bytesToHex(
dataBytes.slice(P2PK_START_INDEX, P2PK_START_INDEX + 20)
)
);
return {
type: 'p2pkh',
addresses: [address],
};
} else if (isP2CS(dataBytes)) {
const addresses = [];
for (let i = 0; i < 2; i++) {
const iStart = i === 0 ? OWNER_START_INDEX : COLD_START_INDEX;
addresses.push(
this.#getAddressFromHashCache(
bytesToHex(dataBytes.slice(iStart, iStart + 20)),
iStart === OWNER_START_INDEX
? 'coldaddress'
: 'pubkeyhash'
)
);
}
return { type: 'p2cs', addresses };
} else if (isP2EXC(dataBytes)) {
const address = this.#getAddressFromHashCache(
bytesToHex(
dataBytes.slice(
P2PK_START_INDEX + 1,
P2PK_START_INDEX + 20 + 1
)
),
'exchangeaddress'
);
return {
type: 'exchange',
addresses: [address],
};
} else {
return { type: 'unknown', addresses: [] };
}
}
// Avoid calculating over and over the same getAddressFromHash by saveing the result in a map
#getAddressFromHashCache(pkh_hex, type) {
if (!this.#knownPKH.has(pkh_hex)) {
this.#knownPKH.set(
pkh_hex,
getAddressFromHash(hexToBytes(pkh_hex), type)
);
}
return this.#knownPKH.get(pkh_hex);
}
/**
* Return true if the transaction contains undelegations regarding the given wallet
* @param {import('./transaction.js').Transaction} tx
*/
#checkForUndelegations(tx) {
for (const vin of tx.vin) {
const status = this.#mempool.getOutpointStatus(vin.outpoint);
if (status & OutpointState.P2CS) {
return true;
}
}
return false;
}
/**
* Return true if the transaction contains delegations regarding the given wallet
* @param {import('./transaction.js').Transaction} tx
*/
#checkForDelegations(tx) {
const txid = tx.txid;
for (let i = 0; i < tx.vout.length; i++) {
const outpoint = new COutpoint({
txid,
n: i,
});
if (
this.#mempool.getOutpointStatus(outpoint) & OutpointState.P2CS
) {
return true;
}
}
return false;
}
/**
* Return the output addresses for a given transaction
* @param {import('./transaction.js').Transaction} tx
*/
#getOutAddress(tx) {
return tx.vout.reduce(
(acc, vout) => [
...acc,
...this.getAddressesFromScript(vout.script).addresses,
],
[]
);
}
/**
* Convert a list of Blockbook transactions to HistoricalTxs
* @param {import('./transaction.js').Transaction} tx - A Transaction
* @returns {Promise<HistoricalTx>} - The corresponding `HistoricalTx`- formatted transaction
*/
async #toHistoricalTX(tx) {
const { credit, ownAllVout } = this.#mempool.getCredit(tx);
const { debit, ownAllVin } = this.#mempool.getDebit(tx);
// The total 'delta' or change in balance, from the Tx's sums
let nAmount = (credit - debit) / COIN;
// Shielded data
const { shieldCredit, shieldDebit, arrShieldReceivers } =
await this.#extractSaplingAmounts(tx);
const nShieldAmount = (shieldCredit - shieldDebit) / COIN;
const ownAllShield = shieldDebit - shieldCredit === tx.valueBalance;
// The receiver addresses, if any
let arrReceivers = this.#getOutAddress(tx);
const getFilteredCredit = (filter) => {
return tx.vout
.filter((_, i) => {
const status = this.#mempool.getOutpointStatus(
new COutpoint({
txid: tx.txid,
n: i,
})
);
return status & filter && status & OutpointState.OURS;
})
.reduce((acc, o) => acc + o.value, 0);
};
// Figure out the type, based on the Tx's properties
let type = HistoricalTxType.UNKNOWN;
if (tx.isCoinStake()) {
type = HistoricalTxType.STAKE;
} else if (tx.isProposalFee()) {
type = HistoricalTxType.PROPOSAL_FEE;
} else if (this.#checkForUndelegations(tx)) {
type = HistoricalTxType.UNDELEGATION;
nAmount = getFilteredCredit(OutpointState.P2PKH) / COIN;
} else if (this.#checkForDelegations(tx)) {
type = HistoricalTxType.DELEGATION;
arrReceivers = arrReceivers.filter((addr) => {
return addr[0] === cChainParams.current.STAKING_PREFIX;
});
nAmount = getFilteredCredit(OutpointState.P2CS) / COIN;
} else if (nAmount + nShieldAmount > 0) {
type = HistoricalTxType.RECEIVED;
} else if (nAmount + nShieldAmount < 0) {
type = HistoricalTxType.SENT;
}
return new HistoricalTx(
type,
tx.txid,
arrReceivers,
arrShieldReceivers,
tx.blockTime,
tx.blockHeight,
nAmount,
nShieldAmount,
ownAllVin && ownAllVout && ownAllShield
);
}
/**
* Extract the sapling spent, received and shield addressed, regarding the wallet, from a tx
* @param {import('./transaction.js').Transaction} tx - a Transaction object
*/
async #extractSaplingAmounts(tx) {
let shieldCredit = 0;
let shieldDebit = 0;
let arrShieldReceivers = [];
if (!tx.hasShieldData || !this.hasShield()) {
return { shieldCredit, shieldDebit, arrShieldReceivers };
}
for (const shieldSpend of tx.shieldSpend) {
const nullifier = reverseAndSwapEndianess(shieldSpend.nullifier);
const spentNote = this.#shield.getNoteFromNullifier(nullifier);
if (spentNote) {
shieldDebit += spentNote.value;
}
}
const myOutputNotes = await this.#shield.decryptTransactionOutputs(
tx.serialize()
);
for (const note of myOutputNotes) {
shieldCredit += note.value;
arrShieldReceivers.push({
recipient: note.recipient,
memo: note.memo,
});
}
return { shieldCredit, shieldDebit, arrShieldReceivers };
}
/*
* @param {Transaction} tx
*/
async #pushToHistoricalTx(tx) {
const hTx = await this.#toHistoricalTX(tx);
this.#historicalTxs.insert(hTx);
}
/**
* @returns {HistoricalTx[]}
*/
getHistoricalTxs() {
return this.#historicalTxs.get();
}
sync = lockableFunction(async () => {
if (this.#isSynced) {
throw new Error('Attempting to sync when already synced');
}
// While syncing the wallet ( DB read + network sync) disable the event balance-update
// This is done to avoid a huge spam of event.
this.#eventEmitter.disableEvent('balance-update');
this.#eventEmitter.disableEvent('new-tx');
await this.#loadShieldFromDisk();
await this.#loadFromDisk();
// Let's set the last processed block 5 blocks behind the actual chain tip
// This is just to be sure since blockbook (as we know)
// usually does not return txs of the actual last block.
this.#lastProcessedBlock = blockCount - 5;
await this.#transparentSync();
if (this.hasShield()) {
debugTimerStart(DebugTopics.WALLET, 'syncShield');
await this.#syncShield();
debugTimerEnd(DebugTopics.WALLET, 'syncShield');
}
this.#isSynced = true;
// At this point download the last missing blocks in the range (blockCount -5, blockCount]
await this.#getLatestBlocks(blockCount);
// Finally avoid address re-use by updating the map #addressIndices
this.#updateCurrentAddress();
// Update both activities post sync
this.#eventEmitter.enableEvent('balance-update');
this.#eventEmitter.enableEvent('new-tx');
this.#eventEmitter.emit('balance-update');
this.#eventEmitter.emit('new-tx');
});
async #transparentSync() {
if (!this.isLoaded() || this.#isSynced) return;
const cNet = getNetwork();
const addr = this.getKeyToExport();
let nStartHeight = Math.max(
...this.#mempool.getTransactions().map((tx) => tx.blockHeight)
);
// Compute the total pages and iterate through them until we've synced everything
const totalPages = await cNet.getNumPages(nStartHeight, addr);
for (let i = totalPages; i > 0; i--) {
this.#eventEmitter.emit(
'transparent-sync-status-update',
i,
totalPages,
false
);
// Fetch this page of transactions
const iPageTxs = await cNet.getTxPage(nStartHeight, addr, i);
for (const tx of iPageTxs.reverse()) {
await this.addTransaction(tx, tx.blockHeight === -1);
}
}
this.#eventEmitter.emit('transparent-sync-status-update', '', '', true);
}
lock = false;
/**
* Initial block and prover sync for the shield object
*/
async #syncShield() {
if (!this.#shield || this.#isSynced) {
return;
}
try {
const network = getNetwork();
const shieldSyncer = await BinaryShieldSyncer.create(
network,
await Database.getInstance(),
this.#shield.getLastSyncedBlock()
);
/** @type{string[]} Array of txs in the current block */
const length = shieldSyncer.getLength();
/** @type {Uint8Array} Array of bytes that we are processing **/
this.#eventEmitter.emit(
'shield-sync-status-update',
0,
length,
false
);
/**
* Array of blocks ready to pass to the shield library
* @type {{txs: string[]; height: number; time: number}[]}
*/
let handleBlocksTime = 0;
const handleAllBlocks = async (blocksArray) => {
const start = performance.now();
// Process the current batch of blocks before starting to parse the next one
if (blocksArray.length) {
const ownTxs = await this.#shield.handleBlocks(
blocksArray.filter(
(b) => b.height > this.#shield.getLastSyncedBlock()
)
);
// TODO: slow! slow! slow!
if (ownTxs.length > 0) {
for (const block of blocksArray) {
for (const tx of block.txs) {
if (ownTxs.includes(tx.hex)) {
const parsed = Transaction.fromHex(tx.hex);
parsed.blockTime = block.time;
parsed.blockHeight = block.height;
await this.addTransaction(parsed);
}
}
}
}
}
handleBlocksTime += performance.now() - start;
// Emit status update
this.#eventEmitter.emit(
'shield-sync-status-update',
shieldSyncer.getReadBytes(),
length,
false
);
};
while (true) {
const blocks = await shieldSyncer.getNextBlocks();
if (blocks === null) break;
await handleAllBlocks(blocks);
}
debugLog(
DebugTopics.WALLET,
`syncShield rust internal ${handleBlocksTime} ms`
);
// At this point it should be safe to assume that shield is ready to use
await this.#saveShieldOnDisk();
} catch (e) {
debugError(DebugTopics.WALLET, e);
}
const networkSaplingRoot = (
await getNetwork().getBlock(this.#shield.getLastSyncedBlock())
).finalsaplingroot;
if (networkSaplingRoot)
await this.#checkShieldSaplingRoot(networkSaplingRoot);
this.#isSynced = true;
this.#eventEmitter.emit('shield-sync-status-update', 0, 0, true);
}
/**
* @todo this needs to take the `vin` as input,
* But currently we don't have any way of getting the UTXO
* out of the vin. This will happen after the mempool refactor,
* But for now we can just recalculate the UTXOs
* @param {number} target - Number of satoshis needed. See Mempool.getUTXOs
*/
#getUTXOsForShield(target = Number.POSITIVE_INFINITY) {
return this.#mempool
.getUTXOs({
requirement: OutpointState.P2PKH | OutpointState.OURS,
target,
blockCount,
})
.map((u) => {
return {
vout: u.outpoint.n,