fedimint_meta_server/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
#![deny(clippy::pedantic)]
#![allow(clippy::module_name_repetitions)]

pub mod db;

use std::collections::BTreeMap;
use std::future;

use async_trait::async_trait;
use db::{
    MetaConsensusKey, MetaDesiredKey, MetaDesiredValue, MetaSubmissionsByKeyPrefix,
    MetaSubmissionsKey,
};
use fedimint_core::config::{
    ConfigGenModuleParams, DkgResult, ServerModuleConfig, ServerModuleConsensusConfig,
    TypedServerModuleConfig, TypedServerModuleConsensusConfig,
};
use fedimint_core::core::ModuleInstanceId;
use fedimint_core::db::{
    Committable, CoreMigrationFn, DatabaseTransaction, DatabaseVersion,
    IDatabaseTransactionOpsCoreTyped, NonCommittable,
};
use fedimint_core::module::audit::Audit;
use fedimint_core::module::{
    api_endpoint, ApiAuth, ApiEndpoint, ApiError, ApiVersion, CoreConsensusVersion, InputMeta,
    ModuleConsensusVersion, ModuleInit, PeerHandle, ServerModuleInit, ServerModuleInitArgs,
    SupportedModuleApiVersions, TransactionItemAmount, CORE_CONSENSUS_VERSION,
};
use fedimint_core::server::DynServerModule;
use fedimint_core::{push_db_pair_items, NumPeers, OutPoint, PeerId, ServerModule};
use fedimint_logging::LOG_MODULE_META;
use fedimint_meta_common::config::{
    MetaClientConfig, MetaConfig, MetaConfigConsensus, MetaConfigLocal, MetaConfigPrivate,
};
pub use fedimint_meta_common::config::{MetaGenParams, MetaGenParamsConsensus, MetaGenParamsLocal};
use fedimint_meta_common::endpoint::{
    GetConsensusRequest, GetSubmissionResponse, GetSubmissionsRequest, SubmitRequest,
    GET_CONSENSUS_ENDPOINT, GET_CONSENSUS_REV_ENDPOINT, GET_SUBMISSIONS_ENDPOINT, SUBMIT_ENDPOINT,
};
use fedimint_meta_common::{
    MetaCommonInit, MetaConsensusItem, MetaConsensusValue, MetaInput, MetaInputError, MetaKey,
    MetaModuleTypes, MetaOutput, MetaOutputError, MetaOutputOutcome, MetaValue,
    MODULE_CONSENSUS_VERSION,
};
use futures::StreamExt;
use rand::{thread_rng, Rng};
use strum::IntoEnumIterator;
use tracing::{debug, info, trace};

use crate::db::{
    DbKeyPrefix, MetaConsensusKeyPrefix, MetaDesiredKeyPrefix, MetaSubmissionValue,
    MetaSubmissionsKeyPrefix,
};

/// Generates the module
#[derive(Debug, Clone)]
pub struct MetaInit;

// TODO: Boilerplate-code
impl ModuleInit for MetaInit {
    type Common = MetaCommonInit;

    /// Dumps all database items for debugging
    async fn dump_database(
        &self,
        dbtx: &mut DatabaseTransaction<'_>,
        prefix_names: Vec<String>,
    ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
        // TODO: Boilerplate-code
        let mut items: BTreeMap<String, Box<dyn erased_serde::Serialize + Send>> = BTreeMap::new();
        let filtered_prefixes = DbKeyPrefix::iter().filter(|f| {
            prefix_names.is_empty() || prefix_names.contains(&f.to_string().to_lowercase())
        });

        for table in filtered_prefixes {
            match table {
                DbKeyPrefix::Desired => {
                    push_db_pair_items!(
                        dbtx,
                        MetaDesiredKeyPrefix,
                        MetaDesiredKey,
                        MetaDesiredValue,
                        items,
                        "Meta Desired"
                    );
                }
                DbKeyPrefix::Consensus => {
                    push_db_pair_items!(
                        dbtx,
                        MetaConsensusKeyPrefix,
                        MetaConsensusKey,
                        MetaConsensusValue,
                        items,
                        "Meta Consensus"
                    );
                }
                DbKeyPrefix::Submissions => {
                    push_db_pair_items!(
                        dbtx,
                        MetaSubmissionsKeyPrefix,
                        MetaSubmissionsKey,
                        MetaSubmissionValue,
                        items,
                        "Meta Submissions"
                    );
                }
            }
        }

        Box::new(items.into_iter())
    }
}

