fedimint_meta_common/
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
#![deny(clippy::pedantic)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::must_use_candidate)]

pub mod endpoint;

use std::fmt;
use std::str::FromStr;

use config::MetaClientConfig;
use fedimint_core::core::{Decoder, ModuleInstanceId, ModuleKind};
use fedimint_core::encoding::{Decodable, DecodeError, Encodable};
use fedimint_core::module::{CommonModuleInit, ModuleCommon, ModuleConsensusVersion};
use fedimint_core::plugin_types_trait_impl_common;
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use thiserror::Error;

// Common contains types shared by both the client and server

// The client and server configuration
pub mod config;

/// Unique name for this module
pub const KIND: ModuleKind = ModuleKind::from_static_str("meta");

/// Modules are non-compatible with older versions
pub const MODULE_CONSENSUS_VERSION: ModuleConsensusVersion = ModuleConsensusVersion::new(0, 0);

/// The meta module was built with flexibility and upgradability in mind. We
/// currently only intend to use one key, which is defined here.
pub const DEFAULT_META_KEY: MetaKey = MetaKey(0);

/// A key identifying a value in the meta module consensus
///
/// Intentionally small (`u8`) to avoid problems with malicious peers
/// submitting lots of votes to waste storage and memory. Since values
/// in the meta module are supposed to be larger aggregates (e.g. json),
/// 256 keys should be plenty.
#[derive(
    Debug,
    Copy,
    Clone,
    Encodable,
    Decodable,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Serialize,
    Deserialize,
)]
pub struct MetaKey(pub u8);

impl fmt::Display for MetaKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl FromStr for MetaKey {
    type Err = <u8 as FromStr>::Err;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(FromStr::from_str(s)?))
    }
}
/// A value of the [`MetaKey`] peers are trying to establish consensus on
///
/// Mostly a newtype around a `Vec<u8>` as meta module does not ever interpret
/// it. Serialized as a hex string, with [`Decodable`] and [`Deserialize`]
/// implementations enforcing size limit of [`Self::MAX_LEN_BYTES`].
#[derive(Debug, Clone, Encodable, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MetaValue(Vec<u8>);

impl FromStr for MetaValue {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self(hex::decode(s)?))
    }
}

impl fmt::Display for MetaValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&hex::encode(&self.0))
    }
}
impl From<&[u8]> for MetaValue {
    fn from(value: &[u8]) -> Self {
        Self(value.to_vec())
    }
}

impl MetaValue {
    /// Maximum size of a [`MetaValue`]
    /// More than 1MB would lead to problems.
    pub const MAX_LEN_BYTES: usize = 1024 * 1024 * 1024;

    pub fn as_slice(&self) -> &[u8] {
        &self.0
    }

    pub fn to_json(&self) -> anyhow::Result<serde_json::Value> {
        Ok(serde_json::from_slice(&self.0)?)
    }
}

impl Decodable for MetaValue {
    fn consensus_decode<R: std::io::Read>(
        r: &mut R,
        modules: &fedimint_core::module::registry::ModuleDecoderRegistry,
    ) -> Result<Self, fedimint_core::encoding::DecodeError> {
        let bytes = Vec::consensus_decode(r, modules)?;

        if Self::MAX_LEN_BYTES < bytes.len() {
            return Err(DecodeError::new_custom(anyhow::format_err!("Too long")));
        }

        Ok(Self(bytes))
    }
}
impl Serialize for MetaValue {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        assert!(self.0.len() <= Self::MAX_LEN_BYTES);
        serializer.serialize_str(&hex::encode(&self.0))
    }
}

// Implement Deserialize for MetaValue
impl<'de> Deserialize<'de> for MetaValue {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct MetaValueVisitor;

        impl<'de> Visitor<'de> for MetaValueVisitor {
            type Value = MetaValue;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a hex string")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                let val = hex::decode(value).map_err(de::Error::custom)?;

                if MetaValue::MAX_LEN_BYTES < val.len() {
                    return Err(de::Error::custom("Too long"));
                }

                Ok(MetaValue(val))
            }
        }

        deserializer.deserialize_str(MetaValueVisitor)
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, Encodable, Decodable)]
pub struct MetaConsensusItem {
    // Since AlephBft will merge and not re-submit the exact same item twice within one session,
    // changing submitted item in sequence `a -> b -> a` will simply ignore the second `a`.
    // To avoid this behavior, an otherwise meaningless `salt` field is used.
    pub salt: u64,
    pub key: MetaKey,
    pub value: MetaValue,
}

/// A [`MetaValue`] in a consensus (which means it has a revision number)
#[derive(Debug, Clone, Encodable, Decodable, Serialize, Deserialize, PartialEq, Eq)]
pub struct MetaConsensusValue {
    pub revision: u64,
    pub value: MetaValue,
}

/// Input for a fedimint transaction
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Encodable, Decodable)]
pub struct MetaInput;

/// Output for a fedimint transaction
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Encodable, Decodable)]
pub struct MetaOutput;

/// Information needed by a client to update output funds
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Encodable, Decodable)]
pub struct MetaOutputOutcome;

/// Errors that might be returned by the server
#[derive(Debug, Clone, Eq, PartialEq, Hash, Error, Encodable, Decodable)]
pub enum MetaInputError {
    #[error("This module does not support inputs")]
    NotSupported,
}

/// Errors that might be returned by the server
#[derive(Debug, Clone, Eq, PartialEq, Hash, Error, Encodable, Decodable)]
pub enum MetaOutputError {
    #[error("This module does not support outputs")]
    NotSupported,
}

/// Contains the types defined above
pub struct MetaModuleTypes;

// Wire together the types for this module
plugin_types_trait_impl_common!(
    KIND,
    MetaModuleTypes,
    MetaClientConfig,
    MetaInput,
    MetaOutput,
    MetaOutputOutcome,
    MetaConsensusItem,
    MetaInputError,
    MetaOutputError
);

#[derive(Debug)]
pub struct MetaCommonInit;

impl CommonModuleInit for MetaCommonInit {
    const CONSENSUS_VERSION: ModuleConsensusVersion = MODULE_CONSENSUS_VERSION;
    const KIND: ModuleKind = KIND;

    type ClientConfig = MetaClientConfig;

    fn decoder() -> Decoder {
        MetaModuleTypes::decoder_builder().build()
    }
}

impl fmt::Display for MetaClientConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "MetaClientConfig")
    }
}
impl fmt::Display for MetaInput {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "MetaInput")
    }
}

impl fmt::Display for MetaOutput {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "MetaOutput")
    }
}

impl fmt::Display for MetaOutputOutcome {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "MetaOutputOutcome")
    }
}

impl fmt::Display for MetaConsensusItem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "MetaConsensusItem")
    }
}