fedimint_core/module/
mod.rs

1//! Core module system traits and types.
2//!
3//! Fedimint supports modules to allow extending its functionality.
4//! Some of the standard functionality is implemented in form of modules as
5//! well. This rust module houses the core trait
6//! [`fedimint_core::module::ModuleCommon`] used by both the server and client
7//! side module traits. Specific server and client traits exist in their
8//! respective crates.
9//!
10//! The top level server-side types are:
11//!
12//! * `fedimint_server::core::ServerModuleInit`
13//! * `fedimint_server::core::ServerModule`
14//!
15//! Top level client-side types are:
16//!
17//! * `ClientModuleInit` (in `fedimint_client`)
18//! * `ClientModule` (in `fedimint_client`)
19pub mod audit;
20pub mod registry;
21
22use std::collections::{BTreeMap, BTreeSet};
23use std::error::Error;
24use std::fmt::{self, Debug, Formatter};
25use std::marker::PhantomData;
26use std::ops;
27use std::pin::Pin;
28use std::sync::Arc;
29use std::sync::atomic::{AtomicU64, Ordering};
30
31use fedimint_logging::LOG_NET_API;
32use futures::Future;
33use jsonrpsee_core::JsonValue;
34use registry::ModuleRegistry;
35use serde::{Deserialize, Serialize};
36use tracing::Instrument;
37
38// TODO: Make this module public and remove theDkgPeerMessage`pub use` below
39mod version;
40pub use self::version::*;
41use crate::core::{
42    ClientConfig, Decoder, DecoderBuilder, Input, InputError, ModuleConsensusItem,
43    ModuleInstanceId, ModuleKind, Output, OutputError, OutputOutcome,
44};
45use crate::db::{
46    Database, DatabaseError, DatabaseKey, DatabaseKeyWithNotify, DatabaseRecord,
47    DatabaseTransaction,
48};
49use crate::encoding::{Decodable, DecodeError, Encodable};
50use crate::fmt_utils::AbbreviateHexBytes;
51use crate::task::MaybeSend;
52use crate::util::FmtCompact;
53use crate::{Amount, apply, async_trait_maybe_send, maybe_add_send, maybe_add_send_sync};
54
55#[derive(Debug, PartialEq, Eq)]
56pub struct InputMeta {
57    pub amount: TransactionItemAmounts,
58    pub pub_key: secp256k1::PublicKey,
59}
60
61/// Unit of account for a given amount.
62#[derive(
63    Debug,
64    Clone,
65    Copy,
66    Eq,
67    PartialEq,
68    Hash,
69    PartialOrd,
70    Ord,
71    Deserialize,
72    Serialize,
73    Encodable,
74    Decodable,
75    Default,
76)]
77pub struct AmountUnit(u64);
78
79impl AmountUnit {
80    /// [`AmountUnit`] with id `0` is reserved for the native Bitcoin currency.
81    /// So e.g. for a mainnet Federation it's a real Bitcoin (msats), for a
82    /// signet one it's a Signet msats, etc.
83    pub const BITCOIN: Self = Self(0);
84
85    pub fn is_bitcoin(self) -> bool {
86        self == Self::BITCOIN
87    }
88
89    pub fn new_custom(unit: u64) -> Self {
90        Self(unit)
91    }
92
93    pub const fn bitcoin() -> Self {
94        Self::BITCOIN
95    }
96}
97
98#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
99pub struct AmountWithUnit {
100    amounts: Amount,
101    unit: AmountUnit,
102}
103
104/// Multi-unit amount
105///
106/// Basically (potentially) multiple amounts, each of different unit.
107///
108/// Note: implementation must be careful not to add zero-amount
109/// entries, as these could mess up equality comparisons, etc.
110#[derive(Debug, Clone, Eq, PartialEq, Hash)]
111pub struct Amounts(BTreeMap<AmountUnit, Amount>);
112
113// Note: no `impl ops::DerefMut` as it could easily accidentally break the
114// invariant
115impl ops::Deref for Amounts {
116    type Target = BTreeMap<AmountUnit, Amount>;
117
118    fn deref(&self) -> &Self::Target {
119        &self.0
120    }
121}
122
123impl Amounts {
124    pub const ZERO: Self = Self(BTreeMap::new());
125
126    pub fn new_bitcoin(amount: Amount) -> Self {
127        if amount == Amount::ZERO {
128            Self(BTreeMap::from([]))
129        } else {
130            Self(BTreeMap::from([(AmountUnit::BITCOIN, amount)]))
131        }
132    }
133
134    pub fn new_bitcoin_msats(msats: u64) -> Self {
135        Self::new_bitcoin(Amount::from_msats(msats))
136    }
137
138    pub fn new_custom(unit: AmountUnit, amount: Amount) -> Self {
139        if amount == Amount::ZERO {
140            Self(BTreeMap::from([]))
141        } else {
142            Self(BTreeMap::from([(unit, amount)]))
143        }
144    }
145
146    pub fn checked_add(mut self, rhs: &Self) -> Option<Self> {
147        self.checked_add_mut(rhs);
148
149        Some(self)
150    }
151
152    pub fn checked_add_mut(&mut self, rhs: &Self) -> Option<&mut Self> {
153        for (unit, amount) in &rhs.0 {
154            debug_assert!(
155                *amount != Amount::ZERO,
156                "`Amounts` must not add (/remove) zero-amount entries"
157            );
158            let prev = self.0.entry(*unit).or_default();
159
160            *prev = prev.checked_add(*amount)?;
161        }
162
163        Some(self)
164    }
165
166    pub fn checked_add_bitcoin(self, amount: Amount) -> Option<Self> {
167        self.checked_add_unit(amount, AmountUnit::BITCOIN)
168    }
169
170    pub fn checked_add_unit(mut self, amount: Amount, unit: AmountUnit) -> Option<Self> {
171        if amount == Amount::ZERO {
172            return Some(self);
173        }
174
175        let prev = self.0.entry(unit).or_default();
176
177        *prev = prev.checked_add(amount)?;
178
179        Some(self)
180    }
181
182    pub fn remove(&mut self, unit: &AmountUnit) -> Option<Amount> {
183        self.0.remove(unit)
184    }
185
186    pub fn get_bitcoin(&self) -> Amount {
187        self.get(&AmountUnit::BITCOIN).copied().unwrap_or_default()
188    }
189
190    pub fn expect_only_bitcoin(&self) -> Amount {
191        #[allow(clippy::option_if_let_else)] // I like it explicitly split into two cases --dpc
192        match self.get(&AmountUnit::BITCOIN) {
193            Some(amount) => {
194                assert!(
195                    self.len() == 1,
196                    "Amounts expected to contain only bitcoin and no other currencies"
197                );
198                *amount
199            }
200            None => Amount::ZERO,
201        }
202    }
203
204    pub fn iter_units(&self) -> impl Iterator<Item = AmountUnit> {
205        self.0.keys().copied()
206    }
207
208    pub fn units(&self) -> BTreeSet<AmountUnit> {
209        self.0.keys().copied().collect()
210    }
211}
212
213impl IntoIterator for Amounts {
214    type Item = (AmountUnit, Amount);
215
216    type IntoIter = <BTreeMap<AmountUnit, Amount> as IntoIterator>::IntoIter;
217
218    fn into_iter(self) -> Self::IntoIter {
219        self.0.into_iter()
220    }
221}
222
223/// Information about the amount represented by an input or output.
224///
225/// * For **inputs** the amount is funding the transaction while the fee is
226///   consuming funding
227/// * For **outputs** the amount and the fee consume funding
228#[derive(Debug, Clone, Eq, PartialEq, Hash)]
229pub struct TransactionItemAmounts {
230    pub amounts: Amounts,
231    pub fees: Amounts,
232}
233
234impl TransactionItemAmounts {
235    pub fn checked_add(self, rhs: &Self) -> Option<Self> {
236        Some(Self {
237            amounts: self.amounts.checked_add(&rhs.amounts)?,
238            fees: self.fees.checked_add(&rhs.fees)?,
239        })
240    }
241}
242
243impl TransactionItemAmounts {
244    pub const ZERO: Self = Self {
245        amounts: Amounts::ZERO,
246        fees: Amounts::ZERO,
247    };
248}
249
250/// All requests from client to server contain these fields
251#[derive(Debug, Serialize, Deserialize, Clone)]
252pub struct ApiRequest<T> {
253    /// Hashed user password if the API requires authentication
254    pub auth: Option<ApiAuth>,
255    /// Parameters required by the API
256    pub params: T,
257}
258
259pub type ApiRequestErased = ApiRequest<JsonValue>;
260
261impl Default for ApiRequestErased {
262    fn default() -> Self {
263        Self {
264            auth: None,
265            params: JsonValue::Null,
266        }
267    }
268}
269
270impl ApiRequestErased {
271    pub fn new<T: Serialize>(params: T) -> Self {
272        Self {
273            auth: None,
274            params: serde_json::to_value(params)
275                .expect("parameter serialization error - this should not happen"),
276        }
277    }
278
279    pub fn to_json(&self) -> JsonValue {
280        serde_json::to_value(self).expect("parameter serialization error - this should not happen")
281    }
282
283    pub fn with_auth(self, auth: ApiAuth) -> Self {
284        Self {
285            auth: Some(auth),
286            params: self.params,
287        }
288    }
289
290    pub fn to_typed<T: serde::de::DeserializeOwned>(
291        self,
292    ) -> Result<ApiRequest<T>, serde_json::Error> {
293        Ok(ApiRequest {
294            auth: self.auth,
295            params: serde_json::from_value::<T>(self.params)?,
296        })
297    }
298}
299
300#[derive(Debug, Clone, Serialize, Deserialize)]
301pub enum ApiMethod {
302    Core(String),
303    Module(ModuleInstanceId, String),
304}
305
306impl fmt::Display for ApiMethod {
307    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
308        match self {
309            Self::Core(s) => f.write_str(s),
310            Self::Module(module_id, s) => f.write_fmt(format_args!("{module_id}-{s}")),
311        }
312    }
313}
314
315#[derive(Debug, Clone, Serialize, Deserialize)]
316pub struct IrohApiRequest {
317    pub method: ApiMethod,
318    pub request: ApiRequestErased,
319}
320
321#[derive(Debug, Clone, Serialize, Deserialize)]
322pub struct IrohGatewayRequest {
323    /// REST API route for specifying which action to take
324    pub route: String,
325
326    /// Parameters for the request
327    pub params: Option<serde_json::Value>,
328
329    /// Password for authenticated requests to the gateway
330    pub password: Option<String>,
331}
332
333#[derive(Debug, Clone, Serialize, Deserialize)]
334pub struct IrohGatewayResponse {
335    pub status: u16,
336    pub body: serde_json::Value,
337}
338
339pub const FEDIMINT_API_ALPN: &[u8] = b"FEDIMINT_API_ALPN";
340pub const FEDIMINT_GATEWAY_ALPN: &[u8] = b"FEDIMINT_GATEWAY_ALPN";
341
342// TODO: either nuke or turn all `api_secret: Option<String>` into `api_secret:
343// Option<ApiAuth>`
344/// Authentication uses the hashed user password in PHC format
345#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
346pub struct ApiAuth(pub String);
347
348impl Debug for ApiAuth {
349    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
350        write!(f, "ApiAuth(****)")
351    }
352}
353
354#[derive(Debug, Clone, Serialize, Deserialize)]
355pub struct ApiError {
356    pub code: i32,
357    pub message: String,
358}
359
360impl Error for ApiError {}
361
362impl fmt::Display for ApiError {
363    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
364        f.write_fmt(format_args!("{} {}", self.code, self.message))
365    }
366}
367
368pub type ApiResult<T> = Result<T, ApiError>;
369
370impl ApiError {
371    pub fn new(code: i32, message: String) -> Self {
372        Self { code, message }
373    }
374
375    pub fn not_found(message: String) -> Self {
376        Self::new(404, message)
377    }
378
379    pub fn bad_request(message: String) -> Self {
380        Self::new(400, message)
381    }
382
383    pub fn unauthorized() -> Self {
384        Self::new(401, "Invalid authorization".to_string())
385    }
386
387    pub fn server_error(message: String) -> Self {
388        Self::new(500, message)
389    }
390}
391
392impl From<DatabaseError> for ApiError {
393    fn from(err: DatabaseError) -> Self {
394        Self {
395            code: 500,
396            message: format!("API server error when writing to database: {err}"),
397        }
398    }
399}
400
401/// State made available to all API endpoints for handling a request
402pub struct ApiEndpointContext {
403    db: Database,
404    has_auth: bool,
405    request_auth: Option<ApiAuth>,
406}
407
408impl ApiEndpointContext {
409    /// `db` should be isolated.
410    pub fn new(db: Database, has_auth: bool, request_auth: Option<ApiAuth>) -> Self {
411        Self {
412            db,
413            has_auth,
414            request_auth,
415        }
416    }
417
418    /// Returns the auth set on the request (regardless of whether it was
419    /// correct)
420    pub fn request_auth(&self) -> Option<ApiAuth> {
421        self.request_auth.clone()
422    }
423
424    /// Whether the request was authenticated as the guardian who controls this
425    /// fedimint server
426    pub fn has_auth(&self) -> bool {
427        self.has_auth
428    }
429
430    pub fn db(&self) -> Database {
431        self.db.clone()
432    }
433
434    /// Waits for key to be present in database.
435    pub fn wait_key_exists<K>(&self, key: K) -> impl Future<Output = K::Value> + use<K>
436    where
437        K: DatabaseKey + DatabaseRecord + DatabaseKeyWithNotify,
438    {
439        let db = self.db.clone();
440        // self contains dbtx which is !Send
441        // try removing this and see the error.
442        async move { db.wait_key_exists(&key).await }
443    }
444
445    /// Waits for key to have a value that matches.
446    pub fn wait_value_matches<K>(
447        &self,
448        key: K,
449        matcher: impl Fn(&K::Value) -> bool + Copy,
450    ) -> impl Future<Output = K::Value>
451    where
452        K: DatabaseKey + DatabaseRecord + DatabaseKeyWithNotify,
453    {
454        let db = self.db.clone();
455        async move { db.wait_key_check(&key, |v| v.filter(matcher)).await.0 }
456    }
457}
458
459#[apply(async_trait_maybe_send!)]
460pub trait TypedApiEndpoint {
461    type State: Sync;
462
463    /// example: /transaction
464    const PATH: &'static str;
465
466    type Param: serde::de::DeserializeOwned + Send;
467    type Response: serde::Serialize;
468
469    async fn handle<'state, 'context>(
470        state: &'state Self::State,
471        context: &'context mut ApiEndpointContext,
472        request: Self::Param,
473    ) -> Result<Self::Response, ApiError>;
474}
475
476pub use serde_json;
477
478/// # Example
479///
480/// ```rust
481/// # use fedimint_core::module::ApiVersion;
482/// # use fedimint_core::module::{api_endpoint, ApiEndpoint, registry::ModuleInstanceId};
483/// struct State;
484///
485/// let _: ApiEndpoint<State> = api_endpoint! {
486///     "/foobar",
487///     ApiVersion::new(0, 3),
488///     async |state: &State, _dbtx, params: ()| -> i32 {
489///         Ok(0)
490///     }
491/// };
492/// ```
493#[macro_export]
494macro_rules! __api_endpoint {
495    (
496        $path:expr_2021,
497        // Api Version this endpoint was introduced in, at the current consensus level
498        // Currently for documentation purposes only.
499        $version_introduced:expr_2021,
500        async |$state:ident: &$state_ty:ty, $context:ident, $param:ident: $param_ty:ty| -> $resp_ty:ty $body:block
501    ) => {{
502        struct Endpoint;
503
504        #[$crate::apply($crate::async_trait_maybe_send!)]
505        impl $crate::module::TypedApiEndpoint for Endpoint {
506            #[allow(deprecated)]
507            const PATH: &'static str = $path;
508            type State = $state_ty;
509            type Param = $param_ty;
510            type Response = $resp_ty;
511
512            async fn handle<'state, 'context>(
513                $state: &'state Self::State,
514                $context: &'context mut $crate::module::ApiEndpointContext,
515                $param: Self::Param,
516            ) -> ::std::result::Result<Self::Response, $crate::module::ApiError> {
517                {
518                    // just to enforce the correct type
519                    const __API_VERSION: $crate::module::ApiVersion = $version_introduced;
520                }
521                $body
522            }
523        }
524
525        $crate::module::ApiEndpoint::from_typed::<Endpoint>()
526    }};
527}
528
529pub use __api_endpoint as api_endpoint;
530
531use self::registry::ModuleDecoderRegistry;
532
533type HandlerFnReturn<'a> =
534    Pin<Box<maybe_add_send!(dyn Future<Output = Result<serde_json::Value, ApiError>> + 'a)>>;
535type HandlerFn<M> = Box<
536    maybe_add_send_sync!(
537        dyn for<'a> Fn(&'a M, ApiEndpointContext, ApiRequestErased) -> HandlerFnReturn<'a>
538    ),
539>;
540
541/// Definition of an API endpoint defined by a module `M`.
542pub struct ApiEndpoint<M> {
543    /// Path under which the API endpoint can be reached. It should start with a
544    /// `/` e.g. `/transaction`. E.g. this API endpoint would be reachable
545    /// under `module_module_instance_id_transaction` depending on the
546    /// module name returned by `[FedertionModule::api_base_name]`.
547    pub path: &'static str,
548    /// Handler for the API call that takes the following arguments:
549    ///   * Reference to the module which defined it
550    ///   * Request parameters parsed into JSON `[Value](serde_json::Value)`
551    pub handler: HandlerFn<M>,
552}
553
554/// Global request ID used for logging
555static REQ_ID: AtomicU64 = AtomicU64::new(0);
556
557// <()> is used to avoid specify state.
558impl ApiEndpoint<()> {
559    pub fn from_typed<E: TypedApiEndpoint>() -> ApiEndpoint<E::State>
560    where
561        <E as TypedApiEndpoint>::Response: MaybeSend,
562        E::Param: Debug,
563        E::Response: Debug,
564    {
565        async fn handle_request<'state, 'context, E>(
566            state: &'state E::State,
567            context: &'context mut ApiEndpointContext,
568            request: ApiRequest<E::Param>,
569        ) -> Result<E::Response, ApiError>
570        where
571            E: TypedApiEndpoint,
572            E::Param: Debug,
573            E::Response: Debug,
574        {
575            tracing::debug!(target: LOG_NET_API, path = E::PATH, ?request, "received api request");
576            let result = E::handle(state, context, request.params).await;
577            match &result {
578                Err(err) => {
579                    tracing::warn!(target: LOG_NET_API, path = E::PATH, err = %err.fmt_compact(), "api request error");
580                }
581                _ => {
582                    tracing::trace!(target: LOG_NET_API, path = E::PATH, "api request complete");
583                }
584            }
585            result
586        }
587
588        ApiEndpoint {
589            path: E::PATH,
590            handler: Box::new(|m, mut context, request| {
591                Box::pin(async move {
592                    let request = request
593                        .to_typed()
594                        .map_err(|e| ApiError::bad_request(e.to_string()))?;
595
596                    let span = tracing::info_span!(
597                        target: LOG_NET_API,
598                        "api_req",
599                        id = REQ_ID.fetch_add(1, Ordering::SeqCst),
600                        method = E::PATH,
601                    );
602                    let ret = handle_request::<E>(m, &mut context, request)
603                        .instrument(span)
604                        .await?;
605
606                    Ok(serde_json::to_value(ret).expect("encoding error"))
607                })
608            }),
609        }
610    }
611}
612
613/// Operations common to Server and Client side module gen dyn newtypes
614///
615/// Due to conflict of `impl Trait for T` for both `ServerModuleInit` and
616/// `ClientModuleInit`, we can't really have a `ICommonModuleInit`, so to unify
617/// them in `ModuleInitRegistry` we move the common functionality to be an
618/// interface over their dyn newtype wrappers. A bit weird, but works.
619#[apply(async_trait_maybe_send!)]
620pub trait IDynCommonModuleInit: Debug {
621    fn decoder(&self) -> Decoder;
622
623    fn module_kind(&self) -> ModuleKind;
624
625    fn to_dyn_common(&self) -> DynCommonModuleInit;
626
627    async fn dump_database(
628        &self,
629        dbtx: &mut DatabaseTransaction<'_>,
630        prefix_names: Vec<String>,
631    ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_>;
632}
633
634/// Trait implemented by every `*ModuleInit` (server or client side)
635pub trait ModuleInit: Debug + Clone + Send + Sync + 'static {
636    type Common: CommonModuleInit;
637
638    fn dump_database(
639        &self,
640        dbtx: &mut DatabaseTransaction<'_>,
641        prefix_names: Vec<String>,
642    ) -> maybe_add_send!(
643        impl Future<
644            Output = Box<
645                dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_,
646            >,
647        >
648    );
649}
650
651#[apply(async_trait_maybe_send!)]
652impl<T> IDynCommonModuleInit for T
653where
654    T: ModuleInit,
655{
656    fn decoder(&self) -> Decoder {
657        T::Common::decoder()
658    }
659
660    fn module_kind(&self) -> ModuleKind {
661        T::Common::KIND
662    }
663
664    fn to_dyn_common(&self) -> DynCommonModuleInit {
665        DynCommonModuleInit::from_inner(Arc::new(self.clone()))
666    }
667
668    async fn dump_database(
669        &self,
670        dbtx: &mut DatabaseTransaction<'_>,
671        prefix_names: Vec<String>,
672    ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
673        <Self as ModuleInit>::dump_database(self, dbtx, prefix_names).await
674    }
675}
676
677dyn_newtype_define!(
678    #[derive(Clone)]
679    pub DynCommonModuleInit(Arc<IDynCommonModuleInit>)
680);
681
682impl AsRef<maybe_add_send_sync!(dyn IDynCommonModuleInit + 'static)> for DynCommonModuleInit {
683    fn as_ref(&self) -> &(maybe_add_send_sync!(dyn IDynCommonModuleInit + 'static)) {
684        self.inner.as_ref()
685    }
686}
687
688impl DynCommonModuleInit {
689    pub fn from_inner(
690        inner: Arc<maybe_add_send_sync!(dyn IDynCommonModuleInit + 'static)>,
691    ) -> Self {
692        Self { inner }
693    }
694}
695
696/// Logic and constant common between server side and client side modules
697#[apply(async_trait_maybe_send!)]
698pub trait CommonModuleInit: Debug + Sized {
699    const CONSENSUS_VERSION: ModuleConsensusVersion;
700    const KIND: ModuleKind;
701
702    type ClientConfig: ClientConfig;
703
704    fn decoder() -> Decoder;
705}
706
707/// Module associated types required by both client and server
708pub trait ModuleCommon {
709    type ClientConfig: ClientConfig;
710    type Input: Input;
711    type Output: Output;
712    type OutputOutcome: OutputOutcome;
713    type ConsensusItem: ModuleConsensusItem;
714    type InputError: InputError;
715    type OutputError: OutputError;
716
717    fn decoder_builder() -> DecoderBuilder {
718        let mut decoder_builder = Decoder::builder();
719        decoder_builder.with_decodable_type::<Self::ClientConfig>();
720        decoder_builder.with_decodable_type::<Self::Input>();
721        decoder_builder.with_decodable_type::<Self::Output>();
722        decoder_builder.with_decodable_type::<Self::OutputOutcome>();
723        decoder_builder.with_decodable_type::<Self::ConsensusItem>();
724        decoder_builder.with_decodable_type::<Self::InputError>();
725        decoder_builder.with_decodable_type::<Self::OutputError>();
726
727        decoder_builder
728    }
729
730    fn decoder() -> Decoder {
731        Self::decoder_builder().build()
732    }
733}
734
735/// Creates a struct that can be used to make our module-decodable structs
736/// interact with `serde`-based APIs (AlephBFT, jsonrpsee). It creates a wrapper
737/// that holds the data as serialized
738// bytes internally.
739#[derive(Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
740pub struct SerdeModuleEncoding<T: Encodable + Decodable>(
741    #[serde(with = "::fedimint_core::encoding::as_hex")] Vec<u8>,
742    #[serde(skip)] PhantomData<T>,
743);
744
745/// Same as [`SerdeModuleEncoding`] but uses base64 instead of hex encoding.
746#[derive(Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
747pub struct SerdeModuleEncodingBase64<T: Encodable + Decodable>(
748    #[serde(with = "::fedimint_core::encoding::as_base64")] Vec<u8>,
749    #[serde(skip)] PhantomData<T>,
750);
751
752impl<T> fmt::Debug for SerdeModuleEncoding<T>
753where
754    T: Encodable + Decodable,
755{
756    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
757        f.write_str("SerdeModuleEncoding(")?;
758        fmt::Debug::fmt(&AbbreviateHexBytes(&self.0), f)?;
759        f.write_str(")")?;
760        Ok(())
761    }
762}
763
764impl<T: Encodable + Decodable> From<&T> for SerdeModuleEncoding<T> {
765    fn from(value: &T) -> Self {
766        let mut bytes = vec![];
767        fedimint_core::encoding::Encodable::consensus_encode(value, &mut bytes)
768            .expect("Writing to buffer can never fail");
769        Self(bytes, PhantomData)
770    }
771}
772
773impl<T: Encodable + Decodable + 'static> SerdeModuleEncoding<T> {
774    pub fn try_into_inner(&self, modules: &ModuleDecoderRegistry) -> Result<T, DecodeError> {
775        Decodable::consensus_decode_whole(&self.0, modules)
776    }
777
778    /// In cases where we know exactly which module kind we expect but don't
779    /// have access to all decoders this function can be used instead.
780    ///
781    /// Note that it just assumes the decoded module instance id to be valid
782    /// since it cannot validate against the decoder registry. The lack of
783    /// access to a decoder registry also makes decoding structs impossible that
784    /// themselves contain module dyn-types (e.g. a module output containing a
785    /// fedimint transaction).
786    pub fn try_into_inner_known_module_kind(&self, decoder: &Decoder) -> Result<T, DecodeError> {
787        let mut reader = std::io::Cursor::new(&self.0);
788        let module_instance = ModuleInstanceId::consensus_decode_partial(
789            &mut reader,
790            &ModuleDecoderRegistry::default(),
791        )?;
792
793        let total_len =
794            u64::consensus_decode_partial(&mut reader, &ModuleDecoderRegistry::default())?;
795
796        // No recursive module decoding is supported since we give an empty decoder
797        // registry to the decode function
798        decoder.decode_complete(
799            &mut reader,
800            total_len,
801            module_instance,
802            &ModuleRegistry::default(),
803        )
804    }
805}
806
807impl<T: Encodable + Decodable> Encodable for SerdeModuleEncoding<T> {
808    fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
809        self.0.consensus_encode(writer)
810    }
811}
812
813impl<T: Encodable + Decodable> Decodable for SerdeModuleEncoding<T> {
814    fn consensus_decode_partial_from_finite_reader<R: std::io::Read>(
815        reader: &mut R,
816        modules: &ModuleDecoderRegistry,
817    ) -> Result<Self, DecodeError> {
818        Ok(Self(
819            Vec::<u8>::consensus_decode_partial_from_finite_reader(reader, modules)?,
820            PhantomData,
821        ))
822    }
823}
824
825impl<T> fmt::Debug for SerdeModuleEncodingBase64<T>
826where
827    T: Encodable + Decodable,
828{
829    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
830        f.write_str("SerdeModuleEncoding2(")?;
831        fmt::Debug::fmt(&AbbreviateHexBytes(&self.0), f)?;
832        f.write_str(")")?;
833        Ok(())
834    }
835}
836
837impl<T: Encodable + Decodable> From<&T> for SerdeModuleEncodingBase64<T> {
838    fn from(value: &T) -> Self {
839        let mut bytes = vec![];
840        fedimint_core::encoding::Encodable::consensus_encode(value, &mut bytes)
841            .expect("Writing to buffer can never fail");
842        Self(bytes, PhantomData)
843    }
844}
845
846impl<T: Encodable + Decodable + 'static> SerdeModuleEncodingBase64<T> {
847    pub fn try_into_inner(&self, modules: &ModuleDecoderRegistry) -> Result<T, DecodeError> {
848        Decodable::consensus_decode_whole(&self.0, modules)
849    }
850
851    /// In cases where we know exactly which module kind we expect but don't
852    /// have access to all decoders this function can be used instead.
853    ///
854    /// Note that it just assumes the decoded module instance id to be valid
855    /// since it cannot validate against the decoder registry. The lack of
856    /// access to a decoder registry also makes decoding structs impossible that
857    /// themselves contain module dyn-types (e.g. a module output containing a
858    /// fedimint transaction).
859    pub fn try_into_inner_known_module_kind(&self, decoder: &Decoder) -> Result<T, DecodeError> {
860        let mut reader = std::io::Cursor::new(&self.0);
861        let module_instance = ModuleInstanceId::consensus_decode_partial(
862            &mut reader,
863            &ModuleDecoderRegistry::default(),
864        )?;
865
866        let total_len =
867            u64::consensus_decode_partial(&mut reader, &ModuleDecoderRegistry::default())?;
868
869        // No recursive module decoding is supported since we give an empty decoder
870        // registry to the decode function
871        decoder.decode_complete(
872            &mut reader,
873            total_len,
874            module_instance,
875            &ModuleRegistry::default(),
876        )
877    }
878}