-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.ts
3749 lines (3521 loc) · 108 KB
/
index.ts
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 * as bitcoin from 'bitcoinjs-lib';
import { Network, networks } from 'bitcoinjs-lib';
import BIP32Factory, { BIP32Interface } from 'bip32';
import * as ecc from '@bitcoinerlab/secp256k1';
import {
EAddressType,
EAvailableNetworks,
EBoostType,
EFeeId,
EPaymentType,
EScanningStrategy,
IAddress,
IAddresses,
IBoostedTransaction,
IBoostedTransactions,
ICustomGetAddress,
ICustomGetScriptHash,
IFormattedTransaction,
IFormattedTransactions,
IGenerateAddresses,
IGenerateAddressesResponse,
IGetAddress,
IGetAddressBalanceRes,
IGetAddressByPath,
IGetAddressesFromPrivateKey,
IGetAddressResponse,
IGetFeeEstimatesResponse,
IGetNextAvailableAddressResponse,
IGetUtxosResponse,
IHeader,
IKeyDerivationPath,
InputData,
IOnchainFees,
IOutput,
IPrivateKeyInfo,
IRbfData,
ISendTransaction,
ISendTx,
ISetupTransaction,
ISweepPrivateKey,
ISweepPrivateKeyRes,
ITransaction,
ITxHash,
IUtxo,
IWallet,
IWalletData,
TAddressIndexInfo,
TAddressTypeContent,
TAvailableNetworks,
TGapLimitOptions,
TGetData,
TGetTotalFeeObj,
TMessageDataMap,
TOnMessage,
TProcessUnconfirmedTransactions,
TServer,
TSetData,
TSetupTransactionResponse,
TTransactionMessage,
TTxDetails,
TTxResult,
TUnspentAddressScriptHashData,
TWalletDataKeys
} from '../types';
import {
decodeOpReturnMessage,
err,
filterAddressesObjForGapLimit,
formatKeyDerivationPath,
generateWalletId,
getAddressesFromPrivateKey,
getAddressFromKeyPair,
getAddressIndexDiff,
getAddressTypeFromPath,
getDataFallback,
getDefaultWalletData,
getDefaultWalletDataKeys,
getElectrumNetwork,
getHighestUsedIndexFromTxHashes,
getKeyDerivationPath,
getKeyDerivationPathObject,
getKeyDerivationPathString,
getScriptHash,
getSeed,
getWalletDataStorageKey,
isPositive,
objectKeys,
objectsMatch,
ok,
Result,
shuffleArray,
validateAddress,
validateMnemonic
} from '../utils';
import {
addressTypes,
defaultFeesShape,
getAddressTypeContent,
getAddressTypes
} from '../shapes';
import { Electrum } from '../electrum';
import { Transaction } from '../transaction';
import { GAP_LIMIT, TRANSACTION_DEFAULTS } from './constants';
import cloneDeep from 'lodash.clonedeep';
import { btcToSats } from '../utils/conversion';
import * as bip39 from 'bip39';
import { TLSSocket } from 'tls';
import { Server } from 'net';
const bip32 = BIP32Factory(ecc);
export class Wallet {
private _network: EAvailableNetworks;
private readonly _mnemonic: string;
private readonly _passphrase: string;
private readonly _seed: Buffer;
private readonly _root: BIP32Interface;
private _data: IWalletData;
private _getData: TGetData;
private _setData?: TSetData;
private _customGetAddress?: (
data: ICustomGetAddress
) => Promise<Result<IGetAddressResponse>>; // For use with Bitkit.
private _customGetScriptHash?: (
data: ICustomGetScriptHash
) => Promise<string>; // For use with Bitkit.
private _pendingRefreshPromises: Array<
(result: Result<IWalletData>) => void
> = [];
private _disableMessagesOnCreate: boolean;
public addressTypesToMonitor: EAddressType[];
public isRefreshing: boolean;
public isSwitchingNetworks: boolean;
public readonly id: string;
public readonly name: string;
public electrumOptions?: {
servers?: TServer | TServer[];
tls?: TLSSocket;
net?: Server;
batchLimit?: number; // Maximum number of requests to be sent in a single batch
batchDelay?: number; // Delay (in milliseconds) between each batch of requests
};
public electrum: Electrum;
public addressType: EAddressType;
public sendMessage: TOnMessage;
public transaction: Transaction;
public feeEstimates: IOnchainFees;
public rbf: boolean;
public selectedFeeId: EFeeId;
public disableMessages: boolean;
public gapLimitOptions: TGapLimitOptions;
private constructor({
mnemonic,
passphrase,
name,
network = EAvailableNetworks.mainnet,
addressType = EAddressType.p2wpkh,
storage,
electrumOptions = {},
onMessage = (): null => null,
customGetAddress,
customGetScriptHash,
rbf = false,
selectedFeeId = EFeeId.normal,
disableMessages = false,
disableMessagesOnCreate = false,
addressTypesToMonitor = Object.values(EAddressType),
gapLimitOptions = {
lookBehind: GAP_LIMIT,
lookAhead: GAP_LIMIT
}
}: IWallet) {
if (!mnemonic) throw new Error('No mnemonic specified.');
if (!validateMnemonic(mnemonic)) throw new Error('Invalid mnemonic.');
if (name && name.includes('-'))
throw new Error('Wallet name cannot include a hyphen (-).');
this._network = network;
this._mnemonic = mnemonic;
this._passphrase = passphrase ?? '';
this._seed = getSeed(this._mnemonic, this._passphrase);
this._root = bip32.fromSeed(
this._seed,
this.getBitcoinNetwork(this._network)
);
this._data = getDefaultWalletData();
this._getData = storage?.getData ?? getDataFallback;
this._setData = storage?.setData;
this._disableMessagesOnCreate = disableMessagesOnCreate;
if (customGetAddress) this._customGetAddress = customGetAddress;
if (customGetScriptHash) this._customGetScriptHash = customGetScriptHash;
this.id = generateWalletId(this._seed);
this.name = name ?? this.id;
this.addressType = addressType;
this.transaction = new Transaction({
wallet: this
});
this.feeEstimates = cloneDeep(defaultFeesShape);
this.disableMessages = disableMessages;
this.sendMessage = <K extends keyof TMessageDataMap>(
key: K,
data: TMessageDataMap[K]
): void => {
if (this.disableMessages) return;
onMessage(key, data);
};
this.electrumOptions = electrumOptions;
this.electrum = new Electrum({
wallet: this,
network: this.network,
...electrumOptions
});
this.rbf = rbf;
this.selectedFeeId = selectedFeeId;
this.isRefreshing = false;
this.isSwitchingNetworks = false;
this.addressTypesToMonitor = addressTypesToMonitor;
if (!this.addressTypesToMonitor.includes(this.addressType)) {
this.addressTypesToMonitor.push(this.addressType);
}
// Remove duplicates
this.addressTypesToMonitor = [...new Set(this.addressTypesToMonitor)];
this.gapLimitOptions = {
lookBehind: isPositive(gapLimitOptions.lookBehind)
? gapLimitOptions.lookBehind
: 1,
lookAhead: isPositive(gapLimitOptions.lookAhead)
? gapLimitOptions.lookAhead
: 1
};
}
public get data(): IWalletData {
return this._data;
}
public get network(): EAvailableNetworks {
return this._network;
}
static async create(params: IWallet): Promise<Result<Wallet>> {
try {
const wallet = new Wallet(params);
if (wallet._disableMessagesOnCreate) wallet.disableMessages = true;
const res = await wallet.setWalletData();
if (res.isErr()) return err(res.error.message);
wallet.updateFeeEstimates();
console.log('Syncing Wallet...');
await wallet.refreshWallet({});
if (wallet._disableMessagesOnCreate) wallet.disableMessages = false;
return ok(wallet);
} catch (e) {
return err(e);
}
}
public async switchNetwork(
network: EAvailableNetworks,
servers?: TServer | TServer[]
): Promise<Result<Wallet>> {
this.isSwitchingNetworks = true;
// Disconnect from Electrum.
await this.electrum.disconnect();
this._network = network;
this._data = getDefaultWalletData();
const params: IWallet = {
...this,
mnemonic: this._mnemonic,
passphrase: this._passphrase,
network,
electrumOptions: {
servers,
tls: this.electrumOptions?.tls,
net: this.electrumOptions?.net
},
storage: {
getData: this._getData,
setData: this._setData
},
data: getDefaultWalletData()
};
const createRes = await Wallet.create(params);
if (createRes.isErr()) return err(createRes.error.message);
Object.assign(this, createRes.value);
await this.updateFeeEstimates(true);
this.isSwitchingNetworks = false;
return ok(this);
}
/**
* Updates the address type for the current wallet.
* @param {EAddressType} addressType
* @returns {Promise<void>}
*/
async updateAddressType(addressType: EAddressType): Promise<void> {
this.addressType = addressType;
if (!this.addressTypesToMonitor.includes(this.addressType)) {
this.addressTypesToMonitor.push(this.addressType);
}
await this.saveWalletData('addressType', addressType);
await this.refreshWallet({});
}
/**
* Refreshes/Syncs the wallet data.
* @param {boolean} [scanAllAddresses]
* @returns {Promise<Result<IWalletData>>}
*/
public async refreshWallet({ scanAllAddresses = false } = {}): Promise<
Result<IWalletData>
> {
if (this.isRefreshing) {
return new Promise((resolve) => {
this._pendingRefreshPromises.push(resolve);
});
}
this.isRefreshing = true;
try {
await this.setZeroIndexAddresses();
const r1 = await this.updateAddressIndexes();
if (r1.isErr()) {
return this._handleRefreshError(r1.error.message);
}
const r2 = await this.getUtxos({
scanningStrategy: scanAllAddresses ? EScanningStrategy.all : undefined
});
if (r2.isErr()) {
return this._handleRefreshError(r2.error.message);
}
const r3 = await this.updateTransactions({ scanAllAddresses });
if (r3.isErr()) {
return this._handleRefreshError(r3.error.message);
}
await this.electrum.subscribeToAddresses();
this._resolveAllPendingRefreshPromises(ok(this.data));
return ok(this.data);
} catch (e) {
return this._handleRefreshError(e);
}
}
private _resolveAllPendingRefreshPromises(result: Result<IWalletData>): void {
this.isRefreshing = false;
while (this._pendingRefreshPromises.length > 0) {
const resolve = this._pendingRefreshPromises.shift();
if (resolve) {
resolve(result);
}
}
}
private _handleRefreshError(errorMessage: string): Result<IWalletData> {
this.isRefreshing = false;
this._resolveAllPendingRefreshPromises(err(errorMessage));
return err(errorMessage);
}
/**
* Sets the wallet data object.
* @returns {Promise<Result<boolean>>}
* @private
*/
private async setWalletData(): Promise<Result<boolean>> {
try {
const storageIdCheckRes = await this.storageIdCheck(this.id);
if (storageIdCheckRes.isErr())
return err(storageIdCheckRes.error.message);
this._data = getDefaultWalletData();
const walletDataResponse = await this.getWalletData();
if (walletDataResponse.isErr())
return err(walletDataResponse.error.message);
this._data = walletDataResponse.value;
return ok(true);
} catch (e) {
return err(e);
}
}
/**
* Ensure we are not overwriting wallet data of a different wallet by checking that the wallet id's match.
* @private
* @async
* @param {string} id
* @returns {Promise<Result<string>>}
*/
private async storageIdCheck(id: string): Promise<Result<string>> {
const storageKey = this.getWalletDataKey('id');
const res = await this._getData(storageKey);
// No id found, it is safe to save to storage.
if (res.isErr() || !res.value) {
// Save id to storage.
this._data.id = id;
await this.saveWalletData('id', id);
return ok('Saved ID to storage.');
}
// If the ID saved in storage does not match return an error and notify the developer.
if (res.value !== id) {
const msg =
'Mismatched id found in storage. Change the wallet name or delete the old wallet from storage and try again.';
console.log(msg);
return err(msg);
}
return ok("ID's match, it's safe to continue.");
}
/**
* Returns the key used for storing wallet data in the key/value pair.
* @returns {string}
* @param key
*/
public getWalletDataKey(key: keyof IWalletData): string {
return getWalletDataStorageKey(this.name, this._network, key);
}
/**
* Gets the wallet data object from storage if able.
* Otherwise, it falls back to the default wallet data object.
* @returns {Promise<Result<IWalletData>>}
*/
public async getWalletData(): Promise<Result<IWalletData>> {
try {
const walletDataKeys = getDefaultWalletDataKeys();
const walletData: IWalletData = getDefaultWalletData();
await Promise.all(
walletDataKeys.map(async (key) => {
let dataResult;
try {
const walletDataKey = this.getWalletDataKey(key);
const getDataRes = await this._getData(walletDataKey);
if (getDataRes.isErr()) {
//dataResult = getDataRes?.value ?? walletData[key];
return err(dataResult.error.message);
}
dataResult = getDataRes?.value;
} catch (e) {
console.log(e);
}
const data = dataResult ?? walletData[key];
switch (key) {
case 'id':
walletData[key] = data as string;
break;
case 'addressType':
walletData[key] = data as EAddressType;
break;
case 'addresses':
case 'changeAddresses':
walletData[key] = data as TAddressTypeContent<IAddresses>;
break;
case 'addressIndex':
case 'changeAddressIndex':
walletData[key] = data as TAddressTypeContent<IAddress>;
break;
case 'lastUsedAddressIndex':
case 'lastUsedChangeAddressIndex':
walletData[key] = data as TAddressTypeContent<IAddress>;
break;
case 'utxos':
walletData[key] = data as IUtxo[];
break;
case 'blacklistedUtxos':
walletData[key] = data as IUtxo[];
break;
case 'unconfirmedTransactions':
case 'transactions':
walletData[key] = data as IFormattedTransactions;
break;
case 'transaction':
walletData[key] = data as ISendTransaction;
break;
case 'balance':
walletData[key] = data as number;
break;
case 'header':
walletData[key] = data as IHeader;
break;
case 'boostedTransactions':
walletData[key] = data as IBoostedTransactions;
break;
case 'selectedFeeId':
walletData[key] = data as EFeeId;
break;
case 'feeEstimates':
walletData[key] = data as IOnchainFees;
break;
default:
console.log(`Unhandled key in getWalletData: ${key}`);
break;
}
})
);
return ok(walletData);
} catch (e) {
console.log(e);
return err(e);
}
}
/**
* Returns the Network object of the currently selected network (bitcoin or testnet).
* @param {TAvailableNetworks} [network]
* @returns {Network}
*/
private getBitcoinNetwork(network?: TAvailableNetworks): Network {
if (!network) network = this._network;
return bitcoin.networks[network];
}
/**
* Ensures the provided mnemonic matches the one stored in the wallet and is valid.
* @param mnemonic
* @returns {boolean}
*/
isValid(mnemonic): boolean {
return mnemonic === this._mnemonic && validateMnemonic(mnemonic);
}
/**
* Returns the address for the specified path and address type.
* @param {string} path
* @param {EAddressType} addressType
* @returns {IGetAddressResponse}
* @private
*/
private async _getAddress(
path: string,
addressType: EAddressType
): Promise<Result<IGetAddressResponse>> {
try {
if (this._customGetAddress) {
const data = {
path,
type: addressType,
selectedNetwork: getElectrumNetwork(this._network)
};
const res = await this._customGetAddress(data);
if (res.isErr()) return err(res.error.message);
}
const keyPair = this._root.derivePath(path);
const network = this.getBitcoinNetwork(this._network);
const addressInfo = getAddressFromKeyPair({
keyPair,
addressType,
network
});
if (addressInfo.isErr()) return err(addressInfo.error.message);
return ok({
...addressInfo.value,
path
});
} catch (e) {
return err(e);
}
}
/**
* Returns a single Bitcoin address based on the provided address type,
* index and whether it is a change address.
* @param {TKeyDerivationIndex} [index]
* @param {boolean} [changeAddress]
* @param {EAddressType} [addressType]
* @returns {string}
*/
public async getAddress({
index,
changeAddress = false,
addressType = this.addressType
}: IGetAddress = {}): Promise<string> {
try {
if (index === undefined) {
const addressIndex = this.data.addressIndex[addressType];
index = addressIndex.index >= 0 ? String(addressIndex.index) : '0';
}
const pathRes = getKeyDerivationPathString({
addressType,
changeAddress,
index,
network: this._network
});
if (pathRes.isErr()) {
return '';
}
const path = pathRes.value;
const res = await this._getAddress(path, addressType);
if (res.isErr()) return '';
return res.value.address;
} catch {
return '';
}
}
/**
* Get address for a given keyPair, network and type.
* @param {string} path
* @param {EAddressType} addressType
* @returns {Promise<Result<string>>}
*/
public async getAddressByPath({
path,
addressType
}: IGetAddressByPath): Promise<Result<IGetAddressResponse>> {
if (!path) {
return err('No path specified');
}
if (!addressType) {
const res = getAddressTypeFromPath(path);
if (res.isErr()) return err(res.error.message);
addressType = res.value;
}
try {
const getAddressRes = await this._getAddress(path, addressType);
if (getAddressRes.isErr()) return err('Unable to get address.');
return ok(getAddressRes.value);
} catch (e) {
return err(e);
}
}
/**
* Attempts to connect to the specified Electrum server(s).
* @param {TServer | TServer[]} servers
* @returns {Promise<Result<string>>}
*/
public async connectToElectrum(
servers?: TServer | TServer[]
): Promise<Result<string>> {
const res = await this.electrum.connectToElectrum({
network: this._network,
servers: servers ?? this.electrumOptions?.servers
});
let msg = 'Unable to connect to Electrum server.';
if (res.isErr()) {
console.log(msg);
return err(msg);
}
msg = 'Connected to Electrum server.';
return ok(msg);
}
/**
* Returns the address balance for the specified address.
* @param {string} address
* @returns {Promise<Result<IGetAddressBalanceRes>>}
*/
public async getAddressBalance(
address: string
): Promise<Result<IGetAddressBalanceRes>> {
const scriptHash = await this.getScriptHash({
address,
network: this._network
});
const res = await this.electrum.getAddressBalance(scriptHash);
if (res.error) return err('Unable to get address balance at this time.');
return ok({ unconfirmed: res.unconfirmed, confirmed: res.confirmed });
}
/**
* Returns combined balance of provided addresses.
* @async
* @param {string[]} addresses
* @returns {Promise<Result<number>>}
*/
public async getAddressesBalance(
addresses: string[] = []
): Promise<Result<number>> {
try {
const network = this._network;
const scriptHashes = await Promise.all(
addresses.map(async (address) => {
return await this.getScriptHash({ address, network });
})
);
const res =
await this.electrum.getAddressScriptHashBalances(scriptHashes);
if (res.error || typeof res.data === 'string') {
return err(JSON.stringify(res.data));
}
return ok(
res.data.reduce((acc, cur) => {
return (
acc +
Number(cur.result?.confirmed ?? 0) +
Number(cur.result?.unconfirmed ?? 0)
);
}, 0) || 0
);
} catch (e) {
return err(e);
}
}
/**
* Get scriptHash for a given address
* @param {string} address
* @param {EAvailableNetworks} network
* @returns {Promise<string>}
*/
public async getScriptHash({
address,
network
}: {
address: string;
network: EAvailableNetworks;
}): Promise<string> {
if (this._customGetScriptHash) {
const selectedNetwork = getElectrumNetwork(network);
return await this._customGetScriptHash({ address, selectedNetwork });
}
return getScriptHash({ address, network });
}
/**
* Returns private key for the provided path.
* @param path
* @returns {string}
*/
getPrivateKey(path: string): string {
const keyPair = this._root.derivePath(path);
return keyPair.toWIF();
}
/**
* Returns the balance for the specified scriptHash.
* @param {string} scriptHash
* @returns {Promise<Result<IGetAddressBalanceRes>>}
*/
public async getScriptHashBalance(
scriptHash: string
): Promise<Result<IGetAddressBalanceRes>> {
const res = await this.electrum.getAddressBalance(scriptHash);
if (res.error) return err('Unable to get address balance at this time.');
return ok({ unconfirmed: res.unconfirmed, confirmed: res.confirmed });
}
/**
* Returns the known balance from storage.
* @returns {number}
*/
public getBalance(): number {
return this?.data?.balance ?? 0;
}
/**
* Generates a series of addresses based on the specified params.
* @async
* @param {string} selectedWallet - Wallet ID
* @param {number} [addressAmount] - Number of addresses to generate.
* @param {number} [changeAddressAmount] - Number of changeAddresses to generate.
* @param {number} [addressIndex] - What index to start generating addresses at.
* @param {number} [changeAddressIndex] - What index to start generating changeAddresses at.
* @param {string} [keyDerivationPath] - The path to generate addresses from.
* @param {string} [addressType] - Determines what type of address to generate (p2pkh, p2sh, p2wpkh).
* @returns {Promise<Result<IGenerateAddressesResponse>>}
*/
public async generateAddresses({
addressAmount = 10,
changeAddressAmount = 10,
addressIndex = 0,
changeAddressIndex = 0,
keyDerivationPath,
addressType = this.addressType
}: IGenerateAddresses): Promise<Result<IGenerateAddressesResponse>> {
const network = this._network;
try {
if (!keyDerivationPath) {
// Set derivation path accordingly based on address type.
const keyDerivationPathResponse = getKeyDerivationPath({
network,
addressType
});
if (keyDerivationPathResponse.isErr())
return err(keyDerivationPathResponse.error.message);
keyDerivationPath = keyDerivationPathResponse.value;
}
const addresses = {} as IAddresses;
const changeAddresses = {} as IAddresses;
const addressArray = new Array(addressAmount).fill(null);
const changeAddressArray = new Array(changeAddressAmount).fill(null);
await Promise.all(
addressArray.map(async (_item, i) => {
const index = i + addressIndex;
const path = { ...keyDerivationPath };
path.index = `${index}`;
const addressPath = formatKeyDerivationPath({
path,
network,
changeAddress: false,
index: `${index}`
});
if (addressPath.isErr()) {
throw addressPath.error;
}
const address = await this.getAddressByPath({
path: addressPath.value.pathString
});
if (address.isErr()) {
throw address.error;
}
const scriptHash = await this.getScriptHash({
address: address.value.address,
network
});
if (!scriptHash) {
throw new Error('Unable to get script hash.');
}
addresses[scriptHash] = {
...address.value,
index,
scriptHash
};
})
);
await Promise.all(
changeAddressArray.map(async (_item, i) => {
const index = i + changeAddressIndex;
const path = { ...keyDerivationPath };
path.index = `${index}`;
const changeAddressPath = formatKeyDerivationPath({
path,
network,
changeAddress: true,
index: `${index}`
});
if (changeAddressPath.isErr()) {
throw changeAddressPath.error;
}
const address = await this.getAddressByPath({
path: changeAddressPath.value.pathString
});
if (address.isErr()) {
throw address.error;
}
const scriptHash = await this.getScriptHash({
address: address.value.address,
network
});
if (!scriptHash) {
throw new Error('Unable to get script hash.');
}
changeAddresses[scriptHash] = {
...address.value,
index,
scriptHash
};
})
);
return ok({ addresses, changeAddresses });
} catch (e) {
return err(e);
}
}
/**
* Ensures the connection to Electrum is still available.
* Will attempt to reconnect if not initially available.
* @returns {Promise<Result<string>>}
*/
public async checkElectrumConnection(): Promise<Result<string>> {
const isConnected = this.electrum.connectedToElectrum;
if (!isConnected) {
return await this.connectToElectrum();
}
// Ensure we're connected by pinging the server.
const pingRes = await this.electrum.isConnected();
if (pingRes) return ok('Is connected to Electrum.Z');
return err('Failed Electrum connection check.');
}
/**
* Returns the next available address for the given addresstype.
* @param {EAddressType} addressType
* @returns {Promise<Result<IGetNextAvailableAddressResponse>>}
*/
public async getNextAvailableAddress(
addressType?: EAddressType
): Promise<Result<IGetNextAvailableAddressResponse>> {
const checkRes = await this.checkElectrumConnection();
if (checkRes.isErr()) return err(checkRes.error.message);
try {
const network = this._network;
addressType = addressType ?? this.addressType;
const currentWallet = this.data;
const { path } = addressTypes[addressType]; // Assuming addressTypes is globally defined.
const result = formatKeyDerivationPath({ path, network });
if (result.isErr()) {
return err(result.error.message);
}
const { pathObject: keyDerivationPath } = result.value;
//The currently known/stored address index.
let addressIndex = currentWallet.addressIndex[addressType];
let lastUsedAddressIndex =
currentWallet.lastUsedAddressIndex[addressType];
let changeAddressIndex = currentWallet.changeAddressIndex[addressType];
let lastUsedChangeAddressIndex =
currentWallet.lastUsedChangeAddressIndex[addressType];
const originalHighestStoredIndexes = this.getHighestStoredAddressIndex({
addressType
});
if (originalHighestStoredIndexes.isErr()) {
return err(originalHighestStoredIndexes.error.message);
}
const originalHighestStoredIndex =
originalHighestStoredIndexes.value.addressIndex;
const originalHighestStoredChangeIndex =
originalHighestStoredIndexes.value.changeAddressIndex;
const addressIndexDiff = getAddressIndexDiff(
originalHighestStoredIndex.index,
lastUsedAddressIndex.index
);
const addressesToGenerate =
this.gapLimitOptions.lookAhead - addressIndexDiff;
let shouldSaveAddresses = false;
let shouldSaveChangeAddresses = false;
if (addressesToGenerate > 0) {
const generatedAddresses = await this.addAddresses({
addressAmount: addressesToGenerate,
addressIndex: 0,
changeAddressAmount: 0,
keyDerivationPath,
addressType,
saveAddresses: false
});
if (generatedAddresses.isErr()) {
return err(generatedAddresses.error);
}
shouldSaveAddresses = true;
if (addressIndex.index < 0) {
const addresses = generatedAddresses.value.addresses;
const sorted = Object.values(addresses).sort(
(a, b) => a.index - b.index
);
if (sorted.length >= 1 && sorted[0].index >= 0)
addressIndex = sorted[0];
}
}
const changeAddressIndexDiff = getAddressIndexDiff(
originalHighestStoredChangeIndex.index,
lastUsedChangeAddressIndex.index
);
const changeAddressesToGenerate =
this.gapLimitOptions.lookAhead - changeAddressIndexDiff;
if (changeAddressesToGenerate > 0) {
const generatedAddresses = await this.addAddresses({
addressAmount: 0,
changeAddressAmount: changeAddressesToGenerate,
changeAddressIndex: 0,
keyDerivationPath,
addressType,
saveAddresses: false
});
if (generatedAddresses.isErr()) {
return err(generatedAddresses.error);
}
shouldSaveChangeAddresses = true;
if (changeAddressIndex.index < 0) {
const changeAddresses = generatedAddresses.value.changeAddresses;
const sorted = Object.values(changeAddresses).sort(
(a, b) => a.index - b.index
);
if (sorted.length >= 1 && sorted[0].index >= 0)
changeAddressIndex = sorted[0];
}
}
// Save any addresses that have been created thus far if necessary.
const promises: Promise<string>[] = [];
if (shouldSaveAddresses) {
promises.push(this.saveWalletData('addresses', this._data.addresses));
}
if (shouldSaveChangeAddresses) {
promises.push(
this.saveWalletData('changeAddresses', this._data.changeAddresses)
);
}
await Promise.all(promises);
let addresses = filterAddressesObjForGapLimit({
addresses: this._data.addresses[addressType],
index: addressIndex.index,
gapLimitOptions: this.gapLimitOptions
});
let changeAddresses = filterAddressesObjForGapLimit({
addresses: this._data.changeAddresses[addressType],
index: changeAddressIndex.index,
gapLimitOptions: this.gapLimitOptions
});