snarkvm_console_network_environment/helpers/
variable_length.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 snarkvm_utilities::{FromBytes, error};
17use std::io::{Read, Result as IoResult};
18
19/// Returns the variable length integer of the given value.
20/// <https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer>
21pub fn variable_length_integer(value: &u64) -> Vec<u8> {
22    match value {
23        // bounded by u8::max_value()
24        0..=252 => vec![*value as u8],
25        // bounded by u16::max_value()
26        253..=65535 => [vec![0xfd], (*value as u16).to_le_bytes().to_vec()].concat(),
27        // bounded by u32::max_value()
28        65536..=4_294_967_295 => [vec![0xfe], (*value as u32).to_le_bytes().to_vec()].concat(),
29        // bounded by u64::max_value()
30        _ => [vec![0xff], value.to_le_bytes().to_vec()].concat(),
31    }
32}
33
34/// Decode the value of a variable length integer.
35/// <https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer>
36pub fn read_variable_length_integer<R: Read>(mut reader: R) -> IoResult<u64> {
37    let flag = u8::read_le(&mut reader)?;
38
39    match flag {
40        0..=252 => Ok(flag as u64),
41        0xfd => match u16::read_le(&mut reader)? {
42            s if s < 253 => Err(error("Invalid variable size integer")),
43            s => Ok(s as u64),
44        },
45        0xfe => match u32::read_le(&mut reader)? {
46            s if s < 65536 => Err(error("Invalid variable size integer")),
47            s => Ok(s as u64),
48        },
49        _ => match u64::read_le(&mut reader)? {
50            s if s < 4_294_967_296 => Err(error("Invalid variable size integer")),
51            s => Ok(s),
52        },
53    }
54}
55
56#[cfg(test)]
57mod test {
58    use super::*;
59
60    const LENGTH_VALUES: [(u64, [u8; 9]); 14] = [
61        (20, [0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
62        (32, [0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
63        (200, [0xc8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
64        (252, [0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
65        (253, [0xfd, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
66        (40000, [0xfd, 0x40, 0x9c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
67        (65535, [0xfd, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
68        (65536, [0xfe, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00]),
69        (2000000000, [0xfe, 0x00, 0x94, 0x35, 0x77, 0x00, 0x00, 0x00, 0x00]),
70        (2000000000, [0xfe, 0x00, 0x94, 0x35, 0x77, 0x00, 0x00, 0x00, 0x00]),
71        (4294967295, [0xfe, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00]),
72        (4294967296, [0xff, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00]),
73        (500000000000000000, [0xff, 0x00, 0x00, 0xb2, 0xd3, 0x59, 0x5b, 0xf0, 0x06]),
74        (18446744073709551615, [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]),
75    ];
76
77    #[test]
78    fn test_variable_length_integer() {
79        LENGTH_VALUES.iter().for_each(|(size, expected_output)| {
80            let variable_length_int = variable_length_integer(size);
81            let pruned_expected_output = &expected_output[..variable_length_int.len()];
82            assert_eq!(pruned_expected_output, &variable_length_int[..]);
83        });
84    }
85
86    #[test]
87    fn test_read_variable_length_integer() {
88        LENGTH_VALUES.iter().for_each(|(expected_size, _expected_output)| {
89            let variable_length_int = variable_length_integer(expected_size);
90            let size = read_variable_length_integer(&variable_length_int[..]).unwrap();
91            assert_eq!(*expected_size, size);
92        });
93    }
94}