/// Implementation of server module non-consensus functions
#[async_trait]
impl ServerModuleInit for MetaInit {
    type Params = MetaGenParams;

    /// Returns the version of this module
    fn versions(&self, _core: CoreConsensusVersion) -> &[ModuleConsensusVersion] {
        &[MODULE_CONSENSUS_VERSION]
    }

    fn supported_api_versions(&self) -> SupportedModuleApiVersions {
        SupportedModuleApiVersions::from_raw(
            (CORE_CONSENSUS_VERSION.major, CORE_CONSENSUS_VERSION.minor),
            (
                MODULE_CONSENSUS_VERSION.major,
                MODULE_CONSENSUS_VERSION.minor,
            ),
            &[(0, 0)],
        )
    }

    /// Initialize the module
    async fn init(&self, args: &ServerModuleInitArgs<Self>) -> anyhow::Result<DynServerModule> {
        Ok(Meta {
            cfg: args.cfg().to_typed()?,
            our_peer_id: args.our_peer_id(),
            num_peers: args.num_peers(),
        }
        .into())
    }

    /// Generates configs for all peers in a trusted manner for testing
    fn trusted_dealer_gen(
        &self,
        peers: &[PeerId],
        params: &ConfigGenModuleParams,
    ) -> BTreeMap<PeerId, ServerModuleConfig> {
        let _params = self.parse_params(params).unwrap();
        // Generate a config for each peer
        peers
            .iter()
            .map(|&peer| {
                let config = MetaConfig {
                    local: MetaConfigLocal {},
                    private: MetaConfigPrivate,
                    consensus: MetaConfigConsensus {},
                };
                (peer, config.to_erased())
            })
            .collect()
    }

    /// Generates configs for all peers in an untrusted manner
    async fn distributed_gen(
        &self,
        _peers: &PeerHandle,
        params: &ConfigGenModuleParams,
    ) -> DkgResult<ServerModuleConfig> {
        let _params = self.parse_params(params).unwrap();

        Ok(MetaConfig {
            local: MetaConfigLocal {},
            private: MetaConfigPrivate,
            consensus: MetaConfigConsensus {},
        }
        .to_erased())
    }

    /// Converts the consensus config into the client config
    fn get_client_config(
        &self,
        config: &ServerModuleConsensusConfig,
    ) -> anyhow::Result<MetaClientConfig> {
        let _config = MetaConfigConsensus::from_erased(config)?;
        Ok(MetaClientConfig {})
    }

    fn validate_config(
        &self,
        _identity: &PeerId,
        _config: ServerModuleConfig,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    /// DB migrations to move from old to newer versions
    fn get_database_migrations(&self) -> BTreeMap<DatabaseVersion, CoreMigrationFn> {
        BTreeMap::new()
    }
}

/// Meta module
#[derive(Debug)]
pub struct Meta {
    pub cfg: MetaConfig,
    pub our_peer_id: PeerId,
    pub num_peers: NumPeers,
}

impl Meta {
    async fn get_desired(dbtx: &mut DatabaseTransaction<'_>) -> Vec<(MetaKey, MetaDesiredValue)> {
        dbtx.find_by_prefix(&MetaDesiredKeyPrefix)
            .await
            .map(|(k, v)| (k.0, v))
            .collect()
            .await
    }

    async fn get_submission(
        dbtx: &mut DatabaseTransaction<'_>,
        key: MetaKey,
        peer_id: PeerId,
    ) -> Option<MetaSubmissionValue> {
        dbtx.get_value(&MetaSubmissionsKey { key, peer_id }).await
    }

    async fn get_consensus(dbtx: &mut DatabaseTransaction<'_>, key: MetaKey) -> Option<MetaValue> {
        dbtx.get_value(&MetaConsensusKey(key))
            .await
            .map(|consensus_value| consensus_value.value)
    }

    async fn change_consensus(
        dbtx: &mut DatabaseTransaction<'_, NonCommittable>,
        key: MetaKey,
        value: MetaValue,
        matching_submissions: Vec<PeerId>,
    ) {
        let value_len = value.as_slice().len();
        let revision = dbtx
            .get_value(&MetaConsensusKey(key))
            .await
            .map(|cv| cv.revision);
        let revision = revision.map(|r| r.wrapping_add(1)).unwrap_or_default();
        dbtx.insert_entry(
            &MetaConsensusKey(key),
            &MetaConsensusValue { revision, value },
        )
        .await;

        info!(target: LOG_MODULE_META, %key, rev = %revision, len = %value_len, "New consensus value");

        for peer_id in matching_submissions {
            dbtx.remove_entry(&MetaSubmissionsKey { key, peer_id })
                .await;
        }
    }
}

/// Implementation of consensus for the server module
#[async_trait]
impl ServerModule for Meta {
    /// Define the consensus types
    type Common = MetaModuleTypes;
    type Init = MetaInit;

