Skip to main content

fedimint_dummy_client/
lib.rs

1#![deny(clippy::pedantic)]
2#![allow(clippy::missing_errors_doc)]
3#![allow(clippy::missing_panics_doc)]
4#![allow(clippy::module_name_repetitions)]
5#![allow(clippy::must_use_candidate)]
6
7use core::cmp::Ordering;
8use std::collections::BTreeMap;
9use std::sync::Arc;
10
11use db::{DbKeyPrefix, DummyClientFundsKey, DummyClientFundsKeyPrefixAll};
12use fedimint_client_module::db::ClientModuleMigrationFn;
13use fedimint_client_module::error::{ClientModuleError, InsufficientBalanceError};
14use fedimint_client_module::module::init::{ClientModuleInit, ClientModuleInitArgs};
15use fedimint_client_module::module::recovery::NoModuleBackup;
16use fedimint_client_module::module::{
17    AccountSupport, ClientContext, ClientModule, OutPointRange, PrimaryModulePriority,
18    PrimaryModuleSupport,
19};
20use fedimint_client_module::sm::{Context, DynState, ModuleNotifier, State, StateTransition};
21use fedimint_client_module::transaction::{
22    ClientInput, ClientInputBundle, ClientInputSM, ClientOutput, ClientOutputBundle, ClientOutputSM,
23};
24use fedimint_client_module::{DynGlobalClientContext, sm_enum_variant_translation};
25use fedimint_core::core::{Account, IntoDynInstance, ModuleInstanceId, ModuleKind, OperationId};
26use fedimint_core::db::{
27    Database, DatabaseTransaction, DatabaseVersion, IDatabaseTransactionOpsCoreTyped,
28};
29use fedimint_core::encoding::{Decodable, Encodable};
30use fedimint_core::module::{
31    AmountUnit, Amounts, ApiVersion, ModuleCommon, ModuleInit, MultiApiVersion,
32};
33use fedimint_core::secp256k1::{Keypair, Secp256k1};
34use fedimint_core::util::BoxStream;
35use fedimint_core::{Amount, OutPoint, apply, async_trait_maybe_send, push_db_pair_items};
36pub use fedimint_dummy_common as common;
37use fedimint_dummy_common::{DummyCommonInit, DummyInput, DummyModuleTypes, DummyOutput};
38use futures::StreamExt;
39use strum::IntoEnumIterator;
40use tokio::sync::watch;
41
42pub mod db;
43mod input_sm;
44mod output_sm;
45
46use input_sm::{DummyInputSMCommon, DummyInputSMState, DummyInputStateMachine};
47use output_sm::{DummyOutputSMCommon, DummyOutputSMState, DummyOutputStateMachine};
48
49/// Wrapper enum for all state machines in the dummy module
50#[derive(Debug, Clone, Eq, PartialEq, Hash, Decodable, Encodable)]
51pub enum DummyStateMachine {
52    Input(DummyInputStateMachine),
53    Output(DummyOutputStateMachine),
54}
55
56impl State for DummyStateMachine {
57    type ModuleContext = DummyClientContext;
58
59    fn transitions(
60        &self,
61        context: &Self::ModuleContext,
62        global_context: &DynGlobalClientContext,
63    ) -> Vec<StateTransition<Self>> {
64        match self {
65            DummyStateMachine::Input(sm) => {
66                sm_enum_variant_translation!(
67                    sm.transitions(context, global_context),
68                    DummyStateMachine::Input
69                )
70            }
71            DummyStateMachine::Output(sm) => {
72                sm_enum_variant_translation!(
73                    sm.transitions(context, global_context),
74                    DummyStateMachine::Output
75                )
76            }
77        }
78    }
79
80    fn operation_id(&self) -> OperationId {
81        match self {
82            DummyStateMachine::Input(sm) => sm.operation_id(),
83            DummyStateMachine::Output(sm) => sm.operation_id(),
84        }
85    }
86}
87
88impl IntoDynInstance for DummyStateMachine {
89    type DynType = DynState;
90
91    fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType {
92        DynState::from_typed(instance_id, self)
93    }
94}
95
96pub struct DummyClientModule {
97    key: Keypair,
98    db: Database,
99    notifier: ModuleNotifier<DummyStateMachine>,
100    client_ctx: ClientContext<Self>,
101    balance_update_sender: watch::Sender<()>,
102}
103
104impl std::fmt::Debug for DummyClientModule {
105    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106        f.debug_struct("DummyClientModule").finish_non_exhaustive()
107    }
108}
109
110/// Data needed by the state machine
111#[derive(Clone)]
112pub struct DummyClientContext {
113    pub balance_update_sender: watch::Sender<()>,
114}
115
116impl std::fmt::Debug for DummyClientContext {
117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118        f.debug_struct("DummyClientContext").finish_non_exhaustive()
119    }
120}
121
122impl Context for DummyClientContext {
123    const KIND: Option<ModuleKind> = None;
124}
125
126#[apply(async_trait_maybe_send!)]
127impl ClientModule for DummyClientModule {
128    type Init = DummyClientInit;
129    type Common = DummyModuleTypes;
130    type Backup = NoModuleBackup;
131    type ModuleStateMachineContext = DummyClientContext;
132    type States = DummyStateMachine;
133
134    fn context(&self) -> Self::ModuleStateMachineContext {
135        DummyClientContext {
136            balance_update_sender: self.balance_update_sender.clone(),
137        }
138    }
139
140    fn input_fee(
141        &self,
142        _amount: &Amounts,
143        _input: &<Self::Common as ModuleCommon>::Input,
144    ) -> Option<Amounts> {
145        Some(Amounts::ZERO)
146    }
147
148    fn output_fee(
149        &self,
150        _amount: &Amounts,
151        _output: &<Self::Common as ModuleCommon>::Output,
152    ) -> Option<Amounts> {
153        Some(Amounts::ZERO)
154    }
155
156    fn supports_being_primary(&self) -> PrimaryModuleSupport {
157        PrimaryModuleSupport::Any {
158            priority: PrimaryModulePriority::LOW,
159            accounts: AccountSupport::PrimaryOnly,
160        }
161    }
162
163    async fn create_final_inputs_and_outputs(
164        &self,
165        dbtx: &mut DatabaseTransaction<'_>,
166        operation_id: OperationId,
167        unit: AmountUnit,
168        input_amount: Amount,
169        output_amount: Amount,
170        _account: Account,
171    ) -> Result<
172        (
173            ClientInputBundle<DummyInput, DummyStateMachine>,
174            ClientOutputBundle<DummyOutput, DummyStateMachine>,
175        ),
176        ClientModuleError,
177    > {
178        dbtx.ensure_isolated().expect("must be isolated");
179
180        match input_amount.cmp(&output_amount) {
181            Ordering::Less => {
182                // Spending: balance subtracted immediately, refund on rejection
183                let missing_input_amount = output_amount.saturating_sub(input_amount);
184
185                let our_funds = get_funds(dbtx, unit).await;
186
187                if our_funds < missing_input_amount {
188                    return Err(InsufficientBalanceError {
189                        requested_amount: missing_input_amount,
190                        total_amount: our_funds,
191                    }
192                    .into());
193                }
194
195                let updated = our_funds.saturating_sub(missing_input_amount);
196
197                dbtx.insert_entry(&DummyClientFundsKey(unit), &updated)
198                    .await;
199
200                let sender = self.balance_update_sender.clone();
201
202                dbtx.on_commit(move || sender.send_replace(()));
203
204                let input = ClientInput {
205                    input: DummyInput {
206                        amount: missing_input_amount,
207                        unit,
208                        pub_key: self.key.public_key(),
209                    },
210                    amounts: Amounts::new_custom(unit, missing_input_amount),
211                    keys: vec![self.key],
212                };
213
214                let input_sm = ClientInputSM {
215                    state_machines: Arc::new(move |out_point_range: OutPointRange| {
216                        out_point_range
217                            .into_iter()
218                            .map(|out_point| {
219                                DummyStateMachine::Input(DummyInputStateMachine {
220                                    common: DummyInputSMCommon {
221                                        operation_id,
222                                        out_point,
223                                        amount: missing_input_amount,
224                                        unit,
225                                    },
226                                    state: DummyInputSMState::Created,
227                                })
228                            })
229                            .collect()
230                    }),
231                };
232
233                Ok((
234                    ClientInputBundle::new(vec![input], vec![input_sm]),
235                    ClientOutputBundle::new(vec![], vec![]),
236                ))
237            }
238            Ordering::Equal => Ok((
239                ClientInputBundle::new(vec![], vec![]),
240                ClientOutputBundle::new(vec![], vec![]),
241            )),
242            Ordering::Greater => {
243                // Receiving: balance added only on acceptance
244                let missing_output_amount = input_amount.saturating_sub(output_amount);
245
246                let output = ClientOutput {
247                    output: DummyOutput {
248                        amount: missing_output_amount,
249                        unit,
250                    },
251                    amounts: Amounts::new_custom(unit, missing_output_amount),
252                };
253
254                let output_sm = ClientOutputSM {
255                    state_machines: Arc::new(move |out_point_range: OutPointRange| {
256                        out_point_range
257                            .into_iter()
258                            .map(|out_point| {
259                                DummyStateMachine::Output(DummyOutputStateMachine {
260                                    common: DummyOutputSMCommon {
261                                        operation_id,
262                                        out_point,
263                                        amount: missing_output_amount,
264                                        unit,
265                                    },
266                                    state: DummyOutputSMState::Created,
267                                })
268                            })
269                            .collect()
270                    }),
271                };
272
273                Ok((
274                    ClientInputBundle::new(vec![], vec![]),
275                    ClientOutputBundle::new(vec![output], vec![output_sm]),
276                ))
277            }
278        }
279    }
280
281    async fn await_primary_module_output(
282        &self,
283        operation_id: OperationId,
284        out_point: OutPoint,
285    ) -> Result<(), ClientModuleError> {
286        let mut stream = self.notifier.subscribe(operation_id).await;
287
288        loop {
289            let DummyStateMachine::Output(output_sm) = stream
290                .next()
291                .await
292                .expect("Stream should not end before reaching final state")
293            else {
294                continue;
295            };
296
297            if output_sm.common.out_point != out_point {
298                continue;
299            }
300
301            match output_sm.state {
302                DummyOutputSMState::Created => {}
303                DummyOutputSMState::Accepted => return Ok(()),
304                DummyOutputSMState::Rejected => {
305                    return Err(ClientModuleError::other("Transaction was rejected"));
306                }
307            }
308        }
309    }
310
311    async fn get_balance(
312        &self,
313        dbtc: &mut DatabaseTransaction<'_>,
314        unit: AmountUnit,
315        _account: Account,
316    ) -> Amount {
317        get_funds(dbtc, unit).await
318    }
319
320    async fn get_balances(&self, dbtx: &mut DatabaseTransaction<'_>) -> Amounts {
321        get_funds_all(dbtx).await
322    }
323
324    async fn subscribe_balance_changes(&self) -> BoxStream<'static, ()> {
325        Box::pin(tokio_stream::wrappers::WatchStream::new(
326            self.balance_update_sender.subscribe(),
327        ))
328    }
329}
330
331impl DummyClientModule {
332    /// The dummy server accepts any public key, so this can be used to create
333    /// funds out of thin air that get converted to e-cash as change.
334    pub fn create_input(&self, amount: Amount) -> ClientInputBundle {
335        let keypair = Keypair::new(&Secp256k1::new(), &mut rand::rngs::OsRng);
336
337        let client_input = ClientInput {
338            input: DummyInput {
339                amount,
340                unit: AmountUnit::BITCOIN,
341                pub_key: keypair.public_key(),
342            },
343            amounts: Amounts::new_bitcoin(amount),
344            keys: vec![keypair],
345        };
346
347        self.client_ctx
348            .make_client_inputs(ClientInputBundle::new_no_sm(vec![client_input]))
349    }
350
351    /// Add funds to the local balance (for testing)
352    pub async fn mock_receive(&self, amount: Amount, unit: AmountUnit) {
353        let mut dbtx = self.db.begin_transaction().await;
354
355        let current = dbtx
356            .get_value(&DummyClientFundsKey(unit))
357            .await
358            .unwrap_or(Amount::ZERO);
359
360        dbtx.insert_entry(&DummyClientFundsKey(unit), &(current + amount))
361            .await;
362
363        dbtx.commit_tx().await;
364    }
365}
366
367async fn get_funds(dbtx: &mut DatabaseTransaction<'_>, unit: AmountUnit) -> Amount {
368    dbtx.get_value(&DummyClientFundsKey(unit))
369        .await
370        .unwrap_or(Amount::ZERO)
371}
372
373async fn get_funds_all(dbtx: &mut DatabaseTransaction<'_>) -> Amounts {
374    dbtx.find_by_prefix(&DummyClientFundsKeyPrefixAll)
375        .await
376        .fold(Amounts::ZERO, |acc, (key, amount)| async move {
377            acc.checked_add_unit(amount, key.0).expect("can't overflow")
378        })
379        .await
380}
381
382#[derive(Debug, Clone)]
383pub struct DummyClientInit;
384
385impl ModuleInit for DummyClientInit {
386    type Common = DummyCommonInit;
387
388    async fn dump_database(
389        &self,
390        dbtx: &mut DatabaseTransaction<'_>,
391        prefix_names: Vec<String>,
392    ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
393        let mut items: BTreeMap<String, Box<dyn erased_serde::Serialize + Send>> = BTreeMap::new();
394        let filtered_prefixes = DbKeyPrefix::iter().filter(|f| {
395            prefix_names.is_empty() || prefix_names.contains(&f.to_string().to_lowercase())
396        });
397
398        for table in filtered_prefixes {
399            match table {
400                DbKeyPrefix::ClientFunds => {
401                    push_db_pair_items!(
402                        dbtx,
403                        DummyClientFundsKeyPrefixAll,
404                        DummyClientFundsKey,
405                        Amount,
406                        items,
407                        "Dummy Funds"
408                    );
409                }
410                DbKeyPrefix::ExternalReservedStart
411                | DbKeyPrefix::CoreInternalReservedStart
412                | DbKeyPrefix::CoreInternalReservedEnd => {}
413            }
414        }
415
416        Box::new(items.into_iter())
417    }
418}
419
420/// Generates the client module
421#[apply(async_trait_maybe_send!)]
422impl ClientModuleInit for DummyClientInit {
423    type Module = DummyClientModule;
424
425    fn supported_api_versions(&self) -> MultiApiVersion {
426        MultiApiVersion::try_from_iter([ApiVersion { major: 0, minor: 0 }])
427            .expect("no version conflicts")
428    }
429
430    async fn init(
431        &self,
432        args: &ClientModuleInitArgs<Self>,
433    ) -> Result<Self::Module, ClientModuleError> {
434        Ok(DummyClientModule {
435            key: args
436                .module_root_secret()
437                .clone()
438                .to_secp_key(&Secp256k1::new()),
439            db: args.db().clone(),
440            notifier: args.notifier().clone(),
441            client_ctx: args.context(),
442            balance_update_sender: watch::channel(()).0,
443        })
444    }
445
446    fn get_database_migrations(&self) -> BTreeMap<DatabaseVersion, ClientModuleMigrationFn> {
447        BTreeMap::new()
448    }
449}