-
Notifications
You must be signed in to change notification settings - Fork 15
/
wallet.rs
1190 lines (1036 loc) · 38.6 KB
/
wallet.rs
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
use moksha_core::{
amount::Amount,
blind::{BlindedMessage, BlindedSignature, BlindingFactor, TotalAmount},
dhke::Dhke,
keyset::KeysetId,
primitives::{
CurrencyUnit, MintInfoResponse, PaymentMethod, PostMeltBolt11Response,
PostMeltBtcOnchainResponse, PostMeltQuoteBolt11Response, PostMeltQuoteBtcOnchainResponse,
PostMintQuoteBolt11Response, PostMintQuoteBtcOnchainResponse,
},
proof::{Proof, Proofs},
token::TokenV3,
};
use secp256k1::PublicKey;
use url::Url;
use crate::{
client::CashuClient,
error::MokshaWalletError,
http::CrossPlatformHttpClient,
localstore::{LocalStore, WalletKeyset},
secret::DeterministicSecret,
};
use lightning_invoice::Bolt11Invoice as LNInvoice;
use std::{
collections::{HashMap, HashSet},
str::FromStr,
vec,
};
#[derive(Clone)]
pub struct Wallet<L, C>
where
L: LocalStore,
C: CashuClient,
{
client: C,
dhke: Dhke,
localstore: L,
secret: DeterministicSecret,
}
pub struct WalletBuilder<L, C: CashuClient = CrossPlatformHttpClient>
where
L: LocalStore,
C: CashuClient + Default,
{
client: Option<C>,
localstore: Option<L>,
}
impl<L, C> WalletBuilder<L, C>
where
L: LocalStore,
C: CashuClient + Default,
{
fn new() -> Self {
Self {
client: Some(C::default()),
localstore: None,
}
}
pub fn with_client(mut self, client: C) -> Self {
self.client = Some(client);
self
}
pub fn with_localstore(mut self, localstore: L) -> Self {
self.localstore = Some(localstore);
self
}
pub async fn build(self) -> Result<Wallet<L, C>, MokshaWalletError> {
let client = self.client.unwrap_or_default();
let localstore = self.localstore.expect("localstore is required");
let mut tx = localstore.begin_tx().await?;
let seed_words = localstore.get_seed(&mut tx).await?;
let seed = match seed_words {
Some(seed) => seed,
None => {
let seed = DeterministicSecret::generate_random_seed_words()?;
localstore.add_seed(&mut tx, &seed).await?;
seed
}
};
tx.commit().await?;
Ok(Wallet::new(
client as C,
localstore,
DeterministicSecret::from_seed_words(&seed)?,
))
}
}
impl<L, C> Default for WalletBuilder<L, C>
where
C: CashuClient + Default,
L: LocalStore,
{
fn default() -> Self {
Self::new()
}
}
impl<L, C> Wallet<L, C>
where
C: CashuClient + Default,
L: LocalStore,
{
fn new(client: C, localstore: L, secret: DeterministicSecret) -> Self {
Self {
client,
dhke: Dhke::new(),
localstore,
secret,
}
}
pub fn builder() -> WalletBuilder<L, C> {
WalletBuilder::default()
}
pub async fn create_quote_bolt11(
&self,
mint_url: &Url,
amount: u64,
) -> Result<PostMintQuoteBolt11Response, MokshaWalletError> {
self.client
.post_mint_quote_bolt11(mint_url, amount, CurrencyUnit::Sat)
.await
}
pub async fn create_quote_onchain(
&self,
mint_url: &Url,
amount: u64,
) -> Result<PostMintQuoteBtcOnchainResponse, MokshaWalletError> {
self.client
.post_mint_quote_onchain(mint_url, amount, CurrencyUnit::Sat)
.await
}
pub async fn is_quote_paid(
&self,
mint_url: &Url,
payment_method: &PaymentMethod,
quote: String,
) -> Result<bool, MokshaWalletError> {
Ok(match payment_method {
PaymentMethod::Bolt11 => {
self.client
.get_mint_quote_bolt11(mint_url, quote)
.await?
.paid
}
PaymentMethod::BtcOnchain => {
self.client
.get_mint_quote_onchain(mint_url, quote)
.await?
.paid
}
})
}
pub async fn is_onchain_paid(
&self,
mint_url: &Url,
quote: String,
) -> Result<bool, MokshaWalletError> {
Ok(self
.client
.get_melt_quote_onchain(mint_url, quote)
.await?
.paid)
}
pub async fn is_onchain_tx_paid(
&self,
mint_url: &Url,
txid: String,
) -> Result<bool, MokshaWalletError> {
Ok(self.client.get_melt_onchain(mint_url, txid).await?.paid)
}
pub async fn get_wallet_keysets(&self) -> Result<Vec<WalletKeyset>, MokshaWalletError> {
let mut tx = self.localstore.begin_tx().await?;
let keysets = self.localstore.get_keysets(&mut tx).await?;
tx.commit().await?;
Ok(keysets)
}
pub async fn get_mint_urls(&self) -> Result<Vec<Url>, MokshaWalletError> {
let keysets = self.get_wallet_keysets().await?;
let mints: HashSet<Url> = keysets.into_iter().map(|k| k.mint_url).collect();
Ok(mints.into_iter().collect())
}
/// Stores the mints keys in the localstore
pub async fn add_mint_keysets(
&self,
mint_url: &Url,
) -> Result<Vec<WalletKeyset>, MokshaWalletError> {
if !self.client.is_v1_supported(mint_url).await? {
return Err(MokshaWalletError::UnsupportedApiVersion);
}
let mint_keysets = self.client.get_keysets(mint_url).await?;
let mut tx = self.localstore.begin_tx().await?;
let mut result = vec![];
for keyset in mint_keysets.keysets.iter() {
let keysets = self
.client
.get_keys_by_id(mint_url, keyset.id.clone())
.await;
let public_keys = match keysets {
Ok(k) => k
.keysets
.into_iter()
.find(|k| k.id == keyset.id && k.unit == keyset.unit)
.expect("no valid keyset found")
.keys
.clone(),
Err(_) => {
//println!("Ignoring keyset without public_keys {:?}", keyset.id);
continue;
}
};
// ignore legacy keysets
let keyset_id = match KeysetId::new(&keyset.id) {
Ok(id) => id,
Err(_) => {
//println!("Ignoring legacy keyset {:?}", keyset.id);
continue;
}
};
let wallet_keyset = WalletKeyset::new(
&keyset_id,
mint_url,
&keyset.unit,
0,
public_keys,
keyset.active,
);
result.push(wallet_keyset.clone());
self.localstore
.upsert_keyset(&mut tx, &wallet_keyset)
.await?;
}
tx.commit().await?;
Ok(result)
}
pub async fn get_balance(&self) -> Result<u64, MokshaWalletError> {
let mut tx = self.localstore.begin_tx().await?;
let total_amount = self.localstore.get_proofs(&mut tx).await?.total_amount();
tx.commit().await?;
Ok(total_amount)
}
pub async fn send_tokens(
&self,
wallet_keyset: &WalletKeyset,
amount: u64,
) -> Result<TokenV3, MokshaWalletError> {
let balance = self.get_balance().await?;
if amount > balance {
return Err(MokshaWalletError::NotEnoughTokens);
}
let mut tx = self.localstore.begin_tx().await?;
let all_proofs = self
.localstore
.get_proofs(&mut tx)
.await?
.proofs_by_keyset(&wallet_keyset.keyset_id);
tx.commit().await?;
let selected_proofs = all_proofs.proofs_for_amount(amount)?;
let selected_tokens = (wallet_keyset.mint_url.to_owned(), selected_proofs.clone()).into();
let (remaining_tokens, result) = self
.swap_tokens(wallet_keyset, &selected_tokens, amount.into())
.await?;
let mut tx = self.localstore.begin_tx().await?;
self.localstore
.delete_proofs(&mut tx, &selected_proofs)
.await?;
self.localstore
.add_proofs(&mut tx, &remaining_tokens.proofs())
.await?;
tx.commit().await?;
Ok(result)
}
pub async fn receive_tokens(
&self,
wallet_keyset: &WalletKeyset,
tokens: &TokenV3,
) -> Result<(), MokshaWalletError> {
let total_amount = tokens.total_amount();
let (_, redeemed_tokens) = self
.swap_tokens(wallet_keyset, tokens, total_amount.into())
.await?;
let mut tx = self.localstore.begin_tx().await?;
self.localstore
.add_proofs(&mut tx, &redeemed_tokens.proofs())
.await?;
tx.commit().await?;
Ok(())
}
pub async fn get_mint_quote(
&self,
mint_url: &Url,
amount: Amount,
currency: CurrencyUnit,
) -> Result<PostMintQuoteBolt11Response, MokshaWalletError> {
self.client
.post_mint_quote_bolt11(mint_url, amount.0, currency)
.await
}
pub async fn get_melt_quote_bolt11(
&self,
mint_url: &Url,
invoice: String,
currency: CurrencyUnit,
) -> Result<PostMeltQuoteBolt11Response, MokshaWalletError> {
self.client
.post_melt_quote_bolt11(mint_url, invoice.clone(), currency)
.await
}
pub async fn pay_invoice(
&self,
wallet_keyset: &WalletKeyset,
melt_quote: &PostMeltQuoteBolt11Response,
invoice: String,
) -> Result<(PostMeltBolt11Response, u64), MokshaWalletError> {
let mut tx = self.localstore.begin_tx().await?;
let all_proofs = self.localstore.get_proofs(&mut tx).await?;
tx.commit().await?;
let ln_amount = Self::get_invoice_amount(&invoice)? + melt_quote.fee_reserve;
if ln_amount > all_proofs.total_amount() {
return Err(MokshaWalletError::NotEnoughTokens);
}
let selected_proofs = all_proofs.proofs_for_amount(ln_amount)?;
let total_proofs = {
let selected_tokens =
(wallet_keyset.mint_url.to_owned(), selected_proofs.clone()).into();
let swap_result = self
.swap_tokens(wallet_keyset, &selected_tokens, ln_amount.into())
.await?;
let mut tx = self.localstore.begin_tx().await?;
self.localstore
.delete_proofs(&mut tx, &selected_proofs)
.await?;
self.localstore
.add_proofs(&mut tx, &swap_result.0.proofs())
.await?;
tx.commit().await?;
swap_result.1.proofs()
};
let fee_blind = self
.create_blank(melt_quote.fee_reserve.into(), &wallet_keyset.keyset_id)
.await?;
let msgs = fee_blind
.iter()
.map(|(msg, _, _)| msg.clone())
.collect::<Vec<BlindedMessage>>();
let secrets = fee_blind
.iter()
.map(|(_, _, secret)| secret.clone())
.collect::<Vec<String>>();
let outputs = fee_blind
.iter()
.map(|(msg, blinding_factor, _)| (msg.clone(), blinding_factor.clone()))
.collect::<Vec<(BlindedMessage, BlindingFactor)>>();
let mut tx = self.localstore.begin_tx().await?;
match self
.melt_token(
&wallet_keyset.mint_url,
melt_quote.to_owned().quote,
&total_proofs,
msgs,
)
.await
{
Ok(response) => {
if !response.paid {
self.localstore.add_proofs(&mut tx, &total_proofs).await?;
}
let change_proofs = self.create_proofs_from_blinded_signatures(
&wallet_keyset.keyset_id,
&wallet_keyset.public_keys,
response.clone().change,
secrets,
outputs,
)?;
self.localstore.add_proofs(&mut tx, &change_proofs).await?;
tx.commit().await?;
Ok((response, change_proofs.total_amount()))
}
Err(e) => {
self.localstore.add_proofs(&mut tx, &total_proofs).await?;
tx.commit().await?;
Err(e)
}
}
}
pub async fn get_melt_quote_btconchain(
&self,
mint_url: &Url,
address: String,
amount: u64,
) -> Result<Vec<PostMeltQuoteBtcOnchainResponse>, MokshaWalletError> {
self.client
.post_melt_quote_onchain(mint_url, address, amount, CurrencyUnit::Sat)
.await
}
pub async fn pay_onchain(
&self,
wallet_keyset: &WalletKeyset,
melt_quote: &PostMeltQuoteBtcOnchainResponse,
) -> Result<PostMeltBtcOnchainResponse, MokshaWalletError> {
let mut tx = self.localstore.begin_tx().await?;
let all_proofs = self.localstore.get_proofs(&mut tx).await?;
tx.commit().await?;
let ln_amount = melt_quote.amount + melt_quote.fee;
if ln_amount > all_proofs.total_amount() {
return Err(MokshaWalletError::NotEnoughTokens);
}
let selected_proofs = all_proofs.proofs_for_amount(ln_amount)?;
let mut tx = self.localstore.begin_tx().await?;
let total_proofs = {
let selected_tokens =
(wallet_keyset.mint_url.to_owned(), selected_proofs.clone()).into();
let swap_result = self
.swap_tokens(wallet_keyset, &selected_tokens, ln_amount.into())
.await?;
self.localstore
.delete_proofs(&mut tx, &selected_proofs)
.await?;
self.localstore
.add_proofs(&mut tx, &swap_result.0.proofs())
.await?;
swap_result.1.proofs()
};
let melt_response = self
.client
.post_melt_onchain(
&wallet_keyset.mint_url,
total_proofs.clone(),
melt_quote.quote.clone(),
)
.await?;
if melt_response.paid {
self.localstore
.delete_proofs(&mut tx, &total_proofs)
.await?;
}
tx.commit().await?;
Ok(melt_response)
}
async fn create_secrets(
&self,
keyset_id: &KeysetId,
amount: u32,
) -> Result<Vec<(String, BlindingFactor)>, MokshaWalletError> {
let mut tx = self.localstore.begin_tx().await?;
let all_keysets = self.localstore.get_keysets(&mut tx).await?;
let keyset = all_keysets
.iter()
.find(|k| k.keyset_id == *keyset_id)
.expect("keyset not found create-secrets");
let start_index = (keyset.last_index + 1) as u32;
let secret_range = self.secret.derive_range(keyset_id, start_index, amount)?;
self.localstore
.update_keyset_last_index(
&mut tx,
&WalletKeyset {
last_index: (start_index + amount - 1) as u64,
..keyset.clone()
},
)
.await?;
tx.commit().await?;
Ok(secret_range)
}
pub async fn swap_tokens(
&self,
wallet_keyset: &WalletKeyset,
tokens: &TokenV3,
splt_amount: Amount,
) -> Result<(TokenV3, TokenV3), MokshaWalletError> {
let total_token_amount = tokens.total_amount();
let first_amount: Amount = (total_token_amount - splt_amount.0).into();
let first_secrets = self
.create_secrets(&wallet_keyset.keyset_id, first_amount.split().len() as u32)
.await?;
let first_outputs = self.create_blinded_messages(
&wallet_keyset.keyset_id,
first_amount,
first_secrets.clone(),
)?;
// ############################################################################
let second_amount = splt_amount.clone();
let second_secrets = self
.create_secrets(&wallet_keyset.keyset_id, second_amount.split().len() as u32)
.await?;
let second_outputs = self.create_blinded_messages(
&wallet_keyset.keyset_id,
second_amount,
second_secrets.clone(),
)?;
let mut total_outputs = vec![];
total_outputs.extend(get_blinded_msg(first_outputs.clone()));
total_outputs.extend(get_blinded_msg(second_outputs.clone()));
if tokens.total_amount() != total_outputs.total_amount() {
return Err(MokshaWalletError::InvalidProofs);
}
let split_result = self
.client
.post_swap(&wallet_keyset.mint_url, tokens.proofs(), total_outputs)
.await?;
if split_result.signatures.is_empty() {
return Ok((TokenV3::empty(), TokenV3::empty()));
}
let len_first = first_secrets.len();
let secrets = [first_secrets, second_secrets].concat();
let outputs = [first_outputs, second_outputs].concat();
let secrets = secrets.into_iter().map(|(s, _)| s).collect::<Vec<String>>();
let proofs = self
.create_proofs_from_blinded_signatures(
&wallet_keyset.keyset_id,
&wallet_keyset.public_keys,
split_result.signatures,
secrets,
outputs,
)?
.proofs();
let first_tokens: TokenV3 = (
wallet_keyset.mint_url.to_owned(),
wallet_keyset.currency_unit.clone(),
proofs[0..len_first].to_vec().into(),
)
.into();
let second_tokens: TokenV3 = (
wallet_keyset.mint_url.to_owned(),
wallet_keyset.currency_unit.clone(),
proofs[len_first..proofs.len()].to_vec().into(),
)
.into();
if tokens.total_amount() != first_tokens.total_amount() + second_tokens.total_amount() {
println!(
"Error in swap: input {:?} != output {:?} + {:?}",
tokens.total_amount(),
first_tokens.total_amount(),
second_tokens.total_amount()
);
}
Ok((first_tokens, second_tokens))
}
pub async fn get_mint_info(
&self,
mint_url: &Url,
) -> Result<MintInfoResponse, MokshaWalletError> {
self.client.get_info(mint_url).await
}
async fn melt_token(
&self,
mint_url: &Url,
quote_id: String,
proofs: &Proofs,
fee_blinded_messages: Vec<BlindedMessage>,
) -> Result<PostMeltBolt11Response, MokshaWalletError> {
let melt_response = self
.client
.post_melt_bolt11(mint_url, proofs.clone(), quote_id, fee_blinded_messages)
.await?;
if melt_response.paid {
let mut tx = self.localstore.begin_tx().await?;
self.localstore.delete_proofs(&mut tx, proofs).await?;
tx.commit().await?;
}
Ok(melt_response)
}
fn decode_invoice(payment_request: &str) -> Result<LNInvoice, MokshaWalletError> {
LNInvoice::from_str(payment_request)
.map_err(|err| MokshaWalletError::DecodeInvoice(payment_request.to_owned(), err))
}
fn get_invoice_amount(payment_request: &str) -> Result<u64, MokshaWalletError> {
let invoice = Self::decode_invoice(payment_request)?;
Ok(invoice
.amount_milli_satoshis()
.ok_or_else(|| MokshaWalletError::InvalidInvoice(payment_request.to_owned()))?
/ 1000)
}
pub async fn mint_tokens(
&self,
wallet_keyset: &WalletKeyset,
payment_method: &PaymentMethod,
amount: Amount,
quote_id: String,
) -> Result<TokenV3, MokshaWalletError> {
let split_amount = amount.split();
let secret_range = self
.create_secrets(&wallet_keyset.keyset_id, split_amount.len() as u32)
.await?;
let blinded_messages = split_amount
.into_iter()
.zip(secret_range)
.map(|(amount, (secret, blinding_factor))| {
let b_ = self.dhke.step1_alice(&secret, &blinding_factor)?;
Ok((
BlindedMessage {
amount,
b_,
id: wallet_keyset.keyset_id.to_string(), // FIXME use keyset_id
},
blinding_factor,
secret,
))
})
.collect::<Result<Vec<(_, _, _)>, MokshaWalletError>>()?;
let signatures = match payment_method {
PaymentMethod::Bolt11 => {
let post_mint_resp = self
.client
.post_mint_bolt11(
&wallet_keyset.mint_url,
quote_id,
blinded_messages
.clone()
.into_iter()
.map(|(msg, _, _)| msg)
.collect::<Vec<BlindedMessage>>(),
)
.await?;
post_mint_resp.signatures
}
PaymentMethod::BtcOnchain => {
let post_mint_resp = self
.client
.post_mint_onchain(
&wallet_keyset.mint_url,
quote_id,
blinded_messages
.clone()
.into_iter()
.map(|(msg, _, _)| msg)
.collect::<Vec<BlindedMessage>>(),
)
.await?;
post_mint_resp.signatures
}
};
// step 3: unblind signatures
let current_keyset_id = wallet_keyset.keyset_id.to_string(); // FIXME
let proofs = signatures
.iter()
.zip(blinded_messages)
.map(|(p, (_, priv_key, secret))| {
let key = wallet_keyset
.public_keys
.get(&p.amount)
.expect("msg amount not found in mint keys");
let pub_alice = self.dhke.step3_alice(p.c_, priv_key, *key).unwrap();
Proof::new(p.amount, secret, pub_alice, current_keyset_id.clone())
})
.collect::<Vec<Proof>>()
.into();
let tokens: TokenV3 = (wallet_keyset.mint_url.to_owned(), proofs).into();
let mut tx = self.localstore.begin_tx().await?;
self.localstore
.add_proofs(&mut tx, &tokens.proofs())
.await?;
tx.commit().await?;
Ok(tokens)
}
pub async fn create_blank(
&self,
fee_reserve: Amount,
keyset_id: &KeysetId,
) -> Result<Vec<(BlindedMessage, BlindingFactor, String)>, MokshaWalletError> {
if fee_reserve.0 == 0 {
return Ok(vec![]);
}
let fee_reserve_float = fee_reserve.0 as f64;
let count = (fee_reserve_float.log2().ceil() as u64).max(1);
let secret_range = self.create_secrets(keyset_id, count as u32).await?;
let blinded_messages = secret_range
.into_iter()
.map(|(secret, blinding_factor)| {
let b_ = self.dhke.step1_alice(secret.clone(), &blinding_factor)?;
Ok((
BlindedMessage {
amount: 1,
b_,
id: keyset_id.to_string(),
},
blinding_factor,
secret,
))
})
.collect::<Result<Vec<(_, _, _)>, MokshaWalletError>>()?;
Ok(blinded_messages)
}
fn create_blinded_messages(
&self,
keyset_id: &KeysetId,
amount: Amount,
secrets_factors: Vec<(String, BlindingFactor)>,
) -> Result<Vec<(BlindedMessage, BlindingFactor)>, MokshaWalletError> {
let split_amount = amount.split();
split_amount
.into_iter()
.zip(secrets_factors)
.map(|(amount, (secret, blinding_factor))| {
let b_ = self.dhke.step1_alice(secret, &blinding_factor)?;
Ok((
BlindedMessage {
amount,
b_,
id: keyset_id.to_string(),
},
blinding_factor,
))
})
.collect::<Result<Vec<(_, _)>, MokshaWalletError>>()
}
fn create_proofs_from_blinded_signatures(
&self,
keyset_id: &KeysetId,
pub_keys: &HashMap<u64, PublicKey>,
signatures: Vec<BlindedSignature>,
secrets: Vec<String>,
outputs: Vec<(BlindedMessage, BlindingFactor)>,
) -> Result<Proofs, MokshaWalletError> {
let current_keyset_id = keyset_id.to_string(); // FIXME
let blinding_factors = outputs
.into_iter()
.map(|(_, secret)| secret)
.collect::<Vec<BlindingFactor>>();
Ok(signatures
.iter()
.zip(blinding_factors)
.zip(secrets)
.map(|((p, blinding_factor), secret)| {
let key = pub_keys
.get(&p.amount)
.ok_or(MokshaWalletError::PubkeyNotFound)?;
let pub_alice = self
.dhke
.step3_alice(p.c_, blinding_factor.to_owned(), *key)?;
Ok(Proof::new(
p.amount,
secret,
pub_alice,
current_keyset_id.clone(),
))
})
.collect::<Result<Vec<_>, MokshaWalletError>>()?
.into())
}
pub async fn get_proofs(&self) -> Result<Proofs, MokshaWalletError> {
let mut tx = self.localstore.begin_tx().await?;
let proofs = self.localstore.get_proofs(&mut tx).await?;
tx.commit().await?;
Ok(proofs)
}
}
// FIXME implement for Vec<BlindedMessage, Secretkey>
fn get_blinded_msg(blinded_messages: Vec<(BlindedMessage, BlindingFactor)>) -> Vec<BlindedMessage> {
blinded_messages
.into_iter()
.map(|(msg, _)| msg)
.collect::<Vec<BlindedMessage>>()
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use crate::client::MockCashuClient;
use crate::localstore::sqlite::SqliteLocalStore;
use crate::localstore::{LocalStore, WalletKeyset};
use crate::wallet::WalletBuilder;
use moksha_core::fixture::{read_fixture, read_fixture_as};
use moksha_core::keyset::{KeysetId, Keysets, MintKeyset};
use moksha_core::primitives::{
CurrencyUnit, KeyResponse, KeysResponse, PaymentMethod, PostMeltBolt11Response,
PostMeltQuoteBolt11Response, PostMintBolt11Response, PostSwapResponse,
};
use moksha_core::token::TokenV3;
use secp256k1::PublicKey;
use url::Url;
fn create_mock() -> MockCashuClient {
let keys = MintKeyset::new("mykey", "");
let key_response = KeyResponse {
keys: keys.public_keys.clone(),
id: keys.keyset_id.clone(),
unit: CurrencyUnit::Sat,
};
let keys_response = KeysResponse::new(key_response.clone());
let keys_by_id_response = keys_response.clone();
let keysets = Keysets::new(keys.keyset_id, CurrencyUnit::Sat, true);
let mut client = MockCashuClient::default();
client
.expect_get_keys()
.returning(move |_| Ok(keys_response.clone()));
client
.expect_get_keysets()
.returning(move |_| Ok(keysets.clone()));
client
.expect_get_keys_by_id()
.returning(move |_, _| Ok(keys_by_id_response.clone()));
client.expect_is_v1_supported().returning(move |_| Ok(true));
client
}
#[tokio::test]
async fn test_blank_blinded_messages_1000_sats() -> anyhow::Result<()> {
let localstore = SqliteLocalStore::with_in_memory().await?;
let wallet_keyset = create_test_wallet_keyset()?;
let mut tx = localstore.begin_tx().await?;
localstore.upsert_keyset(&mut tx, &wallet_keyset).await?;
tx.commit().await?;
let client = create_mock();
let wallet = WalletBuilder::new()
.with_client(client)
.with_localstore(localstore)
.build()
.await?;
let result = wallet
.create_blank(1000.into(), &KeysetId::new("00d31cecf59d18c0")?)
.await;
println!("{:?}", result);
assert!(result.is_ok());
let result = result.unwrap();
assert!(result.len() == 10);
assert!(result.first().unwrap().0.amount == 1);
Ok(())
}
#[tokio::test]
async fn test_blank_blinded_messages_zero_sats() -> anyhow::Result<()> {
let localstore = SqliteLocalStore::with_in_memory().await?;
let wallet_keyset = create_test_wallet_keyset()?;
let mut tx = localstore.begin_tx().await?;
localstore.upsert_keyset(&mut tx, &wallet_keyset).await?;
tx.commit().await?;
let client = create_mock();
let wallet = WalletBuilder::new()
.with_client(client)
.with_localstore(localstore)
.build()
.await?;
let result = wallet
.create_blank(0.into(), &KeysetId::new("00d31cecf59d18c0")?)
.await;
println!("{:?}", result);
assert!(result.is_ok());
assert!(result.unwrap().is_empty());
Ok(())
}
#[tokio::test]
async fn test_blank_blinded_messages_serialize() -> anyhow::Result<()> {
let localstore = SqliteLocalStore::with_in_memory().await?;
let wallet_keyset = create_test_wallet_keyset()?;
let mut tx = localstore.begin_tx().await?;
localstore.upsert_keyset(&mut tx, &wallet_keyset).await?;
tx.commit().await?;
let client = create_mock();
let wallet = WalletBuilder::new()
.with_client(client)
.with_localstore(localstore)
.build()
.await?;
let result = wallet
.create_blank(4000.into(), &KeysetId::new("00d31cecf59d18c0")?)
.await?;
for (blinded_message, _, _) in result {
let out = serde_json::to_string(&blinded_message)?;
assert!(!out.is_empty());
}
Ok(())
}
#[tokio::test]
async fn test_mint_tokens() -> anyhow::Result<()> {
let mint_response =
read_fixture_as::<PostMintBolt11Response>("post_mint_response_20.json")?;
let mut client = create_mock();
client
.expect_post_mint_bolt11()
.returning(move |_, _, _| Ok(mint_response.clone()));
let localstore = SqliteLocalStore::with_in_memory().await?;
let wallet_keyset = create_test_wallet_keyset()?;
let mut tx = localstore.begin_tx().await?;
localstore.upsert_keyset(&mut tx, &wallet_keyset).await?;
tx.commit().await?;
let wallet = WalletBuilder::new()
.with_client(client)
.with_localstore(localstore)
.build()
.await?;
let result = wallet
.mint_tokens(
&wallet_keyset,