Skip to main content

fedimint_mintv2_client/
lib.rs

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;
15pub mod client_db;
16mod ecash;
17mod events;
18mod input;
19pub mod issuance;
20mod migrations;
21mod output;
22mod receive;
23#[cfg(test)]
24mod tests;
25
26use std::collections::{BTreeMap, BTreeSet};
27use std::convert::Infallible;
28use std::sync::Arc;
29use std::time::Duration;
30
31use bitcoin_hashes::sha256;
32use client_db::{RecoveryState, RecoveryStateKey, SpendableNoteAmountPrefix, SpendableNotePrefix};
33pub use events::*;
34use fedimint_api_client::api::DynModuleApi;
35use fedimint_client::module::ClientModule;
36use fedimint_client::transaction::{
37    ClientInput, ClientInputBundle, ClientInputSM, ClientOutput, ClientOutputBundle,
38    ClientOutputSM, FeeQuote, FeeQuoteRequest, TransactionBuilder,
39};
40use fedimint_client_module::db::ClientModuleMigrationFn;
41use fedimint_client_module::error::{
42    ClientModuleError, InsufficientBalanceError, OperationLookupError, TransactionSubmitError,
43};
44use fedimint_client_module::module::init::{
45    ClientModuleInit, ClientModuleInitArgs, ClientModuleRecoverArgs,
46    ClientModuleRecoveryPrepareArgs, RecoveryMode,
47};
48use fedimint_client_module::module::recovery::{NoModuleBackup, RecoveryProgress};
49use fedimint_client_module::module::{
50    AccountSupport, ClientContext, OutPointRange, PrimaryModulePriority, PrimaryModuleSupport,
51};
52use fedimint_client_module::sm::{Context, DynState, ModuleNotifier, State, StateTransition};
53use fedimint_client_module::{DynGlobalClientContext, sm_enum_variant_translation};
54use fedimint_core::base32::{self, FEDIMINT_PREFIX};
55use fedimint_core::config::FederationId;
56use fedimint_core::core::{Account, IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId};
57use fedimint_core::db::{DatabaseTransaction, DatabaseVersion, IDatabaseTransactionOpsCoreTyped};
58use fedimint_core::encoding::{Decodable, DecodeError, Encodable};
59use fedimint_core::module::registry::ModuleDecoderRegistry;
60use fedimint_core::module::{
61    AmountUnit, Amounts, ApiVersion, CommonModuleInit, ModuleCommon, ModuleInit, MultiApiVersion,
62};
63use fedimint_core::secp256k1::rand::{Rng, thread_rng};
64use fedimint_core::secp256k1::{Keypair, PublicKey};
65use fedimint_core::util::backoff_util::custom_backoff;
66use fedimint_core::util::{BoxStream, NextOrPending};
67use fedimint_core::{Amount, OutPoint, PeerId, apply, async_trait_maybe_send};
68use fedimint_derive_secret::DerivableSecret;
69use fedimint_mintv2_common::config::{FeeConsensus, MintClientConfig, client_denominations};
70use fedimint_mintv2_common::{
71    Denomination, KIND, MintCommonInit, MintInput, MintModuleTypes, MintOutput, Note, RecoveryItem,
72};
73use futures::{StreamExt, pin_mut};
74use itertools::Itertools;
75use serde::{Deserialize, Serialize};
76use serde_json::Value;
77use tbs::AggregatePublicKey;
78use thiserror::Error;
79
80use crate::api::MintV2ModuleApi;
81use crate::client_db::SpendableNoteKey;
82pub use crate::ecash::ECash;
83use crate::input::{InputSMCommon, InputSMState, InputStateMachine};
84use crate::issuance::NoteIssuanceRequest;
85use crate::output::{MintOutputStateMachine, OutputSMCommon, OutputSMState};
86use crate::receive::{ReceiveSMState, ReceiveStateMachine};
87
88const TARGET_PER_DENOMINATION: usize = 3;
89const SLICE_SIZE: u64 = 10000;
90/// How long a guardian sits out after failing to answer a slice request.
91const PEER_READMISSION: Duration = Duration::from_secs(60);
92/// How long a single peer is given to answer a slice request.
93///
94/// A slice takes a second or two from a healthy guardian, so waiting half a
95/// minute only delays noticing that one is not going to answer. The timeout
96/// grows on every failed attempt up to [`MAX_SLICE_TIMEOUT`], so a client
97/// on a slow connection where every guardian exceeds the initial timeout
98/// still makes progress instead of retrying forever.
99const SLICE_TIMEOUT: Duration = Duration::from_secs(10);
100/// Upper bound for the per-retry growth of [`SLICE_TIMEOUT`]; the flat
101/// timeout used before the growth was introduced.
102const MAX_SLICE_TIMEOUT: Duration = Duration::from_secs(30);
103const PARALLEL_HASH_REQUESTS: usize = 10;
104const PARALLEL_SLICE_REQUESTS: usize = 10;
105
106#[derive(Debug, Clone, PartialEq, Eq, Hash, Encodable, Decodable)]
107pub struct SpendableNote {
108    pub denomination: Denomination,
109    pub keypair: Keypair,
110    pub signature: tbs::Signature,
111}
112
113impl SpendableNote {
114    pub fn amount(&self) -> Amount {
115        self.denomination.amount()
116    }
117}
118
119impl SpendableNote {
120    fn nonce(&self) -> PublicKey {
121        self.keypair.public_key()
122    }
123
124    fn note(&self) -> Note {
125        Note {
126            denomination: self.denomination,
127            nonce: self.nonce(),
128            signature: self.signature,
129        }
130    }
131}
132
133/// A [`SpendableNote`] whose signature is not decoded yet, with the same
134/// encoding.
135///
136/// Decoding a [`tbs::Signature`] decompresses and subgroup-checks a curve
137/// point, which is expensive, and every spend reads far more notes than it
138/// spends. Reading the note table as this type defers that cost to the notes
139/// actually selected. Since not every byte string is a valid signature it is
140/// only for reading the client's own database; [`Self::decode`] validates.
141#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable)]
142pub struct SpendableNoteUndecoded {
143    pub denomination: Denomination,
144    pub keypair: Keypair,
145    // Must stay in sync with the encoding of `tbs::Signature`, which a test
146    // verifies.
147    pub signature: [u8; 48],
148}
149
150impl SpendableNoteUndecoded {
151    pub fn amount(&self) -> Amount {
152        self.denomination.amount()
153    }
154
155    pub fn decode(self) -> Result<SpendableNote, DecodeError> {
156        Ok(SpendableNote {
157            denomination: self.denomination,
158            keypair: self.keypair,
159            signature: Decodable::consensus_decode_whole(
160                &self.signature,
161                &ModuleDecoderRegistry::default(),
162            )?,
163        })
164    }
165
166    fn decode_own(self) -> SpendableNote {
167        self.decode()
168            .expect("Notes in our own database were encoded from valid signatures")
169    }
170}
171
172impl From<SpendableNote> for SpendableNoteUndecoded {
173    fn from(note: SpendableNote) -> Self {
174        Self {
175            denomination: note.denomination,
176            keypair: note.keypair,
177            signature: note.signature.0.to_compressed(),
178        }
179    }
180}
181
182#[derive(Debug, Clone, Serialize, Deserialize)]
183pub enum MintOperationMeta {
184    Send {
185        ecash: String,
186        custom_meta: Value,
187    },
188    Reissue {
189        change_outpoint_range: OutPointRange,
190        amount: Amount,
191        custom_meta: Value,
192    },
193    Receive {
194        change_outpoint_range: OutPointRange,
195        ecash: String,
196        custom_meta: Value,
197    },
198}
199
200#[derive(Debug, Clone)]
201pub struct MintClientInit;
202
203impl ModuleInit for MintClientInit {
204    type Common = MintCommonInit;
205
206    async fn dump_database(
207        &self,
208        _dbtx: &mut DatabaseTransaction<'_>,
209        _prefix_names: Vec<String>,
210    ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
211        Box::new(BTreeMap::new().into_iter())
212    }
213}
214
215#[apply(async_trait_maybe_send!)]
216impl ClientModuleInit for MintClientInit {
217    type Module = MintClientModule;
218
219    fn supported_api_versions(&self) -> MultiApiVersion {
220        MultiApiVersion::try_from_iter([ApiVersion { major: 0, minor: 1 }])
221            .expect("no version conflicts")
222    }
223
224    fn recovery_mode(&self) -> RecoveryMode {
225        RecoveryMode::Usable
226    }
227
228    async fn prepare_recovery(
229        &self,
230        args: &ClientModuleRecoveryPrepareArgs,
231    ) -> Result<(), ClientModuleError> {
232        if args
233            .db()
234            .begin_transaction_nc()
235            .await
236            .get_value(&RecoveryStateKey)
237            .await
238            .is_some()
239        {
240            return Ok(());
241        }
242
243        // The total is the number of items the federation had processed when
244        // the recovery began, so every note this client issues from here on
245        // lands beyond it and is never rediscovered by the scan. Committing
246        // that bound before the module is initialized is what lets the module
247        // be used while its own recovery is still running: the two cannot
248        // arrive at the same note.
249        let state = RecoveryState {
250            next_index: 0,
251            total_items: args
252                .module_api()
253                .fetch_recovery_count()
254                .await
255                .map_err(ClientModuleError::other)?,
256            requests: BTreeMap::new(),
257            nonces: BTreeSet::new(),
258        };
259
260        let mut dbtx = args.db().begin_transaction().await;
261
262        dbtx.insert_entry(&RecoveryStateKey, &state).await;
263
264        dbtx.commit_tx().await;
265
266        Ok(())
267    }
268
269    async fn recover(
270        &self,
271        args: &ClientModuleRecoverArgs<Self>,
272        _snapshot: Option<&NoModuleBackup>,
273    ) -> Result<Option<Amount>, ClientModuleError> {
274        let mut state = args
275            .db()
276            .begin_transaction_nc()
277            .await
278            .get_value(&RecoveryStateKey)
279            .await
280            .expect("Prepare recovery commits the state before the recovery is started");
281
282        if state.next_index == state.total_items {
283            return Ok(None);
284        }
285
286        let peer_pool = PeerPool::new(args.api().all_peers());
287
288        let mut recovery_stream = futures::stream::iter(
289            (state.next_index..state.total_items).step_by(SLICE_SIZE as usize),
290        )
291        .map(|start| {
292            let api = args.module_api().clone();
293            let end = std::cmp::min(start + SLICE_SIZE, state.total_items);
294
295            async move { (start, end, api.fetch_recovery_slice_hash(start, end).await) }
296        })
297        .buffered(PARALLEL_HASH_REQUESTS)
298        .map(|(start, end, hash)| {
299            let module_api = args.module_api().clone();
300            let peer_pool = peer_pool.clone();
301
302            async move {
303                (
304                    start,
305                    download_slice(module_api, peer_pool, start, end, hash).await,
306                )
307            }
308        })
309        // Unordered, so a guardian that goes quiet holds up only its own
310        // slice. Delivering in order would let it halt everything: the other
311        // requests would finish, their results would fill the buffer, and no
312        // new request could start until the straggler returned. Downloading
313        // runs ahead of it instead, and the items are put back in order below.
314        .buffer_unordered(PARALLEL_SLICE_REQUESTS);
315
316        // One filter for the whole wallet, so a candidate is found in a single
317        // pass and only then tried against each account's nonces.
318        let tweak_filter = issuance::tweak_filter(args.module_root_secret());
319
320        // Slices that arrived before the ones in front of them. An input
321        // spends an output that has to have been seen already, so items are
322        // scanned in index order however they turn up. This holds whatever
323        // downloaded while a slice was outstanding, which the timeout bounds.
324        let mut pending: BTreeMap<u64, Vec<RecoveryItem>> = BTreeMap::new();
325
326        loop {
327            let items = loop {
328                if let Some(items) = pending.remove(&state.next_index) {
329                    break items;
330                }
331
332                let (start, items) = recovery_stream.next().await.ok_or_else(|| {
333                    ClientModuleError::other("Recovery stream finished before recovery is complete")
334                })?;
335
336                pending.insert(start, items);
337            };
338
339            for item in &items {
340                match item {
341                    RecoveryItem::Output {
342                        denomination,
343                        nonce_hash,
344                        tweak,
345                    } => {
346                        if !issuance::check_tweak(*tweak, tweak_filter) {
347                            continue;
348                        }
349
350                        // Only the ~1/65536 of outputs that pass the filter get
351                        // here, so trying every account costs a handful of
352                        // derivations per candidate rather than per output.
353                        for account in Account::ALL {
354                            let output_secret = issuance::output_secret(
355                                account,
356                                *denomination,
357                                *tweak,
358                                args.module_root_secret(),
359                            );
360
361                            if !issuance::check_nonce(&output_secret, *nonce_hash) {
362                                continue;
363                            }
364
365                            let computed_nonce_hash =
366                                issuance::nonce(&output_secret).consensus_hash();
367
368                            // Ignore possible duplicate nonces
369                            if !state.nonces.insert(computed_nonce_hash) {
370                                continue;
371                            }
372
373                            state.requests.insert(
374                                computed_nonce_hash,
375                                (
376                                    account,
377                                    NoteIssuanceRequest::new(
378                                        account,
379                                        *denomination,
380                                        *tweak,
381                                        args.module_root_secret(),
382                                    ),
383                                ),
384                            );
385
386                            // A nonce belongs to exactly one account.
387                            break;
388                        }
389                    }
390                    RecoveryItem::Input { nonce_hash } => {
391                        state.requests.remove(nonce_hash);
392                        state.nonces.remove(nonce_hash);
393                    }
394                }
395            }
396
397            state.next_index += items.len() as u64;
398
399            let mut dbtx = args.db().begin_transaction().await;
400
401            dbtx.insert_entry(&RecoveryStateKey, &state).await;
402
403            if state.next_index == state.total_items {
404                // Total value of the notes reconstructed during recovery
405                let recovered_amount = state
406                    .requests
407                    .values()
408                    .map(|(_, request)| request.denomination.amount())
409                    .sum::<Amount>();
410
411                // A state machine credits its notes to its operation's
412                // account, so the scan's requests are split by account into
413                // one operation each, with the account recorded up front.
414                let mut requests_by_account: BTreeMap<Account, Vec<NoteIssuanceRequest>> =
415                    BTreeMap::new();
416
417                for (account, request) in state.requests.into_values() {
418                    requests_by_account
419                        .entry(account)
420                        .or_default()
421                        .push(request);
422                }
423
424                let mut state_machines = Vec::new();
425
426                for (account, issuance_requests) in requests_by_account {
427                    let operation_id = OperationId::new_random();
428
429                    args.context()
430                        .set_operation_account_dbtx(&mut dbtx.to_ref_nc(), operation_id, account)
431                        .await;
432
433                    state_machines.push(MintClientStateMachines::Output(MintOutputStateMachine {
434                        common: OutputSMCommon {
435                            operation_id,
436                            range: None,
437                            issuance_requests,
438                        },
439                        state: OutputSMState::Pending,
440                    }));
441                }
442
443                let state_machines = args.context().map_dyn(state_machines).collect();
444
445                args.context()
446                    .add_state_machines_dbtx(&mut dbtx.to_ref_nc(), state_machines)
447                    .await
448                    .expect("state machine is valid");
449
450                dbtx.commit_tx().await;
451
452                return Ok(Some(recovered_amount));
453            }
454
455            dbtx.commit_tx().await;
456
457            args.update_recovery_progress(RecoveryProgress {
458                complete: state.next_index.try_into().unwrap_or(u32::MAX),
459                total: state.total_items.try_into().unwrap_or(u32::MAX),
460            });
461        }
462    }
463
464    async fn init(
465        &self,
466        args: &ClientModuleInitArgs<Self>,
467    ) -> Result<Self::Module, ClientModuleError> {
468        let (tweak_sender, tweak_receiver) = async_channel::bounded(50);
469
470        let filter = issuance::tweak_filter(args.module_root_secret());
471
472        // Only ~1/65536 random tweaks pass the filter, so grinding is
473        // CPU-bound. Pre-grind in the background and feed tweaks through a
474        // channel to keep the cost off the spend path. `send` only suspends
475        // once the channel is full, so we yield explicitly on each found tweak
476        // to keep single-threaded (wasm) runtimes responsive while the channel
477        // still has space.
478        fedimint_core::task::spawn("mintv2-tweak-grinder", async move {
479            loop {
480                let tweak: [u8; 16] = thread_rng().r#gen();
481
482                if !issuance::check_tweak(tweak, filter) {
483                    continue;
484                }
485
486                if tweak_sender.send(tweak).await.is_err() {
487                    return;
488                }
489
490                fedimint_core::task::sleep(Duration::ZERO).await;
491            }
492        });
493
494        Ok(MintClientModule {
495            federation_id: *args.federation_id(),
496            cfg: args.cfg().clone(),
497            root_secret: args.module_root_secret().clone(),
498            notifier: args.notifier().clone(),
499            client_ctx: args.context(),
500            balance_update_sender: tokio::sync::watch::channel(()).0,
501            tweak_receiver,
502        })
503    }
504
505    fn get_database_migrations(&self) -> BTreeMap<DatabaseVersion, ClientModuleMigrationFn> {
506        let mut migrations: BTreeMap<DatabaseVersion, ClientModuleMigrationFn> = BTreeMap::new();
507
508        migrations.insert(DatabaseVersion(0), |dbtx, active, inactive| {
509            Box::pin(migrations::migrate_to_accounts_v1(dbtx, active, inactive))
510        });
511
512        migrations
513    }
514}
515
516#[derive(Debug)]
517pub struct MintClientModule {
518    federation_id: FederationId,
519    cfg: MintClientConfig,
520    root_secret: DerivableSecret,
521    notifier: ModuleNotifier<MintClientStateMachines>,
522    client_ctx: ClientContext<Self>,
523    balance_update_sender: tokio::sync::watch::Sender<()>,
524    tweak_receiver: async_channel::Receiver<[u8; 16]>,
525}
526
527#[derive(Debug, Clone)]
528pub struct MintClientContext {
529    client_ctx: ClientContext<MintClientModule>,
530    tbs_agg_pks: BTreeMap<Denomination, AggregatePublicKey>,
531    tbs_pks: BTreeMap<Denomination, BTreeMap<PeerId, tbs::PublicKeyShare>>,
532    pub balance_update_sender: tokio::sync::watch::Sender<()>,
533}
534
535impl Context for MintClientContext {
536    const KIND: Option<ModuleKind> = Some(KIND);
537}
538
539#[apply(async_trait_maybe_send!)]
540impl ClientModule for MintClientModule {
541    type Init = MintClientInit;
542    type Common = MintModuleTypes;
543    type Backup = NoModuleBackup;
544    type ModuleStateMachineContext = MintClientContext;
545    type States = MintClientStateMachines;
546
547    fn context(&self) -> Self::ModuleStateMachineContext {
548        MintClientContext {
549            client_ctx: self.client_ctx.clone(),
550            tbs_agg_pks: self.cfg.tbs_agg_pks.clone(),
551            tbs_pks: self.cfg.tbs_pks.clone(),
552            balance_update_sender: self.balance_update_sender.clone(),
553        }
554    }
555
556    fn input_fee(
557        &self,
558        amounts: &Amounts,
559        _input: &<Self::Common as ModuleCommon>::Input,
560    ) -> Option<Amounts> {
561        let unit = self.cfg.amount_unit;
562        let amount = amounts.get(&unit).copied().unwrap_or_default();
563        let fee = self.cfg.fee_consensus.fee(amount);
564
565        Some(Amounts::new_custom(unit, fee))
566    }
567
568    fn output_fee(
569        &self,
570        amounts: &Amounts,
571        _output: &<Self::Common as ModuleCommon>::Output,
572    ) -> Option<Amounts> {
573        let unit = self.cfg.amount_unit;
574        let amount = amounts.get(&unit).copied().unwrap_or_default();
575        let fee = self.cfg.fee_consensus.fee(amount);
576
577        Some(Amounts::new_custom(unit, fee))
578    }
579
580    #[cfg(feature = "cli")]
581    async fn handle_cli_command(
582        &self,
583        args: &[std::ffi::OsString],
584    ) -> Result<serde_json::Value, ClientModuleError> {
585        cli::handle_cli_command(self, args)
586            .await
587            .map_err(ClientModuleError::other)
588    }
589
590    fn supports_being_primary(&self) -> PrimaryModuleSupport {
591        PrimaryModuleSupport::selected(
592            PrimaryModulePriority::HIGH,
593            [self.cfg.amount_unit],
594            AccountSupport::All,
595        )
596    }
597
598    async fn create_final_inputs_and_outputs(
599        &self,
600        dbtx: &mut DatabaseTransaction<'_>,
601        operation_id: OperationId,
602        unit: AmountUnit,
603        input_amount: Amount,
604        output_amount: Amount,
605        account: Account,
606    ) -> Result<
607        (
608            ClientInputBundle<MintInput, MintClientStateMachines>,
609            ClientOutputBundle<MintOutput, MintClientStateMachines>,
610        ),
611        ClientModuleError,
612    > {
613        let (notes, denominations) = self
614            .select_inputs_and_change(dbtx, unit, input_amount, output_amount, account)
615            .await?;
616        let inputs = Self::create_input_bundle(operation_id, notes, false, self.cfg.amount_unit);
617        let outputs = self
618            .create_output_bundle(account, operation_id, denominations)
619            .await;
620        let sender = self.balance_update_sender.clone();
621        dbtx.on_commit(move || sender.send_replace(()));
622        Ok((inputs, outputs))
623    }
624
625    async fn quote_final_inputs_and_outputs(
626        &self,
627        dbtx: &mut DatabaseTransaction<'_>,
628        _operation_id: OperationId,
629        unit: AmountUnit,
630        input_amount: Amount,
631        output_amount: Amount,
632        account: Account,
633    ) -> Result<FeeQuoteRequest, ClientModuleError> {
634        let (notes, denominations) = self
635            .select_inputs_and_change(dbtx, unit, input_amount, output_amount, account)
636            .await?;
637        Ok(FeeQuoteRequest {
638            input_amount: Amounts::new_custom(unit, notes.iter().map(SpendableNote::amount).sum()),
639            output_amount: Amounts::new_custom(
640                unit,
641                denominations.iter().map(|d| d.amount()).sum(),
642            ),
643            input_fee: Amounts::new_custom(
644                unit,
645                notes
646                    .iter()
647                    .map(|note| self.cfg.fee_consensus.fee(note.amount()))
648                    .sum(),
649            ),
650            output_fee: Amounts::new_custom(
651                unit,
652                denominations
653                    .iter()
654                    .map(|d| self.cfg.fee_consensus.fee(d.amount()))
655                    .sum(),
656            ),
657            account,
658        })
659    }
660
661    async fn await_primary_module_output(
662        &self,
663        operation_id: OperationId,
664        outpoint: OutPoint,
665    ) -> Result<(), ClientModuleError> {
666        self.await_output_sm_success(operation_id, outpoint)
667            .await
668            .map_err(ClientModuleError::other)
669    }
670
671    async fn get_balance(
672        &self,
673        dbtx: &mut DatabaseTransaction<'_>,
674        unit: AmountUnit,
675        account: Account,
676    ) -> Amount {
677        if unit != self.cfg.amount_unit {
678            return Amount::ZERO;
679        }
680
681        self.get_count_by_denomination_dbtx(dbtx, account)
682            .await
683            .into_iter()
684            .map(|(denomination, count)| denomination.amount().mul_u64(count))
685            .sum()
686    }
687
688    async fn subscribe_balance_changes(&self) -> BoxStream<'static, ()> {
689        Box::pin(tokio_stream::wrappers::WatchStream::new(
690            self.balance_update_sender.subscribe(),
691        ))
692    }
693}
694
695impl MintClientModule {
696    async fn select_inputs_and_change(
697        &self,
698        dbtx: &mut DatabaseTransaction<'_>,
699        unit: AmountUnit,
700        mut input_amount: Amount,
701        mut output_amount: Amount,
702        account: Account,
703    ) -> Result<(Vec<SpendableNote>, Vec<Denomination>), ClientModuleError> {
704        if unit != self.cfg.amount_unit {
705            return Err(ClientModuleError::other(
706                "Module can only handle its configured amount unit",
707            ));
708        }
709
710        let requested_amount = output_amount.saturating_sub(input_amount);
711        // `select_funding_input` only reads notes, so the balance it left behind is
712        // still accurate for reporting a total below.
713        let Some(funding_notes) = self
714            .select_funding_input(dbtx, account, requested_amount)
715            .await
716        else {
717            let total_amount = self.get_balance(dbtx, unit, account).await;
718            return Err(InsufficientBalanceError {
719                requested_amount,
720                total_amount,
721            }
722            .into());
723        };
724
725        for note in &funding_notes {
726            self.remove_spendable_note(dbtx, account, note).await;
727        }
728
729        input_amount += funding_notes.iter().map(SpendableNote::amount).sum();
730
731        output_amount += funding_notes
732            .iter()
733            .map(|input| self.cfg.fee_consensus.fee(input.amount()))
734            .sum();
735
736        assert!(output_amount <= input_amount);
737
738        let (input_notes, output_amounts) = self
739            .rebalance(
740                dbtx,
741                account,
742                &self.cfg.fee_consensus,
743                input_amount - output_amount,
744            )
745            .await;
746
747        for note in &input_notes {
748            self.remove_spendable_note(dbtx, account, note).await;
749        }
750
751        input_amount += input_notes.iter().map(SpendableNote::amount).sum();
752
753        output_amount += input_notes
754            .iter()
755            .map(|note| self.cfg.fee_consensus.fee(note.amount()))
756            .sum();
757
758        output_amount += output_amounts
759            .iter()
760            .map(|denomination| {
761                denomination.amount() + self.cfg.fee_consensus.fee(denomination.amount())
762            })
763            .sum();
764
765        assert!(output_amount <= input_amount);
766
767        let mut spendable_notes = funding_notes
768            .into_iter()
769            .chain(input_notes)
770            .collect::<Vec<SpendableNote>>();
771
772        // We sort the notes by denomination to minimize the leaked information.
773        spendable_notes.sort_by_key(|note| note.denomination);
774
775        let mut denominations = represent_amount_with_fees(
776            input_amount.saturating_sub(output_amount),
777            &self.cfg.fee_consensus,
778        )
779        .into_iter()
780        .chain(output_amounts)
781        .collect::<Vec<Denomination>>();
782
783        // We sort the amounts to minimize the leaked information.
784        denominations.sort();
785
786        Ok((spendable_notes, denominations))
787    }
788
789    async fn select_funding_input(
790        &self,
791        dbtx: &mut DatabaseTransaction<'_>,
792        account: Account,
793        mut excess_output: Amount,
794    ) -> Option<Vec<SpendableNote>> {
795        let mut selected_notes = Vec::new();
796        let mut target_notes = Vec::new();
797        let mut excess_notes = Vec::new();
798
799        for amount in client_denominations().rev() {
800            let notes_amount = dbtx
801                .find_by_prefix(&SpendableNoteAmountPrefix(account, amount))
802                .await
803                .map(|entry| entry.0.1)
804                .collect::<Vec<SpendableNoteUndecoded>>()
805                .await;
806
807            target_notes.extend(notes_amount.iter().take(TARGET_PER_DENOMINATION).copied());
808
809            if notes_amount.len() > 2 * TARGET_PER_DENOMINATION {
810                for note in notes_amount.into_iter().skip(TARGET_PER_DENOMINATION) {
811                    let note_fee = self.cfg.fee_consensus.fee(note.amount());
812
813                    let note_value = note
814                        .amount()
815                        .checked_sub(note_fee)
816                        .expect("All our notes are economical");
817
818                    excess_output = excess_output.saturating_sub(note_value);
819
820                    selected_notes.push(note);
821                }
822            } else {
823                excess_notes.extend(notes_amount.into_iter().skip(TARGET_PER_DENOMINATION));
824            }
825        }
826
827        if excess_output == Amount::ZERO {
828            return Some(
829                selected_notes
830                    .into_iter()
831                    .map(SpendableNoteUndecoded::decode_own)
832                    .collect(),
833            );
834        }
835
836        for note in excess_notes.into_iter().chain(target_notes) {
837            let note_amount = note.amount();
838            let note_value = note_amount
839                .checked_sub(self.cfg.fee_consensus.fee(note_amount))
840                .expect("All our notes are economical");
841
842            excess_output = excess_output.saturating_sub(note_value);
843
844            selected_notes.push(note);
845
846            if excess_output == Amount::ZERO {
847                return Some(
848                    selected_notes
849                        .into_iter()
850                        .map(SpendableNoteUndecoded::decode_own)
851                        .collect(),
852                );
853            }
854        }
855
856        None
857    }
858
859    async fn rebalance(
860        &self,
861        dbtx: &mut DatabaseTransaction<'_>,
862        account: Account,
863        fee: &FeeConsensus,
864        mut excess_input: Amount,
865    ) -> (Vec<SpendableNote>, Vec<Denomination>) {
866        let n_denominations = self.get_count_by_denomination_dbtx(dbtx, account).await;
867
868        let mut notes = dbtx
869            .find_by_prefix_sorted_descending(&SpendableNotePrefix(account))
870            .await
871            .map(|entry| entry.0.1)
872            .fuse();
873
874        let mut input_notes = Vec::new();
875        let mut output_denominations = Vec::new();
876
877        for d in client_denominations() {
878            let n_denomination = n_denominations.get(&d).copied().unwrap_or(0);
879
880            let n_missing = TARGET_PER_DENOMINATION.saturating_sub(n_denomination as usize);
881
882            for _ in 0..n_missing {
883                match excess_input.checked_sub(d.amount() + fee.fee(d.amount())) {
884                    Some(remaining_excess) => excess_input = remaining_excess,
885                    None => match notes.next().await {
886                        Some(note) => {
887                            if note.amount() <= d.amount() + fee.fee(d.amount()) {
888                                break;
889                            }
890
891                            excess_input += note.amount() - (d.amount() + fee.fee(d.amount()));
892
893                            input_notes.push(note.decode_own());
894                        }
895                        None => break,
896                    },
897                }
898
899                output_denominations.push(d);
900            }
901        }
902
903        (input_notes, output_denominations)
904    }
905
906    fn create_input_bundle(
907        operation_id: OperationId,
908        notes: Vec<SpendableNote>,
909        include_receive_sm: bool,
910        amount_unit: AmountUnit,
911    ) -> ClientInputBundle<MintInput, MintClientStateMachines> {
912        let inputs = notes
913            .iter()
914            .map(|spendable_note| ClientInput {
915                input: MintInput::new_v0(spendable_note.note()),
916                keys: vec![spendable_note.keypair],
917                amounts: Amounts::new_custom(amount_unit, spendable_note.amount()),
918            })
919            .collect();
920
921        let input_sms = vec![ClientInputSM {
922            state_machines: Arc::new(move |range: OutPointRange| {
923                let mut sms = vec![MintClientStateMachines::Input(InputStateMachine {
924                    common: InputSMCommon {
925                        operation_id,
926                        txid: range.txid(),
927                        spendable_notes: notes.clone(),
928                    },
929                    state: InputSMState::Pending,
930                })];
931
932                if include_receive_sm {
933                    sms.push(MintClientStateMachines::Receive(ReceiveStateMachine {
934                        common: crate::receive::ReceiveSMCommon {
935                            operation_id,
936                            txid: range.txid(),
937                        },
938                        state: crate::receive::ReceiveSMState::Pending,
939                    }));
940                }
941
942                sms
943            }),
944        }];
945
946        ClientInputBundle::new(inputs, input_sms)
947    }
948
949    /// Build the blinded outputs and their output state machines for a
950    /// reissue transaction.
951    ///
952    /// # Cancel safety
953    ///
954    /// Cancel safe: this only reads pre-ground blinding tweaks from an
955    /// in-memory channel and constructs values, it performs no database
956    /// writes. Dropping the future merely discards the tweaks it had taken,
957    /// which are random (so nothing is lost) and replenished by the
958    /// background grinder task.
959    async fn create_output_bundle(
960        &self,
961        account: Account,
962        operation_id: OperationId,
963        requested_denominations: Vec<Denomination>,
964    ) -> ClientOutputBundle<MintOutput, MintClientStateMachines> {
965        let issuance_requests = futures::stream::iter(requested_denominations)
966            .zip(self.tweak_receiver.clone())
967            .map(|(d, tweak)| NoteIssuanceRequest::new(account, d, tweak, &self.root_secret))
968            .collect::<Vec<NoteIssuanceRequest>>()
969            .await;
970
971        let amount_unit = self.cfg.amount_unit;
972        let outputs = issuance_requests
973            .iter()
974            .map(|request| ClientOutput {
975                output: request.output(),
976                amounts: Amounts::new_custom(amount_unit, request.denomination.amount()),
977            })
978            .collect();
979
980        let output_sms = vec![ClientOutputSM {
981            state_machines: Arc::new(move |range: OutPointRange| {
982                vec![MintClientStateMachines::Output(MintOutputStateMachine {
983                    common: OutputSMCommon {
984                        operation_id,
985                        range: Some(range),
986                        issuance_requests: issuance_requests.clone(),
987                    },
988                    state: OutputSMState::Pending,
989                })]
990            }),
991        }];
992
993        ClientOutputBundle::new(outputs, output_sms)
994    }
995
996    /// Wait for the output state machine of the given outpoint to reach a
997    /// terminal state.
998    ///
999    /// # Cancel safety
1000    ///
1001    /// Cancel safe: this only subscribes to the operation's state
1002    /// notifications and waits, it performs no database writes. Dropping the
1003    /// future stops the wait; the underlying state machine keeps running in
1004    /// the executor.
1005    async fn await_output_sm_success(
1006        &self,
1007        operation_id: OperationId,
1008        outpoint: OutPoint,
1009    ) -> Result<(), AwaitOutputError> {
1010        let stream = self
1011            .notifier
1012            .subscribe(operation_id)
1013            .await
1014            .filter_map(|state| async {
1015                let MintClientStateMachines::Output(state) = state else {
1016                    return None;
1017                };
1018
1019                if !state.common.range?.into_iter().contains(&outpoint) {
1020                    return None;
1021                }
1022
1023                match state.state {
1024                    OutputSMState::Pending => None,
1025                    OutputSMState::Success => Some(Ok(())),
1026                    OutputSMState::Aborted => Some(Err(AwaitOutputError::Rejected)),
1027                    OutputSMState::Failure => Some(Err(AwaitOutputError::Failed)),
1028                }
1029            });
1030
1031        pin_mut!(stream);
1032
1033        stream.next_or_pending().await
1034    }
1035
1036    /// Count the `ECash` notes an account holds by denomination.
1037    pub async fn get_count_by_denomination(&self, account: Account) -> BTreeMap<Denomination, u64> {
1038        self.get_count_by_denomination_dbtx(
1039            &mut self.client_ctx.module_db().begin_transaction_nc().await,
1040            account,
1041        )
1042        .await
1043    }
1044
1045    async fn get_count_by_denomination_dbtx(
1046        &self,
1047        dbtx: &mut DatabaseTransaction<'_>,
1048        account: Account,
1049    ) -> BTreeMap<Denomination, u64> {
1050        dbtx.find_by_prefix(&SpendableNotePrefix(account))
1051            .await
1052            .fold(BTreeMap::new(), |mut acc, entry| async move {
1053                acc.entry(entry.0.1.denomination)
1054                    .and_modify(|count| *count += 1)
1055                    .or_insert(1);
1056
1057                acc
1058            })
1059            .await
1060    }
1061
1062    /// Send `ECash` for the given amount and return the send operation ID. The
1063    /// amount will be rounded up to a multiple of 512 msats which is the
1064    /// smallest denomination used throughout the client. If the rounded
1065    /// amount cannot be covered with the ecash notes in the client's
1066    /// database the client will create a transaction to reissue the
1067    /// required denominations. To cancel a successful ecash send simply
1068    /// receive it yourself.
1069    ///
1070    /// If `include_invite` is set, the federation's invite code is embedded in
1071    /// the returned ecash so a recipient that has not joined the federation can
1072    /// do so directly from the received ecash.
1073    ///
1074    /// # Cancel safety
1075    ///
1076    /// This method is cancel safe. Every database mutation it makes happens
1077    /// inside a single
1078    /// [`autocommit`](fedimint_core::db::Database::autocommit) transaction
1079    /// (spending the notes for the fast path, and creating the change-making
1080    /// reissue transaction otherwise), so dropping the future either commits
1081    /// a unit of work in full or leaves the database untouched: notes are
1082    /// never removed without a persisted operation that produces the ecash or
1083    /// returns the change. Federation submission is driven by a state machine
1084    /// in the executor rather than awaited here, so a cancelled call cannot
1085    /// abort an in-flight reissue; if change-making had already been
1086    /// submitted it completes on its own and the notes return to the balance.
1087    pub async fn send(
1088        &self,
1089        account: Account,
1090        amount: Amount,
1091        custom_meta: Value,
1092        include_invite: bool,
1093    ) -> Result<(OperationId, ECash), SendECashError> {
1094        let amount = round_to_multiple(amount, client_denominations().next().unwrap().amount());
1095
1096        if let Some((operation_id, ecash)) = self
1097            .client_ctx
1098            .module_db()
1099            .autocommit(
1100                |dbtx, _| {
1101                    Box::pin(self.send_ecash_dbtx(
1102                        dbtx,
1103                        account,
1104                        amount,
1105                        custom_meta.clone(),
1106                        include_invite,
1107                    ))
1108                },
1109                Some(100),
1110            )
1111            .await
1112            .expect("Failed to commit dbtx after 100 retries")
1113        {
1114            return Ok((operation_id, ecash));
1115        }
1116
1117        self.client_ctx
1118            .global_api()
1119            .session_count()
1120            .await
1121            .map_err(|_| SendECashError::Offline)?;
1122
1123        let operation_id = OperationId::new_random();
1124
1125        let output = self
1126            .create_output_bundle(account, operation_id, represent_amount(amount))
1127            .await;
1128        let output = self.client_ctx.make_client_outputs(output);
1129        let cm = custom_meta.clone();
1130
1131        let range = self
1132            .client_ctx
1133            .finalize_and_submit_transaction(
1134                operation_id,
1135                MintCommonInit::KIND.as_str(),
1136                move |change_outpoint_range| MintOperationMeta::Reissue {
1137                    change_outpoint_range,
1138                    amount,
1139                    custom_meta: cm.clone(),
1140                },
1141                TransactionBuilder::new(account).with_outputs(output),
1142            )
1143            .await
1144            .map_err(|error| match error {
1145                TransactionSubmitError::InsufficientFunds(_) => SendECashError::InsufficientBalance,
1146                other => SendECashError::Failed(other),
1147            })?;
1148
1149        for outpoint in range {
1150            self.await_output_sm_success(operation_id, outpoint)
1151                .await
1152                .map_err(|_| SendECashError::Failure)?;
1153        }
1154
1155        Box::pin(self.send(account, amount, custom_meta, include_invite)).await
1156    }
1157
1158    /// Fast path for [`Self::send`]: if exact change is already held, spend
1159    /// those notes and record the send operation. Returns `None` when exact
1160    /// change is not available, leaving the caller to make change.
1161    ///
1162    /// # Cancel safety
1163    ///
1164    /// All writes go to the passed `dbtx`, so this inherits the cancel safety
1165    /// of that transaction: it must be run inside an `autocommit` (as `send`
1166    /// does) for the note spend and the operation log entry to commit or roll
1167    /// back together.
1168    async fn send_ecash_dbtx(
1169        &self,
1170        dbtx: &mut DatabaseTransaction<'_>,
1171        account: Account,
1172        remaining_amount: Amount,
1173        custom_meta: Value,
1174        include_invite: bool,
1175    ) -> Result<Option<(OperationId, ECash)>, Infallible> {
1176        let Some(notes) =
1177            Self::select_exact_change(&mut dbtx.to_ref_nc(), account, remaining_amount).await
1178        else {
1179            return Ok(None);
1180        };
1181
1182        for spendable_note in &notes {
1183            self.remove_spendable_note(dbtx, account, spendable_note)
1184                .await;
1185        }
1186
1187        Ok(Some(
1188            self.record_send(dbtx, account, notes, custom_meta, include_invite)
1189                .await,
1190        ))
1191    }
1192
1193    /// Bundle notes already removed from `account` and record the send: the
1194    /// operation log entry, the event and the balance ping. Shared by the
1195    /// exact-change [`Self::send`] and by [`Self::send_max`], which differ only
1196    /// in how they pick the notes.
1197    async fn record_send(
1198        &self,
1199        dbtx: &mut DatabaseTransaction<'_>,
1200        account: Account,
1201        notes: Vec<SpendableNote>,
1202        custom_meta: Value,
1203        include_invite: bool,
1204    ) -> (OperationId, ECash) {
1205        let ecash = if include_invite {
1206            let invite = self.client_ctx.get_invite_code().await;
1207            ECash::new_with_invite(notes, &invite)
1208        } else {
1209            ECash::new(self.federation_id, notes)
1210        }
1211        .with_unit(self.cfg.amount_unit);
1212        let amount = ecash.amount();
1213        let operation_id = OperationId::new_random();
1214
1215        self.client_ctx
1216            .add_operation_log_entry_dbtx(
1217                dbtx,
1218                operation_id,
1219                account,
1220                MintCommonInit::KIND.as_str(),
1221                MintOperationMeta::Send {
1222                    ecash: base32::encode_prefixed(FEDIMINT_PREFIX, &ecash),
1223                    custom_meta,
1224                },
1225            )
1226            .await;
1227
1228        self.client_ctx
1229            .log_event(
1230                dbtx,
1231                SendPaymentEvent {
1232                    operation_id,
1233                    amount,
1234                    account,
1235                    ecash: base32::encode_prefixed(FEDIMINT_PREFIX, &ecash),
1236                },
1237            )
1238            .await;
1239
1240        let sender = self.balance_update_sender.clone();
1241        dbtx.on_commit(move || sender.send_replace(()));
1242
1243        (operation_id, ecash)
1244    }
1245
1246    /// Hand out everything `account` holds as one note bundle, or `None` if it
1247    /// holds nothing.
1248    ///
1249    /// Not [`Self::send`] with the account's balance as its amount: a send
1250    /// rounds up to a whole denomination and takes its free path only when the
1251    /// notes sum to that amount exactly, which a figure in whole sats
1252    /// generally is not. Missing the free path drops the send onto the path
1253    /// that builds a real transaction, which covers its fee out of the same
1254    /// account, so asking for everything fails on the balance the user is
1255    /// looking at.
1256    ///
1257    /// This is how funds move between accounts: `send_max` one, then
1258    /// [`Self::receive`] the bundle into another, which reissues the notes to
1259    /// the destination's own nonces so a later recovery finds them where they
1260    /// now are.
1261    pub async fn send_max(
1262        &self,
1263        account: Account,
1264        custom_meta: Value,
1265        include_invite: bool,
1266    ) -> Option<(OperationId, ECash)> {
1267        self.client_ctx
1268            .module_db()
1269            .autocommit(
1270                |dbtx, _| {
1271                    Box::pin(self.send_max_dbtx(dbtx, account, custom_meta.clone(), include_invite))
1272                },
1273                Some(100),
1274            )
1275            .await
1276            .expect("Failed to commit dbtx after 100 retries")
1277    }
1278
1279    async fn send_max_dbtx(
1280        &self,
1281        dbtx: &mut DatabaseTransaction<'_>,
1282        account: Account,
1283        custom_meta: Value,
1284        include_invite: bool,
1285    ) -> Result<Option<(OperationId, ECash)>, Infallible> {
1286        let notes = dbtx
1287            .find_by_prefix(&SpendableNotePrefix(account))
1288            .await
1289            .map(|entry| entry.0.1.decode_own())
1290            .collect::<Vec<SpendableNote>>()
1291            .await;
1292
1293        if notes.is_empty() {
1294            return Ok(None);
1295        }
1296
1297        for spendable_note in &notes {
1298            self.remove_spendable_note(dbtx, account, spendable_note)
1299                .await;
1300        }
1301
1302        Ok(Some(
1303            self.record_send(dbtx, account, notes, custom_meta, include_invite)
1304                .await,
1305        ))
1306    }
1307
1308    /// Receive the `ECash` by reissuing the notes and return the operation ID.
1309    pub async fn receive(
1310        &self,
1311        account: Account,
1312        ecash: ECash,
1313        custom_meta: Value,
1314    ) -> Result<OperationId, ReceiveECashError> {
1315        let operation_id = OperationId::from_encodable(&ecash);
1316
1317        if ecash.mint() != Some(self.federation_id) {
1318            return Err(ReceiveECashError::WrongFederation);
1319        }
1320
1321        if ecash
1322            .notes()
1323            .iter()
1324            .any(|note| note.amount() <= self.cfg.fee_consensus.base_fee())
1325        {
1326            return Err(ReceiveECashError::UneconomicalDenomination);
1327        }
1328
1329        let input =
1330            Self::create_input_bundle(operation_id, ecash.notes(), true, self.cfg.amount_unit);
1331        let input = self.client_ctx.make_client_inputs(input);
1332        let ec = base32::encode_prefixed(FEDIMINT_PREFIX, &ecash);
1333        let amount = ecash.amount();
1334        let tx_builder = TransactionBuilder::new(account).with_inputs(input);
1335
1336        self.client_ctx
1337            .finalize_and_submit_transaction_with_events(
1338                operation_id,
1339                MintCommonInit::KIND.as_str(),
1340                move |change_outpoint_range| MintOperationMeta::Receive {
1341                    change_outpoint_range,
1342                    ecash: ec.clone(),
1343                    custom_meta: custom_meta.clone(),
1344                },
1345                tx_builder,
1346                vec![self.client_ctx.make_event(ReceivePaymentEvent {
1347                    operation_id,
1348                    amount,
1349                    account,
1350                })],
1351            )
1352            .await
1353            .map_err(|error| match error {
1354                TransactionSubmitError::OperationAlreadyExists(_) => {
1355                    ReceiveECashError::AlreadyReceived
1356                }
1357                TransactionSubmitError::InsufficientFunds(_) => {
1358                    ReceiveECashError::InsufficientFunds
1359                }
1360                other => ReceiveECashError::Failed(other),
1361            })?;
1362
1363        Ok(operation_id)
1364    }
1365
1366    /// Computes the exact fee a `receive(ecash)` would incur given the client's
1367    /// current note inventory, without submitting anything.
1368    ///
1369    /// This runs the same change generation the real receive does
1370    /// (`create_final_inputs_and_outputs`, including funding selection and
1371    /// rebalancing) against a non-committable transaction that is dropped
1372    /// rather than committed, so the client's notes are read but left
1373    /// untouched. The quote is point-in-time: it depends on the current
1374    /// inventory and can move as notes change.
1375    pub async fn receive_fee_quote(
1376        &self,
1377        account: Account,
1378        ecash: &ECash,
1379    ) -> Result<FeeQuote, TransactionSubmitError> {
1380        // A receive submits the ecash notes as explicit inputs and no explicit
1381        // outputs; the shared, module-agnostic fee quote runs the primary-module
1382        // balancing (rebalancing + minting change) over the real inventory.
1383        let notes = ecash.notes();
1384        let input_amount: Amount = notes.iter().map(SpendableNote::amount).sum();
1385        let input_fee: Amount = notes
1386            .iter()
1387            .map(|note| self.cfg.fee_consensus.fee(note.amount()))
1388            .sum();
1389
1390        self.client_ctx
1391            .fee_quote(
1392                OperationId::new_random(),
1393                FeeQuoteRequest {
1394                    input_amount: Amounts::new_custom(self.cfg.amount_unit, input_amount),
1395                    output_amount: Amounts::ZERO,
1396                    input_fee: Amounts::new_custom(self.cfg.amount_unit, input_fee),
1397                    output_fee: Amounts::ZERO,
1398                    account,
1399                },
1400            )
1401            .await
1402    }
1403
1404    /// Computes the fee a `send(amount)` would incur given the client's current
1405    /// note inventory, without sending anything.
1406    ///
1407    /// A send is free when the client's existing notes can cover the (rounded)
1408    /// amount exactly — it just hands those notes out. Otherwise the send first
1409    /// reissues itself the right denominations, and that self-reissue
1410    /// transaction is the only thing a send ever pays a fee for. This quote
1411    /// mirrors that: it returns [`FeeQuote::ZERO`] when exact change is
1412    /// available, and otherwise quotes the reissue the same way the real send
1413    /// submits it (explicit outputs `represent_amount(amount)`, no explicit
1414    /// inputs) via the shared, module-agnostic fee quote over the real
1415    /// inventory. The quote is point-in-time: it depends on the current
1416    /// inventory and can move as notes change.
1417    pub async fn send_fee_quote(
1418        &self,
1419        account: Account,
1420        amount: Amount,
1421    ) -> Result<FeeQuote, TransactionSubmitError> {
1422        let amount = round_to_multiple(amount, client_denominations().next().unwrap().amount());
1423
1424        // Exact-change path: handing out existing notes never costs a fee.
1425        if self.can_make_exact_change(account, amount).await {
1426            return Ok(FeeQuote::ZERO);
1427        }
1428
1429        // Reissue path: the send mints itself `represent_amount(amount)` as
1430        // explicit outputs (no explicit inputs) and the primary module funds and
1431        // balances it. Quote that exact transaction.
1432        let denominations = represent_amount(amount);
1433        let output_amount: Amount = denominations.iter().map(|d| d.amount()).sum();
1434        let output_fee: Amount = denominations
1435            .iter()
1436            .map(|d| self.cfg.fee_consensus.fee(d.amount()))
1437            .sum();
1438
1439        self.client_ctx
1440            .fee_quote(
1441                OperationId::new_random(),
1442                FeeQuoteRequest {
1443                    input_amount: Amounts::ZERO,
1444                    output_amount: Amounts::new_custom(self.cfg.amount_unit, output_amount),
1445                    input_fee: Amounts::ZERO,
1446                    output_fee: Amounts::new_custom(self.cfg.amount_unit, output_fee),
1447                    account,
1448                },
1449            )
1450            .await
1451    }
1452
1453    /// Returns whether the client's current notes can be handed out to cover
1454    /// `amount` exactly — the free path in [`Self::send`] — without modifying
1455    /// the inventory. Shares its greedy selection with
1456    /// [`Self::send_ecash_dbtx`] via [`Self::select_exact_change`].
1457    async fn can_make_exact_change(&self, account: Account, remaining_amount: Amount) -> bool {
1458        let mut dbtx = self.client_ctx.module_db().begin_transaction_nc().await;
1459
1460        Self::select_exact_change(&mut dbtx, account, remaining_amount)
1461            .await
1462            .is_some()
1463    }
1464
1465    /// Greedily selects spendable notes (largest-first) summing to *exactly*
1466    /// `remaining_amount`, or `None` if the inventory can't make exact change.
1467    /// Reads the DB but does not modify it. Single source of truth for the free
1468    /// (hand-out-existing-notes) selection shared by [`Self::send_ecash_dbtx`]
1469    /// and [`Self::can_make_exact_change`].
1470    async fn select_exact_change(
1471        dbtx: &mut DatabaseTransaction<'_>,
1472        account: Account,
1473        mut remaining_amount: Amount,
1474    ) -> Option<Vec<SpendableNote>> {
1475        let mut stream = dbtx
1476            .find_by_prefix_sorted_descending(&SpendableNotePrefix(account))
1477            .await
1478            .map(|entry| entry.0.1);
1479
1480        let mut notes = vec![];
1481
1482        while let Some(spendable_note) = stream.next().await {
1483            remaining_amount = match remaining_amount.checked_sub(spendable_note.amount()) {
1484                Some(amount) => amount,
1485                None => continue,
1486            };
1487
1488            notes.push(spendable_note.decode_own());
1489
1490            if remaining_amount == Amount::ZERO {
1491                break;
1492            }
1493        }
1494
1495        (remaining_amount == Amount::ZERO).then_some(notes)
1496    }
1497
1498    /// Await the final state of the receive operation.
1499    pub async fn await_final_receive_operation_state(
1500        &self,
1501        operation_id: OperationId,
1502    ) -> Result<FinalReceiveOperationState, OperationLookupError> {
1503        let operation = self.client_ctx.get_operation(operation_id).await?;
1504        let mut stream = self.notifier.subscribe(operation_id).await;
1505
1506        let mut stream = self
1507            .client_ctx
1508            .outcome_or_updates(&operation, operation_id, |_| true, move || {
1509                async_stream::stream! {
1510                    loop {
1511                        if let Some(MintClientStateMachines::Receive(state)) = stream.next().await {
1512                            match state.state {
1513                                ReceiveSMState::Pending => {}
1514                                ReceiveSMState::Success => {
1515                                    yield FinalReceiveOperationState::Success;
1516                                    return;
1517                                }
1518                                ReceiveSMState::Rejected(..) => {
1519                                    yield FinalReceiveOperationState::Rejected;
1520                                    return;
1521                                }
1522                            }
1523                        }
1524                    }
1525                }
1526            })
1527            .into_stream();
1528
1529        let mut final_state = None;
1530
1531        while let Some(state) = stream.next().await {
1532            final_state = Some(state);
1533        }
1534
1535        Ok(final_state.expect("Stream contains one final state"))
1536    }
1537
1538    async fn remove_spendable_note(
1539        &self,
1540        dbtx: &mut DatabaseTransaction<'_>,
1541        account: Account,
1542        spendable_note: &SpendableNote,
1543    ) {
1544        dbtx.remove_entry(&SpendableNoteKey(account, spendable_note.clone().into()))
1545            .await
1546            .expect("Must delete existing spendable note");
1547    }
1548}
1549
1550/// Hands out guardians so that only one slice request is outstanding to each.
1551///
1552/// Whichever peer finishes first takes the next slice, so a slow guardian
1553/// receives less work without anyone having to measure how slow it is, and one
1554/// that is not answering ties up a single request rather than a share of all
1555/// of them.
1556#[derive(Clone)]
1557struct PeerPool {
1558    receiver: async_channel::Receiver<PeerId>,
1559    sender: async_channel::Sender<PeerId>,
1560}
1561
1562impl PeerPool {
1563    fn new(peers: &BTreeSet<PeerId>) -> Self {
1564        let (sender, receiver) = async_channel::bounded(peers.len().max(1));
1565
1566        for peer in peers {
1567            sender
1568                .try_send(*peer)
1569                .expect("Capacity was sized to hold every peer");
1570        }
1571
1572        Self { receiver, sender }
1573    }
1574
1575    /// Wait for a guardian with no request outstanding.
1576    async fn acquire(&self) -> PeerId {
1577        self.receiver
1578            .recv()
1579            .await
1580            .expect("The sender is held for as long as the receiver")
1581    }
1582
1583    /// Take a guardian out of rotation, putting it back once it has sat out
1584    /// [`PEER_READMISSION`].
1585    ///
1586    /// Dropping it for good would cost a guardian that timed out once the rest
1587    /// of the recovery, which on a federation of four is a quarter of the
1588    /// capacity thrown away for a single bad request.
1589    fn retire(&self, peer: PeerId) {
1590        let pool = self.clone();
1591
1592        fedimint_core::runtime::spawn("mintv2 recovery peer readmission", async move {
1593            fedimint_core::runtime::sleep(PEER_READMISSION).await;
1594
1595            pool.release(peer);
1596        });
1597    }
1598
1599    /// Put a guardian back for the next slice.
1600    fn release(&self, peer: PeerId) {
1601        self.sender
1602            .try_send(peer)
1603            .expect("Only peers taken from the pool are put back");
1604    }
1605}
1606
1607/// Download a slice, asking one guardian at a time and holding it for the
1608/// duration of the request.
1609async fn download_slice(
1610    module_api: DynModuleApi,
1611    peers: PeerPool,
1612    start: u64,
1613    end: u64,
1614    expected_hash: sha256::Hash,
1615) -> Vec<RecoveryItem> {
1616    let mut timeouts = custom_backoff(SLICE_TIMEOUT, MAX_SLICE_TIMEOUT, None);
1617
1618    loop {
1619        let peer = peers.acquire().await;
1620
1621        let timeout = timeouts.next().expect("The backoff never gives up");
1622
1623        let result = module_api
1624            .fetch_recovery_slice(peer, timeout, start, end)
1625            .await;
1626
1627        match result {
1628            Ok(data) if data.consensus_hash::<sha256::Hash>() == expected_hash => {
1629                peers.release(peer);
1630
1631                return data;
1632            }
1633            // Either served something the other guardians disagree with, or
1634            // did not answer at all. Either way it sits out for a while: a
1635            // request that reaches the timeout took many times longer than a
1636            // healthy guardian needs, so asking it again mostly buys another
1637            // timeout. The timeout grows in case it is the client's own
1638            // connection that is too slow for the initial one.
1639            Ok(_) | Err(_) => peers.retire(peer),
1640        }
1641    }
1642}
1643
1644/// A failure to send e-cash by preparing notes to hand to the recipient.
1645#[derive(Error, Debug)]
1646#[non_exhaustive]
1647pub enum SendECashError {
1648    /// The client needs to reissue notes to make change, but has no
1649    /// connection to the federation to do so.
1650    #[error("We need to reissue notes but the client is offline")]
1651    Offline,
1652    /// The client's balance cannot cover the amount requested.
1653    #[error("The clients balance is insufficient")]
1654    InsufficientBalance,
1655    /// The client failed to prepare the notes for a reason it cannot
1656    /// recover from.
1657    #[error("A non-recoverable error has occurred")]
1658    Failure,
1659    /// The change-making reissue transaction could not be submitted for a
1660    /// reason unrelated to funding.
1661    #[error("The reissue transaction could not be submitted")]
1662    Failed(#[source] TransactionSubmitError),
1663}
1664
1665/// A failure to receive e-cash by reissuing it.
1666#[derive(Error, Debug)]
1667#[non_exhaustive]
1668pub enum ReceiveECashError {
1669    /// The e-cash was issued by a different federation.
1670    #[error("The ECash is from a different federation")]
1671    WrongFederation,
1672
1673    /// One of the notes is worth no more than the fee to reissue it.
1674    #[error("ECash contains an uneconomical denomination")]
1675    UneconomicalDenomination,
1676
1677    /// The client cannot cover the fee the reissue costs.
1678    #[error("Receiving ecash requires additional funds")]
1679    InsufficientFunds,
1680
1681    /// An operation for this exact e-cash already exists, so it was already
1682    /// received.
1683    #[error("The ECash was already received")]
1684    AlreadyReceived,
1685
1686    /// The reissue transaction could not be submitted for a reason unrelated
1687    /// to funding.
1688    #[error("The reissue transaction could not be submitted")]
1689    Failed(#[source] TransactionSubmitError),
1690}
1691
1692/// Why an output's state machine did not issue its notes.
1693#[derive(Debug, Error)]
1694enum AwaitOutputError {
1695    /// The transaction that creates the output was rejected.
1696    #[error("Transaction was rejected")]
1697    Rejected,
1698
1699    /// The notes of the output could not be finalized.
1700    #[error("Failed to finalize notes")]
1701    Failed,
1702}
1703
1704#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
1705pub enum FinalReceiveOperationState {
1706    // The ecash notes have been reissued
1707    Success,
1708    // The ecash notes were already spent
1709    Rejected,
1710}
1711
1712#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
1713pub enum MintClientStateMachines {
1714    Input(InputStateMachine),
1715    Output(MintOutputStateMachine),
1716    Receive(ReceiveStateMachine),
1717}
1718
1719impl IntoDynInstance for MintClientStateMachines {
1720    type DynType = DynState;
1721
1722    fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
1723        DynState::from_typed(instance_id, self)
1724    }
1725}
1726
1727impl State for MintClientStateMachines {
1728    type ModuleContext = MintClientContext;
1729
1730    fn transitions(
1731        &self,
1732        context: &Self::ModuleContext,
1733        global_context: &DynGlobalClientContext,
1734    ) -> Vec<StateTransition<Self>> {
1735        match self {
1736            MintClientStateMachines::Input(redemption_state) => {
1737                sm_enum_variant_translation!(
1738                    redemption_state.transitions(context, global_context),
1739                    MintClientStateMachines::Input
1740                )
1741            }
1742            MintClientStateMachines::Output(issuance_state) => {
1743                sm_enum_variant_translation!(
1744                    issuance_state.transitions(context, global_context),
1745                    MintClientStateMachines::Output
1746                )
1747            }
1748            MintClientStateMachines::Receive(receive_state) => {
1749                sm_enum_variant_translation!(
1750                    receive_state.transitions(context, global_context),
1751                    MintClientStateMachines::Receive
1752                )
1753            }
1754        }
1755    }
1756
1757    fn operation_id(&self) -> OperationId {
1758        match self {
1759            MintClientStateMachines::Input(redemption_state) => redemption_state.operation_id(),
1760            MintClientStateMachines::Output(issuance_state) => issuance_state.operation_id(),
1761            MintClientStateMachines::Receive(receive_state) => receive_state.operation_id(),
1762        }
1763    }
1764}
1765
1766fn round_to_multiple(amount: Amount, min_denomiation: Amount) -> Amount {
1767    Amount::from_msats(amount.msats.next_multiple_of(min_denomiation.msats))
1768}
1769
1770fn represent_amount_with_fees(
1771    mut remaining_amount: Amount,
1772    fee_consensus: &FeeConsensus,
1773) -> Vec<Denomination> {
1774    let mut denominations = Vec::new();
1775
1776    // Add denominations with a greedy algorithm
1777    for denomination in client_denominations().rev() {
1778        let n_add =
1779            remaining_amount / (denomination.amount() + fee_consensus.fee(denomination.amount()));
1780
1781        denominations.extend(std::iter::repeat_n(denomination, n_add as usize));
1782
1783        remaining_amount -=
1784            n_add * (denomination.amount() + fee_consensus.fee(denomination.amount()));
1785    }
1786
1787    // We sort the notes by amount to minimize the leaked information.
1788    denominations.sort();
1789
1790    denominations
1791}
1792
1793fn represent_amount(mut remaining_amount: Amount) -> Vec<Denomination> {
1794    let mut denominations = Vec::new();
1795
1796    // Add denominations with a greedy algorithm
1797    for denomination in client_denominations().rev() {
1798        let n_add = remaining_amount / denomination.amount();
1799
1800        denominations.extend(std::iter::repeat_n(denomination, n_add as usize));
1801
1802        remaining_amount -= n_add * denomination.amount();
1803    }
1804
1805    denominations
1806}