-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdashwallet.js
3646 lines (3173 loc) · 98.9 KB
/
dashwallet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
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
(function (exports) {
"use strict";
let Wallet = {};
//@ts-ignore
exports.Wallet = Wallet;
let DashApi = {};
//@ts-ignore
let DashHd = exports.DashHd || require("dashhd");
//@ts-ignore
let DashKeys = exports.DashKeys || require("dashkeys");
//@ts-ignore
let DashPhrase = exports.DashPhrase || require("dashphrase");
//@ts-ignore
let DashTx = exports.DashTx || require("dashtx");
let dashTx = DashTx.create();
/*
let Secp256k1 = require("@dashincubator/secp256k1");
async function sign({ privateKey, hash }) {
let sigOpts = { canonical: true };
let sigBuf = await Secp256k1.sign(hash, privateKey, sigOpts);
return Tx.utils.u8ToHex(sigBuf);
}
*/
/** @typedef {import('dashsight').CoreUtxo} CoreUtxo */
/** @typedef {import('dashtx').TxInfo} TxInfoRaw */
/** @typedef {import('dashtx').TxInfoSigned} TxInfoSigned */
/** @typedef {import('dashtx').TxOutput} TxOutput */
/** @typedef {import('dashsight').GetTxs} GetTxs */
/** @typedef {import('dashsight').GetUtxos} GetUtxos */
/** @typedef {import('dashsight').InstantSend} InstantSend */
/** @typedef {import('dashsight').InsightUtxo} InsightUtxo */
/**
* @typedef MaybeHasAddress
* @prop {String} [address]
*/
const DUFFS = 100000000;
const DUST = 10000;
const FEE = 1000;
DashApi.DUFFS = DUFFS;
DashApi.DashTypes = {
name: "dash",
pubKeyHashVersion: "4c",
privateKeyVersion: "cc",
coinType: "5",
};
DashApi.DUST = DUST;
DashApi.FEE = FEE;
const SATOSHIS = 100000000;
Wallet.SATOSHIS = SATOSHIS;
const XPUBS_WALLET = "__XPUBS__";
const ADDRS_WALLET = "__ADDRS__";
const XPUB_CHAR_LEN = 111;
const ADDR_CHAR_LEN = 34;
let XPUB_VERSIONS = ["xpub", "tpub"];
let ADDR_VERSIONS = ["X", "Y"];
/** @param {Number} satoshis */
function toDustFixed(satoshis) {
let dashNum = satoshis / SATOSHIS;
let dash = dashNum.toFixed(8);
dash = dash.slice(0, 6) + " " + dash.slice(6);
return dash;
}
/**
* @template {Pick<CoreUtxo, "satoshis">} T
* @param {Array<T>} utxos
* @param {Number} output - including fee estimate
* @return {Array<T>}
*/
DashApi.selectOptimalUtxos = function (utxos, output) {
let balance = DashTx.sum(utxos);
let fees = DashTx.appraise({
//@ts-ignore
inputs: [{}],
outputs: [{}],
});
let fullSats = output + fees.min;
if (balance < fullSats) {
return [];
}
// from largest to smallest
utxos.sort(function (a, b) {
return b.satoshis - a.satoshis;
});
/** @type Array<T> */
let included = [];
let total = 0;
// try to get just one
utxos.every(function (utxo) {
if (utxo.satoshis > fullSats) {
included[0] = utxo;
total = utxo.satoshis;
return true;
}
return false;
});
if (total) {
return included;
}
// try to use as few coins as possible
utxos.some(function (utxo, i) {
included.push(utxo);
total += utxo.satoshis;
if (total >= fullSats) {
return true;
}
// it quickly becomes astronomically unlikely to hit the one
// exact possibility that least to paying the absolute minimum,
// but remains about 75% likely to hit any of the mid value
// possibilities
if (i < 2) {
// 1 input 25% chance of minimum (needs ~2 tries)
// 2 inputs 6.25% chance of minimum (needs ~8 tries)
fullSats = fullSats + DashTx.MIN_INPUT_SIZE;
return false;
}
// but by 3 inputs... 1.56% chance of minimum (needs ~32 tries)
// by 10 inputs... 0.00953674316% chance (needs ~524288 tries)
fullSats = fullSats + DashTx.MIN_INPUT_SIZE + 1;
});
return included;
};
let COIN_TYPE = 5;
/**
* Like CoreUtxo, but only the parts we need for a transaction
* @typedef MiniUtxo
* @property {String} txId
* @property {Number} outputIndex - a.k.a. vout index
* @property {String} [address] - coined pubKeyHash
* @property {String} script - hex
* @property {Number} satoshis
*/
/**
* How we interpret a coin for selection and usage
* @typedef CoinInfo
* @prop {Number} satoshis
* @prop {Number} faceValue
* @prop {Number} stamps
* @prop {Number} dust
*/
/**
* How we interpret how a coin will be denominated
* @typedef {CoinInfo & DenomInfoPartial} DenomInfo
*
* @typedef DenomInfoPartial
* @prop {Array<Number>} denoms
* @prop {Number} stampsPerCoin
* @prop {Number} stampsRemaining
* @prop {Number} fee
* @prop {Boolean} transactable - if stampsPerCoin >= 2
* @prop {Number} stampsNeeded - if stampsPerCoin < 2
*/
/**
* Coin info + Utxo info
* @typedef {CoinInfo & CoreUtxo} UtxoCoinInfo
*/
/**
* How we interpret a send amount
* @typedef SendInfo
* @prop {Number} satoshis
* @prop {Array<Number>} denoms
* @prop {Number} _lowFaceValue
* @prop {Number} faceValue
* @prop {Number} dustNeeded
*/
/**
* @typedef WalletAddress
* @prop {String} [addr] - may be added (but not stored)
* @prop {Number} checked_at
* @prop {String} hdpath - hdkey path (ex: "m/44'/5'/0'/0")
* @prop {Number} index - hdkey path index
* @prop {Array<[Number, String]>} txs - tx.time and tx.txid
* @prop {Array<MiniUtxo>} utxos
* @prop {String} wallet - name of wallet (not a true id)
*
* @typedef WalletWifPartial
* @prop {String} wif - private key
*
* @typedef {Required<WalletAddress> & WalletWifPartial} WalletWif
*/
/**
* @typedef Config
* @prop {Number} staletime
* @prop {Safe} safe
* @prop {Store} store
* @prop {DashSightPartial} dashsight
* @prop {Array<Number>} denomAmounts - TODO move to settings
* @prop {Array<Number>} denomSatoshis - TODO move to settings
*/
/**
* @typedef DashSightPartial
* @prop {InstantSend} instantSend
* @prop {GetTxs} getTxs
* @prop {GetUtxos} getUtxos
*/
/**
* @typedef Store
* @prop {StoreSave} save
*
* @callback StoreSave
* @param { Cache|
* Object.<String,PayWallet>|
* Preferences|
* Object.<String,PrivateWallet> } data
*/
/**
* @typedef WalletInstance
* @prop {Contact} contact
* @prop {Sync} sync
*/
/**
* @callback Sync
* @param {SyncOpts} opts
*
* @typedef SyncOpts
* @prop {Number} now - value to be used for 'checked_at'
* @prop {Number} [staletime] - default 60_000 ms, set to 0 to force checking
*/
/**
* Add or generate and return (mutual) xpub key(s) for a contact
* @callback Contact
* @param {ContactOpts} opts
* @returns {Promise<[String, PayWallet]>} - rxXPub, txXPub, txStaticAddr
*
* @typedef ContactOpts
* @prop {String} handle
* @prop {String} xpub - receive-only xpub key from friend
* @prop {String} address - reusable address, e.g. for Coinbase
* @prop {Boolean} [legacyPrefix] - to allow recovery of non-prefixed contacts
* @prop {String} [addr] - legacy property for address
*/
/**
* Find a friend's xpub key
* @callback FindPayWallets
* @param {FindFriendOpts} opts
* @returns {Promise<Array<PayWallet>>} - wallets matching this friend
*
* @typedef FindFriendOpts
* @prop {String} handle
*/
/**
* Find a private wallet by handle
* @callback FindPrivateWallets
* @param {FindFriendOpts} opts
* @returns {Promise<Array<PrivateWallet>>} - wallets matching this friend
*/
/**
* @typedef Safe
* @prop {Object<String, PrivateWallet>} privateWallets
* @prop {Object<String, PayWallet>} payWallets
* @prop {Preferences} preferences
* @prop {Cache} cache
*
* @typedef {Object.<String, unknown>} Preferences
*
* TODO txs and wifs?
* @typedef Cache
* @prop {Object<String, WalletAddress>} addresses
*/
/**
* @typedef PrivateWallet
* @prop {String?} contact
* @prop {String?} device
* @prop {String} label
* @prop {String} phrase
* @prop {Array<WifInfo>} wifs - TODO maybe Object.<String, WifInfo>
* @prop {String} name
* @prop {Number} priority
* @prop {String} created_at - ISO Date
* @prop {String?} archived_at - ISO Date
*
* @typedef WifInfo
* @prop {String} address
* @prop {String} [addr] - deprecated, use address
* @prop {String} wif
* @prop {String} created_at - ISO Date
*/
/**
* @typedef PayWallet
* @prop {String?} contact
* @prop {String?} device
* @prop {String} label
* @prop {String} name
* @prop {Number} priority
* @prop {String} address - instead of xpub, e.g. for coinbase
* @prop {String} addr - deprecated, use address
* @prop {String} xpub
* @prop {String} created_at - ISO Date
* @prop {String?} archived_at - ISO Date
*/
Wallet.DashTypes = DashApi.DashTypes;
Wallet.DUFFS = DashApi.DUFFS;
//@ts-ignore - TODO
Wallet.sum = DashTx.sum;
//@ts-ignore - TODO
Wallet.toDash = DashTx.toDash;
Wallet.toSats = DashTx.toSats;
Wallet.DENOM_AMOUNTS = [
1000, 500, 200, 100, 50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01,
0.005, 0.002, 0.001,
];
// Ex: we could add additional denoms via some setting
if (false) {
Wallet.DENOM_AMOUNTS.push(0.0005);
Wallet.DENOM_AMOUNTS.push(0.0002);
Wallet.DENOM_AMOUNTS.push(0.0001);
}
/** @type {Array<Number>} */
Wallet.DENOM_SATS = [];
amountsToSats(Wallet.DENOM_AMOUNTS, Wallet.DENOM_SATS);
{
let __LAST_DENOM__ = Wallet.DENOM_SATS.length - 1;
Wallet.__UNIT_TEST_DENOM_INFO__ = {
__DENOMS__: Wallet.DENOM_SATS,
__MIN_DENOM__: Wallet.DENOM_SATS[__LAST_DENOM__],
__STAMP__: 200,
__MIN_STAMPS__: 2,
};
}
/**
* @param {Array<Number>} amounts
* @param {Array<Number>} sats
*/
function amountsToSats(amounts, sats) {
for (let amount of amounts) {
let satoshis = amount * SATOSHIS;
satoshis = Math.round(satoshis);
sats.push(satoshis);
}
return sats;
}
/**
* @param {Config} config
* @returns {Promise<WalletInstance>}
*/
Wallet.create = async function (config) {
let safe = config.safe;
let wallet = {};
let dashsight = config.dashsight;
// TODO: move to config
wallet.__DENOMS__ = Wallet.DENOM_SATS;
let __LAST_DENOM__ = wallet.__DENOMS__.length - 1;
wallet.__MIN_DENOM__ = Wallet.DENOM_SATS[__LAST_DENOM__];
wallet.__STAMP__ = 200;
wallet.__MIN_STAMPS__ = 2;
if (!config.denomAmounts?.length) {
config.denomAmounts = Wallet.DENOM_AMOUNTS;
}
config.denomSatoshis = amountsToSats(config.denomAmounts, []);
if ("undefined" === typeof config.staletime) {
config.staletime = 60 * 1000;
}
// TODO rename shareXPubWith, receiveXPubFrom, receiveAddrFrom?
/** @type {Contact} */
wallet.contact = async function ({
handle,
xpub,
address,
addr,
legacyPrefix,
}) {
address = address || addr || "";
if (!handle) {
throw new Error(`no 'handle' given`);
}
let specials = ["main", "savings", "wifs"];
let ihandle = handle.toLowerCase();
let isSpecial = specials.includes(ihandle);
if (isSpecial) {
throw new Error(`${handle} may not be used as a contact name`);
}
if (!legacyPrefix) {
let prefixes = ["#", "@"];
let prefix = handle[0];
let validPrefix = prefixes.includes(prefix);
if (!validPrefix) {
throw new Error(
`contact names should start with '#' (ex: '#john') for local contacts, or '@' for live-wallet/self-published contacts (ex: '@john.dev'), not '${handle}'`,
);
}
}
let safe = config.safe;
/** @type {PayWallet} */
let txWallet;
let hasAddr = xpub || address;
if (hasAddr) {
txWallet = await _getOrCreateWallet(handle, xpub, address);
// most recently added will sort first;
txWallet.priority = Date.now();
await config.store.save(safe.payWallets);
} else {
let txws = await wallet.findPayWallets({ handle });
txWallet = txws[0];
}
/** @type {PrivateWallet} */
let rxWallet;
/** @type {Array<PrivateWallet>} */
let rxws = Object.values(safe.privateWallets)
.filter(function (wallet) {
return wallet.contact === handle;
})
.sort(wallet._sort);
if (!rxws.length) {
// TODO use main wallet as seed
rxWallet = await Wallet.generate({
name: handle,
label: handle,
priority: Date.now(),
contact: handle,
});
for (let i = 1; ; i += 1) {
if (!safe.privateWallets[`${handle}:${i}`]) {
safe.privateWallets[`${handle}:${i}`] = rxWallet;
break;
}
}
await config.store.save(safe.privateWallets);
rxws.push(rxWallet);
}
rxWallet = rxws[0];
// Note: we should never have a WIF wallet here
_transitionPhrase(rxWallet); // TODO remove
let salt = "";
let seed = await DashPhrase.toSeed(rxWallet.phrase, salt);
let walletKey = await DashHd.fromSeed(seed);
// The full path looks like `m/44'/5'/0'/0/0`
// We "harden" the prefix `m/44'/5'/0'/0`
let account = 0;
let usage = 0;
let hdPath = `m/44'/${COIN_TYPE}'/${account}'/${usage}`;
/** @type {import('dashhd').HDXKey} */
let xprvKey = await DashHd.derivePath(walletKey, hdPath);
let selfXPub = await DashHd.toXPub(xprvKey);
return [selfXPub, txWallet];
};
wallet.befriend = wallet.contact;
/**
* @param {String} handle - contact's handle
* @param {String} xpub
* @param {String} address
* @returns {Promise<PayWallet>}
*/
async function _getOrCreateWallet(handle, xpub, address) {
if (xpub) {
await Wallet.assertXPub(xpub);
}
let txWallet = Object.values(safe.payWallets)
.sort(wallet._sort)
.find(function (wallet) {
if (wallet.contact !== handle) {
return false;
}
if (xpub.length > 0) {
return xpub === wallet.xpub;
}
if (address.length > 0) {
return address === wallet.address || wallet.addr;
}
return false;
});
if (!txWallet) {
txWallet = Wallet.generatePayWallet({
handle: handle,
xpub: xpub,
address: address,
});
for (let i = 1; ; i += 1) {
if (!safe.payWallets[`${handle}:${i}`]) {
safe.payWallets[`${handle}:${i}`] = txWallet;
break;
}
}
}
return txWallet;
}
/**
* @typedef WalletAccount
* @prop {Number} faceValue - spendable amount
* @prop {Number} _satoshis - spendable + dust amounts
* @prop {Array<CoreUtxo>} utxos
*/
/**
* @returns {Object<String, WalletAccount>}
*/
wallet.accounts = function () {
/** @type {Object<String, Array<Required<MiniUtxo>>>} */
let accounts = {};
let addrs = Object.keys(safe.cache.addresses);
for (let addr of addrs) {
let addrInfo = safe.cache.addresses[addr];
let isSpendable = hasWif(addrInfo);
if (!isSpendable) {
continue;
}
let accountName = addrInfo.wallet;
if (!accounts[accountName]) {
accounts[accountName] = {
faceValue: 0,
_satoshis: 0,
utxos: [],
};
}
let account = accounts[accountName];
let isLooseWif = hasLooseWif(addrInfo);
if (isLooseWif) {
// ignore wifs
}
for (let utxo of addrInfo.utxos) {
let _utxo = Object.assign({ address: addr }, utxo);
account.utxos.push(_utxo);
// TODO maybe denominate and break change for more accurate face value
//let outputInfo = Wallet._denominateCoins(d, inputInfos, breakChange);
let coinInfo = Wallet._parseCoinInfo(wallet, _utxo.satoshis);
account.faceValue += coinInfo.faceValue;
account._satoshis += _utxo.satoshis;
}
}
return accounts;
};
/**
* Show balances of addresses for which we have the private keys (WIF)
* (don't forget to sync first!)
* @returns {Promise<Object.<String, Number>>}
*/
wallet.balances = async function () {
/** @type {Object.<String, Number>} */
let balances = {};
Object.values(safe.cache.addresses).forEach(function (addrInfo) {
let isSpendable = hasWif(addrInfo);
if (!isSpendable) {
return;
}
let isLooseWif = hasLooseWif(addrInfo);
if (isLooseWif) {
// ignore wifs
}
let b = addrInfo.utxos.reduce(
/**
* @param {Number} satoshis
* @param {InsightUtxo} utxo
*/
function (satoshis, utxo) {
return utxo.satoshis + satoshis;
},
0,
);
if (!balances[addrInfo.wallet]) {
balances[addrInfo.wallet] = 0;
}
balances[addrInfo.wallet] += b;
});
return balances;
};
/**
* @param {Object} opts
* @param {Array<String>} opts.wifs
* @param {Number} [opts.now] - ms since epoch (e.g. Date.now())
* @param {Number} [opts.staletime] - when to refresh
* @returns {Promise<Array<WalletAddress>>}
* TODO - multiuse: true
*/
wallet.import = async function ({ wifs, now = Date.now(), staletime = 0 }) {
/** @type {Array<WalletAddress>} */
let addrInfos = [];
await wifs.reduce(async function (promise, wif) {
await promise;
//@ts-ignore bad export
let addr = await DashKeys.wifToAddr(wif);
let addrInfo = safe.cache.addresses[addr];
await indexNonHdAddr("wifs", addr, now, staletime);
addrInfos.push(
Object.assign(
{ address: addr, addr: addr },
safe.cache.addresses[addr],
),
);
// TODO force duplicate option? (for partially-synced wallets)
// don't add an address that's already in an HD wallet
if (addrInfo?.hdpath.startsWith("m")) {
return;
}
let exists = safe.privateWallets.wifs.wifs.some(
/** @param {WifInfo} wifInfo */
function (wifInfo) {
if (wifInfo.wif === wif) {
return true;
}
},
);
if (!exists) {
// the first "wifs" is the name of the wallet
safe.privateWallets.wifs.wifs.push({
address: addr,
addr: addr,
wif: wif,
created_at: new Date().toISOString(),
});
}
}, Promise.resolve());
await config.store.save(safe.privateWallets);
await config.store.save(safe.cache);
return addrInfos;
};
/**
* @returns {Array<CoreUtxo>}
*/
wallet.utxos = function () {
/** @type {Array<Required<MiniUtxo>>} */
let utxos = [];
let addrs = Object.keys(safe.cache.addresses);
for (let addr of addrs) {
let addrInfo = safe.cache.addresses[addr];
let isSpendable = hasWif(addrInfo);
if (!isSpendable) {
continue;
}
if ("*" === addrInfo.hdpath) {
// ignore wifs
}
for (let utxo of addrInfo.utxos) {
let _utxo = Object.assign({ address: addr }, utxo);
utxos.push(_utxo);
}
}
return utxos;
};
/** @param {WalletAddress} addrInfo */
function hasWif(addrInfo) {
return !!addrInfo.hdpath;
}
/** @param {WalletAddress} addrInfo */
function hasLooseWif(addrInfo) {
return "*" === addrInfo.hdpath;
}
/**
* Find the address that matches the prefix.
* @param {String} addrPrefix -
* @returns {Promise<Required<WalletAddress>?>}
*/
wallet.findAddr = async function (addrPrefix) {
let addrInfos = await wallet.findAddrs(addrPrefix);
if (!addrInfos.length) {
return null;
}
if (1 === addrInfos.length) {
return addrInfos[0];
}
throw new Error(
`ambiguous address prefix '${addrPrefix}' has multiple matches`,
);
};
/**
* Find the address that matches the prefix.
* @param {String} addrPrefix -
* @returns {Promise<Array<Required<WalletAddress>>>}
*/
wallet.findAddrs = async function (addrPrefix) {
/** @type {Array<Required<WalletAddress>>} */
let addrInfos = [];
if (ADDR_CHAR_LEN === addrPrefix.length) {
let addrInfo = safe.cache.addresses[addrPrefix];
if (addrInfo) {
addrInfos.push(
Object.assign({ address: addrPrefix, addr: addrPrefix }, addrInfo),
);
}
return addrInfos;
}
let addrs = Object.keys(safe.cache.addresses)
.sort()
.filter(function (addr) {
if (addr.startsWith(addrPrefix)) {
return true;
}
});
addrs.forEach(function (addr) {
let addrInfo = safe.cache.addresses[addr];
addrInfos.push(Object.assign({ address: addr, addr: addr }, addrInfo));
});
return addrInfos;
};
/** @type {FindPayWallets} */
wallet.findPayWallets = async function ({ handle }) {
// TODO filter out archived wallets?
let txws = Object.values(safe.payWallets)
.filter(function (wallet) {
return wallet.contact === handle;
})
.sort(wallet._sort);
return txws;
};
/**
* @param {PayWallet|PrivateWallet} a
* @param {PayWallet|PrivateWallet} b
*/
wallet._sort = function (a, b) {
return b.priority - a.priority;
};
/** @type {FindPrivateWallets } */
wallet.findPrivateWallets = async function ({ handle }) {
// TODO filter out archived wallets?
let txws = Object.values(safe.privateWallets)
.filter(function (wallet) {
return wallet.contact === handle || wallet.name === handle;
})
.sort(wallet._sort);
return txws;
};
/**
* @typedef NextInfo
* @prop {Number} start
* @prop {String} [addr]
* @prop {Array<String>} addrs
*/
/**
* @param {Object} opts
* @param {import('dashhd').HDXKey} opts.xKey
* @param {Number} opts.count - how many next addresses
* @param {Number} opts.offset - where to start
* @returns {Promise<Array<String>>} - next n unused addresses
*/
wallet._nextWalletAddrs = async function ({ xKey, count = 1, offset }) {
let addrs = [];
for (let i = 0; i < count; i += 1) {
let index = offset + i;
let addressKey = await deriveAddress(xKey, index);
let addr = await DashHd.toAddr(addressKey.publicKey);
addrs.push(addr);
}
return addrs;
};
/**
* @param {Object} opts
* @param {String} opts.handle
* @param {String} opts.hdpath
* @returns {Promise<import('dashhd').HDXKey>}
*/
wallet._recoverXPrv = async function ({ handle, hdpath }) {
let ws = await wallet.findPrivateWallets({ handle });
if (!ws.length) {
throw new Error(`could not find wallet or account for '${handle}'`);
}
ws.forEach(function (w) {
_transitionPhrase(w); // TODO remove
});
let w = ws[0];
let hasRecoveryPhrase = w.phrase?.length > 0;
if (!hasRecoveryPhrase) {
throw new Error(
"[Sanity Fail] must use private wallet from a recovery phrase (not WIF or pay wallet)",
);
}
let salt = "";
let seed = await DashPhrase.toSeed(w.phrase, salt);
let walletKey = await DashHd.fromSeed(seed);
/** @type {import('dashhd').HDXKey} */
let xprvKey = await DashHd.derivePath(walletKey, hdpath);
return xprvKey;
};
/**
* @param {Object} opts
* @param {String} opts.handle
* @param {Number} opts.count
* @param {Number} [opts.now]
* @param {Number} [opts.staletime]
* @param {Boolean} [opts.allowReuse]
*/
wallet.getNextPayAddrs = async function ({
handle,
count = 1,
now = Date.now(),
staletime = config.staletime,
allowReuse = false,
}) {
let walletName;
let xpub;
let isAddrLen = handle.length === ADDR_CHAR_LEN;
let isXPubLen = handle.length === XPUB_CHAR_LEN;
let wallets = await wallet.findPayWallets({ handle });
let payWallet = wallets?.[0]; // newest is first
if (payWallet?.name) {
walletName = payWallet.name;
xpub = payWallet.xpub;
} else if (isXPubLen) {
let prefix = handle.slice(0, 4);
let isValid = XPUB_VERSIONS.includes(prefix);
if (isValid) {
walletName = XPUBS_WALLET;
xpub = handle;
}
}
if (xpub) {
let addrsInfo = await wallet._getNextPayAddrs({
walletName: payWallet.name,
xpub: payWallet.xpub,
count: count,
now: now,
});
//@ts-ignore
addrsInfo.xpub = xpub;
return addrsInfo;
}
if (isAddrLen) {
if (count !== 1) {
let err = new Error(
`can't get ${count} addresses from single address for '${handle}'`,
);
Object.assign(err, {
code: "E_TOO_FEW_ADDRESSES",
need: count,
lastAddress: [handle],
});
throw err;
}
let addrInfo = await indexPayAddr(
ADDRS_WALLET,
handle,
"*",
-1,
now,
staletime,
);
if (addrInfo.txs.length) {
if (!allowReuse) {
//@ts-ignore - TODO
throw createReuseError(addrInfo.address);
}
}
let addrsInfo = { index: -1, addresses: [handle] };
return addrsInfo;
}
let limit = count;
let addrsInfo = await wallet._getNextLooseAddrs({
wallets,
limit,
now,
staletime,
allowReuse,
});
let lossyCount = addrsInfo?.addresses?.length || 0;
let hasAddrs = count === lossyCount;
if (!hasAddrs) {
let err = new Error(
`there is no xpub, and only ${lossyCount} (need ${count}) lossy addresses associated with '${handle}'`,
);
Object.assign(err, {
code: "E_TOO_FEW_ADDRESSES",
need: count,
lastAddress: addrsInfo?.addresses?.at(-1),
});
throw err;
}
return addrsInfo;
};
/**
* @param {Object} opts
* @param {String} opts.walletName
* @param {String} opts.xpub
* @param {Number} opts.count
* @param {Number} [opts.now]
* @param {Number} [opts.staletime]
* @param {Boolean} [opts.allowReuse]
*/
wallet._getNextPayAddrs = async function ({
walletName = XPUBS_WALLET,
xpub,
count = 1,
now = Date.now(),
staletime = config.staletime,
allowReuse = false,
}) {
let xKey = await DashHd.fromXKey(xpub);
let hdpath = ""; // TODO include in xKey
let offset = await indexPayAddrs(walletName, xKey, hdpath, now);
await config.store.save(safe.cache);
let payAddrs = await wallet._nextWalletAddrs({
xKey,
offset,
count,
});