Skip to main content

fedimint_unknown_server/
lib.rs

1#![deny(clippy::pedantic)]
2#![allow(clippy::module_name_repetitions)]
3#![allow(clippy::must_use_candidate)]
4
5use std::collections::BTreeMap;
6
7use anyhow::bail;
8use async_trait::async_trait;
9use fedimint_core::config::{
10    ServerModuleConfig, ServerModuleConsensusConfig, TypedServerModuleConfig,
11    TypedServerModuleConsensusConfig,
12};
13use fedimint_core::core::ModuleInstanceId;
14use fedimint_core::db::{DatabaseTransaction, DatabaseVersion};
15use fedimint_core::module::audit::Audit;
16use fedimint_core::module::{
17    ApiEndpoint, CoreConsensusVersion, InputMeta, ModuleConsensusVersion, ModuleInit,
18    TransactionItemAmounts,
19};
20use fedimint_core::{InPoint, OutPoint, PeerId};
21use fedimint_server_core::config::PeerHandleOps;
22use fedimint_server_core::migration::ServerModuleDbMigrationFn;
23use fedimint_server_core::{
24    ConfigGenModuleArgs, ServerModule, ServerModuleInit, ServerModuleInitArgs,
25};
26pub use fedimint_unknown_common as common;
27use fedimint_unknown_common::config::{
28    UnknownClientConfig, UnknownConfig, UnknownConfigConsensus, UnknownConfigPrivate,
29};
30use fedimint_unknown_common::{
31    MODULE_CONSENSUS_VERSION, UnknownCommonInit, UnknownConsensusItem, UnknownInput,
32    UnknownInputError, UnknownModuleTypes, UnknownOutput, UnknownOutputError, UnknownOutputOutcome,
33};
34pub mod db;
35
36/// Generates the module
37#[derive(Debug, Clone)]
38pub struct UnknownInit;
39
40// TODO: Boilerplate-code
41impl ModuleInit for UnknownInit {
42    type Common = UnknownCommonInit;
43
44    /// Dumps all database items for debugging
45    async fn dump_database(
46        &self,
47        _dbtx: &mut DatabaseTransaction<'_>,
48        _prefix_names: Vec<String>,
49    ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
50        Box::new(vec![].into_iter())
51    }
52}
53
54/// Implementation of server module non-consensus functions
55#[async_trait]
56impl ServerModuleInit for UnknownInit {
57    type Module = Unknown;
58
59    /// Returns the version of this module
60    fn versions(&self, _core: CoreConsensusVersion) -> &[ModuleConsensusVersion] {
61        &[MODULE_CONSENSUS_VERSION]
62    }
63
64    /// Initialize the module
65    async fn init(&self, args: &ServerModuleInitArgs<Self>) -> anyhow::Result<Self::Module> {
66        Ok(Unknown::new(args.cfg().to_typed()?))
67    }
68
69    /// Generates configs for all peers in a trusted manner for testing
70    fn trusted_dealer_gen(
71        &self,
72        peers: &[PeerId],
73        _args: &ConfigGenModuleArgs,
74    ) -> BTreeMap<PeerId, ServerModuleConfig> {
75        // Generate a config for each peer
76        peers
77            .iter()
78            .map(|&peer| {
79                let config = UnknownConfig {
80                    private: UnknownConfigPrivate,
81                    consensus: UnknownConfigConsensus {},
82                };
83                (peer, config.to_erased())
84            })
85            .collect()
86    }
87
88    /// Generates configs for all peers in an untrusted manner
89    async fn distributed_gen(
90        &self,
91        _peers: &(dyn PeerHandleOps + Send + Sync),
92        _args: &ConfigGenModuleArgs,
93    ) -> anyhow::Result<ServerModuleConfig> {
94        Ok(UnknownConfig {
95            private: UnknownConfigPrivate,
96            consensus: UnknownConfigConsensus {},
97        }
98        .to_erased())
99    }
100
101    /// Converts the consensus config into the client config
102    fn get_client_config(
103        &self,
104        config: &ServerModuleConsensusConfig,
105    ) -> anyhow::Result<UnknownClientConfig> {
106        let _config = UnknownConfigConsensus::from_erased(config)?;
107        Ok(UnknownClientConfig {})
108    }
109
110    fn validate_config(
111        &self,
112        _identity: &PeerId,
113        _config: ServerModuleConfig,
114    ) -> anyhow::Result<()> {
115        Ok(())
116    }
117
118    /// DB migrations to move from old to newer versions
119    fn get_database_migrations(
120        &self,
121    ) -> BTreeMap<DatabaseVersion, ServerModuleDbMigrationFn<Unknown>> {
122        let mut migrations: BTreeMap<DatabaseVersion, ServerModuleDbMigrationFn<_>> =
123            BTreeMap::new();
124        // Unknown module prior to v0.5.0 had a `DATABASE_VERSION` of 1, so we must
125        // insert a no-op migration to ensure that upgrades work.
126        migrations.insert(DatabaseVersion(0), Box::new(|_| Box::pin(async { Ok(()) })));
127        migrations
128    }
129}
130
131/// Unknown module
132#[derive(Debug)]
133pub struct Unknown {
134    pub cfg: UnknownConfig,
135}
136
137/// Implementation of consensus for the server module
138#[async_trait]
139impl ServerModule for Unknown {
140    /// Define the consensus types
141    type Common = UnknownModuleTypes;
142    type Init = UnknownInit;
143
144    async fn consensus_proposal(
145        &self,
146        _dbtx: &mut DatabaseTransaction<'_>,
147    ) -> Vec<UnknownConsensusItem> {
148        Vec::new()
149    }
150
151    async fn process_consensus_item<'a, 'b>(
152        &'a self,
153        _dbtx: &mut DatabaseTransaction<'b>,
154        _consensus_item: UnknownConsensusItem,
155        _peer_id: PeerId,
156    ) -> anyhow::Result<()> {
157        // WARNING: `process_consensus_item` should return an `Err` for items that do
158        // not change any internal consensus state. Failure to do so, will result in an
159        // (potentially significantly) increased consensus history size.
160        // If you are using this code as a template,
161        // make sure to read the [`ServerModule::process_consensus_item`] documentation,
162        bail!("The unknown module does not use consensus items");
163    }
164
165    async fn process_input<'a, 'b, 'c>(
166        &'a self,
167        _dbtx: &mut DatabaseTransaction<'c>,
168        _input: &'b UnknownInput,
169        _in_point: InPoint,
170    ) -> Result<InputMeta, UnknownInputError> {
171        unreachable!();
172    }
173
174    async fn process_output<'a, 'b>(
175        &'a self,
176        _dbtx: &mut DatabaseTransaction<'b>,
177        _output: &'a UnknownOutput,
178        _out_point: OutPoint,
179    ) -> Result<TransactionItemAmounts, UnknownOutputError> {
180        unreachable!();
181    }
182
183    async fn output_status(
184        &self,
185        _dbtx: &mut DatabaseTransaction<'_>,
186        _out_point: OutPoint,
187    ) -> Option<UnknownOutputOutcome> {
188        unreachable!()
189    }
190
191    async fn audit(
192        &self,
193        _dbtx: &mut DatabaseTransaction<'_>,
194        _audit: &mut Audit,
195        _module_instance_id: ModuleInstanceId,
196    ) {
197    }
198
199    fn api_endpoints(&self) -> Vec<ApiEndpoint<Self>> {
200        Vec::new()
201    }
202}
203
204impl Unknown {
205    /// Create new module instance
206    pub fn new(cfg: UnknownConfig) -> Unknown {
207        Unknown { cfg }
208    }
209}