Skip to main content

fedimint_mintv2_client/
output.rs

1use std::collections::BTreeMap;
2
3use fedimint_client::DynGlobalClientContext;
4use fedimint_client_module::module::OutPointRange;
5use fedimint_client_module::sm::{ClientSMDatabaseTransaction, State, StateTransition};
6use fedimint_core::core::OperationId;
7use fedimint_core::db::IDatabaseTransactionOpsCoreTyped;
8use fedimint_core::encoding::{Decodable, Encodable};
9use fedimint_core::{PeerId, runtime};
10use fedimint_mintv2_common::{Denomination, verify_note};
11use serde::{Deserialize, Serialize};
12use tbs::{
13    AggregatePublicKey, BlindedSignature, BlindedSignatureShare, PublicKeyShare,
14    aggregate_signature_shares,
15};
16
17use crate::api::MintV2ModuleApi;
18use crate::client_db::SpendableNoteKey;
19use crate::{MintClientContext, NoteIssuanceRequest};
20
21#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
22pub struct MintOutputStateMachine {
23    pub common: OutputSMCommon,
24    pub state: OutputSMState,
25}
26
27#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
28pub struct OutputSMCommon {
29    pub operation_id: OperationId,
30    pub range: Option<OutPointRange>,
31    pub issuance_requests: Vec<NoteIssuanceRequest>,
32}
33
34#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
35pub enum OutputSMState {
36    /// Issuance request was created, we are waiting for blind signatures.
37    Pending,
38    /// The transaction containing the issuance was rejected, we can stop
39    /// looking for decryption shares.
40    Aborted,
41    /// The transaction containing the issuance was accepted but an unexpected
42    /// error occurred, this should never happen with a honest federation and
43    /// bug-free code.
44    Failure,
45    /// The issuance was completed successfully and the e-cash notes added to
46    /// our wallet.
47    Success,
48}
49
50impl State for MintOutputStateMachine {
51    type ModuleContext = MintClientContext;
52
53    fn transitions(
54        &self,
55        context: &Self::ModuleContext,
56        global_context: &DynGlobalClientContext,
57    ) -> Vec<StateTransition<Self>> {
58        let context = context.clone();
59        let global_context = global_context.clone();
60
61        match &self.state {
62            OutputSMState::Pending => {
63                vec![StateTransition::new(
64                    Self::await_issuance(
65                        global_context.clone(),
66                        self.common.range,
67                        self.common.issuance_requests.clone(),
68                        context.tbs_pks.clone(),
69                        context.tbs_agg_pks.clone(),
70                    ),
71                    move |dbtx, outcome, old_state| {
72                        let balance_update_sender = context.balance_update_sender.clone();
73
74                        dbtx.module_tx()
75                            .on_commit(move || balance_update_sender.send_replace(()));
76
77                        Box::pin(Self::transition_issuance(
78                            global_context.clone(),
79                            dbtx,
80                            outcome,
81                            old_state,
82                        ))
83                    },
84                )]
85            }
86            OutputSMState::Aborted | OutputSMState::Failure | OutputSMState::Success => {
87                vec![]
88            }
89        }
90    }
91
92    fn operation_id(&self) -> OperationId {
93        self.common.operation_id
94    }
95}
96
97/// What the issuance trigger resolves to.
98///
99/// The shares are aggregated and the notes verified in the trigger, off the
100/// async workers, so the transition only unblinds and inserts them.
101#[derive(Debug, Serialize, Deserialize)]
102pub enum IssuanceOutcome {
103    /// The transaction containing the issuance was rejected.
104    Aborted,
105    /// The aggregated signatures of the notes that verified, in order, and
106    /// whether one did not: the verified ones are kept either way, the
107    /// machine fails on the invalid one.
108    Signatures {
109        signatures: Vec<BlindedSignature>,
110        invalid: bool,
111    },
112}
113
114impl MintOutputStateMachine {
115    async fn await_issuance(
116        global_context: DynGlobalClientContext,
117        range: Option<OutPointRange>,
118        issuance_requests: Vec<NoteIssuanceRequest>,
119        tbs_pks: BTreeMap<Denomination, BTreeMap<PeerId, PublicKeyShare>>,
120        tbs_agg_pks: BTreeMap<Denomination, AggregatePublicKey>,
121    ) -> IssuanceOutcome {
122        let signature_shares = if let Some(range) = range {
123            if global_context.await_tx_accepted(range.txid).await.is_err() {
124                return IssuanceOutcome::Aborted;
125            }
126
127            global_context
128                .module_api()
129                .fetch_signature_shares(range, issuance_requests.clone(), tbs_pks)
130                .await
131        } else {
132            global_context
133                .module_api()
134                .fetch_signature_shares_recovery(issuance_requests.clone(), tbs_pks)
135                .await
136        };
137
138        // Aggregating a note's shares is a Lagrange interpolation and verifying
139        // it two pairings; keep them off the async workers.
140        runtime::spawn_blocking(move || {
141            let mut signatures = Vec::with_capacity(issuance_requests.len());
142
143            for (i, request) in issuance_requests.iter().enumerate() {
144                let agg_blind_signature = aggregate_signature_shares(
145                    &signature_shares
146                        .iter()
147                        .map(|(peer, shares)| (peer.to_usize() as u64, shares[i]))
148                        .collect(),
149                );
150
151                let spendable_note = request.finalize(agg_blind_signature);
152
153                let pk = *tbs_agg_pks
154                    .get(&request.denomination)
155                    .expect("No aggregated pk found for denomination");
156
157                if !verify_note(spendable_note.note(), pk) {
158                    return IssuanceOutcome::Signatures {
159                        signatures,
160                        invalid: true,
161                    };
162                }
163
164                signatures.push(agg_blind_signature);
165            }
166
167            IssuanceOutcome::Signatures {
168                signatures,
169                invalid: false,
170            }
171        })
172        .await
173    }
174
175    async fn transition_issuance(
176        global_context: DynGlobalClientContext,
177        dbtx: &mut ClientSMDatabaseTransaction<'_, '_>,
178        outcome: IssuanceOutcome,
179        old_state: MintOutputStateMachine,
180    ) -> MintOutputStateMachine {
181        let (signatures, invalid) = match outcome {
182            IssuanceOutcome::Aborted => {
183                return MintOutputStateMachine {
184                    common: old_state.common,
185                    state: OutputSMState::Aborted,
186                };
187            }
188            IssuanceOutcome::Signatures {
189                signatures,
190                invalid,
191            } => (signatures, invalid),
192        };
193
194        // The notes land in the operation's account, whichever that is.
195        let account = global_context.account(dbtx).await;
196
197        for (request, signature) in old_state.common.issuance_requests.iter().zip(signatures) {
198            dbtx.module_tx()
199                .insert_new_entry(
200                    &SpendableNoteKey(account, request.finalize(signature).into()),
201                    &(),
202                )
203                .await;
204        }
205
206        MintOutputStateMachine {
207            common: old_state.common,
208            state: if invalid {
209                OutputSMState::Failure
210            } else {
211                OutputSMState::Success
212            },
213        }
214    }
215}
216
217pub fn verify_blind_shares(
218    peer: PeerId,
219    signature_shares: Vec<BlindedSignatureShare>,
220    issuance_requests: &[NoteIssuanceRequest],
221    tbs_pks: &BTreeMap<Denomination, BTreeMap<PeerId, PublicKeyShare>>,
222) -> Result<Vec<BlindedSignatureShare>, VerifyBlindSharesError> {
223    if signature_shares.len() != issuance_requests.len() {
224        return Err(VerifyBlindSharesError::ShareCount);
225    }
226
227    for (request, share) in issuance_requests.iter().zip(signature_shares.iter()) {
228        let amount_key = tbs_pks
229            .get(&request.denomination)
230            .expect("No pk shares found for denomination")
231            .get(&peer)
232            .expect("No pk share found for peer");
233
234        if !tbs::verify_signature_share(request.blinded_message(), *share, *amount_key) {
235            return Err(VerifyBlindSharesError::InvalidShare);
236        }
237    }
238
239    Ok(signature_shares)
240}
241
242/// Why a guardian's blind signature shares were rejected.
243#[derive(Debug, thiserror::Error)]
244pub(crate) enum VerifyBlindSharesError {
245    /// The guardian sent a different number of shares than notes were
246    /// requested.
247    #[error("Invalid number of signatures shares")]
248    ShareCount,
249
250    /// A share does not verify against the guardian's public key share.
251    #[error("Invalid blind signature")]
252    InvalidShare,
253}