Skip to main content

fedimint_mint_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
9// Backup and restore logic
10pub mod backup;
11/// Modularized Cli for sending and receiving out-of-band ecash
12#[cfg(feature = "cli")]
13mod cli;
14/// Database keys used throughout the mint client module
15pub mod client_db;
16/// Error types of the mint client
17pub mod error;
18/// State machines for mint inputs
19mod input;
20/// State machines for out-of-band transmitted e-cash notes
21mod oob;
22/// State machines for mint outputs
23pub mod output;
24
25pub mod events;
26
27/// API client impl for mint-specific requests
28pub mod api;
29
30pub mod repair_wallet;
31
32pub mod visualize;
33
34use std::cmp::{Ordering, min};
35use std::collections::{BTreeMap, BTreeSet};
36use std::fmt;
37use std::fmt::{Display, Formatter};
38use std::io::Read;
39use std::str::FromStr;
40use std::sync::{Arc, RwLock};
41use std::time::Duration;
42
43use api::MintFederationApi;
44use async_stream::{stream, try_stream};
45use backup::recovery::{MintRecovery, RecoveryStateV2};
46use base64::Engine as _;
47use bitcoin_hashes::{Hash, HashEngine as BitcoinHashEngine, sha256, sha256t};
48use client_db::{
49    DbKeyPrefix, NoteKeyPrefix, RecoveryFinalizedKey, RecoveryStateKey, RecoveryStateV2Key,
50    ReusedNoteIndices, migrate_state_to_v2, migrate_to_v1,
51};
52use events::{NoteSpent, OOBNotesReissued, OOBNotesSpent, ReceivePaymentEvent, SendPaymentEvent};
53use fedimint_api_client::api::{DynModuleApi, FederationError, FederationResult};
54use fedimint_client_module::db::{ClientModuleMigrationFn, migrate_state};
55pub use fedimint_client_module::error::InsufficientBalanceError;
56use fedimint_client_module::error::{
57    AddStateMachinesError, ClientModuleError, OperationLookupError, TransactionSubmitError,
58};
59use fedimint_client_module::module::init::{
60    ClientModuleInit, ClientModuleInitArgs, ClientModuleRecoverArgs, RecoveryMode,
61};
62use fedimint_client_module::module::recovery::RecoveryProgress;
63use fedimint_client_module::module::{
64    AccountSupport, ClientContext, ClientModule, IClientModule, OutPointRange,
65    PrimaryModulePriority, PrimaryModuleSupport,
66};
67use fedimint_client_module::oplog::{OperationLogEntry, UpdateStreamOrOutcome};
68use fedimint_client_module::sm::{Context, DynState, ModuleNotifier, State, StateTransition};
69use fedimint_client_module::transaction::{
70    ClientInput, ClientInputBundle, ClientInputSM, ClientOutput, ClientOutputBundle,
71    ClientOutputSM, FeeQuote, FeeQuoteRequest, TransactionBuilder,
72};
73use fedimint_client_module::{DynGlobalClientContext, sm_enum_variant_translation};
74use fedimint_core::base32::{FEDIMINT_PREFIX, encode_prefixed};
75use fedimint_core::config::{FederationId, FederationIdPrefix};
76use fedimint_core::core::{
77    Account, Decoder, IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId,
78};
79use fedimint_core::db::{
80    AutocommitError, Database, DatabaseTransaction, DatabaseVersion,
81    IDatabaseTransactionOpsCoreTyped,
82};
83use fedimint_core::encoding::{Decodable, DecodeError, Encodable};
84use fedimint_core::invite_code::InviteCode;
85use fedimint_core::module::registry::{ModuleDecoderRegistry, ModuleRegistry};
86use fedimint_core::module::{
87    AmountUnit, Amounts, ApiVersion, CommonModuleInit, ModuleCommon, ModuleInit, MultiApiVersion,
88};
89use fedimint_core::secp256k1::rand::prelude::IteratorRandom;
90use fedimint_core::secp256k1::rand::thread_rng;
91use fedimint_core::secp256k1::{All, Keypair, Secp256k1};
92use fedimint_core::util::{BoxFuture, BoxStream, FmtCompact as _, NextOrPending, SafeUrl};
93use fedimint_core::{
94    Amount, IdxRange, OutPoint, PeerId, Tiered, TieredCounts, TieredMulti, TransactionId, apply,
95    async_trait_maybe_send, base32, push_db_pair_items, runtime,
96};
97use fedimint_derive_secret::{ChildId, DerivableSecret};
98use fedimint_logging::LOG_CLIENT_MODULE_MINT;
99pub use fedimint_mint_common as common;
100use fedimint_mint_common::config::{FeeConsensus, MintClientConfig};
101pub use fedimint_mint_common::*;
102use futures::future::try_join_all;
103use futures::{StreamExt, TryStreamExt as _, pin_mut};
104use hex::ToHex;
105use input::MintInputStateCreatedBundle;
106use itertools::Itertools as _;
107use output::MintOutputStatesCreatedMulti;
108use serde::{Deserialize, Serialize};
109use strum::IntoEnumIterator;
110use tbs::AggregatePublicKey;
111use tracing::{debug, warn};
112
113use crate::backup::EcashBackup;
114use crate::client_db::{
115    CancelledOOBSpendKey, CancelledOOBSpendKeyPrefix, NextECashNoteIndexKey,
116    NextECashNoteIndexKeyPrefix, NoteKey,
117};
118pub use crate::error::{
119    AwaitOutputFinalizedError, FetchRecoverySliceError, OOBNotesParseError,
120    PrepareEcashBackupError, RepairWalletError, SelectNotesError, SendOOBNotesError, SpendOOBError,
121    SubscribeReissueExternalNotesError, SubscribeSpendNotesError, ValidateNotesError,
122    VerifyBlindShareError,
123};
124use crate::input::{MintInputCommon, MintInputStateMachine, MintInputStates};
125use crate::oob::{MintOOBStateMachine, MintOOBStates, MintOOBStatesCreatedMulti};
126use crate::output::{
127    MintOutputCommon, MintOutputStateMachine, MintOutputStates, NoteIssuanceRequest,
128};
129
130const MINT_E_CASH_TYPE_CHILD_ID: ChildId = ChildId(0);
131
132const OOB_SPEND_NO_TIMEOUT: Duration = Duration::MAX;
133
134#[derive(Clone)]
135struct PeerSelector {
136    latency: Arc<RwLock<BTreeMap<PeerId, Duration>>>,
137}
138
139impl PeerSelector {
140    fn new(peers: BTreeSet<PeerId>) -> Self {
141        let latency = peers
142            .into_iter()
143            .map(|peer| (peer, Duration::ZERO))
144            .collect();
145
146        Self {
147            latency: Arc::new(RwLock::new(latency)),
148        }
149    }
150
151    fn choose_peer(&self) -> PeerId {
152        let latency = self.latency.read().expect("poisoned");
153
154        let peer_a = latency.iter().choose(&mut thread_rng()).expect("no peers");
155        let peer_b = latency.iter().choose(&mut thread_rng()).expect("no peers");
156
157        if peer_a.1 <= peer_b.1 {
158            *peer_a.0
159        } else {
160            *peer_b.0
161        }
162    }
163
164    fn report(&self, peer: PeerId, duration: Duration) {
165        self.latency
166            .write()
167            .expect("poisoned")
168            .entry(peer)
169            .and_modify(|latency| *latency = *latency * 9 / 10 + duration / 10)
170            .or_insert(duration);
171    }
172
173    fn remove(&self, peer: PeerId) {
174        self.latency.write().expect("poisoned").remove(&peer);
175    }
176}
177
178/// Downloads a slice with a pre-fetched hash for verification
179async fn download_slice_with_hash(
180    module_api: DynModuleApi,
181    peer_selector: PeerSelector,
182    start: u64,
183    end: u64,
184    expected_hash: sha256::Hash,
185) -> Vec<RecoveryItem> {
186    const TIMEOUT: Duration = Duration::from_secs(30);
187
188    loop {
189        let peer = peer_selector.choose_peer();
190        let start_time = fedimint_core::time::now();
191
192        match runtime::timeout(TIMEOUT, module_api.fetch_recovery_slice(peer, start, end)).await {
193            Ok(Ok(data)) => {
194                let elapsed = fedimint_core::time::now()
195                    .duration_since(start_time)
196                    .unwrap_or(Duration::ZERO);
197
198                peer_selector.report(peer, elapsed);
199
200                if data.consensus_hash::<sha256::Hash>() == expected_hash {
201                    return data;
202                }
203
204                peer_selector.remove(peer);
205            }
206            Ok(Err(..)) | Err(..) => {
207                peer_selector.report(peer, TIMEOUT);
208            }
209        }
210    }
211}
212
213/// An encapsulation of [`FederationId`] and e-cash notes in the form of
214/// [`TieredMulti<SpendableNote>`] for the purpose of spending e-cash
215/// out-of-band. Also used for validating and reissuing such out-of-band notes.
216///
217/// ## Invariants
218/// * Has to contain at least one `Notes` item
219/// * Has to contain at least one `FederationIdPrefix` item
220#[derive(Clone, Debug, Encodable, PartialEq, Eq)]
221pub struct OOBNotes(Vec<OOBNotesPart>);
222
223/// For extendability [`OOBNotes`] consists of parts, where client can ignore
224/// ones they don't understand.
225#[derive(Clone, Debug, Decodable, Encodable, PartialEq, Eq)]
226enum OOBNotesPart {
227    Notes(TieredMulti<SpendableNote>),
228    FederationIdPrefix(FederationIdPrefix),
229    /// Invite code to join the federation by which the e-cash was issued
230    ///
231    /// Introduced in 0.3.0
232    Invite {
233        // This is a vec for future-proofness, in case we want to include multiple guardian APIs
234        peer_apis: Vec<(PeerId, SafeUrl)>,
235        federation_id: FederationId,
236    },
237    ApiSecret(String),
238    #[encodable_default]
239    Default {
240        variant: u64,
241        bytes: Vec<u8>,
242    },
243}
244
245impl OOBNotes {
246    pub fn new(
247        federation_id_prefix: FederationIdPrefix,
248        notes: TieredMulti<SpendableNote>,
249    ) -> Self {
250        Self(vec![
251            OOBNotesPart::FederationIdPrefix(federation_id_prefix),
252            OOBNotesPart::Notes(notes),
253        ])
254    }
255
256    pub fn new_with_invite(notes: TieredMulti<SpendableNote>, invite: &InviteCode) -> Self {
257        let mut data = vec![
258            // FIXME: once we can break compatibility with 0.2 we can remove the prefix in case an
259            // invite is present
260            OOBNotesPart::FederationIdPrefix(invite.federation_id().to_prefix()),
261            OOBNotesPart::Notes(notes),
262            OOBNotesPart::Invite {
263                peer_apis: vec![(invite.peer(), invite.url())],
264                federation_id: invite.federation_id(),
265            },
266        ];
267        if let Some(api_secret) = invite.api_secret() {
268            data.push(OOBNotesPart::ApiSecret(api_secret));
269        }
270        Self(data)
271    }
272
273    pub fn federation_id_prefix(&self) -> FederationIdPrefix {
274        self.0
275            .iter()
276            .find_map(|data| match data {
277                OOBNotesPart::FederationIdPrefix(prefix) => Some(*prefix),
278                OOBNotesPart::Invite { federation_id, .. } => Some(federation_id.to_prefix()),
279                _ => None,
280            })
281            .expect("Invariant violated: OOBNotes does not contain a FederationIdPrefix")
282    }
283
284    pub fn notes(&self) -> &TieredMulti<SpendableNote> {
285        self.0
286            .iter()
287            .find_map(|data| match data {
288                OOBNotesPart::Notes(notes) => Some(notes),
289                _ => None,
290            })
291            .expect("Invariant violated: OOBNotes does not contain any notes")
292    }
293
294    pub fn notes_json(&self) -> Result<serde_json::Value, serde_json::Error> {
295        let mut notes_map = serde_json::Map::new();
296        for notes in &self.0 {
297            match notes {
298                OOBNotesPart::Notes(notes) => {
299                    let notes_json: serde_json::Map<String, serde_json::Value> = notes
300                        .iter()
301                        .map(|(amount, notes_vec)| {
302                            let notes_with_nonce: Vec<serde_json::Value> = notes_vec
303                                .iter()
304                                .map(|note| {
305                                    serde_json::json!({
306                                        "signature": note.signature,
307                                        "spend_key": note.spend_key,
308                                        "nonce": note.nonce(),
309                                    })
310                                })
311                                .collect();
312                            (
313                                amount.msats.to_string(),
314                                serde_json::Value::Array(notes_with_nonce),
315                            )
316                        })
317                        .collect();
318                    notes_map.insert("notes".to_string(), serde_json::Value::Object(notes_json));
319                }
320                OOBNotesPart::FederationIdPrefix(prefix) => {
321                    notes_map.insert(
322                        "federation_id_prefix".to_string(),
323                        serde_json::to_value(prefix.to_string())?,
324                    );
325                }
326                OOBNotesPart::Invite {
327                    peer_apis,
328                    federation_id,
329                } => {
330                    let (peer_id, api) = peer_apis
331                        .first()
332                        .cloned()
333                        .expect("Decoding makes sure peer_apis isn't empty");
334                    notes_map.insert(
335                        "invite".to_string(),
336                        serde_json::to_value(InviteCode::new(
337                            api,
338                            peer_id,
339                            *federation_id,
340                            self.api_secret(),
341                        ))?,
342                    );
343                }
344                OOBNotesPart::ApiSecret(_) => { /* already covered inside `Invite` */ }
345                OOBNotesPart::Default { variant, bytes } => {
346                    notes_map.insert(
347                        format!("default_{variant}"),
348                        serde_json::to_value(bytes.encode_hex::<String>())?,
349                    );
350                }
351            }
352        }
353        Ok(serde_json::Value::Object(notes_map))
354    }
355
356    pub fn federation_invite(&self) -> Option<InviteCode> {
357        self.0.iter().find_map(|data| {
358            let OOBNotesPart::Invite {
359                peer_apis,
360                federation_id,
361            } = data
362            else {
363                return None;
364            };
365            let (peer_id, api) = peer_apis
366                .first()
367                .cloned()
368                .expect("Decoding makes sure peer_apis isn't empty");
369            Some(InviteCode::new(
370                api,
371                peer_id,
372                *federation_id,
373                self.api_secret(),
374            ))
375        })
376    }
377
378    fn api_secret(&self) -> Option<String> {
379        self.0.iter().find_map(|data| {
380            let OOBNotesPart::ApiSecret(api_secret) = data else {
381                return None;
382            };
383            Some(api_secret.clone())
384        })
385    }
386}
387
388impl Decodable for OOBNotes {
389    fn consensus_decode_partial<R: Read>(
390        r: &mut R,
391        _modules: &ModuleDecoderRegistry,
392    ) -> Result<Self, DecodeError> {
393        let inner =
394            Vec::<OOBNotesPart>::consensus_decode_partial(r, &ModuleDecoderRegistry::default())?;
395
396        // TODO: maybe write some macros for defining TLV structs?
397        if !inner
398            .iter()
399            .any(|data| matches!(data, OOBNotesPart::Notes(_)))
400        {
401            return Err(DecodeError::from_str(
402                "No e-cash notes were found in OOBNotes data",
403            ));
404        }
405
406        let maybe_federation_id_prefix = inner.iter().find_map(|data| match data {
407            OOBNotesPart::FederationIdPrefix(prefix) => Some(*prefix),
408            _ => None,
409        });
410
411        let maybe_invite = inner.iter().find_map(|data| match data {
412            OOBNotesPart::Invite {
413                federation_id,
414                peer_apis,
415            } => Some((federation_id, peer_apis)),
416            _ => None,
417        });
418
419        match (maybe_federation_id_prefix, maybe_invite) {
420            (Some(p), Some((ip, _))) => {
421                if p != ip.to_prefix() {
422                    return Err(DecodeError::from_str(
423                        "Inconsistent Federation ID provided in OOBNotes data",
424                    ));
425                }
426            }
427            (None, None) => {
428                return Err(DecodeError::from_str(
429                    "No Federation ID provided in OOBNotes data",
430                ));
431            }
432            _ => {}
433        }
434
435        if let Some((_, invite)) = maybe_invite
436            && invite.is_empty()
437        {
438            return Err(DecodeError::from_str("Invite didn't contain API endpoints"));
439        }
440
441        Ok(OOBNotes(inner))
442    }
443}
444
445const BASE64_URL_SAFE: base64::engine::GeneralPurpose = base64::engine::GeneralPurpose::new(
446    &base64::alphabet::URL_SAFE,
447    base64::engine::general_purpose::PAD,
448);
449
450impl FromStr for OOBNotes {
451    type Err = OOBNotesParseError;
452
453    /// Decode a set of out-of-band e-cash notes from a base64 or base32 string.
454    fn from_str(s: &str) -> Result<Self, Self::Err> {
455        let s: String = s.chars().filter(|&c| !c.is_whitespace()).collect();
456
457        let oob_notes_bytes = if let Ok(oob_notes_bytes) =
458            base32::decode_prefixed_bytes(FEDIMINT_PREFIX, &s)
459        {
460            oob_notes_bytes
461        } else if let Ok(oob_notes_bytes) = BASE64_URL_SAFE.decode(&s) {
462            oob_notes_bytes
463        } else if let Ok(oob_notes_bytes) = base64::engine::general_purpose::STANDARD.decode(&s) {
464            oob_notes_bytes
465        } else {
466            return Err(OOBNotesParseError::Encoding);
467        };
468
469        let oob_notes =
470            OOBNotes::consensus_decode_whole(&oob_notes_bytes, &ModuleDecoderRegistry::default())?;
471
472        if oob_notes.notes().is_empty() {
473            return Err(OOBNotesParseError::Empty);
474        }
475
476        Ok(oob_notes)
477    }
478}
479
480impl Display for OOBNotes {
481    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
482        let bytes = Encodable::consensus_encode_to_vec(self);
483
484        f.write_str(&BASE64_URL_SAFE.encode(&bytes))
485    }
486}
487
488impl Serialize for OOBNotes {
489    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
490    where
491        S: serde::Serializer,
492    {
493        serializer.serialize_str(&self.to_string())
494    }
495}
496
497impl<'de> Deserialize<'de> for OOBNotes {
498    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
499    where
500        D: serde::Deserializer<'de>,
501    {
502        let s = String::deserialize(deserializer)?;
503        FromStr::from_str(&s).map_err(serde::de::Error::custom)
504    }
505}
506
507impl OOBNotes {
508    /// Returns the total value of all notes in msat as `Amount`
509    pub fn total_amount(&self) -> Amount {
510        self.notes().total_amount()
511    }
512}
513
514/// The high-level state of a reissue operation started with
515/// [`MintClientModule::reissue_external_notes`].
516#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
517pub enum ReissueExternalNotesState {
518    /// The operation has been created and is waiting to be accepted by the
519    /// federation.
520    Created,
521    /// We are waiting for blind signatures to arrive but can already assume the
522    /// transaction to be successful.
523    Issuing,
524    /// The operation has been completed successfully.
525    Done,
526    /// Some error happened and the operation failed.
527    Failed(String),
528}
529
530/// The result of [`MintClientModule::subscribe_reissue_external_notes`].
531pub type SubscribeReissueExternalNotesResult =
532    Result<UpdateStreamOrOutcome<ReissueExternalNotesState>, SubscribeReissueExternalNotesError>;
533
534/// The high-level state of a raw e-cash spend operation started with
535/// [`MintClientModule::spend_notes_with_selector`].
536#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
537pub enum SpendOOBState {
538    /// The e-cash has been selected and given to the caller
539    Created,
540    /// The user requested a cancellation of the operation, we are waiting for
541    /// the outcome of the cancel transaction.
542    UserCanceledProcessing,
543    /// The user-requested cancellation was successful, we got all our money
544    /// back.
545    UserCanceledSuccess,
546    /// The user-requested cancellation failed, the e-cash notes have been spent
547    /// by someone else already.
548    UserCanceledFailure,
549    /// We tried to cancel the operation automatically after the timeout but
550    /// failed, indicating the recipient reissued the e-cash to themselves,
551    /// making the out-of-band spend **successful**.
552    Success,
553    /// We tried to cancel the operation automatically after the timeout and
554    /// succeeded, indicating the recipient did not reissue the e-cash to
555    /// themselves, meaning the out-of-band spend **failed**.
556    Refunded,
557}
558
559#[derive(Debug, Clone, Serialize, Deserialize)]
560pub struct MintOperationMeta {
561    pub variant: MintOperationMetaVariant,
562    pub amount: Amount,
563    pub extra_meta: serde_json::Value,
564}
565
566#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
567#[serde(rename_all = "snake_case")]
568pub enum MintOperationMetaVariant {
569    // TODO: add migrations for operation log and clean up schema
570    /// Either `legacy_out_point` or both `txid` and `out_point_indices` will be
571    /// present.
572    Reissuance {
573        // Removed in 0.3.0:
574        #[serde(skip_serializing, default, rename = "out_point")]
575        legacy_out_point: Option<OutPoint>,
576        // Introduced in 0.3.0:
577        #[serde(default)]
578        txid: Option<TransactionId>,
579        // Introduced in 0.3.0:
580        #[serde(default)]
581        out_point_indices: Vec<u64>,
582    },
583    SpendOOB {
584        requested_amount: Amount,
585        oob_notes: OOBNotes,
586        #[serde(default)]
587        no_timeout: bool,
588    },
589}
590
591#[derive(Debug, Clone)]
592pub struct MintClientInit;
593
594const SLICE_SIZE: u64 = 10000;
595const PARALLEL_HASH_REQUESTS: usize = 10;
596const PARALLEL_SLICE_REQUESTS: usize = 10;
597
598impl MintClientInit {
599    #[allow(clippy::too_many_lines)]
600    async fn recover_from_slices(
601        &self,
602        args: &ClientModuleRecoverArgs<Self>,
603    ) -> Result<Option<Amount>, RecoverFromSlicesError> {
604        // Try to load existing state or create new one if we can fetch recovery count
605        let mut state = if let Some(state) = args
606            .db()
607            .begin_transaction_nc()
608            .await
609            .get_value(&RecoveryStateV2Key)
610            .await
611        {
612            state
613        } else {
614            // Try to fetch recovery count - if this fails, the endpoint doesn't exist
615            let total_items = args.module_api().fetch_recovery_count().await?;
616
617            RecoveryStateV2::new(
618                total_items,
619                args.cfg().tbs_pks.tiers().copied().collect(),
620                args.module_root_secret(),
621            )
622        };
623
624        if state.next_index == state.total_items {
625            return Ok(None);
626        }
627
628        let peer_selector = PeerSelector::new(args.api().all_peers().clone());
629
630        let mut recovery_stream = futures::stream::iter(
631            (state.next_index..state.total_items).step_by(SLICE_SIZE as usize),
632        )
633        .map(move |start| {
634            let api = args.module_api().clone();
635            let end = std::cmp::min(start + SLICE_SIZE, state.total_items);
636
637            async move { (start, end, api.fetch_recovery_slice_hash(start, end).await) }
638        })
639        .buffered(PARALLEL_HASH_REQUESTS)
640        .map(move |(start, end, hash)| {
641            download_slice_with_hash(
642                args.module_api().clone(),
643                peer_selector.clone(),
644                start,
645                end,
646                hash,
647            )
648        })
649        .buffered(PARALLEL_SLICE_REQUESTS);
650
651        let secret = args.module_root_secret().clone();
652
653        loop {
654            let items = recovery_stream
655                .next()
656                .await
657                .expect("mint recovery stream finished before recovery is complete");
658
659            for item in &items {
660                match item {
661                    RecoveryItem::Output { amount, nonce } => {
662                        state.handle_output(*amount, *nonce, &secret);
663                    }
664                    RecoveryItem::Input { nonce } => {
665                        state.handle_input(*nonce);
666                    }
667                }
668            }
669
670            state.next_index += items.len() as u64;
671
672            let mut dbtx = args.db().begin_transaction().await;
673
674            dbtx.insert_entry(&RecoveryStateV2Key, &state).await;
675
676            if state.next_index == state.total_items {
677                // Finalize recovery - create state machines for pending outputs
678                let finalized = state.finalize();
679
680                // Total value of the notes reconstructed during recovery
681                let recovered_amount = finalized
682                    .pending_notes
683                    .iter()
684                    .map(|(amount, _)| *amount)
685                    .sum::<Amount>();
686
687                // Collect blind nonces to fetch outpoints from server
688                let blind_nonces: Vec<BlindNonce> = finalized
689                    .pending_notes
690                    .iter()
691                    .map(|(_, req)| BlindNonce(req.blinded_message()))
692                    .collect();
693
694                // Fetch outpoints for all blind nonces
695                let outpoints = if blind_nonces.is_empty() {
696                    vec![]
697                } else {
698                    args.module_api()
699                        .fetch_blind_nonce_outpoints(blind_nonces)
700                        .await
701                        .map_err(RecoverFromSlicesError::BlindNonceOutpoints)?
702                };
703
704                // Create state machines for pending notes
705                let state_machines: Vec<MintClientStateMachines> = finalized
706                    .pending_notes
707                    .into_iter()
708                    .zip(outpoints)
709                    .map(|((amount, issuance_request), out_point)| {
710                        MintClientStateMachines::Output(MintOutputStateMachine {
711                            common: MintOutputCommon {
712                                operation_id: OperationId::new_random(),
713                                out_point_range: OutPointRange::new_single(
714                                    out_point.txid,
715                                    out_point.out_idx,
716                                )
717                                .expect("Can't overflow"),
718                            },
719                            state: MintOutputStates::Created(output::MintOutputStatesCreated {
720                                amount,
721                                issuance_request,
722                            }),
723                        })
724                    })
725                    .collect();
726
727                let state_machines = args.context().map_dyn(state_machines).collect();
728
729                args.context()
730                    .add_state_machines_dbtx(&mut dbtx.to_ref_nc(), state_machines)
731                    .await?;
732
733                // Restore NextECashNoteIndexKey
734                for (amount, note_idx) in finalized.next_note_idx {
735                    dbtx.insert_entry(&NextECashNoteIndexKey(amount), &note_idx.as_u64())
736                        .await;
737                }
738
739                dbtx.commit_tx().await;
740
741                return Ok(Some(recovered_amount));
742            }
743
744            dbtx.commit_tx().await;
745
746            args.update_recovery_progress(RecoveryProgress {
747                complete: state.next_index.try_into().unwrap_or(u32::MAX),
748                total: state.total_items.try_into().unwrap_or(u32::MAX),
749            });
750        }
751    }
752}
753
754/// A failure of the mint's slice-based recovery.
755#[derive(Debug, thiserror::Error)]
756enum RecoverFromSlicesError {
757    /// The federation could not say how many recovery items it has.
758    #[error(transparent)]
759    RecoveryCount(#[from] FederationError),
760
761    /// The federation could not say where the recovered notes were issued.
762    #[error("Failed to fetch blind nonce outpoints")]
763    BlindNonceOutpoints(#[source] FederationError),
764
765    /// The state machines that finalize the recovered notes could not be
766    /// added.
767    #[error(transparent)]
768    StateMachines(#[from] AddStateMachinesError),
769}
770
771impl ModuleInit for MintClientInit {
772    type Common = MintCommonInit;
773
774    async fn dump_database(
775        &self,
776        dbtx: &mut DatabaseTransaction<'_>,
777        prefix_names: Vec<String>,
778    ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
779        let mut mint_client_items: BTreeMap<String, Box<dyn erased_serde::Serialize + Send>> =
780            BTreeMap::new();
781        let filtered_prefixes = DbKeyPrefix::iter().filter(|f| {
782            prefix_names.is_empty() || prefix_names.contains(&f.to_string().to_lowercase())
783        });
784
785        for table in filtered_prefixes {
786            match table {
787                DbKeyPrefix::Note => {
788                    push_db_pair_items!(
789                        dbtx,
790                        NoteKeyPrefix,
791                        NoteKey,
792                        SpendableNoteUndecoded,
793                        mint_client_items,
794                        "Notes"
795                    );
796                }
797                DbKeyPrefix::NextECashNoteIndex => {
798                    push_db_pair_items!(
799                        dbtx,
800                        NextECashNoteIndexKeyPrefix,
801                        NextECashNoteIndexKey,
802                        u64,
803                        mint_client_items,
804                        "NextECashNoteIndex"
805                    );
806                }
807                DbKeyPrefix::CancelledOOBSpend => {
808                    push_db_pair_items!(
809                        dbtx,
810                        CancelledOOBSpendKeyPrefix,
811                        CancelledOOBSpendKey,
812                        (),
813                        mint_client_items,
814                        "CancelledOOBSpendKey"
815                    );
816                }
817                DbKeyPrefix::RecoveryFinalized => {
818                    if let Some(val) = dbtx.get_value(&RecoveryFinalizedKey).await {
819                        mint_client_items.insert("RecoveryFinalized".to_string(), Box::new(val));
820                    }
821                }
822                DbKeyPrefix::RecoveryState
823                | DbKeyPrefix::ReusedNoteIndices
824                | DbKeyPrefix::RecoveryStateV2
825                | DbKeyPrefix::ExternalReservedStart
826                | DbKeyPrefix::CoreInternalReservedStart
827                | DbKeyPrefix::CoreInternalReservedEnd => {}
828            }
829        }
830
831        Box::new(mint_client_items.into_iter())
832    }
833}
834
835#[apply(async_trait_maybe_send!)]
836impl ClientModuleInit for MintClientInit {
837    type Module = MintClientModule;
838
839    fn supported_api_versions(&self) -> MultiApiVersion {
840        MultiApiVersion::try_from_iter([ApiVersion { major: 0, minor: 0 }])
841            .expect("no version conflicts")
842    }
843
844    async fn init(
845        &self,
846        args: &ClientModuleInitArgs<Self>,
847    ) -> Result<Self::Module, ClientModuleError> {
848        Ok(MintClientModule {
849            federation_id: *args.federation_id(),
850            cfg: args.cfg().clone(),
851            secret: args.module_root_secret().clone(),
852            secp: Secp256k1::new(),
853            notifier: args.notifier().clone(),
854            client_ctx: args.context(),
855            balance_update_sender: tokio::sync::watch::channel(()).0,
856        })
857    }
858
859    fn recovery_mode(&self) -> RecoveryMode {
860        RecoveryMode::Unusable
861    }
862
863    async fn recover(
864        &self,
865        args: &ClientModuleRecoverArgs<Self>,
866        snapshot: Option<&<Self::Module as ClientModule>::Backup>,
867    ) -> Result<Option<Amount>, ClientModuleError> {
868        let mut dbtx = args.db().begin_transaction_nc().await;
869
870        // Check if V2 (slice-based) recovery state exists
871        if dbtx.get_value(&RecoveryStateV2Key).await.is_some() {
872            return self
873                .recover_from_slices(args)
874                .await
875                .map_err(ClientModuleError::other);
876        }
877
878        // Check if V1 (session-based) recovery state exists
879        if dbtx.get_value(&RecoveryStateKey).await.is_some() {
880            return args
881                .recover_from_history::<MintRecovery>(self, snapshot)
882                .await;
883        }
884
885        // No existing recovery state - determine which to use based on endpoint
886        // availability
887        if args.module_api().fetch_recovery_count().await.is_ok() {
888            // New endpoint available - use V2 slice-based recovery
889            self.recover_from_slices(args)
890                .await
891                .map_err(ClientModuleError::other)
892        } else {
893            // Old federation - use V1 session-based recovery
894            args.recover_from_history::<MintRecovery>(self, snapshot)
895                .await
896        }
897    }
898
899    fn get_database_migrations(&self) -> BTreeMap<DatabaseVersion, ClientModuleMigrationFn> {
900        let mut migrations: BTreeMap<DatabaseVersion, ClientModuleMigrationFn> = BTreeMap::new();
901        migrations.insert(DatabaseVersion(0), |dbtx, _, _| {
902            Box::pin(migrate_to_v1(dbtx))
903        });
904        migrations.insert(DatabaseVersion(1), |_, active_states, inactive_states| {
905            Box::pin(async { migrate_state(active_states, inactive_states, migrate_state_to_v2) })
906        });
907
908        migrations
909    }
910
911    fn used_db_prefixes(&self) -> Option<BTreeSet<u8>> {
912        Some(
913            DbKeyPrefix::iter()
914                .map(|p| p as u8)
915                .chain(
916                    DbKeyPrefix::ExternalReservedStart as u8
917                        ..=DbKeyPrefix::CoreInternalReservedEnd as u8,
918                )
919                .collect(),
920        )
921    }
922}
923
924/// The `MintClientModule` is responsible for handling e-cash minting
925/// operations. It interacts with the mint server to issue, reissue, and
926/// validate e-cash notes.
927///
928/// # Derivable Secret
929///
930/// The `DerivableSecret` is a cryptographic secret that can be used to derive
931/// other secrets. In the context of the `MintClientModule`, it is used to
932/// derive the blinding and spend keys for e-cash notes. The `DerivableSecret`
933/// is initialized when the `MintClientModule` is created and is kept private
934/// within the module.
935///
936/// # Blinding Key
937///
938/// The blinding key is derived from the `DerivableSecret` and is used to blind
939/// the e-cash note during the issuance process. This ensures that the mint
940/// server cannot link the e-cash note to the client that requested it,
941/// providing privacy for the client.
942///
943/// # Spend Key
944///
945/// The spend key is also derived from the `DerivableSecret` and is used to
946/// spend the e-cash note. Only the client that possesses the `DerivableSecret`
947/// can derive the correct spend key to spend the e-cash note. This ensures that
948/// only the owner of the e-cash note can spend it.
949pub struct MintClientModule {
950    federation_id: FederationId,
951    cfg: MintClientConfig,
952    secret: DerivableSecret,
953    secp: Secp256k1<All>,
954    notifier: ModuleNotifier<MintClientStateMachines>,
955    pub client_ctx: ClientContext<Self>,
956    balance_update_sender: tokio::sync::watch::Sender<()>,
957}
958
959impl fmt::Debug for MintClientModule {
960    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
961        f.debug_struct("MintClientModule")
962            .field("federation_id", &self.federation_id)
963            .field("cfg", &self.cfg)
964            .field("notifier", &self.notifier)
965            .field("client_ctx", &self.client_ctx)
966            .finish_non_exhaustive()
967    }
968}
969
970// TODO: wrap in Arc
971#[derive(Clone)]
972pub struct MintClientContext {
973    pub federation_id: FederationId,
974    pub client_ctx: ClientContext<MintClientModule>,
975    pub mint_decoder: Decoder,
976    pub tbs_pks: Tiered<AggregatePublicKey>,
977    pub peer_tbs_pks: BTreeMap<PeerId, Tiered<tbs::PublicKeyShare>>,
978    pub secret: DerivableSecret,
979    // FIXME: putting a DB ref here is an antipattern, global context should become more powerful
980    // but we need to consider it more carefully as its APIs will be harder to change.
981    pub module_db: Database,
982    /// Notifies subscribers when the balance changes
983    pub balance_update_sender: tokio::sync::watch::Sender<()>,
984}
985
986impl fmt::Debug for MintClientContext {
987    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
988        f.debug_struct("MintClientContext")
989            .field("federation_id", &self.federation_id)
990            .finish_non_exhaustive()
991    }
992}
993
994impl MintClientContext {
995    fn await_cancel_oob_payment(&self, operation_id: OperationId) -> BoxFuture<'static, ()> {
996        let db = self.module_db.clone();
997        Box::pin(async move {
998            db.wait_key_exists(&CancelledOOBSpendKey(operation_id))
999                .await;
1000        })
1001    }
1002}
1003
1004impl Context for MintClientContext {
1005    const KIND: Option<ModuleKind> = Some(KIND);
1006}
1007
1008#[apply(async_trait_maybe_send!)]
1009impl ClientModule for MintClientModule {
1010    type Init = MintClientInit;
1011    type Common = MintModuleTypes;
1012    type Backup = EcashBackup;
1013    type ModuleStateMachineContext = MintClientContext;
1014    type States = MintClientStateMachines;
1015
1016    fn context(&self) -> Self::ModuleStateMachineContext {
1017        MintClientContext {
1018            federation_id: self.federation_id,
1019            client_ctx: self.client_ctx.clone(),
1020            mint_decoder: self.decoder(),
1021            tbs_pks: self.cfg.tbs_pks.clone(),
1022            peer_tbs_pks: self.cfg.peer_tbs_pks.clone(),
1023            secret: self.secret.clone(),
1024            module_db: self.client_ctx.module_db().clone(),
1025            balance_update_sender: self.balance_update_sender.clone(),
1026        }
1027    }
1028
1029    fn input_fee(
1030        &self,
1031        amount: &Amounts,
1032        _input: &<Self::Common as ModuleCommon>::Input,
1033    ) -> Option<Amounts> {
1034        Some(Amounts::new_bitcoin(
1035            self.cfg.fee_consensus.fee(amount.get_bitcoin()),
1036        ))
1037    }
1038
1039    fn output_fee(
1040        &self,
1041        amount: &Amounts,
1042        _output: &<Self::Common as ModuleCommon>::Output,
1043    ) -> Option<Amounts> {
1044        Some(Amounts::new_bitcoin(
1045            self.cfg.fee_consensus.fee(amount.get_bitcoin()),
1046        ))
1047    }
1048
1049    #[cfg(feature = "cli")]
1050    async fn handle_cli_command(
1051        &self,
1052        args: &[std::ffi::OsString],
1053    ) -> Result<serde_json::Value, ClientModuleError> {
1054        cli::handle_cli_command(self, args)
1055            .await
1056            .map_err(ClientModuleError::other)
1057    }
1058
1059    fn supports_backup(&self) -> bool {
1060        true
1061    }
1062
1063    async fn backup(&self) -> Result<EcashBackup, ClientModuleError> {
1064        self.client_ctx
1065            .module_db()
1066            .autocommit(
1067                |dbtx_ctx, _| {
1068                    Box::pin(async { self.prepare_plaintext_ecash_backup(dbtx_ctx).await })
1069                },
1070                None,
1071            )
1072            .await
1073            .map_err(|e| match e {
1074                AutocommitError::ClosureError { error, .. } => ClientModuleError::other(error),
1075                AutocommitError::CommitFailed { last_error, .. } => {
1076                    ClientModuleError::other(last_error)
1077                }
1078            })
1079    }
1080
1081    fn supports_being_primary(&self) -> PrimaryModuleSupport {
1082        PrimaryModuleSupport::selected(
1083            PrimaryModulePriority::HIGH,
1084            [AmountUnit::BITCOIN],
1085            AccountSupport::PrimaryOnly,
1086        )
1087    }
1088
1089    async fn create_final_inputs_and_outputs(
1090        &self,
1091        dbtx: &mut DatabaseTransaction<'_>,
1092        operation_id: OperationId,
1093        unit: AmountUnit,
1094        mut input_amount: Amount,
1095        mut output_amount: Amount,
1096        _account: Account,
1097    ) -> Result<
1098        (
1099            ClientInputBundle<MintInput, MintClientStateMachines>,
1100            ClientOutputBundle<MintOutput, MintClientStateMachines>,
1101        ),
1102        ClientModuleError,
1103    > {
1104        let consolidation_inputs = self
1105            .consolidate_notes(dbtx)
1106            .await
1107            .map_err(ClientModuleError::other)?;
1108
1109        if unit != AmountUnit::BITCOIN {
1110            return Err(ClientModuleError::other("Module can only handle Bitcoin"));
1111        }
1112
1113        input_amount += consolidation_inputs
1114            .iter()
1115            .map(|input| input.0.amounts.get_bitcoin())
1116            .sum();
1117
1118        output_amount += consolidation_inputs
1119            .iter()
1120            .map(|input| self.cfg.fee_consensus.fee(input.0.amounts.get_bitcoin()))
1121            .sum();
1122
1123        let additional_inputs = self
1124            .create_sufficient_input(dbtx, output_amount.saturating_sub(input_amount))
1125            .await?;
1126
1127        input_amount += additional_inputs
1128            .iter()
1129            .map(|input| input.0.amounts.get_bitcoin())
1130            .sum();
1131
1132        output_amount += additional_inputs
1133            .iter()
1134            .map(|input| self.cfg.fee_consensus.fee(input.0.amounts.get_bitcoin()))
1135            .sum();
1136
1137        let outputs = self
1138            .create_output(
1139                dbtx,
1140                operation_id,
1141                2,
1142                input_amount.saturating_sub(output_amount),
1143            )
1144            .await;
1145
1146        Ok((
1147            create_bundle_for_inputs(
1148                [consolidation_inputs, additional_inputs].concat(),
1149                operation_id,
1150            ),
1151            outputs,
1152        ))
1153    }
1154
1155    async fn await_primary_module_output(
1156        &self,
1157        operation_id: OperationId,
1158        out_point: OutPoint,
1159    ) -> Result<(), ClientModuleError> {
1160        self.await_output_finalized(operation_id, out_point)
1161            .await
1162            .map_err(ClientModuleError::other)
1163    }
1164
1165    async fn get_balance(
1166        &self,
1167        dbtx: &mut DatabaseTransaction<'_>,
1168        unit: AmountUnit,
1169        _account: Account,
1170    ) -> Amount {
1171        if unit != AmountUnit::BITCOIN {
1172            return Amount::ZERO;
1173        }
1174
1175        self.get_note_counts_by_denomination(dbtx)
1176            .await
1177            .total_amount()
1178    }
1179
1180    async fn get_balances(&self, dbtx: &mut DatabaseTransaction<'_>) -> Amounts {
1181        Amounts::new_bitcoin(
1182            <Self as ClientModule>::get_balance(self, dbtx, AmountUnit::BITCOIN, Account::Primary)
1183                .await,
1184        )
1185    }
1186
1187    async fn subscribe_balance_changes(&self) -> BoxStream<'static, ()> {
1188        Box::pin(tokio_stream::wrappers::WatchStream::new(
1189            self.balance_update_sender.subscribe(),
1190        ))
1191    }
1192
1193    async fn leave(&self, dbtx: &mut DatabaseTransaction<'_>) -> Result<(), ClientModuleError> {
1194        let balance = ClientModule::get_balances(self, dbtx).await;
1195
1196        for (unit, amount) in balance {
1197            if Amount::from_units(0) < amount {
1198                return Err(ClientModuleError::other(format!(
1199                    "Outstanding balance: {amount}, unit: {unit:?}"
1200                )));
1201            }
1202        }
1203
1204        if !self.client_ctx.get_own_active_states().await.is_empty() {
1205            return Err(ClientModuleError::other("Pending operations"));
1206        }
1207        Ok(())
1208    }
1209
1210    async fn handle_rpc(
1211        &self,
1212        method: String,
1213        request: serde_json::Value,
1214    ) -> BoxStream<'_, Result<serde_json::Value, ClientModuleError>> {
1215        let stream: BoxStream<'_, Result<serde_json::Value, RpcError>> = Box::pin(try_stream! {
1216            match method.as_str() {
1217                "reissue_external_notes" => {
1218                    let req: ReissueExternalNotesRequest = serde_json::from_value(request)?;
1219                    let result = self.reissue_external_notes(req.oob_notes, req.extra_meta).await?;
1220                    yield serde_json::to_value(result)?;
1221                }
1222                "subscribe_reissue_external_notes" => {
1223                    let req: SubscribeReissueExternalNotesRequest = serde_json::from_value(request)?;
1224                    let stream = self.subscribe_reissue_external_notes(req.operation_id).await?;
1225                    for await state in stream.into_stream() {
1226                        yield serde_json::to_value(state)?;
1227                    }
1228                }
1229                "spend_notes" => {
1230                    let req: SpendNotesRequest = serde_json::from_value(request)?;
1231                    let result = self.spend_notes_with_selector(
1232                        &SelectNotesWithExactAmount,
1233                        req.amount,
1234                        req.try_cancel_after,
1235                        req.include_invite,
1236                        req.extra_meta
1237                    ).await?;
1238                    yield serde_json::to_value(result)?;
1239                }
1240                "spend_notes_expert" => {
1241                    let req: SpendNotesExpertRequest = serde_json::from_value(request)?;
1242                    let result = self.spend_notes_with_selector(
1243                        &SelectNotesWithAtleastAmount,
1244                        req.min_amount,
1245                        req.try_cancel_after,
1246                        req.include_invite,
1247                        req.extra_meta
1248                    ).await?;
1249                    yield serde_json::to_value(result)?;
1250                }
1251                "validate_notes" => {
1252                    let req: ValidateNotesRequest = serde_json::from_value(request)?;
1253                    let result = self.validate_notes(&req.oob_notes)?;
1254                    yield serde_json::to_value(result)?;
1255                }
1256                "try_cancel_spend_notes" => {
1257                    let req: TryCancelSpendNotesRequest = serde_json::from_value(request)?;
1258                    let result = self.try_cancel_spend_notes(req.operation_id).await;
1259                    yield serde_json::to_value(result)?;
1260                }
1261                "subscribe_spend_notes" => {
1262                    let req: SubscribeSpendNotesRequest = serde_json::from_value(request)?;
1263                    let stream = self.subscribe_spend_notes(req.operation_id).await?;
1264                    for await state in stream.into_stream() {
1265                        yield serde_json::to_value(state)?;
1266                    }
1267                }
1268                "await_spend_oob_refund" => {
1269                    let req: AwaitSpendOobRefundRequest = serde_json::from_value(request)?;
1270                    let value = self.await_spend_oob_refund(req.operation_id).await;
1271                    yield serde_json::to_value(value)?;
1272                }
1273                "note_counts_by_denomination" => {
1274                    let mut dbtx = self.client_ctx.module_db().begin_transaction_nc().await;
1275                    let note_counts = self.get_note_counts_by_denomination(&mut dbtx).await;
1276                    yield serde_json::to_value(note_counts)?;
1277                }
1278                _ => {
1279                    Err(RpcError::UnknownMethod { method: method.clone() })?;
1280                    unreachable!()
1281                },
1282            }
1283        });
1284        Box::pin(stream.map_err(ClientModuleError::other))
1285    }
1286}
1287
1288/// A failure of a mint module RPC request.
1289#[derive(Debug, thiserror::Error)]
1290enum RpcError {
1291    /// The request's parameters do not fit the method, or its response could
1292    /// not be serialized.
1293    #[error(transparent)]
1294    Json(#[from] serde_json::Error),
1295
1296    /// The notes could not be reissued.
1297    #[error(transparent)]
1298    Reissue(#[from] ReissueExternalNotesError),
1299
1300    /// The reissue's updates could not be followed.
1301    #[error(transparent)]
1302    SubscribeReissue(#[from] SubscribeReissueExternalNotesError),
1303
1304    /// The notes to spend could not be selected or prepared.
1305    #[error(transparent)]
1306    Spend(#[from] SpendOOBError),
1307
1308    /// The notes to validate are invalid.
1309    #[error(transparent)]
1310    Validate(#[from] ValidateNotesError),
1311
1312    /// The spend's updates could not be followed.
1313    #[error(transparent)]
1314    SubscribeSpend(#[from] SubscribeSpendNotesError),
1315
1316    /// The request names a method the module does not have.
1317    #[error("Unknown method: {method}")]
1318    UnknownMethod { method: String },
1319}
1320
1321#[derive(Deserialize)]
1322struct ReissueExternalNotesRequest {
1323    oob_notes: OOBNotes,
1324    extra_meta: serde_json::Value,
1325}
1326
1327#[derive(Deserialize)]
1328struct SubscribeReissueExternalNotesRequest {
1329    operation_id: OperationId,
1330}
1331
1332/// Caution: if no notes of the correct denomination are available the next
1333/// bigger note will be selected. You might want to use `spend_notes` instead.
1334#[derive(Deserialize)]
1335struct SpendNotesExpertRequest {
1336    min_amount: Amount,
1337    try_cancel_after: Option<Duration>,
1338    include_invite: bool,
1339    extra_meta: serde_json::Value,
1340}
1341
1342#[derive(Deserialize)]
1343struct SpendNotesRequest {
1344    amount: Amount,
1345    try_cancel_after: Option<Duration>,
1346    include_invite: bool,
1347    extra_meta: serde_json::Value,
1348}
1349
1350#[derive(Deserialize)]
1351struct ValidateNotesRequest {
1352    oob_notes: OOBNotes,
1353}
1354
1355#[derive(Deserialize)]
1356struct TryCancelSpendNotesRequest {
1357    operation_id: OperationId,
1358}
1359
1360#[derive(Deserialize)]
1361struct SubscribeSpendNotesRequest {
1362    operation_id: OperationId,
1363}
1364
1365#[derive(Deserialize)]
1366struct AwaitSpendOobRefundRequest {
1367    operation_id: OperationId,
1368}
1369
1370/// A failure to reissue e-cash notes received from a third party.
1371#[derive(thiserror::Error, Debug)]
1372#[non_exhaustive]
1373pub enum ReissueExternalNotesError {
1374    /// The notes are worth nothing, so there is nothing to reissue.
1375    #[error("Reissuing zero-amount e-cash is not supported")]
1376    ZeroAmount,
1377
1378    /// The notes were issued by a different federation.
1379    #[error("The notes were issued by federation {found}, not {expected}")]
1380    WrongFederationId {
1381        /// The federation this client belongs to.
1382        expected: FederationIdPrefix,
1383        /// The federation the notes name.
1384        found: FederationIdPrefix,
1385    },
1386
1387    /// An operation for these exact notes already exists, so they were already
1388    /// handed to this federation.
1389    #[error("We already reissued these notes")]
1390    AlreadyReissued,
1391
1392    /// The notes cannot be spent.
1393    #[error("The notes could not be validated")]
1394    Notes(#[from] ValidateNotesError),
1395
1396    /// The reissue transaction could not be built or submitted.
1397    #[error("The reissue transaction could not be submitted")]
1398    Transaction(#[source] TransactionSubmitError),
1399}
1400
1401impl MintClientModule {
1402    async fn create_sufficient_input(
1403        &self,
1404        dbtx: &mut DatabaseTransaction<'_>,
1405        min_amount: Amount,
1406    ) -> Result<Vec<(ClientInput<MintInput>, SpendableNote)>, ClientModuleError> {
1407        if min_amount == Amount::ZERO {
1408            return Ok(vec![]);
1409        }
1410
1411        let selected_notes = Self::select_notes(
1412            dbtx,
1413            &SelectNotesWithAtleastAmount,
1414            min_amount,
1415            self.cfg.fee_consensus.clone(),
1416        )
1417        .await
1418        .map_err(|error| match error {
1419            // The one failure the client acts on: it tells "the wallet is too
1420            // poor for this transaction" apart from every other failure.
1421            SelectNotesError::InsufficientBalance(error) => {
1422                ClientModuleError::InsufficientBalance(error)
1423            }
1424            other => ClientModuleError::other(other),
1425        })?;
1426
1427        for (amount, note) in selected_notes.iter_items() {
1428            debug!(target: LOG_CLIENT_MODULE_MINT, %amount, %note, "Spending note as sufficient input to fund a tx");
1429            MintClientModule::delete_spendable_note(&self.client_ctx, dbtx, amount, note).await;
1430        }
1431
1432        let sender = self.balance_update_sender.clone();
1433        dbtx.on_commit(move || sender.send_replace(()));
1434
1435        let inputs = self
1436            .create_input_from_notes(selected_notes)
1437            .map_err(ClientModuleError::other)?;
1438
1439        assert!(!inputs.is_empty());
1440
1441        Ok(inputs)
1442    }
1443
1444    /// Returns the number of held e-cash notes per denomination
1445    #[deprecated(
1446        since = "0.5.0",
1447        note = "Use `get_note_counts_by_denomination` instead"
1448    )]
1449    pub async fn get_notes_tier_counts(&self, dbtx: &mut DatabaseTransaction<'_>) -> TieredCounts {
1450        self.get_note_counts_by_denomination(dbtx).await
1451    }
1452
1453    /// Pick [`SpendableNote`]s by given counts, when available
1454    ///
1455    /// Return the notes picked, and counts of notes that were not available.
1456    pub async fn get_available_notes_by_tier_counts(
1457        &self,
1458        dbtx: &mut DatabaseTransaction<'_>,
1459        counts: TieredCounts,
1460    ) -> (TieredMulti<SpendableNoteUndecoded>, TieredCounts) {
1461        dbtx.find_by_prefix(&NoteKeyPrefix)
1462            .await
1463            .fold(
1464                (TieredMulti::<SpendableNoteUndecoded>::default(), counts),
1465                |(mut notes, mut counts), (key, note)| async move {
1466                    let amount = key.amount;
1467                    if 0 < counts.get(amount) {
1468                        counts.dec(amount);
1469                        notes.push(amount, note);
1470                    }
1471
1472                    (notes, counts)
1473                },
1474            )
1475            .await
1476    }
1477
1478    // TODO: put "notes per denomination" default into cfg
1479    /// Creates a mint output close to the given `amount`, issuing e-cash
1480    /// notes such that the client holds `notes_per_denomination` notes of each
1481    /// e-cash note denomination held.
1482    pub async fn create_output(
1483        &self,
1484        dbtx: &mut DatabaseTransaction<'_>,
1485        operation_id: OperationId,
1486        notes_per_denomination: u16,
1487        exact_amount: Amount,
1488    ) -> ClientOutputBundle<MintOutput, MintClientStateMachines> {
1489        if exact_amount == Amount::ZERO {
1490            return ClientOutputBundle::new(vec![], vec![]);
1491        }
1492
1493        // Change layout: carve notes out of `exact_amount`, paying each note's
1494        // own fee from that same value (the leftover below a note's fee is dust).
1495        let denominations = represent_amount(
1496            exact_amount,
1497            &self.get_note_counts_by_denomination(dbtx).await,
1498            &self.cfg.tbs_pks,
1499            notes_per_denomination,
1500            &self.cfg.fee_consensus,
1501        );
1502
1503        self.create_output_for_denominations(dbtx, operation_id, denominations)
1504            .await
1505    }
1506
1507    /// Issues note outputs worth *exactly* `amount`, with no fee carved out of
1508    /// that value — the federation fee is funded separately by the primary
1509    /// module's balancing (extra inputs pulled in by
1510    /// `create_final_inputs_and_outputs`). This is how a *target* amount should
1511    /// be minted (e.g. an ecash send reissuing itself the denominations to hand
1512    /// out), as opposed to laying out change; it mirrors mintv2's `send`.
1513    ///
1514    /// Because the smallest denomination is 1 msat (denominations are
1515    /// contiguous powers of two), every amount is exactly representable, so
1516    /// a single reissue always yields notes that can be spent for the exact
1517    /// amount.
1518    async fn create_exact_output(
1519        &self,
1520        dbtx: &mut DatabaseTransaction<'_>,
1521        operation_id: OperationId,
1522        amount: Amount,
1523    ) -> ClientOutputBundle<MintOutput, MintClientStateMachines> {
1524        if amount == Amount::ZERO {
1525            return ClientOutputBundle::new(vec![], vec![]);
1526        }
1527
1528        self.create_output_for_denominations(
1529            dbtx,
1530            operation_id,
1531            self.represent_exact_amount(amount),
1532        )
1533        .await
1534    }
1535
1536    /// Decomposes `amount` into the minimal set of note denominations summing
1537    /// to *exactly* `amount` — a plain greedy power-of-two breakdown with
1538    /// no fee subtracted (unlike [`represent_amount`], which lays out
1539    /// change). Used when minting a target amount; see
1540    /// [`Self::create_exact_output`].
1541    fn represent_exact_amount(&self, amount: Amount) -> TieredCounts {
1542        represent_amount(
1543            amount,
1544            &TieredCounts::default(),
1545            &self.cfg.tbs_pks,
1546            0,
1547            &FeeConsensus::zero(),
1548        )
1549    }
1550
1551    async fn create_output_for_denominations(
1552        &self,
1553        dbtx: &mut DatabaseTransaction<'_>,
1554        operation_id: OperationId,
1555        denominations: TieredCounts,
1556    ) -> ClientOutputBundle<MintOutput, MintClientStateMachines> {
1557        let mut outputs = Vec::new();
1558        let mut issuance_requests = Vec::new();
1559
1560        for (amount, num) in denominations.iter() {
1561            for _ in 0..num {
1562                let (issuance_request, blind_nonce) = self.new_ecash_note(amount, dbtx).await;
1563
1564                debug!(
1565                    %amount,
1566                    "Generated issuance request"
1567                );
1568
1569                outputs.push(ClientOutput {
1570                    output: MintOutput::new_v0(amount, blind_nonce),
1571                    amounts: Amounts::new_bitcoin(amount),
1572                });
1573
1574                issuance_requests.push((amount, issuance_request));
1575            }
1576        }
1577
1578        let state_generator = Arc::new(move |out_point_range: OutPointRange| {
1579            assert_eq!(out_point_range.count(), issuance_requests.len());
1580            vec![MintClientStateMachines::Output(MintOutputStateMachine {
1581                common: MintOutputCommon {
1582                    operation_id,
1583                    out_point_range,
1584                },
1585                state: MintOutputStates::CreatedMulti(MintOutputStatesCreatedMulti {
1586                    issuance_requests: out_point_range
1587                        .into_iter()
1588                        .map(|out_point| out_point.out_idx)
1589                        .zip(issuance_requests.clone())
1590                        .collect(),
1591                }),
1592            })]
1593        });
1594
1595        ClientOutputBundle::new(
1596            outputs,
1597            vec![ClientOutputSM {
1598                state_machines: state_generator,
1599            }],
1600        )
1601    }
1602
1603    /// Returns the number of held e-cash notes per denomination
1604    pub async fn get_note_counts_by_denomination(
1605        &self,
1606        dbtx: &mut DatabaseTransaction<'_>,
1607    ) -> TieredCounts {
1608        dbtx.find_by_prefix(&NoteKeyPrefix)
1609            .await
1610            .fold(
1611                TieredCounts::default(),
1612                |mut acc, (key, _note)| async move {
1613                    acc.inc(key.amount, 1);
1614                    acc
1615                },
1616            )
1617            .await
1618    }
1619
1620    /// Returns the number of held e-cash notes per denomination
1621    #[deprecated(
1622        since = "0.5.0",
1623        note = "Use `get_note_counts_by_denomination` instead"
1624    )]
1625    pub async fn get_wallet_summary(&self, dbtx: &mut DatabaseTransaction<'_>) -> TieredCounts {
1626        self.get_note_counts_by_denomination(dbtx).await
1627    }
1628
1629    /// Estimates the total fees to spend all currently held notes.
1630    ///
1631    /// This is useful for calculating max withdrawable amounts, where all
1632    /// notes will be spent. Notes that are uneconomical to spend (fee >= value)
1633    /// are excluded from the calculation since the wallet won't spend them.
1634    pub async fn estimate_spend_all_fees(&self) -> Amount {
1635        let mut dbtx = self.client_ctx.module_db().begin_transaction_nc().await;
1636        let note_counts = self.get_note_counts_by_denomination(&mut dbtx).await;
1637
1638        note_counts
1639            .iter()
1640            .filter_map(|(amount, count)| {
1641                let note_fee = self.cfg.fee_consensus.fee(amount);
1642                if note_fee < amount {
1643                    note_fee.checked_mul(count as u64)
1644                } else {
1645                    None
1646                }
1647            })
1648            .fold(Amount::ZERO, |acc, fee| {
1649                acc.checked_add(fee).expect("fee sum overflow")
1650            })
1651    }
1652
1653    /// Wait for the e-cash notes to be retrieved. If this is not possible
1654    /// because another terminal state was reached an error describing the
1655    /// failure is returned.
1656    pub async fn await_output_finalized(
1657        &self,
1658        operation_id: OperationId,
1659        out_point: OutPoint,
1660    ) -> Result<(), AwaitOutputFinalizedError> {
1661        let stream = self
1662            .notifier
1663            .subscribe(operation_id)
1664            .await
1665            .filter_map(|state| async {
1666                let MintClientStateMachines::Output(state) = state else {
1667                    return None;
1668                };
1669
1670                if state.common.txid() != out_point.txid
1671                    || !state
1672                        .common
1673                        .out_point_range
1674                        .out_idx_iter()
1675                        .contains(&out_point.out_idx)
1676                {
1677                    return None;
1678                }
1679
1680                match state.state {
1681                    MintOutputStates::Succeeded(_) => Some(Ok(())),
1682                    MintOutputStates::Aborted(_) => {
1683                        Some(Err(AwaitOutputFinalizedError::TransactionRejected))
1684                    }
1685                    MintOutputStates::Failed(failed) => {
1686                        Some(Err(AwaitOutputFinalizedError::Failed {
1687                            reason: failed.error,
1688                        }))
1689                    }
1690                    MintOutputStates::Created(_) | MintOutputStates::CreatedMulti(_) => None,
1691                }
1692            });
1693        pin_mut!(stream);
1694
1695        stream.next_or_pending().await
1696    }
1697
1698    /// Provisional implementation of note consolidation
1699    ///
1700    /// When a certain denomination crosses the threshold of notes allowed,
1701    /// spend some chunk of them as inputs.
1702    ///
1703    /// Return notes and the sume of their amount.
1704    pub async fn consolidate_notes(
1705        &self,
1706        dbtx: &mut DatabaseTransaction<'_>,
1707    ) -> Result<Vec<(ClientInput<MintInput>, SpendableNote)>, ValidateNotesError> {
1708        /// At how many notes of the same denomination should we try to
1709        /// consolidate
1710        const MAX_NOTES_PER_TIER_TRIGGER: usize = 8;
1711        /// Number of notes per tier to leave after threshold was crossed
1712        const MIN_NOTES_PER_TIER: usize = 4;
1713        /// Maximum number of notes to consolidate per one tx,
1714        /// to limit the size of a transaction produced.
1715        const MAX_NOTES_TO_CONSOLIDATE_IN_TX: usize = 20;
1716        // it's fine, it's just documentation
1717        #[allow(clippy::assertions_on_constants)]
1718        {
1719            assert!(MIN_NOTES_PER_TIER <= MAX_NOTES_PER_TIER_TRIGGER);
1720        }
1721
1722        let counts = self.get_note_counts_by_denomination(dbtx).await;
1723
1724        let should_consolidate = counts
1725            .iter()
1726            .any(|(_, count)| MAX_NOTES_PER_TIER_TRIGGER < count);
1727
1728        if !should_consolidate {
1729            return Ok(vec![]);
1730        }
1731
1732        let mut max_count = MAX_NOTES_TO_CONSOLIDATE_IN_TX;
1733
1734        let excessive_counts: TieredCounts = counts
1735            .iter()
1736            .map(|(amount, count)| {
1737                let take = (count.saturating_sub(MIN_NOTES_PER_TIER)).min(max_count);
1738
1739                max_count -= take;
1740                (amount, take)
1741            })
1742            .collect();
1743
1744        let (selected_notes, unavailable) = self
1745            .get_available_notes_by_tier_counts(dbtx, excessive_counts)
1746            .await;
1747
1748        debug_assert!(
1749            unavailable.is_empty(),
1750            "Can't have unavailable notes on a subset of all notes: {unavailable:?}"
1751        );
1752
1753        if !selected_notes.is_empty() {
1754            debug!(target: LOG_CLIENT_MODULE_MINT, note_num=selected_notes.count_items(), denominations_msats=?selected_notes.iter_items().map(|(amount, _)| amount.msats).collect::<Vec<_>>(), "Will consolidate excessive notes");
1755        }
1756
1757        let mut selected_notes_decoded = vec![];
1758        for (amount, note) in selected_notes.iter_items() {
1759            let spendable_note_decoded = note.decode()?;
1760            debug!(target: LOG_CLIENT_MODULE_MINT, %amount, %note, "Consolidating note");
1761            Self::delete_spendable_note(&self.client_ctx, dbtx, amount, &spendable_note_decoded)
1762                .await;
1763            selected_notes_decoded.push((amount, spendable_note_decoded));
1764        }
1765
1766        let sender = self.balance_update_sender.clone();
1767        dbtx.on_commit(move || sender.send_replace(()));
1768
1769        self.create_input_from_notes(selected_notes_decoded.into_iter().collect())
1770    }
1771
1772    /// Create a mint input from external, potentially untrusted notes
1773    #[allow(clippy::type_complexity)]
1774    pub fn create_input_from_notes(
1775        &self,
1776        notes: TieredMulti<SpendableNote>,
1777    ) -> Result<Vec<(ClientInput<MintInput>, SpendableNote)>, ValidateNotesError> {
1778        let mut inputs_and_notes = Vec::new();
1779
1780        for (index, (amount, spendable_note)) in notes.into_iter_items().enumerate() {
1781            let key = self
1782                .cfg
1783                .tbs_pks
1784                .get(amount)
1785                .ok_or(ValidateNotesError::InvalidAmountTier { index, amount })?;
1786
1787            let note = spendable_note.note();
1788
1789            if !note.verify(*key) {
1790                return Err(ValidateNotesError::InvalidSignature { index });
1791            }
1792
1793            inputs_and_notes.push((
1794                ClientInput {
1795                    input: MintInput::new_v0(amount, note),
1796                    keys: vec![spendable_note.spend_key],
1797                    amounts: Amounts::new_bitcoin(amount),
1798                },
1799                spendable_note,
1800            ));
1801        }
1802
1803        Ok(inputs_and_notes)
1804    }
1805
1806    async fn spend_notes_oob(
1807        &self,
1808        dbtx: &mut DatabaseTransaction<'_>,
1809        notes_selector: &impl NotesSelector,
1810        amount: Amount,
1811        try_cancel_after: Option<Duration>,
1812    ) -> Result<
1813        (
1814            OperationId,
1815            Vec<MintClientStateMachines>,
1816            TieredMulti<SpendableNote>,
1817        ),
1818        SpendOOBError,
1819    > {
1820        if amount == Amount::ZERO {
1821            return Err(SpendOOBError::ZeroAmount);
1822        }
1823
1824        let selected_notes =
1825            Self::select_notes(dbtx, notes_selector, amount, FeeConsensus::zero()).await?;
1826
1827        let operation_id = spendable_notes_to_operation_id(&selected_notes);
1828
1829        for (amount, note) in selected_notes.iter_items() {
1830            debug!(target: LOG_CLIENT_MODULE_MINT, %amount, %note, "Spending note as oob");
1831            MintClientModule::delete_spendable_note(&self.client_ctx, dbtx, amount, note).await;
1832        }
1833
1834        let sender = self.balance_update_sender.clone();
1835        dbtx.on_commit(move || sender.send_replace(()));
1836
1837        let try_cancel_after = try_cancel_after.unwrap_or(OOB_SPEND_NO_TIMEOUT);
1838        let state_machines = if try_cancel_after == OOB_SPEND_NO_TIMEOUT {
1839            vec![]
1840        } else {
1841            vec![MintClientStateMachines::OOB(MintOOBStateMachine {
1842                operation_id,
1843                state: MintOOBStates::CreatedMulti(MintOOBStatesCreatedMulti {
1844                    spendable_notes: selected_notes.clone().into_iter_items().collect(),
1845                    timeout: fedimint_core::time::now() + try_cancel_after,
1846                }),
1847            })]
1848        };
1849
1850        Ok((operation_id, state_machines, selected_notes))
1851    }
1852
1853    async fn is_no_timeout_oob_spend(
1854        &self,
1855        operation_id: OperationId,
1856    ) -> Result<bool, SubscribeSpendNotesError> {
1857        let operation = self.mint_operation(operation_id).await?;
1858        let MintOperationMetaVariant::SpendOOB { no_timeout, .. } =
1859            operation.meta::<MintOperationMeta>().variant
1860        else {
1861            return Err(SubscribeSpendNotesError::NotAnOutOfBandSpend);
1862        };
1863
1864        Ok(no_timeout)
1865    }
1866
1867    pub async fn await_spend_oob_refund(&self, operation_id: OperationId) -> SpendOOBRefund {
1868        if self
1869            .is_no_timeout_oob_spend(operation_id)
1870            .await
1871            .unwrap_or(false)
1872        {
1873            return SpendOOBRefund {
1874                user_triggered: false,
1875                transaction_ids: vec![],
1876            };
1877        }
1878
1879        Box::pin(
1880            self.notifier
1881                .subscribe(operation_id)
1882                .await
1883                .filter_map(|state| async {
1884                    let MintClientStateMachines::OOB(state) = state else {
1885                        return None;
1886                    };
1887
1888                    match state.state {
1889                        MintOOBStates::TimeoutRefund(refund) => Some(SpendOOBRefund {
1890                            user_triggered: false,
1891                            transaction_ids: vec![refund.refund_txid],
1892                        }),
1893                        MintOOBStates::UserRefund(refund) => Some(SpendOOBRefund {
1894                            user_triggered: true,
1895                            transaction_ids: vec![refund.refund_txid],
1896                        }),
1897                        MintOOBStates::UserRefundMulti(refund) => Some(SpendOOBRefund {
1898                            user_triggered: true,
1899                            transaction_ids: vec![refund.refund_txid],
1900                        }),
1901                        MintOOBStates::Created(_) | MintOOBStates::CreatedMulti(_) => None,
1902                    }
1903                }),
1904        )
1905        .next_or_pending()
1906        .await
1907    }
1908
1909    /// Select notes with `requested_amount` using `notes_selector`.
1910    async fn select_notes(
1911        dbtx: &mut DatabaseTransaction<'_>,
1912        notes_selector: &impl NotesSelector,
1913        requested_amount: Amount,
1914        fee_consensus: FeeConsensus,
1915    ) -> Result<TieredMulti<SpendableNote>, SelectNotesError> {
1916        let note_stream = dbtx
1917            .find_by_prefix_sorted_descending(&NoteKeyPrefix)
1918            .await
1919            .map(|(key, note)| (key.amount, note));
1920
1921        notes_selector
1922            .select_notes(note_stream, requested_amount, fee_consensus)
1923            .await?
1924            .into_iter_items()
1925            .map(|(amt, snote)| Ok((amt, snote.decode()?)))
1926            .collect::<Result<TieredMulti<_>, SelectNotesError>>()
1927    }
1928
1929    async fn get_all_spendable_notes(
1930        dbtx: &mut DatabaseTransaction<'_>,
1931    ) -> TieredMulti<SpendableNoteUndecoded> {
1932        (dbtx
1933            .find_by_prefix(&NoteKeyPrefix)
1934            .await
1935            .map(|(key, note)| (key.amount, note))
1936            .collect::<Vec<_>>()
1937            .await)
1938            .into_iter()
1939            .collect()
1940    }
1941
1942    async fn get_next_note_index(
1943        &self,
1944        dbtx: &mut DatabaseTransaction<'_>,
1945        amount: Amount,
1946    ) -> NoteIndex {
1947        NoteIndex(
1948            dbtx.get_value(&NextECashNoteIndexKey(amount))
1949                .await
1950                .unwrap_or(0),
1951        )
1952    }
1953
1954    /// Derive the note `DerivableSecret` from the Mint's `secret` the `amount`
1955    /// tier and `note_idx`
1956    ///
1957    /// Static to help re-use in other places, that don't have a whole [`Self`]
1958    /// available
1959    ///
1960    /// # E-Cash Note Creation
1961    ///
1962    /// When creating an e-cash note, the `MintClientModule` first derives the
1963    /// blinding and spend keys from the `DerivableSecret`. It then creates a
1964    /// `NoteIssuanceRequest` containing the blinded spend key and sends it to
1965    /// the mint server. The mint server signs the blinded spend key and
1966    /// returns it to the client. The client can then unblind the signed
1967    /// spend key to obtain the e-cash note, which can be spent using the
1968    /// spend key.
1969    pub fn new_note_secret_static(
1970        secret: &DerivableSecret,
1971        amount: Amount,
1972        note_idx: NoteIndex,
1973    ) -> DerivableSecret {
1974        assert_eq!(secret.level(), 2);
1975        debug!(?secret, %amount, %note_idx, "Deriving new mint note");
1976        secret
1977            .child_key(MINT_E_CASH_TYPE_CHILD_ID) // TODO: cache
1978            .child_key(ChildId(note_idx.as_u64()))
1979            .child_key(ChildId(amount.msats))
1980    }
1981
1982    /// We always keep track of an incrementing index in the database and use
1983    /// it as part of the derivation path for the note secret. This ensures that
1984    /// we never reuse the same note secret twice.
1985    async fn new_note_secret(
1986        &self,
1987        amount: Amount,
1988        dbtx: &mut DatabaseTransaction<'_>,
1989    ) -> DerivableSecret {
1990        let new_idx = self.get_next_note_index(dbtx, amount).await;
1991        dbtx.insert_entry(&NextECashNoteIndexKey(amount), &new_idx.next().as_u64())
1992            .await;
1993        Self::new_note_secret_static(&self.secret, amount, new_idx)
1994    }
1995
1996    pub async fn new_ecash_note(
1997        &self,
1998        amount: Amount,
1999        dbtx: &mut DatabaseTransaction<'_>,
2000    ) -> (NoteIssuanceRequest, BlindNonce) {
2001        let secret = self.new_note_secret(amount, dbtx).await;
2002        NoteIssuanceRequest::new(&self.secp, &secret)
2003    }
2004
2005    /// Computes the exact fee `reissue_external_notes(oob_notes)` would incur
2006    /// given the wallet's current note inventory, without submitting anything.
2007    ///
2008    /// Runs the same change generation the real reissue does
2009    /// (`create_final_inputs_and_outputs`, including note consolidation)
2010    /// against a non-committable transaction that is dropped rather than
2011    /// committed, so the wallet's notes are read but left untouched. The
2012    /// quote is point-in-time: it depends on the current inventory and can
2013    /// move as notes change.
2014    pub async fn reissue_fee_quote(
2015        &self,
2016        oob_notes: &OOBNotes,
2017    ) -> Result<FeeQuote, TransactionSubmitError> {
2018        // A reissue submits the external notes as explicit inputs and no explicit
2019        // outputs; the shared, module-agnostic fee quote runs the primary-module
2020        // balancing (note consolidation + minting change) over the real
2021        // inventory.
2022        let input_amount = oob_notes.total_amount();
2023        let input_fee: Amount = oob_notes
2024            .notes()
2025            .iter_items()
2026            .map(|(amount, _)| self.cfg.fee_consensus.fee(amount))
2027            .sum();
2028
2029        self.client_ctx
2030            .fee_quote(
2031                OperationId::new_random(),
2032                FeeQuoteRequest {
2033                    input_amount: Amounts::new_bitcoin(input_amount),
2034                    output_amount: Amounts::ZERO,
2035                    input_fee: Amounts::new_bitcoin(input_fee),
2036                    output_fee: Amounts::ZERO,
2037                    account: Account::Primary,
2038                },
2039            )
2040            .await
2041    }
2042
2043    /// Computes the fee a `send_oob_notes(amount)` would incur given the
2044    /// wallet's current note inventory, without sending anything.
2045    ///
2046    /// A send is free when the wallet's existing notes can cover the (rounded)
2047    /// amount exactly — it just hands those notes out. Otherwise the send first
2048    /// reissues itself the right denominations, and that self-reissue
2049    /// transaction is the only thing a send ever pays a fee for. This quote
2050    /// mirrors that: it returns [`FeeQuote::ZERO`] when exact change is
2051    /// available, and otherwise quotes the reissue the same way the real send
2052    /// submits it (explicit outputs representing `amount`, no explicit inputs)
2053    /// via the shared, module-agnostic fee quote over the real inventory. The
2054    /// quote is point-in-time: it depends on the current inventory and can move
2055    /// as notes change.
2056    pub async fn send_fee_quote(&self, amount: Amount) -> Result<FeeQuote, TransactionSubmitError> {
2057        let amount = self.cfg.fee_consensus.round_up(amount);
2058
2059        let mut dbtx = self.client_ctx.module_db().begin_transaction_nc().await;
2060
2061        // Exact-change path: handing out existing notes never costs a fee. This
2062        // is the same selection `send_oob_notes` tries first (see
2063        // `try_spend_exact_notes_dbtx`).
2064        if Self::select_notes(
2065            &mut dbtx,
2066            &SelectNotesWithExactAmount,
2067            amount,
2068            FeeConsensus::zero(),
2069        )
2070        .await
2071        .is_ok()
2072        {
2073            return Ok(FeeQuote::ZERO);
2074        }
2075
2076        drop(dbtx);
2077
2078        // Reissue path: the send mints itself notes worth exactly `amount` as
2079        // explicit outputs (no explicit inputs) and the primary module funds and
2080        // balances it. Quote that exact transaction — the same exact
2081        // decomposition the real send's `create_exact_output` uses, so a single
2082        // reissue covers it.
2083        let denominations = self.represent_exact_amount(amount);
2084
2085        let output_amount = denominations.total_amount();
2086        let output_fee: Amount = denominations
2087            .iter()
2088            .map(|(denomination, count)| self.cfg.fee_consensus.fee(denomination) * count as u64)
2089            .sum();
2090
2091        self.client_ctx
2092            .fee_quote(
2093                OperationId::new_random(),
2094                FeeQuoteRequest {
2095                    input_amount: Amounts::ZERO,
2096                    output_amount: Amounts::new_bitcoin(output_amount),
2097                    input_fee: Amounts::ZERO,
2098                    output_fee: Amounts::new_bitcoin(output_fee),
2099                    account: Account::Primary,
2100                },
2101            )
2102            .await
2103    }
2104
2105    /// Try to reissue e-cash notes received from a third party to receive them
2106    /// in our wallet. The progress and outcome can be observed using
2107    /// [`MintClientModule::subscribe_reissue_external_notes`].
2108    ///
2109    /// ## Errors
2110    ///
2111    /// - [`ReissueExternalNotesError::ZeroAmount`] if the notes are worth
2112    ///   nothing.
2113    /// - [`ReissueExternalNotesError::WrongFederationId`] if the notes were
2114    ///   issued by a different federation.
2115    /// - [`ReissueExternalNotesError::AlreadyReissued`] if these exact notes
2116    ///   were already reissued.
2117    /// - [`ReissueExternalNotesError::Notes`] if the notes cannot be validated.
2118    /// - [`ReissueExternalNotesError::Transaction`] if the reissue transaction
2119    ///   could not be built or submitted.
2120    pub async fn reissue_external_notes<M: Serialize + Send>(
2121        &self,
2122        oob_notes: OOBNotes,
2123        extra_meta: M,
2124    ) -> Result<OperationId, ReissueExternalNotesError> {
2125        let notes = oob_notes.notes().clone();
2126        let federation_id_prefix = oob_notes.federation_id_prefix();
2127
2128        debug!(
2129            target: LOG_CLIENT_MODULE_MINT,
2130            notes = ?notes
2131                .iter_items()
2132                .map(|(amount, note)| (amount, note.nonce()))
2133                .collect::<Vec<_>>(),
2134            "Reissuing external notes"
2135        );
2136
2137        if notes.total_amount() == Amount::ZERO {
2138            return Err(ReissueExternalNotesError::ZeroAmount);
2139        }
2140
2141        if federation_id_prefix != self.federation_id.to_prefix() {
2142            return Err(ReissueExternalNotesError::WrongFederationId {
2143                expected: self.federation_id.to_prefix(),
2144                found: federation_id_prefix,
2145            });
2146        }
2147
2148        let operation_id = OperationId(
2149            notes
2150                .consensus_hash::<sha256t::Hash<OOBReissueTag>>()
2151                .to_byte_array(),
2152        );
2153
2154        let amount = notes.total_amount();
2155        let mint_inputs = self.create_input_from_notes(notes)?;
2156
2157        let tx = TransactionBuilder::new(Account::Primary).with_inputs(
2158            self.client_ctx
2159                .make_dyn(create_bundle_for_inputs(mint_inputs, operation_id)),
2160        );
2161
2162        let extra_meta = serde_json::to_value(extra_meta)
2163            .expect("MintClientModule::reissue_external_notes extra_meta is serializable");
2164        let operation_meta_gen = move |change_range: OutPointRange| MintOperationMeta {
2165            variant: MintOperationMetaVariant::Reissuance {
2166                legacy_out_point: None,
2167                txid: Some(change_range.txid()),
2168                out_point_indices: change_range
2169                    .into_iter()
2170                    .map(|out_point| out_point.out_idx)
2171                    .collect(),
2172            },
2173            amount,
2174            extra_meta: extra_meta.clone(),
2175        };
2176
2177        self.client_ctx
2178            .finalize_and_submit_transaction_with_events(
2179                operation_id,
2180                MintCommonInit::KIND.as_str(),
2181                operation_meta_gen,
2182                tx,
2183                vec![
2184                    self.client_ctx.make_event(OOBNotesReissued { amount }),
2185                    self.client_ctx.make_event(ReceivePaymentEvent {
2186                        operation_id,
2187                        amount,
2188                    }),
2189                ],
2190            )
2191            .await
2192            .map_err(|error| match error {
2193                TransactionSubmitError::OperationAlreadyExists(_) => {
2194                    ReissueExternalNotesError::AlreadyReissued
2195                }
2196                error => ReissueExternalNotesError::Transaction(error),
2197            })?;
2198
2199        Ok(operation_id)
2200    }
2201
2202    /// Subscribe to updates on the progress of a reissue operation started with
2203    /// [`MintClientModule::reissue_external_notes`].
2204    pub async fn subscribe_reissue_external_notes(
2205        &self,
2206        operation_id: OperationId,
2207    ) -> SubscribeReissueExternalNotesResult {
2208        let operation = self.mint_operation(operation_id).await?;
2209        let (txid, out_points) = match operation.meta::<MintOperationMeta>().variant {
2210            MintOperationMetaVariant::Reissuance {
2211                legacy_out_point,
2212                txid,
2213                out_point_indices,
2214            } => {
2215                // Either txid or legacy_out_point will be present, so we should always
2216                // have a source for the txid
2217                let txid = txid
2218                    .or(legacy_out_point.map(|out_point| out_point.txid))
2219                    .ok_or(SubscribeReissueExternalNotesError::NoTransaction)?;
2220
2221                let out_points = out_point_indices
2222                    .into_iter()
2223                    .map(|out_idx| OutPoint { txid, out_idx })
2224                    .chain(legacy_out_point)
2225                    .collect::<Vec<_>>();
2226
2227                (txid, out_points)
2228            }
2229            MintOperationMetaVariant::SpendOOB { .. } => {
2230                return Err(SubscribeReissueExternalNotesError::NotAReissuance);
2231            }
2232        };
2233
2234        let client_ctx = self.client_ctx.clone();
2235
2236        Ok(self.client_ctx.outcome_or_updates(
2237            &operation,
2238            operation_id,
2239            |state| match state {
2240                ReissueExternalNotesState::Created | ReissueExternalNotesState::Issuing => false,
2241                ReissueExternalNotesState::Done | ReissueExternalNotesState::Failed(_) => true,
2242            },
2243            move || {
2244            stream! {
2245                yield ReissueExternalNotesState::Created;
2246
2247                match client_ctx
2248                    .transaction_updates(operation_id)
2249                    .await
2250                    .await_tx_accepted(txid)
2251                    .await
2252                {
2253                    Ok(()) => {
2254                        yield ReissueExternalNotesState::Issuing;
2255                    }
2256                    Err(e) => {
2257                        yield ReissueExternalNotesState::Failed(format!("Transaction not accepted {e:?}"));
2258                        return;
2259                    }
2260                }
2261
2262                for out_point in out_points {
2263                    if let Err(e) = client_ctx.self_ref().await_output_finalized(operation_id, out_point).await {
2264                        yield ReissueExternalNotesState::Failed(e.fmt_compact().to_string());
2265                        return;
2266                    }
2267                }
2268                yield ReissueExternalNotesState::Done;
2269            }}
2270        ))
2271    }
2272
2273    /// Fetches and removes notes of *at least* amount `min_amount` from the
2274    /// wallet to be sent to the recipient out of band. These spends can be
2275    /// canceled by calling [`MintClientModule::try_cancel_spend_notes`] as long
2276    /// as the recipient hasn't reissued the e-cash notes themselves yet.
2277    ///
2278    /// The client will also automatically attempt to cancel the operation after
2279    /// `try_cancel_after` time has passed. This is a safety mechanism to avoid
2280    /// users forgetting about failed out-of-band transactions. The timeout
2281    /// should be chosen such that the recipient (who is potentially offline at
2282    /// the time of receiving the e-cash notes) had a reasonable timeframe to
2283    /// come online and reissue the notes themselves. Pass `None` to disable
2284    /// automatic cancellation.
2285    #[deprecated(
2286        since = "0.5.0",
2287        note = "Use `spend_notes_with_selector` instead, with `SelectNotesWithAtleastAmount` to maintain the same behavior"
2288    )]
2289    pub async fn spend_notes<M: Serialize + Send>(
2290        &self,
2291        min_amount: Amount,
2292        try_cancel_after: Option<Duration>,
2293        include_invite: bool,
2294        extra_meta: M,
2295    ) -> Result<(OperationId, OOBNotes), SpendOOBError> {
2296        self.spend_notes_with_selector(
2297            &SelectNotesWithAtleastAmount,
2298            min_amount,
2299            try_cancel_after,
2300            include_invite,
2301            extra_meta,
2302        )
2303        .await
2304    }
2305
2306    /// Fetches and removes notes from the wallet to be sent to the recipient
2307    /// out of band. The note selection algorithm is determined by
2308    /// `note_selector`. See the [`NotesSelector`] trait for available
2309    /// implementations.
2310    ///
2311    /// These spends can be canceled by calling
2312    /// [`MintClientModule::try_cancel_spend_notes`] as long
2313    /// as the recipient hasn't reissued the e-cash notes themselves yet.
2314    ///
2315    /// The client will also automatically attempt to cancel the operation after
2316    /// `try_cancel_after` time has passed. This is a safety mechanism to avoid
2317    /// users forgetting about failed out-of-band transactions. The timeout
2318    /// should be chosen such that the recipient (who is potentially offline at
2319    /// the time of receiving the e-cash notes) had a reasonable timeframe to
2320    /// come online and reissue the notes themselves. Pass `None` to disable
2321    /// automatic cancellation.
2322    pub async fn spend_notes_with_selector<M: Serialize + Send>(
2323        &self,
2324        notes_selector: &impl NotesSelector,
2325        requested_amount: Amount,
2326        try_cancel_after: Option<Duration>,
2327        include_invite: bool,
2328        extra_meta: M,
2329    ) -> Result<(OperationId, OOBNotes), SpendOOBError> {
2330        let federation_id_prefix = self.federation_id.to_prefix();
2331        let extra_meta = serde_json::to_value(extra_meta)
2332            .expect("MintClientModule::spend_notes extra_meta is serializable");
2333
2334        self.client_ctx
2335            .module_db()
2336            .autocommit(
2337                |dbtx, _| {
2338                    let extra_meta = extra_meta.clone();
2339                    Box::pin(async {
2340                        let no_timeout = try_cancel_after.is_none();
2341                        let (operation_id, states, notes) = self
2342                            .spend_notes_oob(
2343                                dbtx,
2344                                notes_selector,
2345                                requested_amount,
2346                                try_cancel_after,
2347                            )
2348                            .await?;
2349
2350                        let oob_notes = if include_invite {
2351                            OOBNotes::new_with_invite(
2352                                notes,
2353                                &self.client_ctx.get_invite_code().await,
2354                            )
2355                        } else {
2356                            OOBNotes::new(federation_id_prefix, notes)
2357                        };
2358
2359                        self.client_ctx
2360                            .add_state_machines_dbtx(
2361                                dbtx,
2362                                self.client_ctx.map_dyn(states).collect(),
2363                            )
2364                            .await?;
2365                        self.client_ctx
2366                            .add_operation_log_entry_dbtx(
2367                                dbtx,
2368                                operation_id,
2369                                Account::Primary,
2370                                MintCommonInit::KIND.as_str(),
2371                                MintOperationMeta {
2372                                    variant: MintOperationMetaVariant::SpendOOB {
2373                                        requested_amount,
2374                                        oob_notes: oob_notes.clone(),
2375                                        no_timeout,
2376                                    },
2377                                    amount: oob_notes.total_amount(),
2378                                    extra_meta,
2379                                },
2380                            )
2381                            .await;
2382                        self.client_ctx
2383                            .log_event(
2384                                dbtx,
2385                                OOBNotesSpent {
2386                                    requested_amount,
2387                                    spent_amount: oob_notes.total_amount(),
2388                                    timeout: try_cancel_after,
2389                                    include_invite,
2390                                },
2391                            )
2392                            .await;
2393
2394                        self.client_ctx
2395                            .log_event(
2396                                dbtx,
2397                                SendPaymentEvent {
2398                                    operation_id,
2399                                    amount: oob_notes.total_amount(),
2400                                    oob_notes: encode_prefixed(FEDIMINT_PREFIX, &oob_notes),
2401                                },
2402                            )
2403                            .await;
2404
2405                        Ok::<_, SpendOOBError>((operation_id, oob_notes))
2406                    })
2407                },
2408                Some(100),
2409            )
2410            .await
2411            .map_err(|e| match e {
2412                AutocommitError::ClosureError { error, .. } => error,
2413                AutocommitError::CommitFailed { last_error, .. } => {
2414                    SpendOOBError::Database(last_error)
2415                }
2416            })
2417    }
2418
2419    /// Send e-cash notes for the requested amount.
2420    ///
2421    /// When this method removes ecash notes from the local database it will do
2422    /// so atomically with creating a `SendPaymentEvent` that contains the notes
2423    /// in out of band serilaized from. Hence it is critical for the integrator
2424    /// to display this event to ensure the user always has access to his funds.
2425    ///
2426    /// This method operates in two modes:
2427    ///
2428    /// 1. **Offline mode**: If exact notes are available in the wallet, they
2429    ///    are spent immediately without contacting the federation. A
2430    ///    `SendPaymentEvent` is emitted and the notes are returned.
2431    ///
2432    /// 2. **Online mode**: If exact notes are not available, the method
2433    ///    contacts the federation to trigger a reissuance transaction to obtain
2434    ///    the proper denominations. The method will block until the reissuance
2435    ///    completes, at which point a `SendPaymentEvent` is emitted and the
2436    ///    notes are returned.
2437    ///
2438    /// If the method enters online mode and is cancelled, e.g. the future is
2439    /// dropped, before the reissue transaction is confirmed, any reissued notes
2440    /// will be returned to the wallet and we do not emit a `SendPaymentEvent`.
2441    ///
2442    /// If the federation charges fees, the amount is rounded up to the nearest
2443    /// multiple of the smallest economical denomination before selection of the
2444    /// ecash notes.
2445    pub async fn send_oob_notes<M: Serialize + Send>(
2446        &self,
2447        amount: Amount,
2448        extra_meta: M,
2449    ) -> Result<OOBNotes, SendOOBNotesError> {
2450        let amount = self.cfg.fee_consensus.round_up(amount);
2451
2452        let extra_meta = serde_json::to_value(extra_meta)
2453            .expect("MintClientModule::send_oob_notes extra_meta is serializable");
2454
2455        // Try to spend exact notes from our current balance
2456        let oob_notes: Option<OOBNotes> = self
2457            .client_ctx
2458            .module_db()
2459            .autocommit(
2460                |dbtx, _| {
2461                    let extra_meta = extra_meta.clone();
2462                    Box::pin(async {
2463                        Ok::<Option<OOBNotes>, SendOOBNotesError>(
2464                            self.try_spend_exact_notes_dbtx(
2465                                dbtx,
2466                                amount,
2467                                self.federation_id,
2468                                extra_meta,
2469                            )
2470                            .await,
2471                        )
2472                    })
2473                },
2474                Some(100),
2475            )
2476            .await
2477            .map_err(|e| match e {
2478                AutocommitError::ClosureError { error, .. } => error,
2479                AutocommitError::CommitFailed { last_error, .. } => {
2480                    SendOOBNotesError::Database(last_error)
2481                }
2482            })?;
2483
2484        if let Some(oob_notes) = oob_notes {
2485            return Ok(oob_notes);
2486        }
2487
2488        // Verify we're online
2489        self.client_ctx.global_api().session_count().await?;
2490
2491        let operation_id = OperationId::new_random();
2492
2493        // Reissue ourselves notes worth *exactly* `amount` (fee funded by the
2494        // balancing layer), so the retry below can hand out the exact amount in a
2495        // single reissue — rather than minting `amount` minus fees and having to
2496        // reissue repeatedly to make up the difference. Commit the note index
2497        // counter updates so create_final_inputs_and_outputs won't reuse the same
2498        // indices for change outputs.
2499        let output_bundle = self
2500            .client_ctx
2501            .module_db()
2502            .autocommit(
2503                |dbtx, _| {
2504                    Box::pin(async {
2505                        Ok::<_, SendOOBNotesError>(
2506                            self.create_exact_output(dbtx, operation_id, amount).await,
2507                        )
2508                    })
2509                },
2510                Some(100),
2511            )
2512            .await
2513            .map_err(|e| match e {
2514                AutocommitError::ClosureError { error, .. } => error,
2515                AutocommitError::CommitFailed { last_error, .. } => {
2516                    SendOOBNotesError::Database(last_error)
2517                }
2518            })?;
2519
2520        // The explicit outputs we just minted (worth exactly `amount`) occupy the
2521        // first `explicit_output_count` out points of the transaction; the
2522        // primary module's change is appended after them. The recursion below
2523        // hands out these exact notes, so we must wait for *them* to finalize —
2524        // not just the change.
2525        let explicit_output_count = output_bundle.outputs().len() as u64;
2526
2527        // Combine the output bundle state machines with the send state machine
2528        let combined_bundle = ClientOutputBundle::new(
2529            output_bundle.outputs().to_vec(),
2530            output_bundle.sms().to_vec(),
2531        );
2532
2533        let outputs = self.client_ctx.make_client_outputs(combined_bundle);
2534
2535        let em_clone = extra_meta.clone();
2536
2537        // Submit reissuance transaction with the state machines
2538        let out_point_range = self
2539            .client_ctx
2540            .finalize_and_submit_transaction(
2541                operation_id,
2542                MintCommonInit::KIND.as_str(),
2543                move |change_range: OutPointRange| MintOperationMeta {
2544                    variant: MintOperationMetaVariant::Reissuance {
2545                        legacy_out_point: None,
2546                        txid: Some(change_range.txid()),
2547                        out_point_indices: change_range
2548                            .into_iter()
2549                            .map(|out_point| out_point.out_idx)
2550                            .collect(),
2551                    },
2552                    amount,
2553                    extra_meta: em_clone.clone(),
2554                },
2555                TransactionBuilder::new(Account::Primary).with_outputs(outputs),
2556            )
2557            .await?;
2558
2559        // Wait for *all* of the transaction's outputs to be finalized — both the
2560        // change (returned in `out_point_range`) and the explicit exact-amount
2561        // notes at out points `[0, explicit_output_count)`. The recursion below
2562        // can only hand out the exact notes once they are spendable; awaiting
2563        // only the change (as before) raced the recursion against issuance,
2564        // causing it to re-reissue and drain the wallet.
2565        let txid = out_point_range.txid();
2566        let total_output_count = explicit_output_count + out_point_range.count() as u64;
2567        let all_outputs = OutPointRange::new(txid, IdxRange::from(0..total_output_count));
2568        self.client_ctx
2569            .await_primary_module_outputs(operation_id, all_outputs.into_iter().collect())
2570            .await?;
2571
2572        // Recursively call send_oob_notes to try again with the reissued notes
2573        Box::pin(self.send_oob_notes(amount, extra_meta)).await
2574    }
2575
2576    /// Try to spend exact notes from the current balance.
2577    /// Returns `Some(OOBNotes)` if exact notes are available, `None` otherwise.
2578    async fn try_spend_exact_notes_dbtx(
2579        &self,
2580        dbtx: &mut DatabaseTransaction<'_>,
2581        amount: Amount,
2582        federation_id: FederationId,
2583        extra_meta: serde_json::Value,
2584    ) -> Option<OOBNotes> {
2585        let selected_notes = Self::select_notes(
2586            dbtx,
2587            &SelectNotesWithExactAmount,
2588            amount,
2589            FeeConsensus::zero(),
2590        )
2591        .await
2592        .ok()?;
2593
2594        // Remove notes from our database
2595        for (note_amount, note) in selected_notes.iter_items() {
2596            MintClientModule::delete_spendable_note(&self.client_ctx, dbtx, note_amount, note)
2597                .await;
2598        }
2599
2600        let sender = self.balance_update_sender.clone();
2601        dbtx.on_commit(move || sender.send_replace(()));
2602
2603        let operation_id = spendable_notes_to_operation_id(&selected_notes);
2604
2605        let oob_notes = OOBNotes::new(federation_id.to_prefix(), selected_notes);
2606
2607        // Log the send operation with notes immediately available
2608        self.client_ctx
2609            .add_operation_log_entry_dbtx(
2610                dbtx,
2611                operation_id,
2612                Account::Primary,
2613                MintCommonInit::KIND.as_str(),
2614                MintOperationMeta {
2615                    variant: MintOperationMetaVariant::SpendOOB {
2616                        requested_amount: amount,
2617                        oob_notes: oob_notes.clone(),
2618                        no_timeout: true,
2619                    },
2620                    amount: oob_notes.total_amount(),
2621                    extra_meta,
2622                },
2623            )
2624            .await;
2625
2626        self.client_ctx
2627            .log_event(
2628                dbtx,
2629                SendPaymentEvent {
2630                    operation_id,
2631                    amount: oob_notes.total_amount(),
2632                    oob_notes: encode_prefixed(FEDIMINT_PREFIX, &oob_notes),
2633                },
2634            )
2635            .await;
2636
2637        Some(oob_notes)
2638    }
2639
2640    /// Validate the given notes and return the total amount of the notes.
2641    /// Validation checks that:
2642    /// - the federation ID is correct
2643    /// - the note has a valid signature
2644    /// - the spend key is correct.
2645    pub fn validate_notes(&self, oob_notes: &OOBNotes) -> Result<Amount, ValidateNotesError> {
2646        let federation_id_prefix = oob_notes.federation_id_prefix();
2647        let notes = oob_notes.notes().clone();
2648
2649        let expected = self.federation_id.to_prefix();
2650        if federation_id_prefix != expected {
2651            return Err(ValidateNotesError::WrongFederationId {
2652                expected,
2653                found: federation_id_prefix,
2654            });
2655        }
2656
2657        let tbs_pks = &self.cfg.tbs_pks;
2658
2659        for (index, (amt, snote)) in notes.iter_items().enumerate() {
2660            let key = tbs_pks
2661                .get(amt)
2662                .ok_or(ValidateNotesError::InvalidAmountTier { index, amount: amt })?;
2663
2664            let note = snote.note();
2665            if !note.verify(*key) {
2666                return Err(ValidateNotesError::InvalidSignature { index });
2667            }
2668
2669            let expected_nonce = Nonce(snote.spend_key.public_key());
2670            if note.nonce != expected_nonce {
2671                return Err(ValidateNotesError::WrongSpendKey { index });
2672            }
2673        }
2674
2675        Ok(notes.total_amount())
2676    }
2677
2678    /// Contacts the mint and checks if the supplied notes were already spent.
2679    ///
2680    /// **Caution:** This reduces privacy and can lead to race conditions. **DO
2681    /// NOT** rely on it for receiving funds unless you really know what you are
2682    /// doing.
2683    pub async fn check_note_spent(&self, oob_notes: &OOBNotes) -> FederationResult<bool> {
2684        use crate::api::MintFederationApi;
2685
2686        let api_client = self.client_ctx.module_api();
2687        let any_spent = try_join_all(oob_notes.notes().iter().flat_map(|(_, notes)| {
2688            notes
2689                .iter()
2690                .map(|note| api_client.check_note_spent(note.nonce()))
2691        }))
2692        .await?
2693        .into_iter()
2694        .any(|spent| spent);
2695
2696        Ok(any_spent)
2697    }
2698
2699    /// Try to cancel a spend operation started with
2700    /// [`MintClientModule::spend_notes_with_selector`]. If the e-cash notes
2701    /// have already been spent this operation will fail which can be
2702    /// observed using [`MintClientModule::subscribe_spend_notes`].
2703    pub async fn try_cancel_spend_notes(&self, operation_id: OperationId) {
2704        let mut dbtx = self.client_ctx.module_db().begin_transaction().await;
2705        dbtx.insert_entry(&CancelledOOBSpendKey(operation_id), &())
2706            .await;
2707        if let Err(e) = dbtx.commit_tx_result().await {
2708            warn!("We tried to cancel the same OOB spend multiple times concurrently: {e}");
2709        }
2710    }
2711
2712    /// Subscribe to updates on the progress of a raw e-cash spend operation
2713    /// started with [`MintClientModule::spend_notes_with_selector`].
2714    pub async fn subscribe_spend_notes(
2715        &self,
2716        operation_id: OperationId,
2717    ) -> Result<UpdateStreamOrOutcome<SpendOOBState>, SubscribeSpendNotesError> {
2718        let operation = self.mint_operation(operation_id).await?;
2719        let MintOperationMetaVariant::SpendOOB { no_timeout, .. } =
2720            operation.meta::<MintOperationMeta>().variant
2721        else {
2722            return Err(SubscribeSpendNotesError::NotAnOutOfBandSpend);
2723        };
2724
2725        let client_ctx = self.client_ctx.clone();
2726
2727        Ok(self.client_ctx.outcome_or_updates(
2728            &operation,
2729            operation_id,
2730            |state| match state {
2731                SpendOOBState::Created | SpendOOBState::UserCanceledProcessing => false,
2732                SpendOOBState::UserCanceledSuccess
2733                | SpendOOBState::UserCanceledFailure
2734                | SpendOOBState::Success
2735                | SpendOOBState::Refunded => true,
2736            },
2737            move || {
2738                stream! {
2739                    yield SpendOOBState::Created;
2740
2741                    if no_timeout {
2742                        yield SpendOOBState::Success;
2743                        return;
2744                    }
2745
2746                    let self_ref = client_ctx.self_ref();
2747
2748                    let refund = self_ref
2749                        .await_spend_oob_refund(operation_id)
2750                        .await;
2751
2752                    if refund.user_triggered {
2753                        yield SpendOOBState::UserCanceledProcessing;
2754                    }
2755
2756                    let mut success = true;
2757
2758                    for txid in refund.transaction_ids {
2759                        debug!(
2760                            target: LOG_CLIENT_MODULE_MINT,
2761                            %txid,
2762                            operation_id=%operation_id.fmt_short(),
2763                            "Waiting for oob refund txid"
2764                        );
2765                        if client_ctx
2766                            .transaction_updates(operation_id)
2767                            .await
2768                            .await_tx_accepted(txid)
2769                            .await.is_err() {
2770                                success = false;
2771                            }
2772                    }
2773
2774                    debug!(
2775                        target: LOG_CLIENT_MODULE_MINT,
2776                        operation_id=%operation_id.fmt_short(),
2777                        %success,
2778                        "Done waiting for all refund oob txids"
2779                     );
2780
2781                    match (refund.user_triggered, success) {
2782                        (true, true) => {
2783                            yield SpendOOBState::UserCanceledSuccess;
2784                        },
2785                        (true, false) => {
2786                            yield SpendOOBState::UserCanceledFailure;
2787                        },
2788                        (false, true) => {
2789                            yield SpendOOBState::Refunded;
2790                        },
2791                        (false, false) => {
2792                            yield SpendOOBState::Success;
2793                        }
2794                    }
2795                }
2796            },
2797        ))
2798    }
2799
2800    async fn mint_operation(
2801        &self,
2802        operation_id: OperationId,
2803    ) -> Result<OperationLogEntry, OperationLookupError> {
2804        self.client_ctx.get_operation(operation_id).await
2805    }
2806
2807    async fn delete_spendable_note(
2808        client_ctx: &ClientContext<MintClientModule>,
2809        dbtx: &mut DatabaseTransaction<'_>,
2810        amount: Amount,
2811        note: &SpendableNote,
2812    ) {
2813        client_ctx
2814            .log_event(
2815                dbtx,
2816                NoteSpent {
2817                    nonce: note.nonce(),
2818                },
2819            )
2820            .await;
2821        dbtx.remove_entry(&NoteKey {
2822            amount,
2823            nonce: note.nonce(),
2824        })
2825        .await
2826        .expect("Must deleted existing spendable note");
2827    }
2828
2829    pub async fn advance_note_idx(&self, amount: Amount) -> DerivableSecret {
2830        let db = self.client_ctx.module_db().clone();
2831
2832        db.autocommit(
2833            |dbtx, _| {
2834                Box::pin(async {
2835                    Ok::<DerivableSecret, std::convert::Infallible>(
2836                        self.new_note_secret(amount, dbtx).await,
2837                    )
2838                })
2839            },
2840            None,
2841        )
2842        .await
2843        .expect("The commit is retried until it succeeds and the closure cannot fail")
2844    }
2845
2846    /// Returns secrets for the note indices that were reused by previous
2847    /// clients with same client secret.
2848    pub async fn reused_note_secrets(&self) -> Vec<(Amount, NoteIssuanceRequest, BlindNonce)> {
2849        self.client_ctx
2850            .module_db()
2851            .begin_transaction_nc()
2852            .await
2853            .get_value(&ReusedNoteIndices)
2854            .await
2855            .unwrap_or_default()
2856            .into_iter()
2857            .map(|(amount, note_idx)| {
2858                let secret = Self::new_note_secret_static(&self.secret, amount, note_idx);
2859                let (request, blind_nonce) =
2860                    NoteIssuanceRequest::new(fedimint_core::secp256k1::SECP256K1, &secret);
2861                (amount, request, blind_nonce)
2862            })
2863            .collect()
2864    }
2865}
2866
2867pub fn spendable_notes_to_operation_id(
2868    spendable_selected_notes: &TieredMulti<SpendableNote>,
2869) -> OperationId {
2870    OperationId(
2871        spendable_selected_notes
2872            .consensus_hash::<sha256t::Hash<OOBSpendTag>>()
2873            .to_byte_array(),
2874    )
2875}
2876
2877#[derive(Debug, Serialize, Deserialize, Clone)]
2878pub struct SpendOOBRefund {
2879    pub user_triggered: bool,
2880    /// Empty when the spend disabled automatic refunds and no refund was
2881    /// attempted.
2882    pub transaction_ids: Vec<TransactionId>,
2883}
2884
2885/// Defines a strategy for selecting e-cash notes given a specific target amount
2886/// and fee per note transaction input.
2887#[apply(async_trait_maybe_send!)]
2888pub trait NotesSelector<Note = SpendableNoteUndecoded>: Send + Sync {
2889    /// Select notes from stream for `requested_amount`.
2890    /// The stream must produce items in non- decreasing order of amount.
2891    async fn select_notes(
2892        &self,
2893        // FIXME: async trait doesn't like maybe_add_send
2894        #[cfg(not(target_family = "wasm"))] stream: impl futures::Stream<Item = (Amount, Note)> + Send,
2895        #[cfg(target_family = "wasm")] stream: impl futures::Stream<Item = (Amount, Note)>,
2896        requested_amount: Amount,
2897        fee_consensus: FeeConsensus,
2898    ) -> Result<TieredMulti<Note>, SelectNotesError>;
2899}
2900
2901/// Select notes with total amount of *at least* `request_amount`. If more than
2902/// requested amount of notes are returned it was because exact change couldn't
2903/// be made, and the next smallest amount will be returned.
2904///
2905/// The caller can request change from the federation.
2906pub struct SelectNotesWithAtleastAmount;
2907
2908#[apply(async_trait_maybe_send!)]
2909impl<Note: Send> NotesSelector<Note> for SelectNotesWithAtleastAmount {
2910    async fn select_notes(
2911        &self,
2912        #[cfg(not(target_family = "wasm"))] stream: impl futures::Stream<Item = (Amount, Note)> + Send,
2913        #[cfg(target_family = "wasm")] stream: impl futures::Stream<Item = (Amount, Note)>,
2914        requested_amount: Amount,
2915        fee_consensus: FeeConsensus,
2916    ) -> Result<TieredMulti<Note>, SelectNotesError> {
2917        Ok(select_notes_from_stream(stream, requested_amount, fee_consensus).await?)
2918    }
2919}
2920
2921/// Select notes with total amount of *exactly* `request_amount`. If the amount
2922/// cannot be represented with the available denominations an error is returned,
2923/// this **does not** mean that the balance is too low.
2924pub struct SelectNotesWithExactAmount;
2925
2926#[apply(async_trait_maybe_send!)]
2927impl<Note: Send> NotesSelector<Note> for SelectNotesWithExactAmount {
2928    async fn select_notes(
2929        &self,
2930        #[cfg(not(target_family = "wasm"))] stream: impl futures::Stream<Item = (Amount, Note)> + Send,
2931        #[cfg(target_family = "wasm")] stream: impl futures::Stream<Item = (Amount, Note)>,
2932        requested_amount: Amount,
2933        fee_consensus: FeeConsensus,
2934    ) -> Result<TieredMulti<Note>, SelectNotesError> {
2935        let notes = select_notes_from_stream(stream, requested_amount, fee_consensus).await?;
2936
2937        let selected = notes.total_amount();
2938        if selected != requested_amount {
2939            return Err(SelectNotesError::NoExactAmount {
2940                requested: requested_amount,
2941                selected,
2942            });
2943        }
2944
2945        Ok(notes)
2946    }
2947}
2948
2949// We are using a greedy algorithm to select notes. We start with the largest
2950// then proceed to the lowest tiers/denominations.
2951// But there is a catch: we don't know if there are enough notes in the lowest
2952// tiers, so we need to save a big note in case the sum of the following
2953// small notes are not enough.
2954async fn select_notes_from_stream<Note>(
2955    stream: impl futures::Stream<Item = (Amount, Note)>,
2956    requested_amount: Amount,
2957    fee_consensus: FeeConsensus,
2958) -> Result<TieredMulti<Note>, InsufficientBalanceError> {
2959    if requested_amount == Amount::ZERO {
2960        return Ok(TieredMulti::default());
2961    }
2962    let mut stream = Box::pin(stream);
2963    let mut selected = vec![];
2964    // This is the big note we save in case the sum of the following small notes are
2965    // not sufficient to cover the pending amount
2966    // The tuple is (amount, note, checkpoint), where checkpoint is the index where
2967    // the note should be inserted on the selected vector if it is needed
2968    let mut last_big_note_checkpoint: Option<(Amount, Note, usize)> = None;
2969    let mut pending_amount = requested_amount;
2970    let mut previous_amount: Option<Amount> = None; // used to assert descending order
2971    loop {
2972        if let Some((note_amount, note)) = stream.next().await {
2973            assert!(
2974                previous_amount.is_none_or(|previous| previous >= note_amount),
2975                "notes are not sorted in descending order"
2976            );
2977            previous_amount = Some(note_amount);
2978
2979            if note_amount <= fee_consensus.fee(note_amount) {
2980                continue;
2981            }
2982
2983            match note_amount.cmp(&(pending_amount + fee_consensus.fee(note_amount))) {
2984                Ordering::Less => {
2985                    // keep adding notes until we have enough
2986                    pending_amount += fee_consensus.fee(note_amount);
2987                    pending_amount -= note_amount;
2988                    selected.push((note_amount, note));
2989                }
2990                Ordering::Greater => {
2991                    // probably we don't need this big note, but we'll keep it in case the
2992                    // following small notes don't add up to the
2993                    // requested amount
2994                    last_big_note_checkpoint = Some((note_amount, note, selected.len()));
2995                }
2996                Ordering::Equal => {
2997                    // exactly enough notes, return
2998                    selected.push((note_amount, note));
2999
3000                    let notes: TieredMulti<Note> = selected.into_iter().collect();
3001
3002                    assert!(
3003                        notes.total_amount().msats
3004                            >= requested_amount.msats
3005                                + notes
3006                                    .iter()
3007                                    .map(|note| fee_consensus.fee(note.0))
3008                                    .sum::<Amount>()
3009                                    .msats
3010                    );
3011
3012                    return Ok(notes);
3013                }
3014            }
3015        } else {
3016            assert!(pending_amount > Amount::ZERO);
3017            if let Some((big_note_amount, big_note, checkpoint)) = last_big_note_checkpoint {
3018                // the sum of the small notes don't add up to the pending amount, remove
3019                // them
3020                selected.truncate(checkpoint);
3021                // and use the big note to cover it
3022                selected.push((big_note_amount, big_note));
3023
3024                let notes: TieredMulti<Note> = selected.into_iter().collect();
3025
3026                assert!(
3027                    notes.total_amount().msats
3028                        >= requested_amount.msats
3029                            + notes
3030                                .iter()
3031                                .map(|note| fee_consensus.fee(note.0))
3032                                .sum::<Amount>()
3033                                .msats
3034                );
3035
3036                // so now we have enough to cover the requested amount, return
3037                return Ok(notes);
3038            }
3039
3040            let total_amount = requested_amount.saturating_sub(pending_amount);
3041            // not enough notes, return
3042            return Err(InsufficientBalanceError {
3043                requested_amount,
3044                total_amount,
3045            });
3046        }
3047    }
3048}
3049
3050/// Old and no longer used, will be deleted in the future
3051#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
3052enum MintRestoreStates {
3053    #[encodable_default]
3054    Default { variant: u64, bytes: Vec<u8> },
3055}
3056
3057/// Old and no longer used, will be deleted in the future
3058#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
3059pub struct MintRestoreStateMachine {
3060    operation_id: OperationId,
3061    state: MintRestoreStates,
3062}
3063
3064#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
3065pub enum MintClientStateMachines {
3066    Output(MintOutputStateMachine),
3067    Input(MintInputStateMachine),
3068    OOB(MintOOBStateMachine),
3069    // Removed in https://github.com/fedimint/fedimint/pull/4035 , now ignored
3070    Restore(MintRestoreStateMachine),
3071}
3072
3073impl IntoDynInstance for MintClientStateMachines {
3074    type DynType = DynState;
3075
3076    fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
3077        DynState::from_typed(instance_id, self)
3078    }
3079}
3080
3081impl State for MintClientStateMachines {
3082    type ModuleContext = MintClientContext;
3083
3084    fn transitions(
3085        &self,
3086        context: &Self::ModuleContext,
3087        global_context: &DynGlobalClientContext,
3088    ) -> Vec<StateTransition<Self>> {
3089        match self {
3090            MintClientStateMachines::Output(issuance_state) => {
3091                sm_enum_variant_translation!(
3092                    issuance_state.transitions(context, global_context),
3093                    MintClientStateMachines::Output
3094                )
3095            }
3096            MintClientStateMachines::Input(redemption_state) => {
3097                sm_enum_variant_translation!(
3098                    redemption_state.transitions(context, global_context),
3099                    MintClientStateMachines::Input
3100                )
3101            }
3102            MintClientStateMachines::OOB(oob_state) => {
3103                sm_enum_variant_translation!(
3104                    oob_state.transitions(context, global_context),
3105                    MintClientStateMachines::OOB
3106                )
3107            }
3108            MintClientStateMachines::Restore(_) => {
3109                sm_enum_variant_translation!(vec![], MintClientStateMachines::Restore)
3110            }
3111        }
3112    }
3113
3114    fn operation_id(&self) -> OperationId {
3115        match self {
3116            MintClientStateMachines::Output(issuance_state) => issuance_state.operation_id(),
3117            MintClientStateMachines::Input(redemption_state) => redemption_state.operation_id(),
3118            MintClientStateMachines::OOB(oob_state) => oob_state.operation_id(),
3119            MintClientStateMachines::Restore(r) => r.operation_id,
3120        }
3121    }
3122
3123    fn fmt_visualization(&self, f: &mut dyn std::fmt::Write, indent: &str) -> std::fmt::Result {
3124        match self {
3125            MintClientStateMachines::Output(s) => s.fmt_visualization(f, indent),
3126            MintClientStateMachines::Input(s) => s.fmt_visualization(f, indent),
3127            MintClientStateMachines::OOB(s) => s.fmt_visualization(f, indent),
3128            MintClientStateMachines::Restore(_) => write!(f, "{indent}{self:?}"),
3129        }
3130    }
3131}
3132
3133/// A [`Note`] with associated secret key that allows to proof ownership (spend
3134/// it)
3135#[derive(Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize, Encodable, Decodable)]
3136pub struct SpendableNote {
3137    pub signature: tbs::Signature,
3138    pub spend_key: Keypair,
3139}
3140
3141impl fmt::Debug for SpendableNote {
3142    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
3143        f.debug_struct("SpendableNote")
3144            .field("nonce", &self.nonce())
3145            .field("signature", &self.signature)
3146            .field("spend_key", &self.spend_key)
3147            .finish()
3148    }
3149}
3150impl fmt::Display for SpendableNote {
3151    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
3152        write!(f, "{}", self.nonce().fmt_short())
3153    }
3154}
3155
3156impl SpendableNote {
3157    pub fn nonce(&self) -> Nonce {
3158        Nonce(self.spend_key.public_key())
3159    }
3160
3161    fn note(&self) -> Note {
3162        Note {
3163            nonce: self.nonce(),
3164            signature: self.signature,
3165        }
3166    }
3167
3168    pub fn to_undecoded(&self) -> SpendableNoteUndecoded {
3169        SpendableNoteUndecoded {
3170            signature: self
3171                .signature
3172                .consensus_encode_to_vec()
3173                .try_into()
3174                .expect("Encoded size always correct"),
3175            spend_key: self.spend_key,
3176        }
3177    }
3178}
3179
3180/// A version of [`SpendableNote`] that didn't decode the `signature` yet
3181///
3182/// **Note**: signature decoding from raw bytes is faliable, as not all bytes
3183/// are valid signatures. Therefore this type must not be used for external
3184/// data, and should be limited to optimizing reading from internal database.
3185///
3186/// The signature bytes will be validated in [`Self::decode`].
3187///
3188/// Decoding [`tbs::Signature`] is somewhat CPU-intensive (see benches in this
3189/// crate), and when most of the result will be filtered away or completely
3190/// unused, it makes sense to skip/delay decoding.
3191#[derive(Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable, Serialize)]
3192pub struct SpendableNoteUndecoded {
3193    // Need to keep this in sync with `tbs::Signature`, but there's a test
3194    // verifying they serialize and decode the same.
3195    #[serde(serialize_with = "serdect::array::serialize_hex_lower_or_bin")]
3196    pub signature: [u8; 48],
3197    pub spend_key: Keypair,
3198}
3199
3200impl fmt::Display for SpendableNoteUndecoded {
3201    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
3202        write!(f, "{}", self.nonce().fmt_short())
3203    }
3204}
3205
3206impl fmt::Debug for SpendableNoteUndecoded {
3207    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
3208        f.debug_struct("SpendableNote")
3209            .field("nonce", &self.nonce())
3210            .field("signature", &"[raw]")
3211            .field("spend_key", &self.spend_key)
3212            .finish()
3213    }
3214}
3215
3216impl SpendableNoteUndecoded {
3217    fn nonce(&self) -> Nonce {
3218        Nonce(self.spend_key.public_key())
3219    }
3220
3221    pub fn decode(self) -> Result<SpendableNote, DecodeError> {
3222        Ok(SpendableNote {
3223            signature: Decodable::consensus_decode_partial_from_finite_reader(
3224                &mut self.signature.as_slice(),
3225                &ModuleRegistry::default(),
3226            )?,
3227            spend_key: self.spend_key,
3228        })
3229    }
3230}
3231
3232/// An index used to deterministically derive [`Note`]s
3233///
3234/// We allow converting it to u64 and incrementing it, but
3235/// messing with it should be somewhat restricted to prevent
3236/// silly errors.
3237#[derive(
3238    Copy,
3239    Clone,
3240    Debug,
3241    Serialize,
3242    Deserialize,
3243    PartialEq,
3244    Eq,
3245    Encodable,
3246    Decodable,
3247    Default,
3248    PartialOrd,
3249    Ord,
3250)]
3251pub struct NoteIndex(u64);
3252
3253impl NoteIndex {
3254    pub fn next(self) -> Self {
3255        Self(self.0 + 1)
3256    }
3257
3258    fn prev(self) -> Option<Self> {
3259        self.0.checked_sub(0).map(Self)
3260    }
3261
3262    pub fn as_u64(self) -> u64 {
3263        self.0
3264    }
3265
3266    // Private. If it turns out it is useful outside,
3267    // we can relax and convert to `From<u64>`
3268    // Actually used in tests RN, so cargo complains in non-test builds.
3269    #[allow(unused)]
3270    pub fn from_u64(v: u64) -> Self {
3271        Self(v)
3272    }
3273
3274    pub fn advance(&mut self) {
3275        *self = self.next();
3276    }
3277}
3278
3279impl std::fmt::Display for NoteIndex {
3280    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3281        self.0.fmt(f)
3282    }
3283}
3284
3285struct OOBSpendTag;
3286
3287impl sha256t::Tag for OOBSpendTag {
3288    fn engine() -> sha256::HashEngine {
3289        let mut engine = sha256::HashEngine::default();
3290        engine.input(b"oob-spend");
3291        engine
3292    }
3293}
3294
3295struct OOBReissueTag;
3296
3297impl sha256t::Tag for OOBReissueTag {
3298    fn engine() -> sha256::HashEngine {
3299        let mut engine = sha256::HashEngine::default();
3300        engine.input(b"oob-reissue");
3301        engine
3302    }
3303}
3304
3305/// Determines the denominations to use when representing an amount
3306///
3307/// Algorithm tries to leave the user with a target number of
3308/// `denomination_sets` starting at the lowest denomination.  `self`
3309/// gives the denominations that the user already has.
3310pub fn represent_amount<K>(
3311    amount: Amount,
3312    current_denominations: &TieredCounts,
3313    tiers: &Tiered<K>,
3314    denomination_sets: u16,
3315    fee_consensus: &FeeConsensus,
3316) -> TieredCounts {
3317    let mut remaining_amount = amount;
3318    let mut denominations = TieredCounts::default();
3319
3320    // try to hit the target `denomination_sets`
3321    for tier in tiers.tiers() {
3322        let notes = current_denominations.get(*tier);
3323        let missing_notes = u64::from(denomination_sets).saturating_sub(notes as u64);
3324        let possible_notes = remaining_amount / (*tier + fee_consensus.fee(*tier));
3325
3326        let add_notes = min(possible_notes, missing_notes);
3327        denominations.inc(*tier, add_notes as usize);
3328        remaining_amount -= (*tier + fee_consensus.fee(*tier)) * add_notes;
3329    }
3330
3331    // if there is a remaining amount, add denominations with a greedy algorithm
3332    for tier in tiers.tiers().rev() {
3333        let res = remaining_amount / (*tier + fee_consensus.fee(*tier));
3334        remaining_amount -= (*tier + fee_consensus.fee(*tier)) * res;
3335        denominations.inc(*tier, res as usize);
3336    }
3337
3338    let represented: u64 = denominations
3339        .iter()
3340        .map(|(k, v)| (k + fee_consensus.fee(k)).msats * (v as u64))
3341        .sum();
3342
3343    assert!(represented <= amount.msats);
3344    assert!(represented + fee_consensus.fee(Amount::from_msats(1)).msats >= amount.msats);
3345
3346    denominations
3347}
3348
3349pub(crate) fn create_bundle_for_inputs(
3350    inputs_and_notes: Vec<(ClientInput<MintInput>, SpendableNote)>,
3351    operation_id: OperationId,
3352) -> ClientInputBundle<MintInput, MintClientStateMachines> {
3353    let mut inputs = Vec::new();
3354    let mut input_states = Vec::new();
3355
3356    for (input, spendable_note) in inputs_and_notes {
3357        input_states.push((input.amounts.clone(), spendable_note));
3358        inputs.push(input);
3359    }
3360
3361    let input_sm = Arc::new(move |out_point_range: OutPointRange| {
3362        debug_assert_eq!(out_point_range.into_iter().count(), input_states.len());
3363
3364        vec![MintClientStateMachines::Input(MintInputStateMachine {
3365            common: MintInputCommon {
3366                operation_id,
3367                out_point_range,
3368            },
3369            state: MintInputStates::CreatedBundle(MintInputStateCreatedBundle {
3370                notes: input_states
3371                    .iter()
3372                    .map(|(amounts, note)| (amounts.expect_only_bitcoin(), *note))
3373                    .collect(),
3374            }),
3375        })]
3376    });
3377
3378    ClientInputBundle::new(
3379        inputs,
3380        vec![ClientInputSM {
3381            state_machines: input_sm,
3382        }],
3383    )
3384}
3385
3386#[cfg(test)]
3387mod tests;