1use core::fmt;
8use std::any::{Any, TypeId};
9use std::borrow::Cow;
10use std::collections::BTreeMap;
11use std::fmt::{Debug, Display, Formatter};
12use std::io::Read;
13use std::str::FromStr;
14use std::sync::Arc;
15
16use bitcoin::hashes::{Hash, sha256};
17use fedimint_core::encoding::{Decodable, DecodeError, DynEncodable, Encodable};
18use fedimint_core::module::registry::ModuleDecoderRegistry;
19use rand::RngCore;
20use serde::{Deserialize, Deserializer, Serialize};
21
22use crate::module::registry::ModuleRegistry;
23use crate::{
24 erased_eq_no_instance_id, module_plugin_dyn_newtype_clone_passthrough,
25 module_plugin_dyn_newtype_define, module_plugin_dyn_newtype_display_passthrough,
26 module_plugin_dyn_newtype_encode_decode, module_plugin_dyn_newtype_eq_passthrough,
27 module_plugin_static_trait_define, module_plugin_static_trait_define_config,
28};
29
30pub mod backup;
31
32#[derive(Clone, Copy, PartialEq, Eq, Hash, Encodable, Decodable, PartialOrd, Ord)]
56pub struct OperationId(pub [u8; 32]);
57
58pub struct OperationIdFullFmt<'a>(&'a OperationId);
59pub struct OperationIdShortFmt<'a>(&'a OperationId);
60
61impl OperationId {
62 pub fn new_random() -> Self {
64 let mut rng = rand::thread_rng();
65 let mut bytes = [0u8; 32];
66 rng.fill_bytes(&mut bytes);
67 Self(bytes)
68 }
69
70 pub fn from_encodable<E: Encodable>(encodable: &E) -> Self {
71 Self(encodable.consensus_hash::<sha256::Hash>().to_byte_array())
72 }
73
74 pub fn fmt_short(&'_ self) -> OperationIdShortFmt<'_> {
75 OperationIdShortFmt(self)
76 }
77 pub fn fmt_full(&'_ self) -> OperationIdFullFmt<'_> {
78 OperationIdFullFmt(self)
79 }
80}
81
82impl Display for OperationIdShortFmt<'_> {
83 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
84 fedimint_core::format_hex(&self.0.0[0..4], f)?;
85 f.write_str("_")?;
86 fedimint_core::format_hex(&self.0.0[28..], f)?;
87 Ok(())
88 }
89}
90
91impl Display for OperationIdFullFmt<'_> {
92 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
93 fedimint_core::format_hex(&self.0.0, f)
94 }
95}
96
97impl Debug for OperationId {
98 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
99 write!(f, "OperationId({})", self.fmt_short())
100 }
101}
102
103impl FromStr for OperationId {
104 type Err = hex::FromHexError;
105
106 fn from_str(s: &str) -> Result<Self, Self::Err> {
107 let bytes: [u8; 32] = hex::FromHex::from_hex(s)?;
108 Ok(Self(bytes))
109 }
110}
111
112impl Serialize for OperationId {
113 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
114 if serializer.is_human_readable() {
115 serializer.serialize_str(&self.fmt_full().to_string())
116 } else {
117 serializer.serialize_bytes(&self.0)
118 }
119 }
120}
121
122impl<'de> Deserialize<'de> for OperationId {
123 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
124 where
125 D: Deserializer<'de>,
126 {
127 if deserializer.is_human_readable() {
128 let s = String::deserialize(deserializer)?;
129 let operation_id = Self::from_str(&s)
130 .map_err(|e| serde::de::Error::custom(format!("invalid operation id: {e}")))?;
131 Ok(operation_id)
132 } else {
133 let bytes: [u8; 32] = <[u8; 32]>::deserialize(deserializer)?;
134 Ok(Self(bytes))
135 }
136 }
137}
138
139#[derive(
158 Debug,
159 Clone,
160 Copy,
161 PartialEq,
162 Eq,
163 Hash,
164 PartialOrd,
165 Ord,
166 Serialize,
167 Deserialize,
168 Encodable,
169 Decodable,
170 strum_macros::Display,
171 strum_macros::EnumString,
172)]
173#[serde(rename_all = "lowercase")]
174#[strum(serialize_all = "lowercase", ascii_case_insensitive)]
175#[repr(u8)]
176pub enum Account {
177 Primary = 0,
178 Secondary = 1,
179 Tertiary = 2,
180 Quaternary = 3,
181 Quinary = 4,
182}
183
184impl Account {
185 pub const ALL: [Self; 5] = [
192 Self::Primary,
193 Self::Secondary,
194 Self::Tertiary,
195 Self::Quaternary,
196 Self::Quinary,
197 ];
198
199 pub fn primary() -> Self {
203 Self::Primary
204 }
205
206 pub fn index(self) -> u8 {
208 self as u8
209 }
210}
211
212pub type ModuleInstanceId = u16;
226
227pub const MODULE_INSTANCE_ID_GLOBAL: u16 = u16::MAX;
229
230#[derive(PartialEq, Eq, Clone, PartialOrd, Ord, Serialize, Deserialize, Encodable, Decodable)]
236pub struct ModuleKind(Cow<'static, str>);
237
238impl ModuleKind {
239 pub fn clone_from_str(s: &str) -> Self {
240 Self(Cow::from(s.to_owned()))
241 }
242
243 pub const fn from_static_str(s: &'static str) -> Self {
244 Self(Cow::Borrowed(s))
245 }
246
247 pub fn as_str(&self) -> &str {
248 &self.0
249 }
250}
251
252impl From<String> for ModuleKind {
253 fn from(value: String) -> Self {
254 Self(Cow::Owned(value))
255 }
256}
257
258impl fmt::Display for ModuleKind {
259 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
260 std::fmt::Display::fmt(&self.0, f)
261 }
262}
263
264impl fmt::Debug for ModuleKind {
265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266 std::fmt::Display::fmt(&self.0, f)
267 }
268}
269
270impl From<&'static str> for ModuleKind {
271 fn from(val: &'static str) -> Self {
272 Self::from_static_str(val)
273 }
274}
275
276#[derive(Debug, Hash, PartialEq, Eq, Clone)]
281pub struct DynUnknown(pub Vec<u8>);
282
283impl fmt::Display for DynUnknown {
284 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
285 f.write_str(&self.0.consensus_encode_to_hex())
286 }
287}
288
289impl Encodable for DynUnknown {
296 fn consensus_encode<W: std::io::Write>(&self, w: &mut W) -> Result<(), std::io::Error> {
297 w.write_all(&self.0[..])?;
298 Ok(())
299 }
300}
301
302pub trait IntoDynInstance {
304 type DynType: 'static;
306
307 fn into_dyn(self, instance_id: ModuleInstanceId) -> Self::DynType;
309}
310
311type DecodeFn = Box<
312 dyn for<'a> Fn(
313 Box<dyn Read + 'a>,
314 ModuleInstanceId,
315 &ModuleDecoderRegistry,
316 ) -> Result<Box<dyn Any>, DecodeError>
317 + Send
318 + Sync,
319>;
320
321#[derive(Default)]
322pub struct DecoderBuilder {
323 decode_fns: BTreeMap<TypeId, DecodeFn>,
324 transparent: bool,
325}
326
327impl DecoderBuilder {
328 pub fn build(self) -> Decoder {
329 Decoder {
330 decode_fns: Arc::new(self.decode_fns),
331 }
332 }
333
334 pub fn with_decodable_type<Type>(&mut self)
346 where
347 Type: IntoDynInstance + Decodable,
348 {
349 let is_transparent_decoder = self.transparent;
350 let decode_fn: DecodeFn = Box::new(
353 move |mut reader, instance, decoders: &ModuleDecoderRegistry| {
354 let decoders = if is_transparent_decoder {
358 decoders
359 } else {
360 &ModuleRegistry::default()
361 };
362 let typed_val =
363 Type::consensus_decode_partial(&mut reader, decoders).map_err(|err| {
364 err.context(format!("while decoding Dyn type module_id={instance}"))
365 })?;
366 let dyn_val = typed_val.into_dyn(instance);
367 let any_val: Box<dyn Any> = Box::new(dyn_val);
368 Ok(any_val)
369 },
370 );
371 if self
372 .decode_fns
373 .insert(TypeId::of::<Type::DynType>(), decode_fn)
374 .is_some()
375 {
376 panic!("Tried to add multiple decoders for the same DynType");
377 }
378 }
379}
380
381#[derive(Clone, Default)]
383pub struct Decoder {
384 decode_fns: Arc<BTreeMap<TypeId, DecodeFn>>,
385}
386
387impl Decoder {
388 pub fn builder() -> DecoderBuilder {
391 DecoderBuilder::default()
392 }
393
394 #[doc(hidden)]
396 pub fn builder_system() -> DecoderBuilder {
397 DecoderBuilder {
398 transparent: true,
399 ..DecoderBuilder::default()
400 }
401 }
402
403 pub fn decode_complete<DynType: Any>(
408 &self,
409 reader: &mut dyn Read,
410 total_len: u64,
411 module_id: ModuleInstanceId,
412 decoders: &ModuleDecoderRegistry,
413 ) -> Result<DynType, DecodeError> {
414 let mut reader = reader.take(total_len);
415
416 let val = self.decode_partial(&mut reader, module_id, decoders)?;
417 let left = reader.limit();
418
419 if left != 0 {
420 return Err(fedimint_core::encoding::DecodeError::custom(format!(
421 "Dyn type did not consume all bytes during decoding; module_id={module_id}; \
422 expected={total_len}; left={left}; type={}",
423 std::any::type_name::<DynType>(),
424 )));
425 }
426
427 Ok(val)
428 }
429
430 pub fn decode_partial<DynType: Any>(
433 &self,
434 reader: &mut dyn Read,
435 module_id: ModuleInstanceId,
436 decoders: &ModuleDecoderRegistry,
437 ) -> Result<DynType, DecodeError> {
438 let Some(decode_fn) = self.decode_fns.get(&TypeId::of::<DynType>()) else {
439 panic!(
440 "Types being decoded must be registered: Type unknown to decoder: {}, \
441 (registered decoders={})",
442 std::any::type_name::<DynType>(),
443 self.decode_fns.len()
444 );
445 };
446 Ok(*decode_fn(Box::new(reader), module_id, decoders)?
447 .downcast::<DynType>()
448 .expect("Decode fn returned wrong type, can't happen due to with_decodable_type"))
449 }
450}
451
452impl Debug for Decoder {
453 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
454 write!(f, "Decoder(registered_types = {})", self.decode_fns.len())
455 }
456}
457
458pub trait IClientConfig: Debug + Display + DynEncodable {
459 fn as_any(&self) -> &(dyn Any + Send + Sync);
460 fn module_kind(&self) -> Option<ModuleKind>;
461 fn clone(&self, instance_id: ModuleInstanceId) -> DynClientConfig;
462 fn dyn_hash(&self) -> u64;
463 fn erased_eq_no_instance_id(&self, other: &DynClientConfig) -> bool;
464 fn to_json(&self) -> Option<serde_json::Value>;
465}
466
467module_plugin_static_trait_define_config! {
468 DynClientConfig, ClientConfig, IClientConfig,
469 { },
470 {
471 erased_eq_no_instance_id!(DynClientConfig);
472
473 fn to_json(&self) -> Option<serde_json::Value> {
474 Some(serde_json::to_value(self.to_owned()).expect("serialization can't fail"))
475 }
476 },
477 {
478 erased_eq_no_instance_id!(DynClientConfig);
479
480 fn to_json(&self) -> Option<serde_json::Value> {
481 None
482 }
483 }
484}
485
486module_plugin_dyn_newtype_define! {
487 pub DynClientConfig(Box<IClientConfig>)
489}
490module_plugin_dyn_newtype_encode_decode!(DynClientConfig);
491
492module_plugin_dyn_newtype_clone_passthrough!(DynClientConfig);
493
494module_plugin_dyn_newtype_eq_passthrough!(DynClientConfig);
495
496module_plugin_dyn_newtype_display_passthrough!(DynClientConfig);
497
498pub trait IInput: Debug + Display + DynEncodable {
503 fn as_any(&self) -> &(dyn Any + Send + Sync);
504 fn module_kind(&self) -> Option<ModuleKind>;
505 fn clone(&self, instance_id: ModuleInstanceId) -> DynInput;
506 fn dyn_hash(&self) -> u64;
507 fn erased_eq_no_instance_id(&self, other: &DynInput) -> bool;
508}
509
510module_plugin_static_trait_define! {
511 DynInput, Input, IInput,
512 { },
513 {
514 erased_eq_no_instance_id!(DynInput);
515 }
516}
517
518module_plugin_dyn_newtype_define! {
519 pub DynInput(Box<IInput>)
521}
522module_plugin_dyn_newtype_encode_decode!(DynInput);
523
524module_plugin_dyn_newtype_clone_passthrough!(DynInput);
525
526module_plugin_dyn_newtype_eq_passthrough!(DynInput);
527
528module_plugin_dyn_newtype_display_passthrough!(DynInput);
529
530pub trait IOutput: Debug + Display + DynEncodable {
535 fn as_any(&self) -> &(dyn Any + Send + Sync);
536 fn module_kind(&self) -> Option<ModuleKind>;
537 fn clone(&self, instance_id: ModuleInstanceId) -> DynOutput;
538 fn dyn_hash(&self) -> u64;
539 fn erased_eq_no_instance_id(&self, other: &DynOutput) -> bool;
540}
541
542module_plugin_dyn_newtype_define! {
543 pub DynOutput(Box<IOutput>)
545}
546module_plugin_static_trait_define! {
547 DynOutput, Output, IOutput,
548 { },
549 {
550 erased_eq_no_instance_id!(DynOutput);
551 }
552}
553module_plugin_dyn_newtype_encode_decode!(DynOutput);
554
555module_plugin_dyn_newtype_clone_passthrough!(DynOutput);
556
557module_plugin_dyn_newtype_eq_passthrough!(DynOutput);
558
559module_plugin_dyn_newtype_display_passthrough!(DynOutput);
560
561pub enum FinalizationError {
562 SomethingWentWrong,
563}
564
565pub trait IOutputOutcome: Debug + Display + DynEncodable {
566 fn as_any(&self) -> &(dyn Any + Send + Sync);
567 fn module_kind(&self) -> Option<ModuleKind>;
568 fn clone(&self, module_instance_id: ModuleInstanceId) -> DynOutputOutcome;
569 fn dyn_hash(&self) -> u64;
570 fn erased_eq_no_instance_id(&self, other: &DynOutputOutcome) -> bool;
571}
572
573module_plugin_dyn_newtype_define! {
574 pub DynOutputOutcome(Box<IOutputOutcome>)
576}
577module_plugin_static_trait_define! {
578 DynOutputOutcome, OutputOutcome, IOutputOutcome,
579 { },
580 {
581 erased_eq_no_instance_id!(DynOutputOutcome);
582 }
583}
584module_plugin_dyn_newtype_encode_decode!(DynOutputOutcome);
585module_plugin_dyn_newtype_clone_passthrough!(DynOutputOutcome);
586module_plugin_dyn_newtype_eq_passthrough!(DynOutputOutcome);
587module_plugin_dyn_newtype_display_passthrough!(DynOutputOutcome);
588
589pub trait IModuleConsensusItem: Debug + Display + DynEncodable {
590 fn as_any(&self) -> &(dyn Any + Send + Sync);
591 fn module_kind(&self) -> Option<ModuleKind>;
592 fn clone(&self, module_instance_id: ModuleInstanceId) -> DynModuleConsensusItem;
593 fn dyn_hash(&self) -> u64;
594
595 fn erased_eq_no_instance_id(&self, other: &DynModuleConsensusItem) -> bool;
596}
597
598module_plugin_dyn_newtype_define! {
599 pub DynModuleConsensusItem(Box<IModuleConsensusItem>)
601}
602module_plugin_static_trait_define! {
603 DynModuleConsensusItem, ModuleConsensusItem, IModuleConsensusItem,
604 { },
605 {
606 erased_eq_no_instance_id!(DynModuleConsensusItem);
607 }
608}
609module_plugin_dyn_newtype_encode_decode!(DynModuleConsensusItem);
610
611module_plugin_dyn_newtype_clone_passthrough!(DynModuleConsensusItem);
612
613module_plugin_dyn_newtype_eq_passthrough!(DynModuleConsensusItem);
614
615module_plugin_dyn_newtype_display_passthrough!(DynModuleConsensusItem);
616
617pub trait IOutputError: Debug + Display + DynEncodable {
618 fn as_any(&self) -> &(dyn Any + Send + Sync);
619 fn module_kind(&self) -> Option<ModuleKind>;
620 fn clone(&self, module_instance_id: ModuleInstanceId) -> DynOutputError;
621 fn dyn_hash(&self) -> u64;
622
623 fn erased_eq_no_instance_id(&self, other: &DynOutputError) -> bool;
624}
625
626module_plugin_dyn_newtype_define! {
627 pub DynOutputError(Box<IOutputError>)
628}
629module_plugin_static_trait_define! {
630 DynOutputError, OutputError, IOutputError,
631 { },
632 {
633 erased_eq_no_instance_id!(DynOutputError);
634 }
635}
636module_plugin_dyn_newtype_encode_decode!(DynOutputError);
637
638module_plugin_dyn_newtype_clone_passthrough!(DynOutputError);
639
640module_plugin_dyn_newtype_eq_passthrough!(DynOutputError);
641
642module_plugin_dyn_newtype_display_passthrough!(DynOutputError);
643
644pub trait IInputError: Debug + Display + DynEncodable {
645 fn as_any(&self) -> &(dyn Any + Send + Sync);
646 fn module_kind(&self) -> Option<ModuleKind>;
647 fn clone(&self, module_instance_id: ModuleInstanceId) -> DynInputError;
648 fn dyn_hash(&self) -> u64;
649
650 fn erased_eq_no_instance_id(&self, other: &DynInputError) -> bool;
651}
652
653module_plugin_dyn_newtype_define! {
654 pub DynInputError(Box<IInputError>)
655}
656module_plugin_static_trait_define! {
657 DynInputError, InputError, IInputError,
658 { },
659 {
660 erased_eq_no_instance_id!(DynInputError);
661 }
662}
663module_plugin_dyn_newtype_encode_decode!(DynInputError);
664
665module_plugin_dyn_newtype_clone_passthrough!(DynInputError);
666
667module_plugin_dyn_newtype_eq_passthrough!(DynInputError);
668
669module_plugin_dyn_newtype_display_passthrough!(DynInputError);