1#![deny(clippy::pedantic)]
2#![allow(clippy::cast_possible_wrap)]
3#![allow(clippy::missing_errors_doc)]
4#![allow(clippy::module_name_repetitions)]
5#![allow(clippy::must_use_candidate)]
6
7use std::collections::BTreeMap;
8
9use anyhow::bail;
10use async_trait::async_trait;
11use fedimint_core::config::{
12 ConfigGenModuleParams, ServerModuleConfig, ServerModuleConsensusConfig,
13 TypedServerModuleConfig, TypedServerModuleConsensusConfig,
14};
15use fedimint_core::core::ModuleInstanceId;
16use fedimint_core::db::{DatabaseTransaction, DatabaseVersion, IDatabaseTransactionOpsCoreTyped};
17use fedimint_core::module::audit::Audit;
18use fedimint_core::module::{
19 ApiEndpoint, CORE_CONSENSUS_VERSION, CoreConsensusVersion, InputMeta, ModuleConsensusVersion,
20 ModuleInit, PeerHandle, SupportedModuleApiVersions, TransactionItemAmount,
21};
22use fedimint_core::{Amount, InPoint, OutPoint, PeerId, push_db_pair_items};
23use fedimint_dummy_common::config::{
24 DummyClientConfig, DummyConfig, DummyConfigConsensus, DummyConfigLocal, DummyConfigPrivate,
25 DummyGenParams,
26};
27use fedimint_dummy_common::{
28 DummyCommonInit, DummyConsensusItem, DummyInput, DummyInputError, DummyModuleTypes,
29 DummyOutput, DummyOutputError, DummyOutputOutcome, MODULE_CONSENSUS_VERSION,
30 broken_fed_public_key, fed_public_key,
31};
32use fedimint_server_core::migration::ServerModuleDbMigrationFn;
33use fedimint_server_core::{ServerModule, ServerModuleInit, ServerModuleInitArgs};
34use futures::{FutureExt, StreamExt};
35use strum::IntoEnumIterator;
36
37use crate::db::{
38 DbKeyPrefix, DummyFundsKeyV1, DummyFundsPrefixV1, DummyOutcomeKey, DummyOutcomePrefix,
39 migrate_to_v1,
40};
41
42pub mod db;
43
44#[derive(Debug, Clone)]
46pub struct DummyInit;
47
48impl ModuleInit for DummyInit {
50 type Common = DummyCommonInit;
51
52 async fn dump_database(
54 &self,
55 dbtx: &mut DatabaseTransaction<'_>,
56 prefix_names: Vec<String>,
57 ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
58 let mut items: BTreeMap<String, Box<dyn erased_serde::Serialize + Send>> = BTreeMap::new();
60 let filtered_prefixes = DbKeyPrefix::iter().filter(|f| {
61 prefix_names.is_empty() || prefix_names.contains(&f.to_string().to_lowercase())
62 });
63
64 for table in filtered_prefixes {
65 match table {
66 DbKeyPrefix::Funds => {
67 push_db_pair_items!(
68 dbtx,
69 DummyFundsPrefixV1,
70 DummyFundsKeyV1,
71 Amount,
72 items,
73 "Dummy Funds"
74 );
75 }
76 DbKeyPrefix::Outcome => {
77 push_db_pair_items!(
78 dbtx,
79 DummyOutcomePrefix,
80 DummyOutcomeKey,
81 DummyOutputOutcome,
82 items,
83 "Dummy Outputs"
84 );
85 }
86 }
87 }
88
89 Box::new(items.into_iter())
90 }
91}
92
93#[async_trait]
95impl ServerModuleInit for DummyInit {
96 type Module = Dummy;
97 type Params = DummyGenParams;
98
99 fn versions(&self, _core: CoreConsensusVersion) -> &[ModuleConsensusVersion] {
101 &[MODULE_CONSENSUS_VERSION]
102 }
103
104 fn supported_api_versions(&self) -> SupportedModuleApiVersions {
105 SupportedModuleApiVersions::from_raw(
106 (CORE_CONSENSUS_VERSION.major, CORE_CONSENSUS_VERSION.minor),
107 (
108 MODULE_CONSENSUS_VERSION.major,
109 MODULE_CONSENSUS_VERSION.minor,
110 ),
111 &[(0, 0)],
112 )
113 }
114
115 async fn init(&self, args: &ServerModuleInitArgs<Self>) -> anyhow::Result<Self::Module> {
117 Ok(Dummy::new(args.cfg().to_typed()?))
118 }
119
120 fn trusted_dealer_gen(
122 &self,
123 peers: &[PeerId],
124 params: &ConfigGenModuleParams,
125 ) -> BTreeMap<PeerId, ServerModuleConfig> {
126 let params = self.parse_params(params).unwrap();
127 peers
129 .iter()
130 .map(|&peer| {
131 let config = DummyConfig {
132 local: DummyConfigLocal {},
133 private: DummyConfigPrivate,
134 consensus: DummyConfigConsensus {
135 tx_fee: params.consensus.tx_fee,
136 },
137 };
138 (peer, config.to_erased())
139 })
140 .collect()
141 }
142
143 async fn distributed_gen(
145 &self,
146 _peers: &PeerHandle,
147 params: &ConfigGenModuleParams,
148 ) -> anyhow::Result<ServerModuleConfig> {
149 let params = self.parse_params(params).unwrap();
150
151 Ok(DummyConfig {
152 local: DummyConfigLocal {},
153 private: DummyConfigPrivate,
154 consensus: DummyConfigConsensus {
155 tx_fee: params.consensus.tx_fee,
156 },
157 }
158 .to_erased())
159 }
160
161 fn get_client_config(
163 &self,
164 config: &ServerModuleConsensusConfig,
165 ) -> anyhow::Result<DummyClientConfig> {
166 let config = DummyConfigConsensus::from_erased(config)?;
167 Ok(DummyClientConfig {
168 tx_fee: config.tx_fee,
169 })
170 }
171
172 fn validate_config(
173 &self,
174 _identity: &PeerId,
175 _config: ServerModuleConfig,
176 ) -> anyhow::Result<()> {
177 Ok(())
178 }
179
180 fn get_database_migrations(
182 &self,
183 ) -> BTreeMap<DatabaseVersion, ServerModuleDbMigrationFn<Dummy>> {
184 let mut migrations: BTreeMap<DatabaseVersion, ServerModuleDbMigrationFn<Dummy>> =
185 BTreeMap::new();
186 migrations.insert(
187 DatabaseVersion(0),
188 Box::new(|ctx| migrate_to_v1(ctx).boxed()),
189 );
190 migrations
191 }
192}
193
194#[derive(Debug)]
196pub struct Dummy {
197 pub cfg: DummyConfig,
198}
199
200#[async_trait]
202impl ServerModule for Dummy {
203 type Common = DummyModuleTypes;
205 type Init = DummyInit;
206
207 async fn consensus_proposal(
208 &self,
209 _dbtx: &mut DatabaseTransaction<'_>,
210 ) -> Vec<DummyConsensusItem> {
211 Vec::new()
212 }
213
214 async fn process_consensus_item<'a, 'b>(
215 &'a self,
216 _dbtx: &mut DatabaseTransaction<'b>,
217 _consensus_item: DummyConsensusItem,
218 _peer_id: PeerId,
219 ) -> anyhow::Result<()> {
220 bail!("The dummy module does not use consensus items");
226 }
227
228 async fn process_input<'a, 'b, 'c>(
229 &'a self,
230 dbtx: &mut DatabaseTransaction<'c>,
231 input: &'b DummyInput,
232 _in_point: InPoint,
233 ) -> Result<InputMeta, DummyInputError> {
234 let current_funds = dbtx
235 .get_value(&DummyFundsKeyV1(input.account))
236 .await
237 .unwrap_or(Amount::ZERO);
238
239 if input.amount > current_funds
241 && fed_public_key() != input.account
242 && broken_fed_public_key() != input.account
243 {
244 return Err(DummyInputError::NotEnoughFunds);
245 }
246
247 let updated_funds = if fed_public_key() == input.account {
249 current_funds + input.amount
250 } else if broken_fed_public_key() == input.account {
251 current_funds
253 } else {
254 current_funds.saturating_sub(input.amount)
255 };
256
257 dbtx.insert_entry(&DummyFundsKeyV1(input.account), &updated_funds)
258 .await;
259
260 Ok(InputMeta {
261 amount: TransactionItemAmount {
262 amount: input.amount,
263 fee: self.cfg.consensus.tx_fee,
264 },
265 pub_key: input.account,
267 })
268 }
269
270 async fn process_output<'a, 'b>(
271 &'a self,
272 dbtx: &mut DatabaseTransaction<'b>,
273 output: &'a DummyOutput,
274 out_point: OutPoint,
275 ) -> Result<TransactionItemAmount, DummyOutputError> {
276 let current_funds = dbtx.get_value(&DummyFundsKeyV1(output.account)).await;
278 let updated_funds = current_funds.unwrap_or(Amount::ZERO) + output.amount;
279 dbtx.insert_entry(&DummyFundsKeyV1(output.account), &updated_funds)
280 .await;
281
282 let outcome = DummyOutputOutcome(updated_funds, output.account);
284 dbtx.insert_entry(&DummyOutcomeKey(out_point), &outcome)
285 .await;
286
287 Ok(TransactionItemAmount {
288 amount: output.amount,
289 fee: self.cfg.consensus.tx_fee,
290 })
291 }
292
293 async fn output_status(
294 &self,
295 dbtx: &mut DatabaseTransaction<'_>,
296 out_point: OutPoint,
297 ) -> Option<DummyOutputOutcome> {
298 dbtx.get_value(&DummyOutcomeKey(out_point)).await
300 }
301
302 async fn audit(
303 &self,
304 dbtx: &mut DatabaseTransaction<'_>,
305 audit: &mut Audit,
306 module_instance_id: ModuleInstanceId,
307 ) {
308 audit
309 .add_items(
310 dbtx,
311 module_instance_id,
312 &DummyFundsPrefixV1,
313 |k, v| match k {
314 DummyFundsKeyV1(key)
317 if key == fed_public_key() || key == broken_fed_public_key() =>
318 {
319 v.msats as i64
320 }
321 DummyFundsKeyV1(_) => -(v.msats as i64),
323 },
324 )
325 .await;
326 }
327
328 fn api_endpoints(&self) -> Vec<ApiEndpoint<Self>> {
329 Vec::new()
330 }
331}
332
333impl Dummy {
334 pub fn new(cfg: DummyConfig) -> Dummy {
336 Dummy { cfg }
337 }
338}