    /// Check the difference between what's desired vs submitted and consensus.
    ///
    /// Returns:
    /// Items to submit as our proposal.
    async fn consensus_proposal(
        &self,
        dbtx: &mut DatabaseTransaction<'_>,
    ) -> Vec<MetaConsensusItem> {
        let desired: Vec<_> = Self::get_desired(dbtx).await;

        let mut to_submit = vec![];

        for (
            key,
            MetaDesiredValue {
                value: desired_value,
                salt,
            },
        ) in desired
        {
            let consensus_value = &Self::get_consensus(dbtx, key).await;
            let consensus_submission_value =
                Self::get_submission(dbtx, key, self.our_peer_id).await;
            if consensus_submission_value.as_ref()
                == Some(&MetaSubmissionValue {
                    value: desired_value.clone(),
                    salt,
                })
            {
                // our submission is already registered, nothing to do
            } else if consensus_value.as_ref() == Some(&desired_value) {
                if consensus_submission_value.is_none() {
                    // our desired value is equal to consensus and cleared our
                    // submission (as it is equal the
                    // consensus) so we don't need to propose it
                } else {
                    // we want to submit the same value as the current consensus, usually
                    // to clear the previous submission that did not became the consensus (we were
                    // outvoted)
                    to_submit.push(MetaConsensusItem {
                        key,
                        value: desired_value,
                        salt,
                    });
                }
            } else {
                to_submit.push(MetaConsensusItem {
                    key,
                    value: desired_value,
                    salt,
                });
            }
        }

        trace!(target: LOG_MODULE_META, ?to_submit, "Desired actions");
        to_submit
    }

    /// BUG: This implementation fails to return an `Err` on redundant consensus
    /// items. If you are using this code as a template,
    /// make sure to read the [`ServerModule::process_consensus_item`]
    /// documentation,
    async fn process_consensus_item<'a, 'b>(
        &'a self,
        dbtx: &mut DatabaseTransaction<'b>,
        MetaConsensusItem { key, value, salt }: MetaConsensusItem,
        peer_id: PeerId,
    ) -> anyhow::Result<()> {
        debug!(target: LOG_MODULE_META, %peer_id, %key, %value, %salt, "Received a submission");

        let new_value = MetaSubmissionValue { salt, value };
        // first of all: any new submission overrides previous submission
        if let Some(prev_value) = Self::get_submission(dbtx, key, peer_id).await {
            if prev_value != new_value {
                dbtx.remove_entry(&MetaSubmissionsKey { key, peer_id })
                    .await;
            }
        }
        // then: if the submission is equal to the current consensus, it's ignored
        if Some(&new_value.value) == Self::get_consensus(dbtx, key).await.as_ref() {
            debug!(target: LOG_MODULE_META, %peer_id, %key, "Peer submitted a redundant value");
            return Ok(());
        }

        // otherwise, new submission is recorded
        dbtx.insert_entry(&MetaSubmissionsKey { key, peer_id }, &new_value)
            .await;

        // we check how many peers submitted the same value (including this peer)
        let matching_submissions: Vec<PeerId> = dbtx
            .find_by_prefix(&MetaSubmissionsByKeyPrefix(key))
            .await
            .filter(|(_submission_key, submission_value)| {
                future::ready(new_value.value == submission_value.value)
            })
            .map(|(submission_key, _)| submission_key.peer_id)
            .collect()
            .await;

        let threshold = self.num_peers.threshold();
        info!(target: LOG_MODULE_META,
             %peer_id,
             %key,
            value_len = %new_value.value.as_slice().len(),
             matching = %matching_submissions.len(),
            %threshold, "Peer submitted a value");

        // if threshold or more, change the consensus value
        if threshold <= matching_submissions.len() {
            Self::change_consensus(dbtx, key, new_value.value, matching_submissions).await;
        }

        Ok(())
    }

    async fn process_input<'a, 'b, 'c>(
        &'a self,
        _dbtx: &mut DatabaseTransaction<'c>,
        _input: &'b MetaInput,
    ) -> Result<InputMeta, MetaInputError> {
        Err(MetaInputError::NotSupported)
    }

