1use crate::shim::actors::miner::DeadlineInfo;
125use crate::shim::fvm_shared_latest::piece::PaddedPieceSize;
126use derive_more::From;
127#[cfg(test)]
128use pretty_assertions::assert_eq;
129use schemars::{JsonSchema, Schema, SchemaGenerator};
130use serde::{Deserialize, Deserializer, Serialize, Serializer, de::DeserializeOwned};
131#[cfg(test)]
132use serde_json::json;
133use std::{fmt::Display, str::FromStr};
134use uuid::Uuid;
135
136pub trait HasLotusJson: Sized {
137 type LotusJson: Serialize + DeserializeOwned;
139 #[cfg(test)]
147 fn snapshots() -> Vec<(serde_json::Value, Self)>;
148 fn into_lotus_json(self) -> Self::LotusJson;
149 fn from_lotus_json(lotus_json: Self::LotusJson) -> Self;
150 fn into_lotus_json_value(self) -> serde_json::Result<serde_json::Value> {
151 serde_json::to_value(self.into_lotus_json())
152 }
153 fn into_lotus_json_string(self) -> serde_json::Result<String> {
154 serde_json::to_string(&self.into_lotus_json())
155 }
156 fn into_lotus_json_string_pretty(self) -> serde_json::Result<String> {
157 serde_json::to_string_pretty(&self.into_lotus_json())
158 }
159}
160
161macro_rules! decl_and_test {
162 ($($mod_name:ident for $domain_ty:ty),* $(,)?) => {
163 $(
164 mod $mod_name;
165 )*
166 #[test]
167 fn all_snapshots() {
168 $(
169 print!("test snapshots for {}...", std::any::type_name::<$domain_ty>());
170 std::io::Write::flush(&mut std::io::stdout()).unwrap();
171 assert_all_snapshots::<$domain_ty>();
173 println!("ok.");
174 )*
175 }
176 #[test]
177 fn all_quickchecks() {
178 $(
179 print!("quickcheck for {}...", std::any::type_name::<$domain_ty>());
180 std::io::Write::flush(&mut std::io::stdout()).unwrap();
181 ::quickcheck::quickcheck(assert_unchanged_via_json::<$domain_ty> as fn(_));
183 println!("ok.");
184 )*
185 }
186 }
187}
188#[cfg(doc)]
189pub(crate) use decl_and_test;
190
191decl_and_test!(
192 actor_state for crate::shim::state_tree::ActorState,
193 address for crate::shim::address::Address,
194 beacon_entry for crate::beacon::BeaconEntry,
195 block_header for crate::blocks::CachingBlockHeader,
196 cid for ::cid::Cid,
197 duration for std::time::Duration,
198 percent for crate::shim::percent::Percent,
199 election_proof for crate::blocks::ElectionProof,
200 extended_sector_info for crate::shim::sector::ExtendedSectorInfo,
201 gossip_block for crate::blocks::GossipBlock,
202 key_info for crate::key_management::KeyInfo,
203 message for crate::shim::message::Message,
204 po_st_proof for crate::shim::sector::PoStProof,
205 registered_po_st_proof for crate::shim::sector::RegisteredPoStProof,
206 registered_seal_proof for crate::shim::sector::RegisteredSealProof,
207 sector_info for crate::shim::sector::SectorInfo,
208 sector_size for crate::shim::sector::SectorSize,
209 signature for crate::shim::crypto::Signature,
210 signature_type for crate::shim::crypto::SignatureType,
211 signed_message for crate::message::SignedMessage,
212 ticket for crate::blocks::Ticket,
213 tipset_keys for crate::blocks::TipsetKey,
214 token_amount for crate::shim::econ::TokenAmount,
215 vec_u8 for Vec<u8>,
216 vrf_proof for crate::blocks::VRFProof,
217);
218
219mod actors;
222mod allocation;
223mod arc;
224mod beneficiary_term; mod big_int; mod bit_field; mod bytecode_hash;
228mod entry;
229mod filter_estimate;
230mod hash_map;
231mod ipld; mod miner_info; mod miner_power; mod nonempty; mod opt; mod padded_piece_size;
237mod pending_beneficiary_change; mod power_claim; mod raw_bytes; mod receipt; mod token_state;
242mod tombstone;
243mod transient_data;
244mod vec; mod verifreg_claim;
246
247pub use vec::*;
248
249#[macro_export]
250macro_rules! test_snapshots {
251 ($ty:ty) => {
252 pastey::paste! {
253 #[test]
254 fn [<snapshots_ $ty:snake>]() {
255 use super::*;
256 assert_all_snapshots::<$ty>();
257 }
258 }
259 };
260
261 ($module:path: $ty:ident: $($version:literal),+ $(,)?) => {
262 $(
263 pastey::paste! {
264 #[test]
265 fn [<snapshots_ $module _v $version _ $ty:lower>]() {
266 use super::*;
267 assert_all_snapshots::<$module::[<v $version>]::$ty>();
268 }
269 }
270 )+
271 };
272
273 ($module:path: $nested_path:path: $ty:ident: $($version:literal),+ $(,)?) => {
274 $(
275 pastey::paste! {
276 #[test]
277 fn [<snapshots_ $module _v $version _ $ty:lower>]() {
278 use super::*;
279 assert_all_snapshots::<$module::[<v $version>]::$nested_path::$ty>();
280 }
281 }
282 )+
283 };
284}
285
286#[cfg(any(test, doc))]
287pub fn assert_all_snapshots<T>()
288where
289 T: HasLotusJson,
290 <T as HasLotusJson>::LotusJson: PartialEq + std::fmt::Debug,
291{
292 let snapshots = T::snapshots();
293 assert!(!snapshots.is_empty());
294 for (lotus_json, val) in snapshots {
295 assert_one_snapshot(lotus_json, val);
296 }
297}
298
299#[cfg(test)]
300pub fn assert_one_snapshot<T>(lotus_json: serde_json::Value, val: T)
301where
302 T: HasLotusJson,
303 <T as HasLotusJson>::LotusJson: PartialEq + std::fmt::Debug,
304{
305 let val_lotus_json = val.into_lotus_json();
307 let serialized = serde_json::to_value(&val_lotus_json).unwrap();
308 assert_eq!(
309 serialized.to_string(),
310 lotus_json.to_string(),
311 "snapshot failed for {}",
312 std::any::type_name::<T>()
313 );
314
315 let deserialized = match serde_json::from_value::<T::LotusJson>(lotus_json.clone()) {
318 Ok(lotus_json) => T::from_lotus_json(lotus_json).into_lotus_json(),
319 Err(e) => panic!(
320 "couldn't deserialize a {} from {}: {e}",
321 std::any::type_name::<T::LotusJson>(),
322 lotus_json
323 ),
324 };
325 assert_eq!(deserialized, val_lotus_json);
326}
327
328#[cfg(any(test, doc))]
329pub fn assert_unchanged_via_json<T>(val: T)
330where
331 T: HasLotusJson + Clone + PartialEq + std::fmt::Debug,
332 T::LotusJson: Serialize + serde::de::DeserializeOwned,
333{
334 let temp = val.clone().into_lotus_json();
338 let temp = serde_json::to_value(temp).unwrap();
340 let temp = serde_json::from_value::<T::LotusJson>(temp).unwrap();
342 let temp = T::from_lotus_json(temp);
344
345 assert_eq!(val, temp);
346}
347
348pub mod stringify {
350 use super::*;
351
352 pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
353 where
354 T: Display,
355 S: Serializer,
356 {
357 serializer.collect_str(value)
358 }
359
360 pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
361 where
362 T: FromStr,
363 T::Err: Display,
364 D: Deserializer<'de>,
365 {
366 String::deserialize(deserializer)?
367 .parse()
368 .map_err(serde::de::Error::custom)
369 }
370}
371
372pub mod hexify_bytes {
374 use super::*;
375
376 pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
377 where
378 T: AsRef<[u8]>,
379 S: Serializer,
380 {
381 serializer.serialize_str(&crate::utils::encoding::hex::encode_prefixed(value))
384 }
385
386 pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
387 where
388 T: FromStr,
389 T::Err: Display,
390 D: Deserializer<'de>,
391 {
392 String::deserialize(deserializer)?
393 .parse()
394 .map_err(serde::de::Error::custom)
395 }
396}
397
398pub mod hexify_vec_bytes {
399 use super::*;
400 use std::borrow::Cow;
401
402 pub fn serialize<S>(value: &[u8], serializer: S) -> Result<S::Ok, S::Error>
403 where
404 S: Serializer,
405 {
406 serializer.serialize_str(&crate::utils::encoding::hex::encode_prefixed(value))
407 }
408
409 pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
410 where
411 D: Deserializer<'de>,
412 {
413 let s = String::deserialize(deserializer)?;
414 let s = Cow::from(
415 s.strip_prefix("0x")
416 .or_else(|| s.strip_prefix("0X"))
417 .unwrap_or(&s),
418 );
419
420 let s = if s.len().is_multiple_of(2) {
423 s
424 } else {
425 let mut s = s.into_owned();
426 s.insert(0, '0');
427 Cow::Owned(s)
428 };
429
430 crate::utils::encoding::hex::decode(s.as_ref()).map_err(serde::de::Error::custom)
431 }
432}
433
434pub mod hexify {
436 use super::*;
437 use num_traits::Num;
438 use serde::{Deserializer, Serializer};
439
440 pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
441 where
442 T: Num + std::fmt::LowerHex,
443 S: Serializer,
444 {
445 serializer.serialize_str(format!("{value:#x}").as_str())
446 }
447
448 pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
449 where
450 T: Num,
451 <T as Num>::FromStrRadixErr: std::fmt::Display,
452 D: Deserializer<'de>,
453 {
454 let s = String::deserialize(deserializer)?;
455 crate::utils::encoding::hex::parse_prefixed_int(&s).map_err(serde::de::Error::custom)
456 }
457}
458
459pub mod base64_standard {
461 use super::*;
462
463 use base64::engine::{Engine as _, general_purpose::STANDARD};
464
465 pub fn serialize<S>(value: &[u8], serializer: S) -> Result<S::Ok, S::Error>
466 where
467 S: Serializer,
468 {
469 STANDARD.encode(value).serialize(serializer)
470 }
471
472 pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
473 where
474 D: Deserializer<'de>,
475 {
476 STANDARD
477 .decode(String::deserialize(deserializer)?)
478 .map_err(serde::de::Error::custom)
479 }
480}
481
482pub fn serialize<S, T>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
484where
485 S: Serializer,
486 T: HasLotusJson + Clone,
487{
488 value.clone().into_lotus_json().serialize(serializer)
489}
490
491pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
493where
494 D: Deserializer<'de>,
495 T: HasLotusJson,
496{
497 Ok(T::from_lotus_json(Deserialize::deserialize(deserializer)?))
498}
499
500#[derive(
502 Debug, Deserialize, From, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Clone,
503)]
504#[serde(bound = "T: HasLotusJson + Clone", transparent)]
505pub struct LotusJson<T>(#[serde(with = "self")] pub T);
506
507impl<T> JsonSchema for LotusJson<T>
508where
509 T: HasLotusJson,
510 T::LotusJson: JsonSchema,
511{
512 fn schema_name() -> std::borrow::Cow<'static, str> {
513 T::LotusJson::schema_name()
514 }
515
516 fn schema_id() -> std::borrow::Cow<'static, str> {
517 T::LotusJson::schema_id()
518 }
519
520 fn json_schema(g: &mut SchemaGenerator) -> Schema {
521 T::LotusJson::json_schema(g)
522 }
523}
524
525impl<T> LotusJson<T> {
526 pub fn into_inner(self) -> T {
527 self.0
528 }
529}
530
531macro_rules! lotus_json_with_self {
532 ($($domain_ty:ty),* $(,)?) => {
533 $(
534 impl $crate::lotus_json::HasLotusJson for $domain_ty {
535 type LotusJson = Self;
536 #[cfg(test)]
537 fn snapshots() -> Vec<(serde_json::Value, Self)> {
538 unimplemented!("tests are trivial for HasLotusJson<LotusJson = Self>")
539 }
540 fn into_lotus_json(self) -> Self::LotusJson {
541 self
542 }
543 fn from_lotus_json(lotus_json: Self::LotusJson) -> Self {
544 lotus_json
545 }
546 }
547 )*
548 }
549}
550pub(crate) use lotus_json_with_self;
551
552lotus_json_with_self!(
553 u32,
554 u64,
555 i64,
556 f64,
557 String,
558 chrono::DateTime<chrono::Utc>,
559 serde_json::Value,
560 (),
561 std::path::PathBuf,
562 bool,
563 DeadlineInfo,
564 PaddedPieceSize,
565 Uuid,
566 std::num::NonZeroU32,
567 std::num::NonZeroUsize,
568);
569
570mod fixme {
571 use super::*;
572
573 impl<T: HasLotusJson> HasLotusJson for (T,) {
574 type LotusJson = (T::LotusJson,);
575 #[cfg(test)]
576 fn snapshots() -> Vec<(serde_json::Value, Self)> {
577 unimplemented!("tests are trivial for HasLotusJson<LotusJson = Self>")
578 }
579 fn into_lotus_json(self) -> Self::LotusJson {
580 (self.0.into_lotus_json(),)
581 }
582 fn from_lotus_json(lotus_json: Self::LotusJson) -> Self {
583 (HasLotusJson::from_lotus_json(lotus_json.0),)
584 }
585 }
586
587 impl<A: HasLotusJson, B: HasLotusJson> HasLotusJson for (A, B) {
588 type LotusJson = (A::LotusJson, B::LotusJson);
589 #[cfg(test)]
590 fn snapshots() -> Vec<(serde_json::Value, Self)> {
591 unimplemented!("tests are trivial for HasLotusJson<LotusJson = Self>")
592 }
593 fn into_lotus_json(self) -> Self::LotusJson {
594 (self.0.into_lotus_json(), self.1.into_lotus_json())
595 }
596 fn from_lotus_json(lotus_json: Self::LotusJson) -> Self {
597 (
598 HasLotusJson::from_lotus_json(lotus_json.0),
599 HasLotusJson::from_lotus_json(lotus_json.1),
600 )
601 }
602 }
603
604 impl<A: HasLotusJson, B: HasLotusJson, C: HasLotusJson> HasLotusJson for (A, B, C) {
605 type LotusJson = (A::LotusJson, B::LotusJson, C::LotusJson);
606 #[cfg(test)]
607 fn snapshots() -> Vec<(serde_json::Value, Self)> {
608 unimplemented!("tests are trivial for HasLotusJson<LotusJson = Self>")
609 }
610 fn into_lotus_json(self) -> Self::LotusJson {
611 (
612 self.0.into_lotus_json(),
613 self.1.into_lotus_json(),
614 self.2.into_lotus_json(),
615 )
616 }
617 fn from_lotus_json(lotus_json: Self::LotusJson) -> Self {
618 (
619 HasLotusJson::from_lotus_json(lotus_json.0),
620 HasLotusJson::from_lotus_json(lotus_json.1),
621 HasLotusJson::from_lotus_json(lotus_json.2),
622 )
623 }
624 }
625
626 impl<A: HasLotusJson, B: HasLotusJson, C: HasLotusJson, D: HasLotusJson> HasLotusJson
627 for (A, B, C, D)
628 {
629 type LotusJson = (A::LotusJson, B::LotusJson, C::LotusJson, D::LotusJson);
630 #[cfg(test)]
631 fn snapshots() -> Vec<(serde_json::Value, Self)> {
632 unimplemented!("tests are trivial for HasLotusJson<LotusJson = Self>")
633 }
634 fn into_lotus_json(self) -> Self::LotusJson {
635 (
636 self.0.into_lotus_json(),
637 self.1.into_lotus_json(),
638 self.2.into_lotus_json(),
639 self.3.into_lotus_json(),
640 )
641 }
642 fn from_lotus_json(lotus_json: Self::LotusJson) -> Self {
643 (
644 HasLotusJson::from_lotus_json(lotus_json.0),
645 HasLotusJson::from_lotus_json(lotus_json.1),
646 HasLotusJson::from_lotus_json(lotus_json.2),
647 HasLotusJson::from_lotus_json(lotus_json.3),
648 )
649 }
650 }
651}
652
653#[cfg(test)]
654mod tests {
655 use super::*;
656 use ipld_core::serde::SerdeError;
657 use quickcheck_macros::quickcheck;
658 use rstest::rstest;
659 use serde::de::{IntoDeserializer, value::StringDeserializer};
660
661 #[derive(Debug, Deserialize, Serialize, PartialEq)]
662 struct HexifyVecBytesTest {
663 #[serde(with = "hexify_vec_bytes")]
664 value: Vec<u8>,
665 }
666
667 fn matches_legacy_lowerhex<T: AsRef<[u8]> + std::fmt::LowerHex>(value: T) -> bool {
670 #[derive(Serialize)]
671 struct W<T: AsRef<[u8]>>(#[serde(with = "hexify_bytes")] T);
672
673 serde_json::to_string(&W(&value)).unwrap() == format!("\"{value:#x}\"")
674 }
675
676 fn filled<const N: usize>(bytes: Vec<u8>) -> [u8; N] {
677 let mut arr = [0; N];
678 arr.iter_mut().zip(bytes).for_each(|(a, b)| *a = b);
679 arr
680 }
681
682 fn hexify_de(input: &str) -> Result<u64, SerdeError> {
683 let deserializer: StringDeserializer<SerdeError> =
684 String::from_str(input).unwrap().into_deserializer();
685 hexify::deserialize(deserializer)
686 }
687
688 #[rstest]
689 #[case::nonzero("0x2a", 42)]
690 #[case::zero("0x0", 0)]
691 fn test_hexify_deserialize(#[case] input: &str, #[case] expected: u64) {
692 self::assert_eq!(hexify_de(input).unwrap(), expected);
693 }
694
695 #[rstest]
696 #[case::empty("")]
697 #[case::bare_prefix("0x")]
698 #[case::missing_prefix("2a")]
699 #[case::non_hex_digits("0xzz")]
700 #[case::garbage("cthulhu")]
701 #[case::multibyte_char("0é")]
703 #[case::negative("0x-1")]
704 fn test_hexify_deserialize_invalid(#[case] input: &str) {
705 assert!(hexify_de(input).is_err());
706 }
707
708 #[quickcheck]
709 fn hexify_bytes_matches_legacy_h64(value: u64) -> bool {
710 matches_legacy_lowerhex(ethereum_types::H64::from_low_u64_be(value))
711 }
712
713 #[quickcheck]
714 fn hexify_bytes_matches_legacy_h160(bytes: Vec<u8>) -> bool {
715 matches_legacy_lowerhex(ethereum_types::H160::from(filled::<20>(bytes)))
716 }
717
718 #[quickcheck]
719 fn hexify_bytes_matches_legacy_bloom(bytes: Vec<u8>) -> bool {
720 matches_legacy_lowerhex(ethereum_types::Bloom::from(filled::<256>(bytes)))
721 }
722
723 #[rstest]
724 #[case::empty(vec![], "0x")]
725 #[case::zero(vec![0], "0x00")]
726 #[case::two_bytes(vec![42, 66], "0x2a42")]
727 fn test_hexify_vec_bytes_serialize(#[case] input: Vec<u8>, #[case] expected: &str) {
728 let hexify = HexifyVecBytesTest { value: input };
729 let serialized = serde_json::to_string(&hexify).unwrap();
730 self::assert_eq!(serialized, format!("{{\"value\":\"{}\"}}", expected));
731 }
732
733 fn hexify_vec_bytes_de(input: &str) -> Result<Vec<u8>, SerdeError> {
734 let deserializer: StringDeserializer<SerdeError> =
735 String::from_str(input).unwrap().into_deserializer();
736 hexify_vec_bytes::deserialize(deserializer)
737 }
738
739 #[rstest]
740 #[case::empty("0x", vec![])]
741 #[case::single_nibble("0x0", vec![0])]
742 #[case::uppercase_nibble("0xF", vec![15])]
743 #[case::lowercase("0x2a42", vec![42, 66])]
744 #[case::uppercase_digits("0x2A42", vec![42, 66])]
745 #[case::uppercase_prefix("0X2a42", vec![42, 66])]
746 fn test_hexify_vec_bytes_deserialize(#[case] input: &str, #[case] expected: Vec<u8>) {
747 self::assert_eq!(hexify_vec_bytes_de(input).unwrap(), expected);
748 }
749
750 #[rstest]
751 fn test_hexify_vec_bytes_deserialize_invalid(
752 #[values("cthulhu", "x", "0xazathoth")] input: &str,
753 ) {
754 assert!(hexify_vec_bytes_de(input).is_err());
755 }
756}