Skip to main content

snarkvm_console_program/data/record/
bytes.rs

1// Copyright (c) 2019-2026 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, Private: Visibility> FromBytes for Record<N, Private> {
19    /// Reads the record from a buffer.
20    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
21        // Read the variant.
22        let variant = U8::<N>::new(u8::read_le(&mut reader)?);
23
24        // Set the version based on the variant.
25        let version = match *variant {
26            0 | 1 => U8::zero(),
27            2 | 3 => U8::one(),
28            4.. => return Err(error(format!("Failed to decode record variant ({variant}) for the version"))),
29        };
30
31        // Read the owner.
32        let owner = match *variant {
33            0 | 2 => Owner::Public(Address::read_le(&mut reader)?),
34            1 | 3 => Owner::Private(Private::read_le(&mut reader)?),
35            4.. => return Err(error(format!("Failed to decode record variant ({variant}) for the owner"))),
36        };
37
38        // Read the number of entries in the record data.
39        let num_entries = u8::read_le(&mut reader)?;
40        // Read the record data.
41        let mut data = IndexMap::with_capacity(num_entries as usize);
42        for _ in 0..num_entries {
43            // Read the identifier.
44            let identifier = Identifier::<N>::read_le(&mut reader)?;
45            // Read the entry value (in 2 steps to prevent infinite recursion).
46            let num_bytes = u16::read_le(&mut reader)?;
47            // Read the entry bytes.
48            let mut bytes = Vec::new();
49            (&mut reader).take(num_bytes as u64).read_to_end(&mut bytes)?;
50            // Ensure the declared region is entirely present.
51            if bytes.len() != num_bytes as usize {
52                return Err(error("Failed to read record: entry is truncated"));
53            }
54            // Recover the entry value.
55            let mut slice = bytes.as_slice();
56            let entry = Entry::read_le(&mut slice)?;
57            // Ensure the entry fills its region. Bytes left unread would be dropped on
58            // re-serialization, giving one value a second encoding.
59            if !slice.is_empty() {
60                return Err(error("Failed to read record: entry has trailing bytes"));
61            }
62            // Add the entry.
63            data.insert(identifier, entry);
64        }
65
66        // Read the nonce.
67        let nonce = Group::read_le(&mut reader)?;
68
69        // Prepare the reserved entry names.
70        let reserved = [Identifier::from_str("owner").map_err(|e| error(e.to_string()))?];
71        // Ensure the entries has no duplicate names.
72        if has_duplicates(data.keys().chain(reserved.iter())) {
73            return Err(error("Duplicate entry type found in record"));
74        }
75        // Ensure the number of entries is within the maximum limit.
76        if data.len() > N::MAX_DATA_ENTRIES {
77            return Err(error("Failed to parse record - too many entries"));
78        }
79
80        Ok(Self { owner, data, nonce, version })
81    }
82}
83
84impl<N: Network, Private: Visibility> ToBytes for Record<N, Private> {
85    /// Writes the record to a buffer.
86    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
87        // Set the variant.
88        let variant = match (*self.version, self.owner.is_public()) {
89            (0, true) => 0u8,
90            (0, false) => 1u8,
91            (1, true) => 2u8,
92            (1, false) => 3u8,
93            (_, _) => {
94                return Err(error(format!(
95                    "Failed to encode record - variant mismatch (version = {}, hiding = {}, owner = {})",
96                    self.version,
97                    self.is_hiding(),
98                    self.owner.is_public()
99                )));
100            }
101        };
102
103        #[cfg(debug_assertions)]
104        {
105            // Ensure the version is correct.
106            let is_version_correct = match (!self.is_hiding(), self.owner.is_public()) {
107                (true, true) => variant == 0,
108                (true, false) => variant == 1,
109                (false, true) => variant == 2,
110                (false, false) => variant == 3,
111            };
112            if !is_version_correct {
113                return Err(error(format!(
114                    "Failed to encode record - version mismatch (version = {}, hiding = {}, owner = {})",
115                    self.version,
116                    self.is_hiding(),
117                    self.owner.is_public()
118                )));
119            }
120        }
121
122        // Write the variant.
123        variant.write_le(&mut writer)?;
124
125        // Write the owner.
126        match &self.owner {
127            Owner::Public(owner) => owner.write_le(&mut writer)?,
128            Owner::Private(owner) => owner.write_le(&mut writer)?,
129        };
130
131        // Write the number of entries in the record data.
132        u8::try_from(self.data.len()).or_halt_with::<N>("Record length exceeds u8::MAX").write_le(&mut writer)?;
133        // Write each entry.
134        for (entry_name, entry_value) in &self.data {
135            // Write the entry name.
136            entry_name.write_le(&mut writer)?;
137            // Write the entry value (performed in 2 steps to prevent infinite recursion).
138            let bytes = entry_value.to_bytes_le().map_err(|e| error(e.to_string()))?;
139            // Write the number of bytes.
140            u16::try_from(bytes.len())
141                .or_halt_with::<N>("Record entry exceeds u16::MAX bytes")
142                .write_le(&mut writer)?;
143            // Write the bytes.
144            bytes.write_le(&mut writer)?;
145        }
146
147        // Write the nonce.
148        self.nonce.write_le(&mut writer)
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155    use snarkvm_console_network::MainnetV0;
156
157    type CurrentNetwork = MainnetV0;
158
159    #[test]
160    fn test_bytes() -> Result<()> {
161        // Construct a new record.
162        let expected = Record::<CurrentNetwork, Plaintext<CurrentNetwork>>::from_str(
163            "{ owner: aleo1d5hg2z3ma00382pngntdp68e74zv54jdxy249qhaujhks9c72yrs33ddah.private, token_amount: 100u64.private, _nonce: 0group.public }",
164        )?;
165
166        // Check the byte representation.
167        let expected_bytes = expected.to_bytes_le()?;
168        assert_eq!(expected, Record::read_le(&expected_bytes[..])?);
169
170        // Construct a new record.
171        let expected = Record::<CurrentNetwork, Plaintext<CurrentNetwork>>::from_str(
172            "{ owner: aleo1d5hg2z3ma00382pngntdp68e74zv54jdxy249qhaujhks9c72yrs33ddah.private, token_amount: 100u64.private, _nonce: 0group.public, _version: 1u8.public }",
173        )?;
174
175        // Check the byte representation.
176        let expected_bytes = expected.to_bytes_le()?;
177        assert_eq!(expected, Record::read_le(&expected_bytes[..])?);
178        Ok(())
179    }
180
181    #[test]
182    fn test_record_entry_rejects_trailing_bytes() -> Result<()> {
183        let record = Record::<CurrentNetwork, Plaintext<CurrentNetwork>>::from_str(
184            "{ owner: aleo1d5hg2z3ma00382pngntdp68e74zv54jdxy249qhaujhks9c72yrs33ddah.private, token_amount: 100u64.private, _nonce: 0group.public }",
185        )?;
186        let exact = record.to_bytes_le()?;
187        assert_eq!(record, Record::read_le(&exact[..])?);
188
189        // Locate the sole data entry by its own encoding: the two bytes in front of it
190        // are the `u16` that delimits its region.
191        let identifier = Identifier::<CurrentNetwork>::from_str("token_amount")?;
192        let entry_bytes = record.data().get(&identifier).expect("the record has this entry").to_bytes_le()?;
193        let at = exact
194            .windows(entry_bytes.len())
195            .position(|window| window == entry_bytes.as_slice())
196            .expect("the entry's bytes appear in the record's bytes");
197        assert!(at >= 2);
198        assert_eq!(u16::from_le_bytes([exact[at - 2], exact[at - 1]]) as usize, entry_bytes.len());
199
200        // Declaring more bytes for the entry than it occupies leaves bytes unread.
201        for padding in [1usize, 8, 32] {
202            let mut padded = exact.clone();
203            let declared = u16::try_from(entry_bytes.len() + padding)?;
204            padded[at - 2..at].copy_from_slice(&declared.to_le_bytes());
205            padded.splice(at + entry_bytes.len()..at + entry_bytes.len(), std::iter::repeat_n(0u8, padding));
206            assert_ne!(padded, exact);
207            assert!(
208                Record::<CurrentNetwork, Plaintext<CurrentNetwork>>::read_le(&padded[..]).is_err(),
209                "a record entry declaring {padding} bytes more than it uses must be rejected"
210            );
211        }
212        Ok(())
213    }
214}