1pub mod as_base64;
12pub mod as_hex;
13mod bls12_381;
14pub mod btc;
15mod collections;
16mod iroh;
17mod secp256k1;
18mod threshold_crypto;
19
20use std::borrow::Cow;
21use std::cmp;
22use std::fmt::{Debug, Formatter};
23use std::io::{self, Error, Read, Write};
24use std::time::{Duration, SystemTime, UNIX_EPOCH};
25
26use anyhow::Context;
27use bitcoin::hashes::sha256;
28pub use fedimint_derive::{Decodable, Encodable};
29use hex::{FromHex, ToHex};
30use lightning::util::ser::BigSize;
31use serde::{Deserialize, Serialize};
32use thiserror::Error;
33
34use crate::core::ModuleInstanceId;
35use crate::module::registry::ModuleDecoderRegistry;
36use crate::util::SafeUrl;
37
38pub struct CountWrite<W> {
44 inner: W,
45 count: u64,
46}
47
48impl<W> CountWrite<W> {
49 pub fn count(&self) -> u64 {
51 self.count
52 }
53}
54
55impl<W> From<W> for CountWrite<W> {
56 fn from(inner: W) -> Self {
57 Self { inner, count: 0 }
58 }
59}
60
61impl<W: Write> io::Write for CountWrite<W> {
62 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
63 let written = self.inner.write(buf)?;
64 self.count += written as u64;
65 Ok(written)
66 }
67
68 fn flush(&mut self) -> io::Result<()> {
69 self.inner.flush()
70 }
71}
72
73pub trait DynEncodable {
78 fn consensus_encode_dyn(&self, writer: &mut dyn std::io::Write) -> Result<(), std::io::Error>;
79}
80
81impl Encodable for dyn DynEncodable {
82 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
83 self.consensus_encode_dyn(writer)
84 }
85}
86
87impl<T> DynEncodable for T
88where
89 T: Encodable,
90{
91 fn consensus_encode_dyn(
92 &self,
93 mut writer: &mut dyn std::io::Write,
94 ) -> Result<(), std::io::Error> {
95 <Self as Encodable>::consensus_encode(self, &mut writer)
96 }
97}
98
99impl Encodable for Box<dyn DynEncodable> {
100 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
101 (**self).consensus_encode_dyn(writer)
102 }
103}
104
105impl<T> Encodable for &T
106where
107 T: Encodable,
108{
109 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
110 (**self).consensus_encode(writer)
111 }
112}
113
114pub trait Encodable {
116 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error>;
121
122 fn consensus_encode_to_vec(&self) -> Vec<u8> {
124 let mut bytes = vec![];
125 self.consensus_encode(&mut bytes)
126 .expect("encoding to bytes can't fail for io reasons");
127 bytes
128 }
129
130 fn consensus_encode_to_hex(&self) -> String {
132 self.consensus_encode_to_vec().encode_hex()
136 }
137
138 fn consensus_encode_to_len(&self) -> u64 {
140 let mut writer = CountWrite::from(io::sink());
141 self.consensus_encode(&mut writer)
142 .expect("encoding to bytes can't fail for io reasons");
143
144 writer.count()
145 }
146
147 fn consensus_hash<H>(&self) -> H
153 where
154 H: bitcoin::hashes::Hash,
155 H::Engine: std::io::Write,
156 {
157 let mut engine = H::engine();
158 self.consensus_encode(&mut engine)
159 .expect("writing to HashEngine cannot fail");
160 H::from_engine(engine)
161 }
162
163 fn consensus_hash_sha256(&self) -> sha256::Hash {
165 self.consensus_hash()
166 }
167}
168
169pub const MAX_DECODE_SIZE: usize = 16_000_000;
172
173pub trait Decodable: Sized {
175 #[inline]
212 fn consensus_decode_partial_from_finite_reader<R: std::io::Read>(
213 r: &mut R,
214 modules: &ModuleDecoderRegistry,
215 ) -> Result<Self, DecodeError> {
216 Self::consensus_decode_partial(r, modules)
221 }
222
223 #[inline]
224 fn consensus_decode_whole(
225 slice: &[u8],
226 modules: &ModuleDecoderRegistry,
227 ) -> Result<Self, DecodeError> {
228 let total_len = slice.len() as u64;
229
230 let r = &mut &slice[..];
231 let mut r = Read::take(r, total_len);
232
233 let res = Self::consensus_decode_partial_from_finite_reader(&mut r, modules)?;
238 let left = r.limit();
239
240 if left != 0 {
241 return Err(fedimint_core::encoding::DecodeError::new_custom(
242 anyhow::anyhow!(
243 "Type did not consume all bytes during decoding; expected={}; left={}; type={}",
244 total_len,
245 left,
246 std::any::type_name::<Self>(),
247 ),
248 ));
249 }
250 Ok(res)
251 }
252 #[inline]
262 fn consensus_decode_partial<R: std::io::Read>(
263 r: &mut R,
264 modules: &ModuleDecoderRegistry,
265 ) -> Result<Self, DecodeError> {
266 Self::consensus_decode_partial_from_finite_reader(
267 &mut r.take(MAX_DECODE_SIZE as u64),
268 modules,
269 )
270 }
271
272 fn consensus_decode_hex(
274 hex: &str,
275 modules: &ModuleDecoderRegistry,
276 ) -> Result<Self, DecodeError> {
277 let bytes = Vec::<u8>::from_hex(hex)
278 .map_err(anyhow::Error::from)
279 .map_err(DecodeError::new_custom)?;
280 Decodable::consensus_decode_whole(&bytes, modules)
281 }
282}
283
284impl Encodable for SafeUrl {
285 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), Error> {
286 self.to_string().consensus_encode(writer)
287 }
288}
289
290impl Decodable for SafeUrl {
291 fn consensus_decode_partial_from_finite_reader<D: std::io::Read>(
292 d: &mut D,
293 modules: &ModuleDecoderRegistry,
294 ) -> Result<Self, DecodeError> {
295 String::consensus_decode_partial_from_finite_reader(d, modules)?
296 .parse::<Self>()
297 .map_err(DecodeError::from_err)
298 }
299}
300
301#[derive(Debug, Error)]
302pub struct DecodeError(pub(crate) anyhow::Error);
303
304impl DecodeError {
305 pub fn new_custom(e: anyhow::Error) -> Self {
306 Self(e)
307 }
308}
309
310impl From<anyhow::Error> for DecodeError {
311 fn from(e: anyhow::Error) -> Self {
312 Self(e)
313 }
314}
315
316macro_rules! impl_encode_decode_num_as_plain {
317 ($num_type:ty) => {
318 impl Encodable for $num_type {
319 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), Error> {
320 let bytes = self.to_be_bytes();
321 writer.write_all(&bytes[..])?;
322 Ok(())
323 }
324 }
325
326 impl Decodable for $num_type {
327 fn consensus_decode_partial<D: std::io::Read>(
328 d: &mut D,
329 _modules: &ModuleDecoderRegistry,
330 ) -> Result<Self, crate::encoding::DecodeError> {
331 let mut bytes = [0u8; (<$num_type>::BITS / 8) as usize];
332 d.read_exact(&mut bytes).map_err(DecodeError::from_err)?;
333 Ok(<$num_type>::from_be_bytes(bytes))
334 }
335 }
336 };
337}
338
339macro_rules! impl_encode_decode_num_as_bigsize {
340 ($num_type:ty) => {
341 impl Encodable for $num_type {
342 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), Error> {
343 BigSize(u64::from(*self)).consensus_encode(writer)
344 }
345 }
346
347 impl Decodable for $num_type {
348 fn consensus_decode_partial<D: std::io::Read>(
349 d: &mut D,
350 _modules: &ModuleDecoderRegistry,
351 ) -> Result<Self, crate::encoding::DecodeError> {
352 let varint = BigSize::consensus_decode_partial(d, &Default::default())
353 .context(concat!("VarInt inside ", stringify!($num_type)))?;
354 <$num_type>::try_from(varint.0).map_err(crate::encoding::DecodeError::from_err)
355 }
356 }
357 };
358}
359
360impl_encode_decode_num_as_bigsize!(u64);
361impl_encode_decode_num_as_bigsize!(u32);
362impl_encode_decode_num_as_bigsize!(u16);
363impl_encode_decode_num_as_plain!(u8);
364
365macro_rules! impl_encode_decode_tuple {
366 ($($x:ident),*) => (
367 #[allow(non_snake_case)]
368 impl <$($x: Encodable),*> Encodable for ($($x),*) {
369 fn consensus_encode<W: std::io::Write>(&self, s: &mut W) -> Result<(), std::io::Error> {
370 let &($(ref $x),*) = self;
371 $($x.consensus_encode(s)?;)*
372 Ok(())
373 }
374 }
375
376 #[allow(non_snake_case)]
377 impl<$($x: Decodable),*> Decodable for ($($x),*) {
378 fn consensus_decode_partial<D: std::io::Read>(d: &mut D, modules: &ModuleDecoderRegistry) -> Result<Self, DecodeError> {
379 Ok(($({let $x = Decodable::consensus_decode_partial(d, modules)?; $x }),*))
380 }
381 }
382 );
383}
384
385impl_encode_decode_tuple!(T1, T2);
386impl_encode_decode_tuple!(T1, T2, T3);
387impl_encode_decode_tuple!(T1, T2, T3, T4);
388
389impl<T> Encodable for Option<T>
390where
391 T: Encodable,
392{
393 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
394 if let Some(inner) = self {
395 1u8.consensus_encode(writer)?;
396 inner.consensus_encode(writer)?;
397 } else {
398 0u8.consensus_encode(writer)?;
399 }
400 Ok(())
401 }
402}
403
404impl<T> Decodable for Option<T>
405where
406 T: Decodable,
407{
408 fn consensus_decode_partial_from_finite_reader<D: std::io::Read>(
409 d: &mut D,
410 modules: &ModuleDecoderRegistry,
411 ) -> Result<Self, DecodeError> {
412 let flag = u8::consensus_decode_partial_from_finite_reader(d, modules)?;
413 match flag {
414 0 => Ok(None),
415 1 => Ok(Some(T::consensus_decode_partial_from_finite_reader(
416 d, modules,
417 )?)),
418 _ => Err(DecodeError::from_str(
419 "Invalid flag for option enum, expected 0 or 1",
420 )),
421 }
422 }
423}
424
425impl<T, E> Encodable for Result<T, E>
426where
427 T: Encodable,
428 E: Encodable,
429{
430 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
431 match self {
432 Ok(value) => {
433 1u8.consensus_encode(writer)?;
434 value.consensus_encode(writer)?;
435 }
436 Err(error) => {
437 0u8.consensus_encode(writer)?;
438 error.consensus_encode(writer)?;
439 }
440 }
441
442 Ok(())
443 }
444}
445
446impl<T, E> Decodable for Result<T, E>
447where
448 T: Decodable,
449 E: Decodable,
450{
451 fn consensus_decode_partial_from_finite_reader<D: std::io::Read>(
452 d: &mut D,
453 modules: &ModuleDecoderRegistry,
454 ) -> Result<Self, DecodeError> {
455 let flag = u8::consensus_decode_partial_from_finite_reader(d, modules)?;
456 match flag {
457 0 => Ok(Err(E::consensus_decode_partial_from_finite_reader(
458 d, modules,
459 )?)),
460 1 => Ok(Ok(T::consensus_decode_partial_from_finite_reader(
461 d, modules,
462 )?)),
463 _ => Err(DecodeError::from_str(
464 "Invalid flag for option enum, expected 0 or 1",
465 )),
466 }
467 }
468}
469
470impl<T> Encodable for Box<T>
471where
472 T: Encodable,
473{
474 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), Error> {
475 self.as_ref().consensus_encode(writer)
476 }
477}
478
479impl<T> Decodable for Box<T>
480where
481 T: Decodable,
482{
483 fn consensus_decode_partial_from_finite_reader<D: std::io::Read>(
484 d: &mut D,
485 modules: &ModuleDecoderRegistry,
486 ) -> Result<Self, DecodeError> {
487 Ok(Self::new(T::consensus_decode_partial_from_finite_reader(
488 d, modules,
489 )?))
490 }
491}
492
493impl Encodable for () {
494 fn consensus_encode<W: std::io::Write>(&self, _writer: &mut W) -> Result<(), std::io::Error> {
495 Ok(())
496 }
497}
498
499impl Decodable for () {
500 fn consensus_decode_partial<D: std::io::Read>(
501 _d: &mut D,
502 _modules: &ModuleDecoderRegistry,
503 ) -> Result<Self, DecodeError> {
504 Ok(())
505 }
506}
507
508impl Encodable for &str {
509 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), Error> {
510 self.as_bytes().consensus_encode(writer)
511 }
512}
513
514impl Encodable for String {
515 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), Error> {
516 self.as_bytes().consensus_encode(writer)
517 }
518}
519
520impl Decodable for String {
521 fn consensus_decode_partial_from_finite_reader<D: std::io::Read>(
522 d: &mut D,
523 modules: &ModuleDecoderRegistry,
524 ) -> Result<Self, DecodeError> {
525 Self::from_utf8(Decodable::consensus_decode_partial_from_finite_reader(
526 d, modules,
527 )?)
528 .map_err(DecodeError::from_err)
529 }
530}
531
532impl Encodable for SystemTime {
533 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
534 let duration = self.duration_since(UNIX_EPOCH).expect("valid duration");
535 duration.consensus_encode_dyn(writer)
536 }
537}
538
539impl Decodable for SystemTime {
540 fn consensus_decode_partial<D: std::io::Read>(
541 d: &mut D,
542 modules: &ModuleDecoderRegistry,
543 ) -> Result<Self, DecodeError> {
544 let duration = Duration::consensus_decode_partial(d, modules)?;
545 Ok(UNIX_EPOCH + duration)
546 }
547}
548
549impl Encodable for Duration {
550 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
551 self.as_secs().consensus_encode(writer)?;
552 self.subsec_nanos().consensus_encode(writer)?;
553
554 Ok(())
555 }
556}
557
558impl Decodable for Duration {
559 fn consensus_decode_partial<D: std::io::Read>(
560 d: &mut D,
561 modules: &ModuleDecoderRegistry,
562 ) -> Result<Self, DecodeError> {
563 let secs = Decodable::consensus_decode_partial(d, modules)?;
564 let nsecs = Decodable::consensus_decode_partial(d, modules)?;
565 Ok(Self::new(secs, nsecs))
566 }
567}
568
569impl Encodable for bool {
570 fn consensus_encode<W: Write>(&self, writer: &mut W) -> Result<(), Error> {
571 let bool_as_u8 = u8::from(*self);
572 writer.write_all(&[bool_as_u8])?;
573 Ok(())
574 }
575}
576
577impl Decodable for bool {
578 fn consensus_decode_partial<D: Read>(
579 d: &mut D,
580 _modules: &ModuleDecoderRegistry,
581 ) -> Result<Self, DecodeError> {
582 let mut bool_as_u8 = [0u8];
583 d.read_exact(&mut bool_as_u8)
584 .map_err(DecodeError::from_err)?;
585 match bool_as_u8[0] {
586 0 => Ok(false),
587 1 => Ok(true),
588 _ => Err(DecodeError::from_str("Out of range, expected 0 or 1")),
589 }
590 }
591}
592
593impl DecodeError {
594 #[allow(clippy::should_implement_trait)]
596 pub fn from_str(s: &'static str) -> Self {
597 #[derive(Debug)]
598 struct StrError(&'static str);
599
600 impl std::fmt::Display for StrError {
601 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
602 std::fmt::Display::fmt(&self.0, f)
603 }
604 }
605
606 impl std::error::Error for StrError {}
607
608 Self(anyhow::Error::from(StrError(s)))
609 }
610
611 pub fn from_err<E: std::error::Error + Send + Sync + 'static>(e: E) -> Self {
612 Self(anyhow::Error::from(e))
613 }
614}
615
616impl std::fmt::Display for DecodeError {
617 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
618 f.write_fmt(format_args!("{:#}", self.0))
619 }
620}
621
622impl Encodable for Cow<'static, str> {
623 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
624 self.as_ref().consensus_encode(writer)
625 }
626}
627
628impl Decodable for Cow<'static, str> {
629 fn consensus_decode_partial<D: std::io::Read>(
630 d: &mut D,
631 modules: &ModuleDecoderRegistry,
632 ) -> Result<Self, DecodeError> {
633 Ok(Cow::Owned(String::consensus_decode_partial(d, modules)?))
634 }
635}
636
637#[derive(Debug, Clone, Serialize, Deserialize)]
656pub enum DynRawFallback<T> {
657 Raw {
658 module_instance_id: ModuleInstanceId,
659 #[serde(with = "::fedimint_core::encoding::as_hex")]
660 raw: Vec<u8>,
661 },
662 Decoded(T),
663}
664
665impl<T> cmp::PartialEq for DynRawFallback<T>
666where
667 T: cmp::PartialEq + Encodable,
668{
669 fn eq(&self, other: &Self) -> bool {
670 match (self, other) {
671 (
672 Self::Raw {
673 module_instance_id: mid_self,
674 raw: raw_self,
675 },
676 Self::Raw {
677 module_instance_id: mid_other,
678 raw: raw_other,
679 },
680 ) => mid_self.eq(mid_other) && raw_self.eq(raw_other),
681 (r @ Self::Raw { .. }, d @ Self::Decoded(_))
682 | (d @ Self::Decoded(_), r @ Self::Raw { .. }) => {
683 r.consensus_encode_to_vec() == d.consensus_encode_to_vec()
684 }
685 (Self::Decoded(s), Self::Decoded(o)) => s == o,
686 }
687 }
688}
689
690impl<T> cmp::Eq for DynRawFallback<T> where T: cmp::Eq + Encodable {}
691
692impl<T> DynRawFallback<T>
693where
694 T: Decodable + 'static,
695{
696 pub fn decoded(self) -> Option<T> {
698 match self {
699 Self::Raw { .. } => None,
700 Self::Decoded(v) => Some(v),
701 }
702 }
703
704 pub fn expect_decoded(self) -> T {
706 match self {
707 Self::Raw { .. } => {
708 panic!("Expected decoded value. Possibly `redecode_raw` call is missing.")
709 }
710 Self::Decoded(v) => v,
711 }
712 }
713
714 pub fn expect_decoded_ref(&self) -> &T {
716 match self {
717 Self::Raw { .. } => {
718 panic!("Expected decoded value. Possibly `redecode_raw` call is missing.")
719 }
720 Self::Decoded(v) => v,
721 }
722 }
723
724 pub fn redecode_raw(
729 self,
730 decoders: &ModuleDecoderRegistry,
731 ) -> Result<Self, crate::encoding::DecodeError> {
732 Ok(match self {
733 Self::Raw {
734 module_instance_id,
735 raw,
736 } => match decoders.get(module_instance_id) {
737 Some(decoder) => Self::Decoded(decoder.decode_complete(
738 &mut &raw[..],
739 raw.len() as u64,
740 module_instance_id,
741 decoders,
742 )?),
743 None => Self::Raw {
744 module_instance_id,
745 raw,
746 },
747 },
748 Self::Decoded(v) => Self::Decoded(v),
749 })
750 }
751}
752
753impl<T> From<T> for DynRawFallback<T> {
754 fn from(value: T) -> Self {
755 Self::Decoded(value)
756 }
757}
758
759impl<T> Decodable for DynRawFallback<T>
760where
761 T: Decodable + 'static,
762{
763 fn consensus_decode_partial_from_finite_reader<R: std::io::Read>(
764 reader: &mut R,
765 decoders: &ModuleDecoderRegistry,
766 ) -> Result<Self, crate::encoding::DecodeError> {
767 let module_instance_id =
768 fedimint_core::core::ModuleInstanceId::consensus_decode_partial_from_finite_reader(
769 reader, decoders,
770 )?;
771 Ok(match decoders.get(module_instance_id) {
772 Some(decoder) => {
773 let total_len_u64 =
774 u64::consensus_decode_partial_from_finite_reader(reader, decoders)?;
775 Self::Decoded(decoder.decode_complete(
776 reader,
777 total_len_u64,
778 module_instance_id,
779 decoders,
780 )?)
781 }
782 None => {
783 Self::Raw {
785 module_instance_id,
786 raw: Vec::consensus_decode_partial_from_finite_reader(reader, decoders)?,
787 }
788 }
789 })
790 }
791}
792
793impl<T> Encodable for DynRawFallback<T>
794where
795 T: Encodable,
796{
797 fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
798 match self {
799 Self::Raw {
800 module_instance_id,
801 raw,
802 } => {
803 module_instance_id.consensus_encode(writer)?;
804 raw.consensus_encode(writer)?;
805 Ok(())
806 }
807 Self::Decoded(v) => v.consensus_encode(writer),
808 }
809 }
810}
811
812#[cfg(test)]
813mod tests {
814 use std::fmt::Debug;
815 use std::io::Cursor;
816
817 use super::*;
818 use crate::encoding::{Decodable, Encodable};
819 use crate::module::registry::ModuleRegistry;
820
821 pub(crate) fn test_roundtrip<T>(value: &T)
822 where
823 T: Encodable + Decodable + Eq + Debug,
824 {
825 let mut bytes = Vec::new();
826 value.consensus_encode(&mut bytes).unwrap();
827
828 let mut cursor = Cursor::new(bytes);
829 let decoded =
830 T::consensus_decode_partial(&mut cursor, &ModuleDecoderRegistry::default()).unwrap();
831 assert_eq!(value, &decoded);
832 }
833
834 pub(crate) fn test_roundtrip_expected<T>(value: &T, expected: &[u8])
835 where
836 T: Encodable + Decodable + Eq + Debug,
837 {
838 let mut bytes = Vec::new();
839 value.consensus_encode(&mut bytes).unwrap();
840 assert_eq!(&expected, &bytes);
841
842 let mut cursor = Cursor::new(bytes);
843 let decoded =
844 T::consensus_decode_partial(&mut cursor, &ModuleDecoderRegistry::default()).unwrap();
845 assert_eq!(value, &decoded);
846 }
847
848 #[derive(Debug, Eq, PartialEq, Encodable, Decodable)]
849 enum NoDefaultEnum {
850 Foo,
851 Bar(u32, String),
852 Baz { baz: u8 },
853 }
854
855 #[derive(Debug, Eq, PartialEq, Encodable, Decodable)]
856 enum DefaultEnum {
857 Foo,
858 Bar(u32, String),
859 #[encodable_default]
860 Default {
861 variant: u64,
862 bytes: Vec<u8>,
863 },
864 }
865
866 #[test_log::test]
867 fn test_derive_enum_no_default_roundtrip_success() {
868 let enums = [
869 NoDefaultEnum::Foo,
870 NoDefaultEnum::Bar(
871 42,
872 "The answer to life, the universe, and everything".to_string(),
873 ),
874 NoDefaultEnum::Baz { baz: 0 },
875 ];
876
877 for e in enums {
878 test_roundtrip(&e);
879 }
880 }
881
882 #[test_log::test]
883 fn test_derive_enum_no_default_decode_fail() {
884 let unknown_variant = DefaultEnum::Default {
885 variant: 42,
886 bytes: vec![0, 1, 2, 3],
887 };
888 let mut unknown_variant_encoding = vec![];
889 unknown_variant
890 .consensus_encode(&mut unknown_variant_encoding)
891 .unwrap();
892
893 let mut cursor = Cursor::new(&unknown_variant_encoding);
894 let decode_res =
895 NoDefaultEnum::consensus_decode_partial(&mut cursor, &ModuleRegistry::default());
896
897 match decode_res {
898 Ok(_) => panic!("Should return error"),
899 Err(e) => assert!(e.to_string().contains("Invalid enum variant")),
900 }
901 }
902
903 #[test_log::test]
904 fn test_derive_enum_default_decode_success() {
905 let unknown_variant = NoDefaultEnum::Baz { baz: 123 };
906 let mut unknown_variant_encoding = vec![];
907 unknown_variant
908 .consensus_encode(&mut unknown_variant_encoding)
909 .unwrap();
910
911 let mut cursor = Cursor::new(&unknown_variant_encoding);
912 let decode_res =
913 DefaultEnum::consensus_decode_partial(&mut cursor, &ModuleRegistry::default());
914
915 assert_eq!(
916 decode_res.unwrap(),
917 DefaultEnum::Default {
918 variant: 2,
919 bytes: vec![123],
920 }
921 );
922 }
923
924 #[test_log::test]
925 fn test_derive_struct() {
926 #[derive(Debug, Encodable, Decodable, Eq, PartialEq)]
927 struct TestStruct {
928 vec: Vec<u8>,
929 num: u32,
930 }
931
932 let reference = TestStruct {
933 vec: vec![1, 2, 3],
934 num: 42,
935 };
936 let bytes = [3, 1, 2, 3, 42];
937
938 test_roundtrip_expected(&reference, &bytes);
939 }
940
941 #[test_log::test]
942 fn test_derive_tuple_struct() {
943 #[derive(Debug, Encodable, Decodable, Eq, PartialEq)]
944 struct TestStruct(Vec<u8>, u32);
945
946 let reference = TestStruct(vec![1, 2, 3], 42);
947 let bytes = [3, 1, 2, 3, 42];
948
949 test_roundtrip_expected(&reference, &bytes);
950 }
951
952 #[test_log::test]
953 fn test_derive_enum() {
954 #[derive(Debug, Encodable, Decodable, Eq, PartialEq)]
955 enum TestEnum {
956 Foo(Option<u64>),
957 Bar { bazz: Vec<u8> },
958 }
959
960 let test_cases = [
961 (TestEnum::Foo(Some(42)), vec![0, 2, 1, 42]),
962 (TestEnum::Foo(None), vec![0, 1, 0]),
963 (
964 TestEnum::Bar {
965 bazz: vec![1, 2, 3],
966 },
967 vec![1, 4, 3, 1, 2, 3],
968 ),
969 ];
970
971 for (reference, bytes) in test_cases {
972 test_roundtrip_expected(&reference, &bytes);
973 }
974 }
975
976 #[test_log::test]
977 fn test_systemtime() {
978 test_roundtrip(&fedimint_core::time::now());
979 }
980
981 #[test]
982 fn test_derive_empty_enum_decode() {
983 #[derive(Debug, Encodable, Decodable)]
984 enum NotConstructable {}
985
986 let vec = vec![42u8];
987 let mut cursor = Cursor::new(vec);
988
989 assert!(
990 NotConstructable::consensus_decode_partial(
991 &mut cursor,
992 &ModuleDecoderRegistry::default()
993 )
994 .is_err()
995 );
996 }
997
998 #[test]
999 fn test_custom_index_enum() {
1000 #[derive(Debug, PartialEq, Eq, Encodable, Decodable)]
1001 enum Old {
1002 Foo,
1003 Bar,
1004 Baz,
1005 }
1006
1007 #[derive(Debug, PartialEq, Eq, Encodable, Decodable)]
1008 enum New {
1009 #[encodable(index = 0)]
1010 Foo,
1011 #[encodable(index = 2)]
1012 Baz,
1013 #[encodable_default]
1014 Default { variant: u64, bytes: Vec<u8> },
1015 }
1016
1017 let test_vector = vec![
1018 (Old::Foo, New::Foo),
1019 (
1020 Old::Bar,
1021 New::Default {
1022 variant: 1,
1023 bytes: vec![],
1024 },
1025 ),
1026 (Old::Baz, New::Baz),
1027 ];
1028
1029 for (old, new) in test_vector {
1030 let old_bytes = old.consensus_encode_to_vec();
1031 let decoded_new = New::consensus_decode_whole(&old_bytes, &ModuleRegistry::default())
1032 .expect("Decoding failed");
1033 assert_eq!(decoded_new, new);
1034 }
1035 }
1036
1037 fn encode_value<T: Encodable>(value: &T) -> Vec<u8> {
1038 let mut writer = Vec::new();
1039 value.consensus_encode(&mut writer).unwrap();
1040 writer
1041 }
1042
1043 fn decode_value<T: Decodable>(bytes: &[u8]) -> T {
1044 T::consensus_decode_whole(bytes, &ModuleDecoderRegistry::default()).unwrap()
1045 }
1046
1047 fn keeps_ordering_after_serialization<T: Ord + Encodable + Decodable + Debug>(mut vec: Vec<T>) {
1048 vec.sort();
1049 let mut encoded = vec.iter().map(encode_value).collect::<Vec<_>>();
1050 encoded.sort();
1051 let decoded = encoded.iter().map(|v| decode_value(v)).collect::<Vec<_>>();
1052 for (i, (a, b)) in vec.iter().zip(decoded.iter()).enumerate() {
1053 assert_eq!(a, b, "difference at index {i}");
1054 }
1055 }
1056
1057 #[test]
1058 fn test_lexicographical_sorting() {
1059 #[derive(Ord, PartialOrd, Eq, PartialEq, Debug, Encodable, Decodable)]
1060 struct TestAmount(u64);
1061
1062 #[derive(Ord, PartialOrd, Eq, PartialEq, Debug, Encodable, Decodable)]
1063 struct TestComplexAmount(u16, u32, u64);
1064
1065 #[derive(Ord, PartialOrd, Eq, PartialEq, Debug, Encodable, Decodable)]
1066 struct Text(String);
1067
1068 let amounts = (0..20000).map(TestAmount).collect::<Vec<_>>();
1069 keeps_ordering_after_serialization(amounts);
1070
1071 let complex_amounts = (10..20000)
1072 .flat_map(|i| {
1073 (i - 1..=i + 1).flat_map(move |j| {
1074 (i - 1..=i + 1).map(move |k| TestComplexAmount(i as u16, j as u32, k as u64))
1075 })
1076 })
1077 .collect::<Vec<_>>();
1078 keeps_ordering_after_serialization(complex_amounts);
1079
1080 let texts = (' '..'~')
1081 .flat_map(|i| {
1082 (' '..'~')
1083 .map(|j| Text(format!("{i}{j}")))
1084 .collect::<Vec<_>>()
1085 })
1086 .collect::<Vec<_>>();
1087 keeps_ordering_after_serialization(texts);
1088
1089 }
1093}