snarkvm_ledger_block/
serialize.rs

1// Copyright (c) 2019-2025 Provable Inc.
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::*;
17
18impl<N: Network> Serialize for Block<N> {
19    /// Serializes the block to a JSON-string or buffer.
20    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
21        match serializer.is_human_readable() {
22            true => {
23                let mut block = serializer.serialize_struct("Block", 9)?;
24                block.serialize_field("block_hash", &self.block_hash)?;
25                block.serialize_field("previous_hash", &self.previous_hash)?;
26                block.serialize_field("header", &self.header)?;
27                block.serialize_field("authority", &self.authority)?;
28                block.serialize_field("ratifications", &self.ratifications)?;
29                block.serialize_field("solutions", &self.solutions)?;
30                block.serialize_field("aborted_solution_ids", &self.aborted_solution_ids)?;
31                block.serialize_field("transactions", &self.transactions)?;
32                block.serialize_field("aborted_transaction_ids", &self.aborted_transaction_ids)?;
33                block.end()
34            }
35            false => ToBytesSerializer::serialize_with_size_encoding(self, serializer),
36        }
37    }
38}
39
40impl<'de, N: Network> Deserialize<'de> for Block<N> {
41    /// Deserializes the block from a JSON-string or buffer.
42    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
43        match deserializer.is_human_readable() {
44            true => {
45                let mut block = serde_json::Value::deserialize(deserializer)?;
46                let block_hash: N::BlockHash = DeserializeExt::take_from_value::<D>(&mut block, "block_hash")?;
47
48                // Recover the block.
49                let block = Self::from(
50                    DeserializeExt::take_from_value::<D>(&mut block, "previous_hash")?,
51                    DeserializeExt::take_from_value::<D>(&mut block, "header")?,
52                    DeserializeExt::take_from_value::<D>(&mut block, "authority")?,
53                    DeserializeExt::take_from_value::<D>(&mut block, "ratifications")?,
54                    DeserializeExt::take_from_value::<D>(&mut block, "solutions")?,
55                    DeserializeExt::take_from_value::<D>(&mut block, "aborted_solution_ids")?,
56                    DeserializeExt::take_from_value::<D>(&mut block, "transactions")?,
57                    DeserializeExt::take_from_value::<D>(&mut block, "aborted_transaction_ids")?,
58                )
59                .map_err(de::Error::custom)?;
60
61                // Ensure the block hash matches.
62                match block_hash == block.hash() {
63                    true => Ok(block),
64                    false => Err(de::Error::custom(error("Mismatching block hash, possible data corruption"))),
65                }
66            }
67            false => FromBytesDeserializer::<Self>::deserialize_with_size_encoding(deserializer, "block"),
68        }
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75    use console::network::MainnetV0;
76
77    type CurrentNetwork = MainnetV0;
78
79    #[test]
80    fn test_serde_json() -> Result<()> {
81        let rng = &mut TestRng::default();
82
83        for expected in [crate::test_helpers::sample_genesis_block(rng)].into_iter() {
84            // Serialize
85            let expected_string = &expected.to_string();
86            let candidate_string = serde_json::to_string(&expected)?;
87
88            // Deserialize
89            assert_eq!(expected, Block::from_str(expected_string)?);
90            assert_eq!(expected, serde_json::from_str(&candidate_string)?);
91        }
92        Ok(())
93    }
94
95    #[test]
96    fn test_bincode() -> Result<()> {
97        let rng = &mut TestRng::default();
98
99        for expected in [crate::test_helpers::sample_genesis_block(rng)].into_iter() {
100            // Serialize
101            let expected_bytes = expected.to_bytes_le()?;
102            let expected_bytes_with_size_encoding = bincode::serialize(&expected)?;
103            assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
104
105            // Deserialize
106            assert_eq!(expected, Block::read_le(&expected_bytes[..])?);
107            assert_eq!(expected, bincode::deserialize(&expected_bytes_with_size_encoding[..])?);
108        }
109        Ok(())
110    }
111
112    #[test]
113    fn test_genesis_serde_json() -> Result<()> {
114        // Load the genesis block.
115        let genesis_block = Block::<CurrentNetwork>::read_le(CurrentNetwork::genesis_bytes()).unwrap();
116
117        // Serialize
118        let expected_string = &genesis_block.to_string();
119        let candidate_string = serde_json::to_string(&genesis_block)?;
120
121        // Deserialize
122        assert_eq!(genesis_block, Block::from_str(expected_string)?);
123        assert_eq!(genesis_block, serde_json::from_str(&candidate_string)?);
124
125        Ok(())
126    }
127
128    #[test]
129    fn test_genesis_bincode() -> Result<()> {
130        // Load the genesis block.
131        let genesis_block = Block::<CurrentNetwork>::read_le(CurrentNetwork::genesis_bytes()).unwrap();
132
133        // Serialize
134        let expected_bytes = genesis_block.to_bytes_le()?;
135        let expected_bytes_with_size_encoding = bincode::serialize(&genesis_block)?;
136        assert_eq!(&expected_bytes[..], &expected_bytes_with_size_encoding[8..]);
137
138        // Deserialize
139        assert_eq!(genesis_block, Block::read_le(&expected_bytes[..])?);
140        assert_eq!(genesis_block, bincode::deserialize(&expected_bytes_with_size_encoding[..])?);
141
142        Ok(())
143    }
144}