-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathCashuWallet.ts
1278 lines (1199 loc) · 39.6 KB
/
CashuWallet.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 {
blindMessage,
constructProofFromPromise,
serializeProof
} from '@cashu/crypto/modules/client';
import { deriveBlindingFactor, deriveSecret } from '@cashu/crypto/modules/client/NUT09';
import { createP2PKsecret, getSignedProofs } from '@cashu/crypto/modules/client/NUT11';
import { verifyDLEQProof_reblind } from '@cashu/crypto/modules/client/NUT12';
import { hashToCurve, pointFromHex } from '@cashu/crypto/modules/common';
import { DLEQ, type Proof as NUT11Proof } from '@cashu/crypto/modules/common';
import { bytesToHex, hexToBytes, randomBytes } from '@noble/hashes/utils';
import { CashuMint } from './CashuMint.js';
import { BlindedMessage } from './model/BlindedMessage.js';
import { MintInfo } from './model/MintInfo.js';
import {
GetInfoResponse,
MeltProofOptions,
MeltQuoteState,
MintProofOptions,
MintQuoteResponse,
MintQuoteState,
OutputAmounts,
ProofState,
ReceiveOptions,
RestoreOptions,
SendOptions,
SerializedBlindedSignature,
SerializedDLEQ,
SwapOptions,
type MeltPayload,
type MeltProofsResponse,
type MeltQuotePayload,
type MeltQuoteResponse,
type MintKeys,
type MintKeyset,
type MintPayload,
type MintQuotePayload,
type Proof,
type SendResponse,
type SerializedBlindedMessage,
type SwapPayload,
type Token,
MPPOption,
MeltQuoteOptions,
SwapTransaction,
LockedMintQuoteResponse
} from './model/types/index.js';
import { SubscriptionCanceller } from './model/types/wallet/websocket.js';
import {
bytesToNumber,
getDecodedToken,
getKeepAmounts,
hasValidDleq,
numberToHexPadded64,
splitAmount,
stripDleq,
sumProofs
} from './utils.js';
import { signMintQuote } from './crypto/nut-20.js';
import {
OutputData,
OutputDataFactory,
OutputDataLike,
isOutputDataFactory
} from './model/OutputData.js';
/**
* The default number of proofs per denomination to keep in a wallet.
*/
const DEFAULT_DENOMINATION_TARGET = 3;
/**
* The default unit for the wallet, if not specified in constructor.
*/
const DEFAULT_UNIT = 'sat';
/**
* Class that represents a Cashu wallet.
* This class should act as the entry point for this library
*/
class CashuWallet {
private _keys: Map<string, MintKeys> = new Map();
private _keysetId: string | undefined;
private _keysets: Array<MintKeyset> = [];
private _seed: Uint8Array | undefined = undefined;
private _unit = DEFAULT_UNIT;
private _mintInfo: MintInfo | undefined = undefined;
private _denominationTarget = DEFAULT_DENOMINATION_TARGET;
private _keepFactory: OutputDataFactory | undefined;
private _verbose = false;
mint: CashuMint;
/**
* Internal method for logging messages when verbose mode is enabled
* @param message Message to log
* @param optionalParams Additional parameters to log
*/
private log(message: string, ...optionalParams: Array<any>): void {
if (this._verbose) {
console.log(message, ...optionalParams);
}
}
/**
* Internal method for logging warnings when verbose mode is enabled
* @param message Warning message to log
* @param optionalParams Additional parameters to log
*/
private warn(message: string, ...optionalParams: Array<any>): void {
if (this._verbose) {
console.warn(message, ...optionalParams);
}
}
/**
* @param mint Cashu mint instance is used to make api calls
* @param options.unit optionally set unit (default is 'sat')
* @param options.keys public keys from the mint (will be fetched from mint if not provided)
* @param options.keysets keysets from the mint (will be fetched from mint if not provided)
* @param options.mintInfo mint info from the mint (will be fetched from mint if not provided)
* @param options.denominationTarget target number proofs per denomination (default: see @constant DEFAULT_DENOMINATION_TARGET)
* @param options.bip39seed BIP39 seed for deterministic secrets.
* @param options.keepFactory A function that will be used by all parts of the library that produce proofs to be kept (change, etc.).
* This can lead to poor performance, in which case the seed should be directly provided
*/
constructor(
mint: CashuMint,
options?: {
unit?: string;
keys?: Array<MintKeys> | MintKeys;
keysets?: Array<MintKeyset>;
mintInfo?: GetInfoResponse;
bip39seed?: Uint8Array;
denominationTarget?: number;
keepFactory?: OutputDataFactory;
verbose?: boolean;
}
) {
this.mint = mint;
let keys: Array<MintKeys> = [];
if (options?.keys && !Array.isArray(options.keys)) {
keys = [options.keys];
} else if (options?.keys && Array.isArray(options?.keys)) {
keys = options?.keys;
}
if (keys) keys.forEach((key: MintKeys) => this._keys.set(key.id, key));
if (options?.unit) this._unit = options?.unit;
if (options?.keysets) this._keysets = options.keysets;
if (options?.mintInfo) this._mintInfo = new MintInfo(options.mintInfo);
if (options?.denominationTarget) {
this._denominationTarget = options.denominationTarget;
}
if (options?.bip39seed) {
if (options.bip39seed instanceof Uint8Array) {
this._seed = options.bip39seed;
return;
}
throw new Error('bip39seed must be a valid UInt8Array');
}
if (options?.keepFactory) {
this._keepFactory = options.keepFactory;
}
if (options?.verbose) {
this._verbose = options.verbose;
}
}
get unit(): string {
return this._unit;
}
get keys(): Map<string, MintKeys> {
return this._keys;
}
get keysetId(): string {
if (!this._keysetId) {
throw new Error('No keysetId set');
}
return this._keysetId;
}
set keysetId(keysetId: string) {
this._keysetId = keysetId;
}
get keysets(): Array<MintKeyset> {
return this._keysets;
}
get mintInfo(): MintInfo {
if (!this._mintInfo) {
throw new Error('Mint info not loaded');
}
return this._mintInfo;
}
/**
* Get information about the mint
* @returns mint info
*/
async getMintInfo(): Promise<MintInfo> {
const infoRes = await this.mint.getInfo();
this._mintInfo = new MintInfo(infoRes);
return this._mintInfo;
}
/**
* Get stored information about the mint or request it if not loaded.
* @returns mint info
*/
async lazyGetMintInfo(): Promise<MintInfo> {
if (!this._mintInfo) {
return await this.getMintInfo();
}
return this._mintInfo;
}
/**
* Load mint information, keysets and keys. This function can be called if no keysets are passed in the constructor
*/
async loadMint() {
await this.getMintInfo();
await this.getKeySets();
await this.getKeys();
}
/**
* Choose a keyset to activate based on the lowest input fee
*
* Note: this function will filter out deprecated base64 keysets
*
* @param keysets keysets to choose from
* @returns active keyset
*/
getActiveKeyset(keysets: Array<MintKeyset>): MintKeyset {
let activeKeysets = keysets.filter((k: MintKeyset) => k.active);
// we only consider keyset IDs that start with "00"
activeKeysets = activeKeysets.filter((k: MintKeyset) => k.id.startsWith('00'));
const activeKeyset = activeKeysets.sort(
(a: MintKeyset, b: MintKeyset) => (a.input_fee_ppk ?? 0) - (b.input_fee_ppk ?? 0)
)[0];
if (!activeKeyset) {
throw new Error('No active keyset found');
}
return activeKeyset;
}
/**
* Get keysets from the mint with the unit of the wallet
* @returns keysets with wallet's unit
*/
async getKeySets(): Promise<Array<MintKeyset>> {
const allKeysets = await this.mint.getKeySets();
const unitKeysets = allKeysets.keysets.filter((k: MintKeyset) => k.unit === this._unit);
this._keysets = unitKeysets;
return this._keysets;
}
/**
* Get all active keys from the mint and set the keyset with the lowest fees as the active wallet keyset.
* @returns keyset
*/
async getAllKeys(): Promise<Array<MintKeys>> {
const keysets = await this.mint.getKeys();
this._keys = new Map(keysets.keysets.map((k: MintKeys) => [k.id, k]));
this.keysetId = this.getActiveKeyset(this._keysets).id;
return keysets.keysets;
}
/**
* Get public keys from the mint. If keys were already fetched, it will return those.
*
* If `keysetId` is set, it will fetch and return that specific keyset.
* Otherwise, we select an active keyset with the unit of the wallet.
*
* @param keysetId optional keysetId to get keys for
* @param forceRefresh? if set to true, it will force refresh the keyset from the mint
* @returns keyset
*/
async getKeys(keysetId?: string, forceRefresh?: boolean): Promise<MintKeys> {
if (!(this._keysets.length > 0) || forceRefresh) {
await this.getKeySets();
}
// no keyset id is chosen, let's choose one
if (!keysetId) {
const localKeyset = this.getActiveKeyset(this._keysets);
keysetId = localKeyset.id;
}
// make sure we have keyset for this id
if (!this._keysets.find((k: MintKeyset) => k.id === keysetId)) {
await this.getKeySets();
if (!this._keysets.find((k: MintKeyset) => k.id === keysetId)) {
throw new Error(`could not initialize keys. No keyset with id '${keysetId}' found`);
}
}
// make sure we have keys for this id
if (!this._keys.get(keysetId)) {
const keys = await this.mint.getKeys(keysetId);
this._keys.set(keysetId, keys.keysets[0]);
}
// set and return
this.keysetId = keysetId;
return this._keys.get(keysetId) as MintKeys;
}
/**
* Receive an encoded or raw Cashu token (only supports single tokens. It will only process the first token in the token array)
* @param {(string|Token)} token - Cashu token, either as string or decoded
* @param {ReceiveOptions} [options] - Optional configuration for token processing
* @returns New token with newly created proofs, token entries that had errors
*/
async receive(token: string | Token, options?: ReceiveOptions): Promise<Array<Proof>> {
const { requireDleq, keysetId, outputAmounts, counter, pubkey, privkey, outputData, p2pk } =
options || {};
if (typeof token === 'string') {
token = getDecodedToken(token);
}
const keys = await this.getKeys(keysetId);
if (requireDleq) {
if (token.proofs.some((p: Proof) => !hasValidDleq(p, keys))) {
throw new Error('Token contains proofs with invalid DLEQ');
}
}
const amount = sumProofs(token.proofs) - this.getFeesForProofs(token.proofs);
let newOutputData: { send: Array<OutputDataLike> | OutputDataFactory } | undefined = undefined;
if (outputData) {
newOutputData = { send: outputData };
} else if (this._keepFactory) {
newOutputData = { send: this._keepFactory };
}
const swapTransaction = this.createSwapPayload(
amount,
token.proofs,
keys,
outputAmounts,
counter,
pubkey,
privkey,
newOutputData,
p2pk
);
const { signatures } = await this.mint.swap(swapTransaction.payload);
const proofs = swapTransaction.outputData.map((d, i) => d.toProof(signatures[i], keys));
const orderedProofs: Array<Proof> = [];
swapTransaction.sortedIndices.forEach((s, o) => {
orderedProofs[s] = proofs[o];
});
return orderedProofs;
}
/**
* Send proofs of a given amount, by providing at least the required amount of proofs
* @param amount amount to send
* @param proofs array of proofs (accumulated amount of proofs must be >= than amount)
* @param {SendOptions} [options] - Optional parameters for configuring the send operation
* @returns {SendResponse}
*/
async send(amount: number, proofs: Array<Proof>, options?: SendOptions): Promise<SendResponse> {
const {
proofsWeHave,
offline,
includeFees,
includeDleq,
keysetId,
outputAmounts,
pubkey,
privkey,
outputData
} = options || {};
if (includeDleq) {
proofs = proofs.filter((p: Proof) => p.dleq != undefined);
}
if (sumProofs(proofs) < amount) {
throw new Error('Not enough funds available to send');
}
const { keep: keepProofsOffline, send: sendProofOffline } = this.selectProofsToSend(
proofs,
amount,
options?.includeFees
);
const expectedFee = includeFees ? this.getFeesForProofs(sendProofOffline) : 0;
if (
!offline &&
(sumProofs(sendProofOffline) != amount + expectedFee || // if the exact amount cannot be selected
outputAmounts ||
pubkey ||
privkey ||
keysetId ||
outputData) // these options require a swap
) {
// we need to swap
// input selection, needs fees because of the swap
const { keep: keepProofsSelect, send: sendProofs } = this.selectProofsToSend(
proofs,
amount,
true
);
proofsWeHave?.push(...keepProofsSelect);
const sendRes = await this.swap(amount, sendProofs, options);
let { keep, send } = sendRes;
const serialized = sendRes.serialized;
keep = keepProofsSelect.concat(keep);
if (!includeDleq) {
send = stripDleq(send);
}
return { keep, send, serialized };
}
if (sumProofs(sendProofOffline) < amount + expectedFee) {
throw new Error('Not enough funds available to send');
}
if (!includeDleq) {
return { keep: keepProofsOffline, send: stripDleq(sendProofOffline) };
}
return { keep: keepProofsOffline, send: sendProofOffline };
}
selectProofsToSend(
proofs: Array<Proof>,
amountToSend: number,
includeFees?: boolean
): SendResponse {
const sortedProofs = proofs.sort((a: Proof, b: Proof) => a.amount - b.amount);
const smallerProofs = sortedProofs
.filter((p: Proof) => p.amount <= amountToSend)
.sort((a: Proof, b: Proof) => b.amount - a.amount);
const biggerProofs = sortedProofs
.filter((p: Proof) => p.amount > amountToSend)
.sort((a: Proof, b: Proof) => a.amount - b.amount);
const nextBigger = biggerProofs[0];
if (!smallerProofs.length && nextBigger) {
return {
keep: proofs.filter((p: Proof) => p.secret !== nextBigger.secret),
send: [nextBigger]
};
}
if (!smallerProofs.length && !nextBigger) {
return { keep: proofs, send: [] };
}
let remainder = amountToSend;
let selectedProofs = [smallerProofs[0]];
const returnedProofs = [];
const feePPK = includeFees ? this.getFeesForProofs(selectedProofs) : 0;
remainder -= selectedProofs[0].amount - feePPK / 1000;
if (remainder > 0) {
const { keep, send } = this.selectProofsToSend(
smallerProofs.slice(1),
remainder,
includeFees
);
selectedProofs.push(...send);
returnedProofs.push(...keep);
}
const selectedFeePPK = includeFees ? this.getFeesForProofs(selectedProofs) : 0;
if (sumProofs(selectedProofs) < amountToSend + selectedFeePPK && nextBigger) {
selectedProofs = [nextBigger];
}
return {
keep: proofs.filter((p: Proof) => !selectedProofs.includes(p)),
send: selectedProofs
};
}
/**
* calculates the fees based on inputs (proofs)
* @param proofs input proofs to calculate fees for
* @returns fee amount
*/
getFeesForProofs(proofs: Array<Proof>): number {
if (!this._keysets.length) {
throw new Error('Could not calculate fees. No keysets found');
}
const keysetIds = new Set(proofs.map((p: Proof) => p.id));
keysetIds.forEach((id: string) => {
if (!this._keysets.find((k: MintKeyset) => k.id === id)) {
throw new Error(`Could not calculate fees. No keyset found with id: ${id}`);
}
});
const fees = Math.floor(
Math.max(
(proofs.reduce(
(total: number, curr: Proof) =>
total + (this._keysets.find((k: MintKeyset) => k.id === curr.id)?.input_fee_ppk || 0),
0
) +
999) /
1000,
0
)
);
return fees;
}
/**
* calculates the fees based on inputs for a given keyset
* @param nInputs number of inputs
* @param keysetId keysetId used to lookup `input_fee_ppk`
* @returns fee amount
*/
getFeesForKeyset(nInputs: number, keysetId: string): number {
const fees = Math.floor(
Math.max(
(nInputs * (this._keysets.find((k: MintKeyset) => k.id === keysetId)?.input_fee_ppk || 0) +
999) /
1000,
0
)
);
return fees;
}
/**
* Splits and creates sendable tokens
* if no amount is specified, the amount is implied by the cumulative amount of all proofs
* if both amount and preference are set, but the preference cannot fulfill the amount, then we use the default split
* @param {SwapOptions} [options] - Optional parameters for configuring the swap operation
* @returns promise of the change- and send-proofs
*/
async swap(amount: number, proofs: Array<Proof>, options?: SwapOptions): Promise<SendResponse> {
let { outputAmounts } = options || {};
const { includeFees, keysetId, counter, pubkey, privkey, proofsWeHave, outputData, p2pk } =
options || {};
const keyset = await this.getKeys(keysetId);
const proofsToSend = proofs;
let amountToSend = amount;
const amountAvailable = sumProofs(proofs);
let amountToKeep = amountAvailable - amountToSend - this.getFeesForProofs(proofsToSend);
// send output selection
let sendAmounts = outputAmounts?.sendAmounts || splitAmount(amountToSend, keyset.keys);
// include the fees to spend the the outputs of the swap
if (includeFees) {
let outputFee = this.getFeesForKeyset(sendAmounts.length, keyset.id);
let sendAmountsFee = splitAmount(outputFee, keyset.keys);
while (
this.getFeesForKeyset(sendAmounts.concat(sendAmountsFee).length, keyset.id) > outputFee
) {
outputFee++;
sendAmountsFee = splitAmount(outputFee, keyset.keys);
}
sendAmounts = sendAmounts.concat(sendAmountsFee);
amountToSend += outputFee;
amountToKeep -= outputFee;
}
// keep output selection
let keepAmounts;
if (!outputAmounts?.keepAmounts && proofsWeHave) {
keepAmounts = getKeepAmounts(
proofsWeHave,
amountToKeep,
keyset.keys,
this._denominationTarget
);
} else if (outputAmounts) {
if (outputAmounts.keepAmounts?.reduce((a: number, b: number) => a + b, 0) != amountToKeep) {
throw new Error('Keep amounts do not match amount to keep');
}
keepAmounts = outputAmounts.keepAmounts;
}
if (amountToSend + this.getFeesForProofs(proofsToSend) > amountAvailable) {
this.warn(
`Not enough funds available (${amountAvailable}) for swap amountToSend: ${amountToSend} + fee: ${this.getFeesForProofs(
proofsToSend
)} | length: ${proofsToSend.length}`
);
throw new Error(`Not enough funds available for swap`);
}
if (amountToSend + this.getFeesForProofs(proofsToSend) + amountToKeep != amountAvailable) {
throw new Error('Amounts do not match for swap');
}
outputAmounts = {
keepAmounts: keepAmounts,
sendAmounts: sendAmounts
};
const keepOutputData = outputData?.keep || this._keepFactory;
const sendOutputData = outputData?.send;
const swapTransaction = this.createSwapPayload(
amountToSend,
proofsToSend,
keyset,
outputAmounts,
counter,
pubkey,
privkey,
{ keep: keepOutputData, send: sendOutputData },
p2pk
);
const { signatures } = await this.mint.swap(swapTransaction.payload);
const swapProofs = swapTransaction.outputData.map((d, i) => d.toProof(signatures[i], keyset));
const splitProofsToKeep: Array<Proof> = [];
const splitProofsToSend: Array<Proof> = [];
const reorderedKeepVector = Array(swapTransaction.keepVector.length);
const reorderedProofs = Array(swapProofs.length);
swapTransaction.sortedIndices.forEach((s, i) => {
reorderedKeepVector[s] = swapTransaction.keepVector[i];
reorderedProofs[s] = swapProofs[i];
});
reorderedProofs.forEach((p, i) => {
if (reorderedKeepVector[i]) {
splitProofsToKeep.push(p);
} else {
splitProofsToSend.push(p);
}
});
return {
keep: splitProofsToKeep,
send: splitProofsToSend
};
}
/**
* Regenerates
* @param start set starting point for count (first cycle for each keyset should usually be 0)
* @param count set number of blinded messages that should be generated
* @param options.keysetId set a custom keysetId to restore from. keysetIds can be loaded with `CashuMint.getKeySets()`
*/
async restore(
start: number,
count: number,
options?: RestoreOptions
): Promise<{ proofs: Array<Proof> }> {
const { keysetId } = options || {};
const keys = await this.getKeys(keysetId);
if (!this._seed) {
throw new Error('CashuWallet must be initialized with a seed to use restore');
}
// create blank amounts for unknown restore amounts
const amounts = Array(count).fill(0);
const outputData = OutputData.createDeterministicData(
amounts.length,
this._seed,
start,
keys,
amounts
);
const { outputs, signatures } = await this.mint.restore({
outputs: outputData.map((d) => d.blindedMessage)
});
const outputsWithSignatures: Array<{
signature: SerializedBlindedSignature;
data: OutputData;
}> = [];
for (let i = 0; i < outputs.length; i++) {
const data = outputData.find((d) => d.blindedMessage.B_ === outputs[i].B_);
if (!data) {
continue;
}
outputsWithSignatures[i] = {
signature: signatures[i],
data
};
}
outputsWithSignatures.forEach((o) => (o.data.blindedMessage.amount = o.signature.amount));
return {
proofs: outputsWithSignatures.map((d) => d.data.toProof(d.signature, keys))
};
}
/**
* Requests a mint quote form the mint. Response returns a Lightning payment request for the requested given amount and unit.
* @param amount Amount requesting for mint.
* @param description optional description for the mint quote
* @param pubkey optional public key to lock the quote to
* @returns the mint will return a mint quote with a Lightning invoice for minting tokens of the specified amount and unit
*/
async createMintQuote(amount: number, description?: string) {
const mintQuotePayload: MintQuotePayload = {
unit: this._unit,
amount: amount,
description: description
};
this.log(`Creating mint quote for amount: ${amount} with description: ${description}`);
return await this.mint.createMintQuote(mintQuotePayload);
}
/**
* Requests a mint quote from the mint that is locked to a public key.
* @param amount Amount requesting for mint.
* @param pubkey public key to lock the quote to
* @param description optional description for the mint quote
* @returns the mint will return a mint quote with a Lightning invoice for minting tokens of the specified amount and unit.
* The quote will be locked to the specified `pubkey`.
*/
async createLockedMintQuote(
amount: number,
pubkey: string,
description?: string
): Promise<LockedMintQuoteResponse> {
const { supported } = (await this.getMintInfo()).isSupported(20);
if (!supported) {
throw new Error('Mint does not support NUT-20');
}
const mintQuotePayload: MintQuotePayload = {
unit: this._unit,
amount: amount,
description: description,
pubkey: pubkey
};
const res = await this.mint.createMintQuote(mintQuotePayload);
if (!res.pubkey) {
throw new Error('Mint returned unlocked mint quote');
}
return res as LockedMintQuoteResponse;
}
/**
* Gets an existing mint quote from the mint.
* @param quote Quote ID
* @returns the mint will create and return a Lightning invoice for the specified amount
*/
async checkMintQuote(quote: string) {
return await this.mint.checkMintQuote(quote);
}
/**
* Mint proofs for a given mint quote
* @param amount amount to request
* @param {string} quote - ID of mint quote (when quote is a string)
* @param {LockedMintQuote} quote - containing the quote ID and unlocking private key (when quote is a LockedMintQuote)
* @param {MintProofOptions} [options] - Optional parameters for configuring the Mint Proof operation
* @returns proofs
*/
async mintProofs(
amount: number,
quote: MintQuoteResponse,
options: MintProofOptions & { privateKey: string }
): Promise<Array<Proof>>;
async mintProofs(
amount: number,
quote: string,
options?: MintProofOptions
): Promise<Array<Proof>>;
async mintProofs(
amount: number,
quote: string | MintQuoteResponse,
options?: MintProofOptions & { privateKey?: string }
): Promise<Array<Proof>> {
let { outputAmounts } = options || {};
const { counter, pubkey, p2pk, keysetId, proofsWeHave, outputData, privateKey } = options || {};
const keyset = await this.getKeys(keysetId);
if (!outputAmounts && proofsWeHave) {
outputAmounts = {
keepAmounts: getKeepAmounts(proofsWeHave, amount, keyset.keys, this._denominationTarget),
sendAmounts: []
};
}
let newBlindingData: Array<OutputData> = [];
if (outputData) {
if (isOutputDataFactory(outputData)) {
const amounts = splitAmount(amount, keyset.keys, outputAmounts?.keepAmounts);
for (let i = 0; i < amounts.length; i++) {
newBlindingData.push(outputData(amounts[i], keyset));
}
} else {
newBlindingData = outputData;
}
} else if (this._keepFactory) {
const amounts = splitAmount(amount, keyset.keys, outputAmounts?.keepAmounts);
for (let i = 0; i < amounts.length; i++) {
newBlindingData.push(this._keepFactory(amounts[i], keyset));
}
} else {
newBlindingData = this.createOutputData(
amount,
keyset,
counter,
pubkey,
outputAmounts?.keepAmounts,
p2pk
);
}
let mintPayload: MintPayload;
if (typeof quote !== 'string') {
if (!privateKey) {
throw new Error('Can not sign locked quote without private key');
}
const blindedMessages = newBlindingData.map((d) => d.blindedMessage);
const mintQuoteSignature = signMintQuote(privateKey, quote.quote, blindedMessages);
mintPayload = {
outputs: blindedMessages,
quote: quote.quote,
signature: mintQuoteSignature
};
} else {
mintPayload = {
outputs: newBlindingData.map((d) => d.blindedMessage),
quote: quote
};
}
const { signatures } = await this.mint.mint(mintPayload);
return newBlindingData.map((d, i) => d.toProof(signatures[i], keyset));
}
/**
* Requests a melt quote from the mint. Response returns amount and fees for a given unit in order to pay a Lightning invoice.
* @param invoice LN invoice that needs to get a fee estimate
* @returns the mint will create and return a melt quote for the invoice with an amount and fee reserve
*/
async createMeltQuote(invoice: string): Promise<MeltQuoteResponse> {
const meltQuotePayload: MeltQuotePayload = {
unit: this._unit,
request: invoice
};
const meltQuote = await this.mint.createMeltQuote(meltQuotePayload);
return meltQuote;
}
/**
* Requests a multi path melt quote from the mint.
* @param invoice LN invoice that needs to get a fee estimate
* @param partialAmount the partial amount of the invoice's total to be paid by this instance
* @returns the mint will create and return a melt quote for the invoice with an amount and fee reserve
*/
async createMultiPathMeltQuote(
invoice: string,
partialAmount: number
): Promise<MeltQuoteResponse> {
const { supported, params } = (await this.lazyGetMintInfo()).isSupported(15);
if (!supported) {
throw new Error('Mint does not support NUT-15');
}
if (!params?.some((p) => p.method === 'bolt11' && p.unit === this.unit)) {
throw new Error(`Mint does not support MPP for bolt11 and ${this.unit}`);
}
const mppOption: MPPOption = {
amount: partialAmount
};
const meltOptions: MeltQuoteOptions = {
mpp: mppOption
};
const meltQuotePayload: MeltQuotePayload = {
unit: this._unit,
request: invoice,
options: meltOptions
};
const meltQuote = await this.mint.createMeltQuote(meltQuotePayload);
return meltQuote;
}
/**
* Return an existing melt quote from the mint.
* @param quote ID of the melt quote
* @returns the mint will return an existing melt quote
*/
async checkMeltQuote(quote: string): Promise<MeltQuoteResponse> {
const meltQuote = await this.mint.checkMeltQuote(quote);
return meltQuote;
}
/**
* Melt proofs for a melt quote. proofsToSend must be at least amount+fee_reserve form the melt quote. This function does not perform coin selection!.
* Returns melt quote and change proofs
* @param meltQuote ID of the melt quote
* @param proofsToSend proofs to melt
* @param {MeltProofOptions} [options] - Optional parameters for configuring the Melting Proof operation
* @returns
*/
async meltProofs(
meltQuote: MeltQuoteResponse,
proofsToSend: Array<Proof>,
options?: MeltProofOptions
): Promise<MeltProofsResponse> {
const { keysetId, counter, privkey } = options || {};
const keys = await this.getKeys(keysetId);
const outputData = this.createBlankOutputs(
sumProofs(proofsToSend) - meltQuote.amount,
keys,
counter,
this._keepFactory
);
if (privkey != undefined) {
proofsToSend = getSignedProofs(
proofsToSend.map((p: Proof) => {
return {
amount: p.amount,
C: pointFromHex(p.C),
id: p.id,
secret: new TextEncoder().encode(p.secret)
};
}),
privkey
).map((p: NUT11Proof) => serializeProof(p));
}
proofsToSend = stripDleq(proofsToSend);
const meltPayload: MeltPayload = {
quote: meltQuote.quote,
inputs: proofsToSend,
outputs: outputData.map((d) => d.blindedMessage)
};
const meltResponse = await this.mint.melt(meltPayload);
return {
quote: meltResponse,
change: meltResponse.change?.map((s, i) => outputData[i].toProof(s, keys)) ?? []
};
}
/**
* Creates a split payload
* @param amount amount to send
* @param proofsToSend proofs to split*
* @param outputAmounts? optionally specify the output's amounts to keep and to send.
* @param counter? optionally set counter to derive secret deterministically. CashuWallet class must be initialized with seed phrase to take effect
* @param pubkey? optionally locks ecash to pubkey. Will not be deterministic, even if counter is set!
* @param privkey? will create a signature on the @param proofsToSend secrets if set
* @returns
*/
private createSwapPayload(
amount: number,
proofsToSend: Array<Proof>,
keyset: MintKeys,
outputAmounts?: OutputAmounts,
counter?: number,
pubkey?: string,
privkey?: string,
customOutputData?: {
keep?: Array<OutputDataLike> | OutputDataFactory;
send?: Array<OutputDataLike> | OutputDataFactory;
},
p2pk?: { pubkey: string; locktime?: number; refundKeys?: Array<string> }
): SwapTransaction {
const totalAmount = proofsToSend.reduce((total: number, curr: Proof) => total + curr.amount, 0);
if (outputAmounts && outputAmounts.sendAmounts && !outputAmounts.keepAmounts) {
outputAmounts.keepAmounts = splitAmount(
totalAmount - amount - this.getFeesForProofs(proofsToSend),
keyset.keys
);
}
const keepAmount = totalAmount - amount - this.getFeesForProofs(proofsToSend);
let keepOutputData: Array<OutputDataLike> = [];
let sendOutputData: Array<OutputDataLike> = [];
if (customOutputData?.keep) {
if (isOutputDataFactory(customOutputData.keep)) {
const factory = customOutputData.keep;
const amounts = splitAmount(keepAmount, keyset.keys);
amounts.forEach((a) => {
keepOutputData.push(factory(a, keyset));
});
} else {
keepOutputData = customOutputData.keep;
}
} else {
keepOutputData = this.createOutputData(
keepAmount,
keyset,
counter,
pubkey,
outputAmounts?.keepAmounts,
p2pk,
this._keepFactory
);
}
if (customOutputData?.send) {
if (isOutputDataFactory(customOutputData.send)) {
const factory = customOutputData.send;
const amounts = splitAmount(amount, keyset.keys);
amounts.forEach((a) => {
sendOutputData.push(factory(a, keyset));
});
} else {
sendOutputData = customOutputData.send;
}
} else {
sendOutputData = this.createOutputData(
amount,
keyset,
counter ? counter + keepOutputData.length : undefined,
pubkey,
outputAmounts?.sendAmounts,
p2pk
);
}