    async fn process_output<'a, 'b>(
        &'a self,
        _dbtx: &mut DatabaseTransaction<'b>,
        _output: &'a MetaOutput,
        _out_point: OutPoint,
    ) -> Result<TransactionItemAmount, MetaOutputError> {
        Err(MetaOutputError::NotSupported)
    }

    async fn output_status(
        &self,
        _dbtx: &mut DatabaseTransaction<'_>,
        _out_point: OutPoint,
    ) -> Option<MetaOutputOutcome> {
        None
    }

    async fn audit(
        &self,
        _dbtx: &mut DatabaseTransaction<'_>,
        _audit: &mut Audit,
        _module_instance_id: ModuleInstanceId,
    ) {
    }

    fn api_endpoints(&self) -> Vec<ApiEndpoint<Self>> {
        vec![
            api_endpoint! {
                SUBMIT_ENDPOINT,
                ApiVersion::new(0, 0),
                async |module: &Meta, context, request: SubmitRequest| -> () {

                    match context.request_auth() {
                        None => return Err(ApiError::bad_request("Missing password".to_string())),
                        Some(auth) => {
                            module.handle_submit_request(&mut context.dbtx(), &auth, &request).await?;
                        }
                    }

                    Ok(())
                }
            },
            api_endpoint! {
                GET_CONSENSUS_ENDPOINT,
                ApiVersion::new(0, 0),
                async |module: &Meta, context, request: GetConsensusRequest| -> Option<MetaConsensusValue> {
                    module.handle_get_consensus_request(&mut context.dbtx().into_nc(), &request).await
                }
            },
            api_endpoint! {
                GET_CONSENSUS_REV_ENDPOINT,
                ApiVersion::new(0, 0),
                async |module: &Meta, context, request: GetConsensusRequest| -> Option<u64> {
                    module.handle_get_consensus_revision_request(&mut context.dbtx().into_nc(), &request).await
                }
            },
            api_endpoint! {
                GET_SUBMISSIONS_ENDPOINT,
                ApiVersion::new(0, 0),
                async |module: &Meta, context, request: GetSubmissionsRequest| -> GetSubmissionResponse {
                    match context.request_auth() {
                        None => return Err(ApiError::bad_request("Missing password".to_string())),
                        Some(auth) => {
                            module.handle_get_submissions_request(&mut context.dbtx().into_nc(),&auth, &request).await
                        }
                    }
                }
            },
        ]
    }
}

impl Meta {
    async fn handle_submit_request(
        &self,
        dbtx: &mut DatabaseTransaction<'_, Committable>,
        _auth: &ApiAuth,
        req: &SubmitRequest,
    ) -> Result<(), ApiError> {
        let salt = thread_rng().gen();

        info!(target: LOG_MODULE_META,
             key = %req.key,
             peer_id = %self.our_peer_id,
             value_len = %req.value.as_slice().len(),
             "Our own guardian submitted a value");

        dbtx.insert_entry(
            &MetaDesiredKey(req.key),
            &MetaDesiredValue {
                value: req.value.clone(),
                salt,
            },
        )
        .await;

        Ok(())
    }

    async fn handle_get_consensus_request(
        &self,
        dbtx: &mut DatabaseTransaction<'_, NonCommittable>,
        req: &GetConsensusRequest,
    ) -> Result<Option<MetaConsensusValue>, ApiError> {
        Ok(dbtx.get_value(&MetaConsensusKey(req.0)).await)
    }

    async fn handle_get_consensus_revision_request(
        &self,
        dbtx: &mut DatabaseTransaction<'_, NonCommittable>,
        req: &GetConsensusRequest,
    ) -> Result<Option<u64>, ApiError> {
        Ok(dbtx
            .get_value(&MetaConsensusKey(req.0))
            .await
            .map(|cv| cv.revision))
    }

    async fn handle_get_submissions_request(
        &self,
        dbtx: &mut DatabaseTransaction<'_, NonCommittable>,
        _auth: &ApiAuth,
        req: &GetSubmissionsRequest,
    ) -> Result<BTreeMap<PeerId, MetaValue>, ApiError> {
        Ok(dbtx
            .find_by_prefix(&MetaSubmissionsByKeyPrefix(req.0))
            .await
            .collect::<Vec<_>>()
            .await
            .into_iter()
            .map(|(k, v)| (k.peer_id, v.value))
            .collect())
    }
}