1#![deny(clippy::pedantic)]
2#![allow(clippy::cast_possible_truncation)]
3#![allow(clippy::missing_errors_doc)]
4#![allow(clippy::missing_panics_doc)]
5#![allow(clippy::module_name_repetitions)]
6#![allow(clippy::must_use_candidate)]
7#![allow(clippy::return_self_not_must_use)]
8#![allow(clippy::too_many_lines)]
9
10pub use fedimint_mintv2_common as common;
11
12mod api;
13#[cfg(feature = "cli")]
14mod cli;
15mod client_db;
16mod ecash;
17mod event;
18mod input;
19pub mod issuance;
20mod output;
21mod receive;
22
23use std::collections::{BTreeMap, BTreeSet};
24use std::convert::Infallible;
25use std::sync::{Arc, RwLock};
26use std::time::Duration;
27
28use anyhow::{Context as _, anyhow};
29use bitcoin_hashes::sha256;
30use client_db::{RecoveryState, RecoveryStateKey, SpendableNoteAmountPrefix, SpendableNotePrefix};
31pub use event::*;
32use fedimint_api_client::api::DynModuleApi;
33use fedimint_client::module::ClientModule;
34use fedimint_client::transaction::{
35 ClientInput, ClientInputBundle, ClientInputSM, ClientOutput, ClientOutputBundle,
36 ClientOutputSM, TransactionBuilder,
37};
38use fedimint_client_module::db::ClientModuleMigrationFn;
39use fedimint_client_module::module::init::{
40 ClientModuleInit, ClientModuleInitArgs, ClientModuleRecoverArgs,
41};
42use fedimint_client_module::module::recovery::{NoModuleBackup, RecoveryProgress};
43use fedimint_client_module::module::{
44 ClientContext, OutPointRange, PrimaryModulePriority, PrimaryModuleSupport,
45};
46use fedimint_client_module::sm::{Context, DynState, ModuleNotifier, State, StateTransition};
47use fedimint_client_module::{DynGlobalClientContext, sm_enum_variant_translation};
48use fedimint_core::base32::{self, FEDIMINT_PREFIX};
49use fedimint_core::config::FederationId;
50use fedimint_core::core::{IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId};
51use fedimint_core::db::{DatabaseTransaction, DatabaseVersion, IDatabaseTransactionOpsCoreTyped};
52use fedimint_core::encoding::{Decodable, Encodable};
53use fedimint_core::module::{
54 AmountUnit, Amounts, ApiVersion, CommonModuleInit, ModuleCommon, ModuleInit, MultiApiVersion,
55};
56use fedimint_core::secp256k1::rand::{Rng, thread_rng};
57use fedimint_core::secp256k1::{Keypair, PublicKey};
58use fedimint_core::util::{BoxStream, NextOrPending};
59use fedimint_core::{Amount, OutPoint, PeerId, apply, async_trait_maybe_send};
60use fedimint_derive_secret::DerivableSecret;
61use fedimint_mintv2_common::config::{FeeConsensus, MintClientConfig, client_denominations};
62use fedimint_mintv2_common::{
63 Denomination, KIND, MintCommonInit, MintInput, MintModuleTypes, MintOutput, Note, RecoveryItem,
64};
65use futures::{StreamExt, pin_mut};
66use itertools::Itertools;
67use rand::seq::IteratorRandom;
68use serde::{Deserialize, Serialize};
69use serde_json::Value;
70use tbs::AggregatePublicKey;
71use thiserror::Error;
72
73use crate::api::MintV2ModuleApi;
74use crate::client_db::SpendableNoteKey;
75pub use crate::ecash::ECash;
76use crate::input::{InputSMCommon, InputSMState, InputStateMachine};
77use crate::issuance::NoteIssuanceRequest;
78use crate::output::{MintOutputStateMachine, OutputSMCommon, OutputSMState};
79use crate::receive::{ReceiveSMState, ReceiveStateMachine};
80
81const TARGET_PER_DENOMINATION: usize = 3;
82const SLICE_SIZE: u64 = 10000;
83const PARALLEL_HASH_REQUESTS: usize = 10;
84const PARALLEL_SLICE_REQUESTS: usize = 10;
85
86#[derive(Debug, Clone, PartialEq, Eq, Hash, Encodable, Decodable)]
87pub struct SpendableNote {
88 pub denomination: Denomination,
89 pub keypair: Keypair,
90 pub signature: tbs::Signature,
91}
92
93impl SpendableNote {
94 pub fn amount(&self) -> Amount {
95 self.denomination.amount()
96 }
97}
98
99impl SpendableNote {
100 fn nonce(&self) -> PublicKey {
101 self.keypair.public_key()
102 }
103
104 fn note(&self) -> Note {
105 Note {
106 denomination: self.denomination,
107 nonce: self.nonce(),
108 signature: self.signature,
109 }
110 }
111}
112
113#[derive(Debug, Clone, Serialize, Deserialize)]
114pub enum MintOperationMeta {
115 Send {
116 ecash: String,
117 custom_meta: Value,
118 },
119 Reissue {
120 change_outpoint_range: OutPointRange,
121 amount: Amount,
122 custom_meta: Value,
123 },
124 Receive {
125 change_outpoint_range: OutPointRange,
126 ecash: String,
127 custom_meta: Value,
128 },
129}
130
131#[derive(Debug, Clone)]
132pub struct MintClientInit;
133
134impl ModuleInit for MintClientInit {
135 type Common = MintCommonInit;
136
137 async fn dump_database(
138 &self,
139 _dbtx: &mut DatabaseTransaction<'_>,
140 _prefix_names: Vec<String>,
141 ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
142 Box::new(BTreeMap::new().into_iter())
143 }
144}
145
146#[apply(async_trait_maybe_send!)]
147impl ClientModuleInit for MintClientInit {
148 type Module = MintClientModule;
149
150 fn supported_api_versions(&self) -> MultiApiVersion {
151 MultiApiVersion::try_from_iter([ApiVersion { major: 0, minor: 1 }])
152 .expect("no version conflicts")
153 }
154
155 async fn recover(
156 &self,
157 args: &ClientModuleRecoverArgs<Self>,
158 _snapshot: Option<&NoModuleBackup>,
159 ) -> anyhow::Result<()> {
160 let mut state = if let Some(state) = args
161 .db()
162 .begin_transaction_nc()
163 .await
164 .get_value(&RecoveryStateKey)
165 .await
166 {
167 state
168 } else {
169 RecoveryState {
170 next_index: 0,
171 total_items: args.module_api().fetch_recovery_count().await?,
172 requests: BTreeMap::new(),
173 nonces: BTreeSet::new(),
174 }
175 };
176
177 if state.next_index == state.total_items {
178 return Ok(());
179 }
180
181 let peer_selector = PeerSelector::new(args.api().all_peers().clone());
182
183 let mut recovery_stream = futures::stream::iter(
184 (state.next_index..state.total_items).step_by(SLICE_SIZE as usize),
185 )
186 .map(|start| {
187 let api = args.module_api().clone();
188 let end = std::cmp::min(start + SLICE_SIZE, state.total_items);
189
190 async move { (start, end, api.fetch_recovery_slice_hash(start, end).await) }
191 })
192 .buffered(PARALLEL_HASH_REQUESTS)
193 .map(|(start, end, hash)| {
194 download_slice_with_hash(
195 args.module_api().clone(),
196 peer_selector.clone(),
197 start,
198 end,
199 hash,
200 )
201 })
202 .buffered(PARALLEL_SLICE_REQUESTS);
203
204 let tweak_filter = issuance::tweak_filter(args.module_root_secret());
205
206 loop {
207 let items = recovery_stream
208 .next()
209 .await
210 .context("Recovery stream finished before recovery is complete")?;
211
212 for item in &items {
213 match item {
214 RecoveryItem::Output {
215 denomination,
216 nonce_hash,
217 tweak,
218 } => {
219 if !issuance::check_tweak(*tweak, tweak_filter) {
220 continue;
221 }
222 let output_secret = issuance::output_secret(
223 *denomination,
224 *tweak,
225 args.module_root_secret(),
226 );
227
228 if !issuance::check_nonce(&output_secret, *nonce_hash) {
229 continue;
230 }
231
232 let computed_nonce_hash = issuance::nonce(&output_secret).consensus_hash();
233
234 if !state.nonces.insert(computed_nonce_hash) {
236 continue;
237 }
238
239 state.requests.insert(
240 computed_nonce_hash,
241 NoteIssuanceRequest::new(
242 *denomination,
243 *tweak,
244 args.module_root_secret(),
245 ),
246 );
247 }
248 RecoveryItem::Input { nonce_hash } => {
249 state.requests.remove(nonce_hash);
250 state.nonces.remove(nonce_hash);
251 }
252 }
253 }
254
255 state.next_index += items.len() as u64;
256
257 let mut dbtx = args.db().begin_transaction().await;
258
259 dbtx.insert_entry(&RecoveryStateKey, &state).await;
260
261 if state.next_index == state.total_items {
262 let state_machines = args
263 .context()
264 .map_dyn(vec![MintClientStateMachines::Output(
265 MintOutputStateMachine {
266 common: OutputSMCommon {
267 operation_id: OperationId::new_random(),
268 range: None,
269 issuance_requests: state.requests.into_values().collect(),
270 },
271 state: OutputSMState::Pending,
272 },
273 )])
274 .collect();
275
276 args.context()
277 .add_state_machines_dbtx(&mut dbtx.to_ref_nc(), state_machines)
278 .await
279 .expect("state machine is valid");
280
281 dbtx.commit_tx().await;
282
283 return Ok(());
284 }
285
286 dbtx.commit_tx().await;
287
288 args.update_recovery_progress(RecoveryProgress {
289 complete: state.next_index.try_into().unwrap_or(u32::MAX),
290 total: state.total_items.try_into().unwrap_or(u32::MAX),
291 });
292 }
293 }
294
295 async fn init(&self, args: &ClientModuleInitArgs<Self>) -> anyhow::Result<Self::Module> {
296 let (tweak_sender, tweak_receiver) = async_channel::bounded(50);
297
298 let filter = issuance::tweak_filter(args.module_root_secret());
299
300 tokio::task::spawn_blocking(move || {
301 loop {
302 let tweak: [u8; 16] = thread_rng().r#gen();
303
304 if !issuance::check_tweak(tweak, filter) {
305 continue;
306 }
307
308 if tweak_sender.send_blocking(tweak).is_err() {
309 return;
310 }
311 }
312 });
313
314 Ok(MintClientModule {
315 federation_id: *args.federation_id(),
316 cfg: args.cfg().clone(),
317 root_secret: args.module_root_secret().clone(),
318 notifier: args.notifier().clone(),
319 client_ctx: args.context(),
320 balance_update_sender: tokio::sync::watch::channel(()).0,
321 tweak_receiver,
322 })
323 }
324
325 fn get_database_migrations(&self) -> BTreeMap<DatabaseVersion, ClientModuleMigrationFn> {
326 BTreeMap::new()
327 }
328}
329
330#[derive(Debug)]
331pub struct MintClientModule {
332 federation_id: FederationId,
333 cfg: MintClientConfig,
334 root_secret: DerivableSecret,
335 notifier: ModuleNotifier<MintClientStateMachines>,
336 client_ctx: ClientContext<Self>,
337 balance_update_sender: tokio::sync::watch::Sender<()>,
338 tweak_receiver: async_channel::Receiver<[u8; 16]>,
339}
340
341#[derive(Debug, Clone)]
342pub struct MintClientContext {
343 client_ctx: ClientContext<MintClientModule>,
344 tbs_agg_pks: BTreeMap<Denomination, AggregatePublicKey>,
345 tbs_pks: BTreeMap<Denomination, BTreeMap<PeerId, tbs::PublicKeyShare>>,
346 pub balance_update_sender: tokio::sync::watch::Sender<()>,
347}
348
349impl Context for MintClientContext {
350 const KIND: Option<ModuleKind> = Some(KIND);
351}
352
353#[apply(async_trait_maybe_send!)]
354impl ClientModule for MintClientModule {
355 type Init = MintClientInit;
356 type Common = MintModuleTypes;
357 type Backup = NoModuleBackup;
358 type ModuleStateMachineContext = MintClientContext;
359 type States = MintClientStateMachines;
360
361 fn context(&self) -> Self::ModuleStateMachineContext {
362 MintClientContext {
363 client_ctx: self.client_ctx.clone(),
364 tbs_agg_pks: self.cfg.tbs_agg_pks.clone(),
365 tbs_pks: self.cfg.tbs_pks.clone(),
366 balance_update_sender: self.balance_update_sender.clone(),
367 }
368 }
369
370 fn input_fee(
371 &self,
372 amounts: &Amounts,
373 _input: &<Self::Common as ModuleCommon>::Input,
374 ) -> Option<Amounts> {
375 Some(Amounts::new_bitcoin(
376 self.cfg.fee_consensus.fee(amounts.get_bitcoin()),
377 ))
378 }
379
380 fn output_fee(
381 &self,
382 amounts: &Amounts,
383 _output: &<Self::Common as ModuleCommon>::Output,
384 ) -> Option<Amounts> {
385 Some(Amounts::new_bitcoin(
386 self.cfg.fee_consensus.fee(amounts.get_bitcoin()),
387 ))
388 }
389
390 #[cfg(feature = "cli")]
391 async fn handle_cli_command(
392 &self,
393 args: &[std::ffi::OsString],
394 ) -> anyhow::Result<serde_json::Value> {
395 cli::handle_cli_command(self, args).await
396 }
397
398 fn supports_being_primary(&self) -> PrimaryModuleSupport {
399 PrimaryModuleSupport::selected(PrimaryModulePriority::HIGH, [AmountUnit::BITCOIN])
400 }
401
402 async fn create_final_inputs_and_outputs(
403 &self,
404 dbtx: &mut DatabaseTransaction<'_>,
405 operation_id: OperationId,
406 unit: AmountUnit,
407 mut input_amount: Amount,
408 mut output_amount: Amount,
409 ) -> anyhow::Result<(
410 ClientInputBundle<MintInput, MintClientStateMachines>,
411 ClientOutputBundle<MintOutput, MintClientStateMachines>,
412 )> {
413 if unit != AmountUnit::BITCOIN {
414 anyhow::bail!("Module can only handle Bitcoin");
415 }
416
417 let funding_notes = self
418 .select_funding_input(dbtx, output_amount.saturating_sub(input_amount))
419 .await
420 .context("Insufficient funds")?;
421
422 for note in &funding_notes {
423 self.remove_spendable_note(dbtx, note).await;
424 }
425
426 input_amount += funding_notes.iter().map(SpendableNote::amount).sum();
427
428 output_amount += funding_notes
429 .iter()
430 .map(|input| self.cfg.fee_consensus.fee(input.amount()))
431 .sum();
432
433 assert!(output_amount <= input_amount);
434
435 let (input_notes, output_amounts) = self
436 .rebalance(dbtx, &self.cfg.fee_consensus, input_amount - output_amount)
437 .await;
438
439 for note in &input_notes {
440 self.remove_spendable_note(dbtx, note).await;
441 }
442
443 input_amount += input_notes.iter().map(SpendableNote::amount).sum();
444
445 output_amount += input_notes
446 .iter()
447 .map(|note| self.cfg.fee_consensus.fee(note.amount()))
448 .sum();
449
450 output_amount += output_amounts
451 .iter()
452 .map(|denomination| {
453 denomination.amount() + self.cfg.fee_consensus.fee(denomination.amount())
454 })
455 .sum();
456
457 assert!(output_amount <= input_amount);
458
459 let mut spendable_notes = funding_notes
460 .into_iter()
461 .chain(input_notes)
462 .collect::<Vec<SpendableNote>>();
463
464 spendable_notes.sort_by_key(|note| note.denomination);
466
467 let input_bundle = Self::create_input_bundle(operation_id, spendable_notes, false);
468
469 let mut denominations = represent_amount_with_fees(
470 input_amount.saturating_sub(output_amount),
471 &self.cfg.fee_consensus,
472 )
473 .into_iter()
474 .chain(output_amounts)
475 .collect::<Vec<Denomination>>();
476
477 denominations.sort();
479
480 let output_bundle = self.create_output_bundle(operation_id, denominations).await;
481
482 Ok((input_bundle, output_bundle))
483 }
484
485 async fn await_primary_module_output(
486 &self,
487 operation_id: OperationId,
488 outpoint: OutPoint,
489 ) -> anyhow::Result<()> {
490 self.await_output_sm_success(operation_id, outpoint).await
491 }
492
493 async fn get_balance(&self, dbtx: &mut DatabaseTransaction<'_>, unit: AmountUnit) -> Amount {
494 if unit != AmountUnit::BITCOIN {
495 return Amount::ZERO;
496 }
497
498 self.get_count_by_denomination_dbtx(dbtx)
499 .await
500 .into_iter()
501 .map(|(denomination, count)| denomination.amount().mul_u64(count))
502 .sum()
503 }
504
505 async fn subscribe_balance_changes(&self) -> BoxStream<'static, ()> {
506 Box::pin(tokio_stream::wrappers::WatchStream::new(
507 self.balance_update_sender.subscribe(),
508 ))
509 }
510}
511
512impl MintClientModule {
513 async fn select_funding_input(
514 &self,
515 dbtx: &mut DatabaseTransaction<'_>,
516 mut excess_output: Amount,
517 ) -> Option<Vec<SpendableNote>> {
518 let mut selected_notes = Vec::new();
519 let mut target_notes = Vec::new();
520 let mut excess_notes = Vec::new();
521
522 for amount in client_denominations().rev() {
523 let notes_amount = dbtx
524 .find_by_prefix(&SpendableNoteAmountPrefix(amount))
525 .await
526 .map(|entry| entry.0.0)
527 .collect::<Vec<SpendableNote>>()
528 .await;
529
530 target_notes.extend(notes_amount.iter().take(TARGET_PER_DENOMINATION).cloned());
531
532 if notes_amount.len() > 2 * TARGET_PER_DENOMINATION {
533 for note in notes_amount.into_iter().skip(TARGET_PER_DENOMINATION) {
534 let note_fee = self.cfg.fee_consensus.fee(note.amount());
535
536 let note_value = note
537 .amount()
538 .checked_sub(note_fee)
539 .expect("All our notes are economical");
540
541 excess_output = excess_output.saturating_sub(note_value);
542
543 selected_notes.push(note);
544 }
545 } else {
546 excess_notes.extend(notes_amount.into_iter().skip(TARGET_PER_DENOMINATION));
547 }
548 }
549
550 if excess_output == Amount::ZERO {
551 return Some(selected_notes);
552 }
553
554 for note in excess_notes.into_iter().chain(target_notes) {
555 let note_amount = note.amount();
556 let note_value = note_amount
557 .checked_sub(self.cfg.fee_consensus.fee(note_amount))
558 .expect("All our notes are economical");
559
560 excess_output = excess_output.saturating_sub(note_value);
561
562 selected_notes.push(note);
563
564 if excess_output == Amount::ZERO {
565 return Some(selected_notes);
566 }
567 }
568
569 None
570 }
571
572 async fn rebalance(
573 &self,
574 dbtx: &mut DatabaseTransaction<'_>,
575 fee: &FeeConsensus,
576 mut excess_input: Amount,
577 ) -> (Vec<SpendableNote>, Vec<Denomination>) {
578 let n_denominations = self.get_count_by_denomination_dbtx(dbtx).await;
579
580 let mut notes = dbtx
581 .find_by_prefix_sorted_descending(&SpendableNotePrefix)
582 .await
583 .map(|entry| entry.0.0)
584 .fuse();
585
586 let mut input_notes = Vec::new();
587 let mut output_denominations = Vec::new();
588
589 for d in client_denominations() {
590 let n_denomination = n_denominations.get(&d).copied().unwrap_or(0);
591
592 let n_missing = TARGET_PER_DENOMINATION.saturating_sub(n_denomination as usize);
593
594 for _ in 0..n_missing {
595 match excess_input.checked_sub(d.amount() + fee.fee(d.amount())) {
596 Some(remaining_excess) => excess_input = remaining_excess,
597 None => match notes.next().await {
598 Some(note) => {
599 if note.amount() <= d.amount() + fee.fee(d.amount()) {
600 break;
601 }
602
603 excess_input += note.amount() - (d.amount() + fee.fee(d.amount()));
604
605 input_notes.push(note);
606 }
607 None => break,
608 },
609 }
610
611 output_denominations.push(d);
612 }
613 }
614
615 (input_notes, output_denominations)
616 }
617
618 fn create_input_bundle(
619 operation_id: OperationId,
620 notes: Vec<SpendableNote>,
621 include_receive_sm: bool,
622 ) -> ClientInputBundle<MintInput, MintClientStateMachines> {
623 let inputs = notes
624 .iter()
625 .map(|spendable_note| ClientInput {
626 input: MintInput::new_v0(spendable_note.note()),
627 keys: vec![spendable_note.keypair],
628 amounts: Amounts::new_bitcoin(spendable_note.amount()),
629 })
630 .collect();
631
632 let input_sms = vec![ClientInputSM {
633 state_machines: Arc::new(move |range: OutPointRange| {
634 let mut sms = vec![MintClientStateMachines::Input(InputStateMachine {
635 common: InputSMCommon {
636 operation_id,
637 txid: range.txid(),
638 spendable_notes: notes.clone(),
639 },
640 state: InputSMState::Pending,
641 })];
642
643 if include_receive_sm {
644 sms.push(MintClientStateMachines::Receive(ReceiveStateMachine {
645 common: crate::receive::ReceiveSMCommon {
646 operation_id,
647 txid: range.txid(),
648 },
649 state: crate::receive::ReceiveSMState::Pending,
650 }));
651 }
652
653 sms
654 }),
655 }];
656
657 ClientInputBundle::new(inputs, input_sms)
658 }
659
660 async fn create_output_bundle(
661 &self,
662 operation_id: OperationId,
663 requested_denominations: Vec<Denomination>,
664 ) -> ClientOutputBundle<MintOutput, MintClientStateMachines> {
665 let issuance_requests = futures::stream::iter(requested_denominations)
666 .zip(self.tweak_receiver.clone())
667 .map(|(d, tweak)| NoteIssuanceRequest::new(d, tweak, &self.root_secret))
668 .collect::<Vec<NoteIssuanceRequest>>()
669 .await;
670
671 let outputs = issuance_requests
672 .iter()
673 .map(|request| ClientOutput {
674 output: request.output(),
675 amounts: Amounts::new_bitcoin(request.denomination.amount()),
676 })
677 .collect();
678
679 let output_sms = vec![ClientOutputSM {
680 state_machines: Arc::new(move |range: OutPointRange| {
681 vec![MintClientStateMachines::Output(MintOutputStateMachine {
682 common: OutputSMCommon {
683 operation_id,
684 range: Some(range),
685 issuance_requests: issuance_requests.clone(),
686 },
687 state: OutputSMState::Pending,
688 })]
689 }),
690 }];
691
692 ClientOutputBundle::new(outputs, output_sms)
693 }
694
695 async fn await_output_sm_success(
696 &self,
697 operation_id: OperationId,
698 outpoint: OutPoint,
699 ) -> anyhow::Result<()> {
700 let stream = self
701 .notifier
702 .subscribe(operation_id)
703 .await
704 .filter_map(|state| async {
705 let MintClientStateMachines::Output(state) = state else {
706 return None;
707 };
708
709 if !state.common.range?.into_iter().contains(&outpoint) {
710 return None;
711 }
712
713 match state.state {
714 OutputSMState::Pending => None,
715 OutputSMState::Success => Some(Ok(())),
716 OutputSMState::Aborted => Some(Err(anyhow!("Transaction was rejected"))),
717 OutputSMState::Failure => Some(Err(anyhow!("Failed to finalize notes",))),
718 }
719 });
720
721 pin_mut!(stream);
722
723 stream.next_or_pending().await
724 }
725
726 pub async fn get_count_by_denomination(&self) -> BTreeMap<Denomination, u64> {
728 self.get_count_by_denomination_dbtx(
729 &mut self.client_ctx.module_db().begin_transaction_nc().await,
730 )
731 .await
732 }
733
734 async fn get_count_by_denomination_dbtx(
735 &self,
736 dbtx: &mut DatabaseTransaction<'_>,
737 ) -> BTreeMap<Denomination, u64> {
738 dbtx.find_by_prefix(&SpendableNotePrefix)
739 .await
740 .fold(BTreeMap::new(), |mut acc, entry| async move {
741 acc.entry(entry.0.0.denomination)
742 .and_modify(|count| *count += 1)
743 .or_insert(1);
744
745 acc
746 })
747 .await
748 }
749
750 pub async fn send(&self, amount: Amount, custom_meta: Value) -> Result<ECash, SendECashError> {
760 let amount = round_to_multiple(amount, client_denominations().next().unwrap().amount());
761
762 if let Some(ecash) = self
763 .client_ctx
764 .module_db()
765 .autocommit(
766 |dbtx, _| Box::pin(self.send_ecash_dbtx(dbtx, amount, custom_meta.clone())),
767 Some(100),
768 )
769 .await
770 .expect("Failed to commit dbtx after 100 retries")
771 {
772 return Ok(ecash);
773 }
774
775 self.client_ctx
776 .global_api()
777 .session_count()
778 .await
779 .map_err(|_| SendECashError::Offline)?;
780
781 let operation_id = OperationId::new_random();
782
783 let output = self
784 .create_output_bundle(operation_id, represent_amount(amount))
785 .await;
786 let output = self.client_ctx.make_client_outputs(output);
787 let cm = custom_meta.clone();
788
789 let range = self
790 .client_ctx
791 .finalize_and_submit_transaction(
792 operation_id,
793 MintCommonInit::KIND.as_str(),
794 move |change_outpoint_range| MintOperationMeta::Reissue {
795 change_outpoint_range,
796 amount,
797 custom_meta: cm.clone(),
798 },
799 TransactionBuilder::new().with_outputs(output),
800 )
801 .await
802 .map_err(|_| SendECashError::InsufficientBalance)?;
803
804 for outpoint in range {
805 self.await_output_sm_success(operation_id, outpoint)
806 .await
807 .map_err(|_| SendECashError::Failure)?;
808 }
809
810 Box::pin(self.send(amount, custom_meta)).await
811 }
812
813 async fn send_ecash_dbtx(
814 &self,
815 dbtx: &mut DatabaseTransaction<'_>,
816 mut remaining_amount: Amount,
817 custom_meta: Value,
818 ) -> Result<Option<ECash>, Infallible> {
819 let mut stream = dbtx
820 .find_by_prefix_sorted_descending(&SpendableNotePrefix)
821 .await
822 .map(|entry| entry.0.0);
823
824 let mut notes = vec![];
825
826 while let Some(spendable_note) = stream.next().await {
827 remaining_amount = match remaining_amount.checked_sub(spendable_note.amount()) {
828 Some(amount) => amount,
829 None => continue,
830 };
831
832 notes.push(spendable_note);
833 }
834
835 drop(stream);
836
837 if remaining_amount != Amount::ZERO {
838 return Ok(None);
839 }
840
841 for spendable_note in ¬es {
842 self.remove_spendable_note(dbtx, spendable_note).await;
843 }
844
845 let ecash = ECash::new(self.federation_id, notes);
846 let amount = ecash.amount();
847 let operation_id = OperationId::new_random();
848
849 self.client_ctx
850 .add_operation_log_entry_dbtx(
851 dbtx,
852 operation_id,
853 MintCommonInit::KIND.as_str(),
854 MintOperationMeta::Send {
855 ecash: base32::encode_prefixed(FEDIMINT_PREFIX, &ecash),
856 custom_meta,
857 },
858 )
859 .await;
860
861 self.client_ctx
862 .log_event(
863 dbtx,
864 SendPaymentEvent {
865 operation_id,
866 amount,
867 ecash: base32::encode_prefixed(FEDIMINT_PREFIX, &ecash),
868 },
869 )
870 .await;
871
872 Ok(Some(ecash))
873 }
874
875 pub async fn receive(
878 &self,
879 ecash: ECash,
880 custom_meta: Value,
881 ) -> Result<OperationId, ReceiveECashError> {
882 let operation_id = OperationId::from_encodable(&ecash);
883
884 if self.client_ctx.operation_exists(operation_id).await {
885 return Ok(operation_id);
886 }
887
888 if ecash.mint() != Some(self.federation_id) {
889 return Err(ReceiveECashError::WrongFederation);
890 }
891
892 if ecash
893 .notes()
894 .iter()
895 .any(|note| note.amount() <= self.cfg.fee_consensus.base_fee())
896 {
897 return Err(ReceiveECashError::UneconomicalDenomination);
898 }
899
900 let input = Self::create_input_bundle(operation_id, ecash.notes(), true);
901 let input = self.client_ctx.make_client_inputs(input);
902 let ec = base32::encode_prefixed(FEDIMINT_PREFIX, &ecash);
903
904 self.client_ctx
905 .finalize_and_submit_transaction(
906 operation_id,
907 MintCommonInit::KIND.as_str(),
908 move |change_outpoint_range| MintOperationMeta::Receive {
909 change_outpoint_range,
910 ecash: ec.clone(),
911 custom_meta: custom_meta.clone(),
912 },
913 TransactionBuilder::new().with_inputs(input),
914 )
915 .await
916 .map_err(|_| ReceiveECashError::InsufficientFunds)?;
917
918 let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
919
920 self.client_ctx
921 .log_event(
922 &mut dbtx,
923 ReceivePaymentEvent {
924 operation_id,
925 amount: ecash.amount(),
926 },
927 )
928 .await;
929
930 dbtx.commit_tx().await;
931
932 Ok(operation_id)
933 }
934
935 pub async fn await_final_receive_operation_state(
937 &self,
938 operation_id: OperationId,
939 ) -> FinalReceiveOperationState {
940 let mut stream = self.notifier.subscribe(operation_id).await;
941
942 loop {
943 let Some(MintClientStateMachines::Receive(state)) = stream.next().await else {
944 continue;
945 };
946
947 match state.state {
948 ReceiveSMState::Pending => {}
949 ReceiveSMState::Success => return FinalReceiveOperationState::Success,
950 ReceiveSMState::Rejected(..) => return FinalReceiveOperationState::Rejected,
951 }
952 }
953 }
954
955 async fn remove_spendable_note(
956 &self,
957 dbtx: &mut DatabaseTransaction<'_>,
958 spendable_note: &SpendableNote,
959 ) {
960 dbtx.remove_entry(&SpendableNoteKey(spendable_note.clone()))
961 .await
962 .expect("Must delete existing spendable note");
963 }
964}
965
966#[derive(Clone)]
967struct PeerSelector {
968 latency: Arc<RwLock<BTreeMap<PeerId, Duration>>>,
969}
970
971impl PeerSelector {
972 fn new(peers: BTreeSet<PeerId>) -> Self {
973 let latency = peers
974 .into_iter()
975 .map(|peer| (peer, Duration::ZERO))
976 .collect();
977
978 Self {
979 latency: Arc::new(RwLock::new(latency)),
980 }
981 }
982
983 fn choose_peer(&self) -> PeerId {
985 let latency = self.latency.read().unwrap();
986
987 let peer_a = latency.iter().choose(&mut thread_rng()).unwrap();
988 let peer_b = latency.iter().choose(&mut thread_rng()).unwrap();
989
990 if peer_a.1 <= peer_b.1 {
991 *peer_a.0
992 } else {
993 *peer_b.0
994 }
995 }
996
997 fn report(&self, peer: PeerId, duration: Duration) {
999 self.latency
1000 .write()
1001 .unwrap()
1002 .entry(peer)
1003 .and_modify(|latency| *latency = *latency * 9 / 10 + duration * 1 / 10)
1004 .or_insert(duration);
1005 }
1006
1007 fn remove(&self, peer: PeerId) {
1008 self.latency.write().unwrap().remove(&peer);
1009 }
1010}
1011
1012async fn download_slice_with_hash(
1014 module_api: DynModuleApi,
1015 peer_selector: PeerSelector,
1016 start: u64,
1017 end: u64,
1018 expected_hash: sha256::Hash,
1019) -> Vec<RecoveryItem> {
1020 const TIMEOUT: Duration = Duration::from_secs(30);
1021
1022 loop {
1023 let peer = peer_selector.choose_peer();
1024 let start_time = fedimint_core::time::now();
1025
1026 if let Ok(data) = module_api
1027 .fetch_recovery_slice(peer, TIMEOUT, start, end)
1028 .await
1029 {
1030 let elapsed = fedimint_core::time::now()
1031 .duration_since(start_time)
1032 .unwrap_or_default();
1033
1034 peer_selector.report(peer, elapsed);
1035
1036 if data.consensus_hash::<sha256::Hash>() == expected_hash {
1037 return data;
1038 }
1039
1040 peer_selector.remove(peer);
1041 } else {
1042 peer_selector.report(peer, TIMEOUT);
1043 }
1044 }
1045}
1046
1047#[derive(Error, Debug, Clone, Eq, PartialEq)]
1048pub enum SendECashError {
1049 #[error("We need to reissue notes but the client is offline")]
1050 Offline,
1051 #[error("The clients balance is insufficient")]
1052 InsufficientBalance,
1053 #[error("A non-recoverable error has occurred")]
1054 Failure,
1055}
1056
1057#[derive(Error, Debug, Clone, Eq, PartialEq)]
1058pub enum ReceiveECashError {
1059 #[error("The ECash is from a different federation")]
1060 WrongFederation,
1061 #[error("ECash contains an uneconomical denomination")]
1062 UneconomicalDenomination,
1063 #[error("Receiving ecash requires additional funds")]
1064 InsufficientFunds,
1065}
1066
1067#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
1068pub enum FinalReceiveOperationState {
1069 Success,
1071 Rejected,
1073}
1074
1075#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
1076pub enum MintClientStateMachines {
1077 Input(InputStateMachine),
1078 Output(MintOutputStateMachine),
1079 Receive(ReceiveStateMachine),
1080}
1081
1082impl IntoDynInstance for MintClientStateMachines {
1083 type DynType = DynState;
1084
1085 fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
1086 DynState::from_typed(instance_id, self)
1087 }
1088}
1089
1090impl State for MintClientStateMachines {
1091 type ModuleContext = MintClientContext;
1092
1093 fn transitions(
1094 &self,
1095 context: &Self::ModuleContext,
1096 global_context: &DynGlobalClientContext,
1097 ) -> Vec<StateTransition<Self>> {
1098 match self {
1099 MintClientStateMachines::Input(redemption_state) => {
1100 sm_enum_variant_translation!(
1101 redemption_state.transitions(context, global_context),
1102 MintClientStateMachines::Input
1103 )
1104 }
1105 MintClientStateMachines::Output(issuance_state) => {
1106 sm_enum_variant_translation!(
1107 issuance_state.transitions(context, global_context),
1108 MintClientStateMachines::Output
1109 )
1110 }
1111 MintClientStateMachines::Receive(receive_state) => {
1112 sm_enum_variant_translation!(
1113 receive_state.transitions(context, global_context),
1114 MintClientStateMachines::Receive
1115 )
1116 }
1117 }
1118 }
1119
1120 fn operation_id(&self) -> OperationId {
1121 match self {
1122 MintClientStateMachines::Input(redemption_state) => redemption_state.operation_id(),
1123 MintClientStateMachines::Output(issuance_state) => issuance_state.operation_id(),
1124 MintClientStateMachines::Receive(receive_state) => receive_state.operation_id(),
1125 }
1126 }
1127}
1128
1129fn round_to_multiple(amount: Amount, min_denomiation: Amount) -> Amount {
1130 Amount::from_msats(amount.msats.next_multiple_of(min_denomiation.msats))
1131}
1132
1133fn represent_amount_with_fees(
1134 mut remaining_amount: Amount,
1135 fee_consensus: &FeeConsensus,
1136) -> Vec<Denomination> {
1137 let mut denominations = Vec::new();
1138
1139 for denomination in client_denominations().rev() {
1141 let n_add =
1142 remaining_amount / (denomination.amount() + fee_consensus.fee(denomination.amount()));
1143
1144 denominations.extend(std::iter::repeat_n(denomination, n_add as usize));
1145
1146 remaining_amount -=
1147 n_add * (denomination.amount() + fee_consensus.fee(denomination.amount()));
1148 }
1149
1150 denominations.sort();
1152
1153 denominations
1154}
1155
1156fn represent_amount(mut remaining_amount: Amount) -> Vec<Denomination> {
1157 let mut denominations = Vec::new();
1158
1159 for denomination in client_denominations().rev() {
1161 let n_add = remaining_amount / denomination.amount();
1162
1163 denominations.extend(std::iter::repeat_n(denomination, n_add as usize));
1164
1165 remaining_amount -= n_add * denomination.amount();
1166 }
1167
1168 denominations
1169}