1pub 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
38mod 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#[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
79#[cfg(feature = "uniffi")]
80uniffi::custom_newtype!(AmountUnit, u64);
81
82impl AmountUnit {
83 pub const BITCOIN: Self = Self(0);
87
88 pub fn is_bitcoin(self) -> bool {
89 self == Self::BITCOIN
90 }
91
92 pub fn new_custom(unit: u64) -> Self {
93 Self(unit)
94 }
95
96 pub const fn bitcoin() -> Self {
97 Self::BITCOIN
98 }
99}
100
101#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
102pub struct AmountWithUnit {
103 amounts: Amount,
104 unit: AmountUnit,
105}
106
107#[derive(Debug, Clone, Eq, PartialEq, Hash, Encodable, Decodable)]
114pub struct Amounts(BTreeMap<AmountUnit, Amount>);
115
116impl ops::Deref for Amounts {
119 type Target = BTreeMap<AmountUnit, Amount>;
120
121 fn deref(&self) -> &Self::Target {
122 &self.0
123 }
124}
125
126impl Amounts {
127 pub const ZERO: Self = Self(BTreeMap::new());
128
129 pub fn new_bitcoin(amount: Amount) -> Self {
130 if amount == Amount::ZERO {
131 Self(BTreeMap::from([]))
132 } else {
133 Self(BTreeMap::from([(AmountUnit::BITCOIN, amount)]))
134 }
135 }
136
137 pub fn new_bitcoin_msats(msats: u64) -> Self {
138 Self::new_bitcoin(Amount::from_msats(msats))
139 }
140
141 pub fn new_custom(unit: AmountUnit, amount: Amount) -> Self {
142 if amount == Amount::ZERO {
143 Self(BTreeMap::from([]))
144 } else {
145 Self(BTreeMap::from([(unit, amount)]))
146 }
147 }
148
149 pub fn checked_add(mut self, rhs: &Self) -> Option<Self> {
150 self.checked_add_mut(rhs)?;
151
152 Some(self)
153 }
154
155 pub fn checked_add_mut(&mut self, rhs: &Self) -> Option<&mut Self> {
156 for (unit, amount) in &rhs.0 {
157 debug_assert!(
158 *amount != Amount::ZERO,
159 "`Amounts` must not add (/remove) zero-amount entries"
160 );
161 let prev = self.0.entry(*unit).or_default();
162
163 *prev = prev.checked_add(*amount)?;
164 }
165
166 Some(self)
167 }
168
169 pub fn checked_add_bitcoin(self, amount: Amount) -> Option<Self> {
170 self.checked_add_unit(amount, AmountUnit::BITCOIN)
171 }
172
173 pub fn checked_add_unit(mut self, amount: Amount, unit: AmountUnit) -> Option<Self> {
174 if amount == Amount::ZERO {
175 return Some(self);
176 }
177
178 let prev = self.0.entry(unit).or_default();
179
180 *prev = prev.checked_add(amount)?;
181
182 Some(self)
183 }
184
185 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
186 let mut result = self.clone();
187
188 for (unit, amount) in &other.0 {
189 if *amount == Amount::ZERO {
190 continue;
191 }
192
193 let prev = result.0.entry(*unit).or_default();
194
195 *prev = prev.checked_sub(*amount)?;
196
197 if *prev == Amount::ZERO {
198 result.0.remove(unit);
199 }
200 }
201
202 Some(result)
203 }
204
205 pub fn remove(&mut self, unit: &AmountUnit) -> Option<Amount> {
206 self.0.remove(unit)
207 }
208
209 pub fn get_bitcoin(&self) -> Amount {
210 self.get(&AmountUnit::BITCOIN).copied().unwrap_or_default()
211 }
212
213 pub fn expect_only_bitcoin(&self) -> Amount {
214 #[allow(clippy::option_if_let_else)] match self.get(&AmountUnit::BITCOIN) {
216 Some(amount) => {
217 assert!(
218 self.len() == 1,
219 "Amounts expected to contain only bitcoin and no other currencies"
220 );
221 *amount
222 }
223 None => Amount::ZERO,
224 }
225 }
226
227 pub fn iter_units(&self) -> impl Iterator<Item = AmountUnit> {
228 self.0.keys().copied()
229 }
230
231 pub fn units(&self) -> BTreeSet<AmountUnit> {
232 self.0.keys().copied().collect()
233 }
234}
235
236impl IntoIterator for Amounts {
237 type Item = (AmountUnit, Amount);
238
239 type IntoIter = <BTreeMap<AmountUnit, Amount> as IntoIterator>::IntoIter;
240
241 fn into_iter(self) -> Self::IntoIter {
242 self.0.into_iter()
243 }
244}
245
246#[derive(Debug, Clone, Eq, PartialEq, Hash)]
252pub struct TransactionItemAmounts {
253 pub amounts: Amounts,
254 pub fees: Amounts,
255}
256
257impl TransactionItemAmounts {
258 pub fn checked_add(self, rhs: &Self) -> Option<Self> {
259 Some(Self {
260 amounts: self.amounts.checked_add(&rhs.amounts)?,
261 fees: self.fees.checked_add(&rhs.fees)?,
262 })
263 }
264}
265
266impl TransactionItemAmounts {
267 pub const ZERO: Self = Self {
268 amounts: Amounts::ZERO,
269 fees: Amounts::ZERO,
270 };
271}
272
273#[derive(Debug, Serialize, Deserialize, Clone)]
275pub struct ApiRequest<T> {
276 pub auth: Option<ApiAuth>,
278 pub params: T,
280}
281
282pub type ApiRequestErased = ApiRequest<JsonValue>;
283
284impl Default for ApiRequestErased {
285 fn default() -> Self {
286 Self {
287 auth: None,
288 params: JsonValue::Null,
289 }
290 }
291}
292
293impl ApiRequestErased {
294 pub fn new<T: Serialize>(params: T) -> Self {
295 Self {
296 auth: None,
297 params: serde_json::to_value(params)
298 .expect("parameter serialization error - this should not happen"),
299 }
300 }
301
302 pub fn to_json(&self) -> JsonValue {
303 serde_json::to_value(self).expect("parameter serialization error - this should not happen")
304 }
305
306 pub fn with_auth(self, auth: ApiAuth) -> Self {
307 Self {
308 auth: Some(auth),
309 params: self.params,
310 }
311 }
312
313 pub fn to_typed<T: serde::de::DeserializeOwned>(
314 self,
315 ) -> Result<ApiRequest<T>, serde_json::Error> {
316 Ok(ApiRequest {
317 auth: self.auth,
318 params: serde_json::from_value::<T>(self.params)?,
319 })
320 }
321}
322
323#[derive(Debug, Clone, Serialize, Deserialize)]
324pub enum ApiMethod {
325 Core(String),
326 Module(ModuleInstanceId, String),
327}
328
329impl fmt::Display for ApiMethod {
330 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331 match self {
332 Self::Core(s) => f.write_str(s),
333 Self::Module(module_id, s) => f.write_fmt(format_args!("{module_id}-{s}")),
334 }
335 }
336}
337
338#[derive(Debug, Clone, Serialize, Deserialize)]
339pub struct IrohApiRequest {
340 pub method: ApiMethod,
341 pub request: ApiRequestErased,
342}
343
344#[derive(Debug, Clone, Serialize, Deserialize)]
345pub struct IrohGatewayRequest {
346 pub route: String,
348
349 pub params: Option<serde_json::Value>,
351
352 pub password: Option<String>,
354}
355
356#[derive(Debug, Clone, Serialize, Deserialize)]
357pub struct IrohGatewayResponse {
358 pub status: u16,
359 pub body: serde_json::Value,
360}
361
362pub const FEDIMINT_API_ALPN: &[u8] = b"FEDIMINT_API_ALPN";
363pub const FEDIMINT_GATEWAY_ALPN: &[u8] = b"FEDIMINT_GATEWAY_ALPN";
364
365#[derive(Clone, Serialize, Deserialize)]
370pub struct ApiAuth(String);
371
372impl ApiAuth {
373 pub fn new(s: String) -> Self {
374 Self(s)
375 }
376
377 pub fn as_str(&self) -> &str {
378 &self.0
379 }
380
381 pub fn verify(&self, password: &str) -> bool {
382 use subtle::ConstantTimeEq as _;
383 bool::from(self.0.as_bytes().ct_eq(password.as_bytes()))
384 }
385}
386
387impl Debug for ApiAuth {
388 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
389 write!(f, "ApiAuth(****)")
390 }
391}
392
393#[derive(Debug, Clone, Serialize, Deserialize)]
394pub struct ApiError {
395 pub code: i32,
396 pub message: String,
397}
398
399impl Error for ApiError {}
400
401impl fmt::Display for ApiError {
402 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
403 f.write_fmt(format_args!("{} {}", self.code, self.message))
404 }
405}
406
407pub type ApiResult<T> = Result<T, ApiError>;
408
409impl ApiError {
410 pub fn new(code: i32, message: String) -> Self {
411 Self { code, message }
412 }
413
414 pub fn not_found(message: String) -> Self {
415 Self::new(404, message)
416 }
417
418 pub fn bad_request(message: String) -> Self {
419 Self::new(400, message)
420 }
421
422 pub fn unauthorized() -> Self {
423 Self::new(401, "Invalid authorization".to_string())
424 }
425
426 pub fn server_error(message: String) -> Self {
427 Self::new(500, message)
428 }
429}
430
431impl From<DatabaseError> for ApiError {
432 fn from(err: DatabaseError) -> Self {
433 Self {
434 code: 500,
435 message: format!("API server error when writing to database: {err}"),
436 }
437 }
438}
439
440pub struct ApiEndpointContext {
442 db: Database,
443 has_auth: bool,
444 request_auth: Option<ApiAuth>,
445}
446
447impl ApiEndpointContext {
448 pub fn new(db: Database, has_auth: bool, request_auth: Option<ApiAuth>) -> Self {
450 Self {
451 db,
452 has_auth,
453 request_auth,
454 }
455 }
456
457 pub fn request_auth(&self) -> Option<ApiAuth> {
460 self.request_auth.clone()
461 }
462
463 pub fn has_auth(&self) -> bool {
466 self.has_auth
467 }
468
469 pub fn db(&self) -> Database {
470 self.db.clone()
471 }
472
473 pub fn wait_key_exists<K>(&self, key: K) -> impl Future<Output = K::Value> + use<K>
475 where
476 K: DatabaseKey + DatabaseRecord + DatabaseKeyWithNotify,
477 {
478 let db = self.db.clone();
479 async move { db.wait_key_exists(&key).await }
482 }
483
484 pub fn wait_value_matches<K>(
486 &self,
487 key: K,
488 matcher: impl Fn(&K::Value) -> bool + Copy,
489 ) -> impl Future<Output = K::Value>
490 where
491 K: DatabaseKey + DatabaseRecord + DatabaseKeyWithNotify,
492 {
493 let db = self.db.clone();
494 async move { db.wait_key_check(&key, |v| v.filter(matcher)).await.0 }
495 }
496}
497
498#[apply(async_trait_maybe_send!)]
499pub trait TypedApiEndpoint {
500 type State: Sync;
501
502 const PATH: &'static str;
504 const VERSION: ApiVersion;
505 type Param: serde::de::DeserializeOwned + Send;
506 type Response: serde::Serialize;
507
508 async fn handle<'state, 'context>(
509 state: &'state Self::State,
510 context: &'context mut ApiEndpointContext,
511 request: Self::Param,
512 ) -> Result<Self::Response, ApiError>;
513}
514
515pub use serde_json;
516
517#[macro_export]
533macro_rules! __api_endpoint {
534 (
535 $path:expr_2021,
536 $version_introduced:expr_2021,
538 async |$state:ident: &$state_ty:ty, $context:ident, $param:ident: $param_ty:ty| -> $resp_ty:ty $body:block
539 ) => {{
540 struct Endpoint;
541
542 #[$crate::apply($crate::async_trait_maybe_send!)]
543 impl $crate::module::TypedApiEndpoint for Endpoint {
544 #[allow(deprecated)]
545 const PATH: &'static str = $path;
546 const VERSION: $crate::module::ApiVersion = $version_introduced;
547 type State = $state_ty;
548 type Param = $param_ty;
549 type Response = $resp_ty;
550
551 async fn handle<'state, 'context>(
552 $state: &'state Self::State,
553 $context: &'context mut $crate::module::ApiEndpointContext,
554 $param: Self::Param,
555 ) -> ::std::result::Result<Self::Response, $crate::module::ApiError> {
556 $body
557 }
558 }
559
560 $crate::module::ApiEndpoint::from_typed::<Endpoint>()
561 }};
562}
563
564pub use __api_endpoint as api_endpoint;
565
566use self::registry::ModuleDecoderRegistry;
567
568type HandlerFnReturn<'a> =
569 Pin<Box<maybe_add_send!(dyn Future<Output = Result<serde_json::Value, ApiError>> + 'a)>>;
570type HandlerFn<M> = Box<
571 maybe_add_send_sync!(
572 dyn for<'a> Fn(&'a M, ApiEndpointContext, ApiRequestErased) -> HandlerFnReturn<'a>
573 ),
574>;
575
576pub struct ApiEndpoint<M> {
578 pub path: &'static str,
583 pub handler: HandlerFn<M>,
587 pub version: ApiVersion,
589}
590
591static REQ_ID: AtomicU64 = AtomicU64::new(0);
593
594impl ApiEndpoint<()> {
596 pub fn from_typed<E: TypedApiEndpoint>() -> ApiEndpoint<E::State>
597 where
598 <E as TypedApiEndpoint>::Response: MaybeSend,
599 E::Param: Debug,
600 E::Response: Debug,
601 {
602 async fn handle_request<'state, 'context, E>(
603 state: &'state E::State,
604 context: &'context mut ApiEndpointContext,
605 request: ApiRequest<E::Param>,
606 ) -> Result<E::Response, ApiError>
607 where
608 E: TypedApiEndpoint,
609 E::Param: Debug,
610 E::Response: Debug,
611 {
612 tracing::debug!(target: LOG_NET_API, path = E::PATH, ?request, "received api request");
613 let result = E::handle(state, context, request.params).await;
614 match &result {
615 Err(err) => {
616 tracing::warn!(target: LOG_NET_API, path = E::PATH, err = %err.fmt_compact(), "api request error");
617 }
618 _ => {
619 tracing::trace!(target: LOG_NET_API, path = E::PATH, "api request complete");
620 }
621 }
622 result
623 }
624
625 ApiEndpoint {
626 path: E::PATH,
627 version: E::VERSION,
628 handler: Box::new(|m, mut context, request| {
629 Box::pin(async move {
630 let request = request
631 .to_typed()
632 .map_err(|e| ApiError::bad_request(e.to_string()))?;
633
634 let span = tracing::info_span!(
635 target: LOG_NET_API,
636 "api_req",
637 id = REQ_ID.fetch_add(1, Ordering::SeqCst),
638 method = E::PATH,
639 );
640 let ret = handle_request::<E>(m, &mut context, request)
641 .instrument(span)
642 .await?;
643
644 Ok(serde_json::to_value(ret).expect("encoding error"))
645 })
646 }),
647 }
648 }
649}
650
651#[apply(async_trait_maybe_send!)]
658pub trait IDynCommonModuleInit: Debug {
659 fn decoder(&self) -> Decoder;
660
661 fn module_kind(&self) -> ModuleKind;
662
663 fn to_dyn_common(&self) -> DynCommonModuleInit;
664
665 async fn dump_database(
666 &self,
667 dbtx: &mut DatabaseTransaction<'_>,
668 prefix_names: Vec<String>,
669 ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_>;
670}
671
672pub trait ModuleInit: Debug + Clone + Send + Sync + 'static {
674 type Common: CommonModuleInit;
675
676 fn dump_database(
677 &self,
678 dbtx: &mut DatabaseTransaction<'_>,
679 prefix_names: Vec<String>,
680 ) -> maybe_add_send!(
681 impl Future<
682 Output = Box<
683 dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_,
684 >,
685 >
686 );
687}
688
689#[apply(async_trait_maybe_send!)]
690impl<T> IDynCommonModuleInit for T
691where
692 T: ModuleInit,
693{
694 fn decoder(&self) -> Decoder {
695 T::Common::decoder()
696 }
697
698 fn module_kind(&self) -> ModuleKind {
699 T::Common::KIND
700 }
701
702 fn to_dyn_common(&self) -> DynCommonModuleInit {
703 DynCommonModuleInit::from_inner(Arc::new(self.clone()))
704 }
705
706 async fn dump_database(
707 &self,
708 dbtx: &mut DatabaseTransaction<'_>,
709 prefix_names: Vec<String>,
710 ) -> Box<dyn Iterator<Item = (String, Box<dyn erased_serde::Serialize + Send>)> + '_> {
711 <Self as ModuleInit>::dump_database(self, dbtx, prefix_names).await
712 }
713}
714
715dyn_newtype_define!(
716 #[derive(Clone)]
717 pub DynCommonModuleInit(Arc<IDynCommonModuleInit>)
718);
719
720impl AsRef<maybe_add_send_sync!(dyn IDynCommonModuleInit + 'static)> for DynCommonModuleInit {
721 fn as_ref(&self) -> &(maybe_add_send_sync!(dyn IDynCommonModuleInit + 'static)) {
722 self.inner.as_ref()
723 }
724}
725
726impl DynCommonModuleInit {
727 pub fn from_inner(
728 inner: Arc<maybe_add_send_sync!(dyn IDynCommonModuleInit + 'static)>,
729 ) -> Self {
730 Self { inner }
731 }
732}
733
734#[apply(async_trait_maybe_send!)]
736pub trait CommonModuleInit: Debug + Sized {
737 const CONSENSUS_VERSION: ModuleConsensusVersion;
738 const KIND: ModuleKind;
739
740 type ClientConfig: ClientConfig;
741
742 fn decoder() -> Decoder;
743}
744
745pub trait ModuleCommon {
747 type ClientConfig: ClientConfig;
748 type Input: Input;
749 type Output: Output;
750 type OutputOutcome: OutputOutcome;
751 type ConsensusItem: ModuleConsensusItem;
752 type InputError: InputError;
753 type OutputError: OutputError;
754
755 fn decoder_builder() -> DecoderBuilder {
756 let mut decoder_builder = Decoder::builder();
757 decoder_builder.with_decodable_type::<Self::ClientConfig>();
758 decoder_builder.with_decodable_type::<Self::Input>();
759 decoder_builder.with_decodable_type::<Self::Output>();
760 decoder_builder.with_decodable_type::<Self::OutputOutcome>();
761 decoder_builder.with_decodable_type::<Self::ConsensusItem>();
762 decoder_builder.with_decodable_type::<Self::InputError>();
763 decoder_builder.with_decodable_type::<Self::OutputError>();
764
765 decoder_builder
766 }
767
768 fn decoder() -> Decoder {
769 Self::decoder_builder().build()
770 }
771}
772
773#[derive(Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
778pub struct SerdeModuleEncoding<T: Encodable + Decodable>(
779 #[serde(with = "::fedimint_core::encoding::as_hex")] Vec<u8>,
780 #[serde(skip)] PhantomData<T>,
781);
782
783#[derive(Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
785pub struct SerdeModuleEncodingBase64<T: Encodable + Decodable>(
786 #[serde(with = "::fedimint_core::encoding::as_base64")] Vec<u8>,
787 #[serde(skip)] PhantomData<T>,
788);
789
790impl<T> fmt::Debug for SerdeModuleEncoding<T>
791where
792 T: Encodable + Decodable,
793{
794 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
795 f.write_str("SerdeModuleEncoding(")?;
796 fmt::Debug::fmt(&AbbreviateHexBytes(&self.0), f)?;
797 f.write_str(")")?;
798 Ok(())
799 }
800}
801
802impl<T: Encodable + Decodable> From<&T> for SerdeModuleEncoding<T> {
803 fn from(value: &T) -> Self {
804 let mut bytes = vec![];
805 fedimint_core::encoding::Encodable::consensus_encode(value, &mut bytes)
806 .expect("Writing to buffer can never fail");
807 Self(bytes, PhantomData)
808 }
809}
810
811impl<T: Encodable + Decodable + 'static> SerdeModuleEncoding<T> {
812 pub fn try_into_inner(&self, modules: &ModuleDecoderRegistry) -> Result<T, DecodeError> {
813 Decodable::consensus_decode_whole(&self.0, modules)
814 }
815
816 pub fn try_into_inner_known_module_kind(&self, decoder: &Decoder) -> Result<T, DecodeError> {
825 let mut reader = std::io::Cursor::new(&self.0);
826 let module_instance = ModuleInstanceId::consensus_decode_partial(
827 &mut reader,
828 &ModuleDecoderRegistry::default(),
829 )?;
830
831 let total_len =
832 u64::consensus_decode_partial(&mut reader, &ModuleDecoderRegistry::default())?;
833
834 decoder.decode_complete(
837 &mut reader,
838 total_len,
839 module_instance,
840 &ModuleRegistry::default(),
841 )
842 }
843}
844
845impl<T: Encodable + Decodable> Encodable for SerdeModuleEncoding<T> {
846 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
847 self.0.consensus_encode(writer)
848 }
849}
850
851impl<T: Encodable + Decodable> Decodable for SerdeModuleEncoding<T> {
852 fn consensus_decode_partial_from_finite_reader<R: std::io::Read>(
853 reader: &mut R,
854 modules: &ModuleDecoderRegistry,
855 ) -> Result<Self, DecodeError> {
856 Ok(Self(
857 Vec::<u8>::consensus_decode_partial_from_finite_reader(reader, modules)?,
858 PhantomData,
859 ))
860 }
861}
862
863impl<T> fmt::Debug for SerdeModuleEncodingBase64<T>
864where
865 T: Encodable + Decodable,
866{
867 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
868 f.write_str("SerdeModuleEncoding2(")?;
869 fmt::Debug::fmt(&AbbreviateHexBytes(&self.0), f)?;
870 f.write_str(")")?;
871 Ok(())
872 }
873}
874
875impl<T: Encodable + Decodable> From<&T> for SerdeModuleEncodingBase64<T> {
876 fn from(value: &T) -> Self {
877 let mut bytes = vec![];
878 fedimint_core::encoding::Encodable::consensus_encode(value, &mut bytes)
879 .expect("Writing to buffer can never fail");
880 Self(bytes, PhantomData)
881 }
882}
883
884impl<T: Encodable + Decodable + 'static> SerdeModuleEncodingBase64<T> {
885 pub fn try_into_inner(&self, modules: &ModuleDecoderRegistry) -> Result<T, DecodeError> {
886 Decodable::consensus_decode_whole(&self.0, modules)
887 }
888
889 pub fn try_into_inner_known_module_kind(&self, decoder: &Decoder) -> Result<T, DecodeError> {
898 let mut reader = std::io::Cursor::new(&self.0);
899 let module_instance = ModuleInstanceId::consensus_decode_partial(
900 &mut reader,
901 &ModuleDecoderRegistry::default(),
902 )?;
903
904 let total_len =
905 u64::consensus_decode_partial(&mut reader, &ModuleDecoderRegistry::default())?;
906
907 decoder.decode_complete(
910 &mut reader,
911 total_len,
912 module_instance,
913 &ModuleRegistry::default(),
914 )
915 }
916}