Skip to main content

snarkvm_console_network/
consensus_heights.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 crate::{FromBytes, ToBytes, io_error};
17
18use enum_iterator::{Sequence, last};
19use snarkvm_algorithms::snark::varuna::VarunaVersion;
20use std::io;
21
22/// The different consensus versions.
23/// If you need the version active for a specific height, see: `N::CONSENSUS_VERSION`.
24#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Sequence)]
25#[repr(u16)]
26pub enum ConsensusVersion {
27    /// V1: The initial genesis consensus version.
28    V1 = 1,
29    /// V2: Update to the block reward and execution cost algorithms.
30    V2 = 2,
31    /// V3: Update to the number of validators and finalize scope RNG seed.
32    V3 = 3,
33    /// V4: Update to the Varuna version.
34    V4 = 4,
35    /// V5: Update to the number of validators and enable batch proposal spend limits.
36    V5 = 5,
37    /// V6: Update to the number of validators.
38    V6 = 6,
39    /// V7: Update to program rules.
40    V7 = 7,
41    /// V8: Update to inclusion version, record commitment version, and introduces sender ciphertexts.
42    V8 = 8,
43    /// V9: Support for program upgradability.
44    V9 = 9,
45    /// V10: Lower fees, appropriate record output type checking.
46    V10 = 10,
47    /// V11: Expand array size limit to 512 and introduce ECDSA signature verification opcodes.
48    V11 = 11,
49    /// V12: Prevent connection to forked nodes, disable StringType, enable block timestamp.
50    V12 = 12,
51    /// V13: Introduces external structs.
52    V13 = 13,
53    /// V14: Increase the program size limit to 512 kB, the transaction size limit to 540 kB,
54    ///      the array size limit to 2048, and the `Future` argument bit size to 32 bits.
55    ///      Introduces `aleo::GENERATOR`, `aleo::GENERATOR_POWERS`, `snark.verify` opcodes,
56    ///      and dynamic dispatch, and identifier literal types.
57    V14 = 14,
58    /// V15: Introduces the record-existence check and `commit.*.raw` instruction variants.
59    ///      Increase the anchor time to 35.
60    V15 = 15,
61    /// V16: Moves the block's spend limit check to the finalize phase.
62    ///      Supports storing of transaction rejection reasons.
63    ///      Increase the program size limit to 2048 kB and the transaction size limit to 2304 kB.
64    ///      Update the deployment storage cost for programs exceeding 512 kB.
65    V16 = 16,
66    /// V17: NOTE: V17 landed chronologically on mainnet before it landed on testnet.
67    ///      Reverts the anchor time to 25.
68    V17 = 17,
69    /// V18: Enables native credits record translation, introduces block-wide deployment limits,
70    ///      and enforces canonical subDAG certificate ordering.
71    V18 = 18,
72    /// V19: Reverts from the V18 block-wide synthesis limit to per-transaction
73    ///      deployment variable and constraint limits. The first V19 block still
74    ///      uses the block-wide synthesis limit.
75    V19 = 19,
76    /// V20: Adds more accurate type checking for the root call, and bounds the size of every
77    /// `PlaintextType` declared in a deployed program.
78    V20 = 20,
79    /// V21: TBD
80    V21 = 21,
81}
82
83impl ToBytes for ConsensusVersion {
84    fn write_le<W: io::Write>(&self, writer: W) -> io::Result<()> {
85        (*self as u16).write_le(writer)
86    }
87}
88
89impl FromBytes for ConsensusVersion {
90    fn read_le<R: io::Read>(reader: R) -> io::Result<Self> {
91        match u16::read_le(reader)? {
92            0 => Err(io_error("Zero is not a valid consensus version")),
93            1 => Ok(Self::V1),
94            2 => Ok(Self::V2),
95            3 => Ok(Self::V3),
96            4 => Ok(Self::V4),
97            5 => Ok(Self::V5),
98            6 => Ok(Self::V6),
99            7 => Ok(Self::V7),
100            8 => Ok(Self::V8),
101            9 => Ok(Self::V9),
102            10 => Ok(Self::V10),
103            11 => Ok(Self::V11),
104            12 => Ok(Self::V12),
105            13 => Ok(Self::V13),
106            14 => Ok(Self::V14),
107            15 => Ok(Self::V15),
108            16 => Ok(Self::V16),
109            17 => Ok(Self::V17),
110            18 => Ok(Self::V18),
111            19 => Ok(Self::V19),
112            20 => Ok(Self::V20),
113            21 => Ok(Self::V21),
114            _ => Err(io_error("Invalid consensus version")),
115        }
116    }
117}
118
119impl ConsensusVersion {
120    pub fn latest() -> Self {
121        last::<ConsensusVersion>().expect("At least one ConsensusVersion should be defined.")
122    }
123}
124
125impl std::fmt::Display for ConsensusVersion {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        // Use Debug formatting for Display.
128        write!(f, "{self:?}")
129    }
130}
131
132/// The number of consensus versions.
133pub(crate) const NUM_CONSENSUS_VERSIONS: usize = enum_iterator::cardinality::<ConsensusVersion>();
134
135/// The consensus version height for `CanaryV0`.
136pub const CANARY_V0_CONSENSUS_VERSION_HEIGHTS: [(ConsensusVersion, u32); NUM_CONSENSUS_VERSIONS] = [
137    (ConsensusVersion::V1, 0),
138    (ConsensusVersion::V2, 2_900_000),
139    (ConsensusVersion::V3, 4_560_000),
140    (ConsensusVersion::V4, 5_730_000),
141    (ConsensusVersion::V5, 5_780_000),
142    (ConsensusVersion::V6, 6_240_000),
143    (ConsensusVersion::V7, 6_880_000),
144    (ConsensusVersion::V8, 7_565_000),
145    (ConsensusVersion::V9, 8_028_000),
146    (ConsensusVersion::V10, 8_600_000),
147    (ConsensusVersion::V11, 9_510_000),
148    (ConsensusVersion::V12, 10_030_000),
149    (ConsensusVersion::V13, 10_881_000),
150    (ConsensusVersion::V14, 11_960_000),
151    (ConsensusVersion::V15, u32::MAX),
152    (ConsensusVersion::V16, u32::MAX),
153    (ConsensusVersion::V17, u32::MAX),
154    (ConsensusVersion::V18, u32::MAX),
155    (ConsensusVersion::V19, u32::MAX),
156    (ConsensusVersion::V20, u32::MAX),
157    (ConsensusVersion::V21, u32::MAX),
158];
159
160/// The consensus version height for `MainnetV0`.
161pub const MAINNET_V0_CONSENSUS_VERSION_HEIGHTS: [(ConsensusVersion, u32); NUM_CONSENSUS_VERSIONS] = [
162    (ConsensusVersion::V1, 0),
163    (ConsensusVersion::V2, 2_800_000),
164    (ConsensusVersion::V3, 4_900_000),
165    (ConsensusVersion::V4, 6_135_000),
166    (ConsensusVersion::V5, 7_060_000),
167    (ConsensusVersion::V6, 7_560_000),
168    (ConsensusVersion::V7, 7_570_000),
169    (ConsensusVersion::V8, 9_430_000),
170    (ConsensusVersion::V9, 10_272_000),
171    (ConsensusVersion::V10, 11_205_000),
172    (ConsensusVersion::V11, 12_870_000),
173    (ConsensusVersion::V12, 13_815_000),
174    (ConsensusVersion::V13, 16_850_000),
175    (ConsensusVersion::V14, 17_700_000),
176    (ConsensusVersion::V15, 19_264_000),
177    (ConsensusVersion::V16, 19_860_000),
178    (ConsensusVersion::V17, 19_860_001),
179    (ConsensusVersion::V18, 20_794_000),
180    (ConsensusVersion::V19, 21_342_000),
181    (ConsensusVersion::V20, 22_175_000),
182    (ConsensusVersion::V21, u32::MAX),
183];
184
185/// The consensus version heights for `TestnetV0`.
186pub const TESTNET_V0_CONSENSUS_VERSION_HEIGHTS: [(ConsensusVersion, u32); NUM_CONSENSUS_VERSIONS] = [
187    (ConsensusVersion::V1, 0),
188    (ConsensusVersion::V2, 2_950_000),
189    (ConsensusVersion::V3, 4_800_000),
190    (ConsensusVersion::V4, 6_625_000),
191    (ConsensusVersion::V5, 6_765_000),
192    (ConsensusVersion::V6, 7_600_000),
193    (ConsensusVersion::V7, 8_365_000),
194    (ConsensusVersion::V8, 9_173_000),
195    (ConsensusVersion::V9, 9_800_000),
196    (ConsensusVersion::V10, 10_525_000),
197    (ConsensusVersion::V11, 11_952_000),
198    (ConsensusVersion::V12, 12_669_000),
199    (ConsensusVersion::V13, 14_906_000),
200    (ConsensusVersion::V14, 15_370_000),
201    (ConsensusVersion::V15, 16_886_000),
202    (ConsensusVersion::V16, 17_319_000),
203    (ConsensusVersion::V17, 18_295_000),
204    (ConsensusVersion::V18, 18_296_000),
205    (ConsensusVersion::V19, 18_813_000),
206    (ConsensusVersion::V20, 19_374_000),
207    (ConsensusVersion::V21, u32::MAX),
208];
209
210/// The consensus version heights when the `test_consensus_heights` feature is enabled.
211// We want each to come immediately after the previous one by default for faster testing.
212// Whether activating them all at height 0 is possible is open for investigation.
213// If a test needs to stay on one consensus version for a while, consider just locally testing or using a custom `CONSENSUS_VERSION_HEIGHTS` environment variable.
214pub const TEST_CONSENSUS_VERSION_HEIGHTS: [(ConsensusVersion, u32); NUM_CONSENSUS_VERSIONS] = [
215    (ConsensusVersion::V1, 0),
216    (ConsensusVersion::V2, 5),
217    (ConsensusVersion::V3, 6),
218    (ConsensusVersion::V4, 7),
219    (ConsensusVersion::V5, 8),
220    (ConsensusVersion::V6, 9),
221    (ConsensusVersion::V7, 10),
222    (ConsensusVersion::V8, 11),
223    (ConsensusVersion::V9, 12),
224    (ConsensusVersion::V10, 13),
225    (ConsensusVersion::V11, 14),
226    (ConsensusVersion::V12, 15),
227    (ConsensusVersion::V13, 16),
228    (ConsensusVersion::V14, 17),
229    (ConsensusVersion::V15, 18),
230    (ConsensusVersion::V16, 19),
231    (ConsensusVersion::V17, 20),
232    (ConsensusVersion::V18, 21),
233    (ConsensusVersion::V19, 22),
234    (ConsensusVersion::V20, 23),
235    (ConsensusVersion::V21, 24),
236];
237
238#[cfg(any(test, feature = "test", feature = "test_consensus_heights"))]
239pub fn load_test_consensus_heights() -> [(ConsensusVersion, u32); NUM_CONSENSUS_VERSIONS] {
240    // Attempt to read the test consensus heights from the environment variable.
241    load_test_consensus_heights_inner(std::env::var("CONSENSUS_VERSION_HEIGHTS").ok())
242}
243
244#[cfg(any(test, feature = "test", feature = "test_consensus_heights", feature = "wasm"))]
245pub(crate) fn load_test_consensus_heights_inner(
246    consensus_version_heights: Option<String>,
247) -> [(ConsensusVersion, u32); NUM_CONSENSUS_VERSIONS] {
248    // Define a closure to verify the consensus heights.
249    let verify_consensus_heights = |heights: &[(ConsensusVersion, u32); NUM_CONSENSUS_VERSIONS]| {
250        // Assert that the genesis height is 0.
251        assert_eq!(heights[0].1, 0, "Genesis height must be 0.");
252        // Assert that the consensus heights are strictly increasing.
253        for window in heights.windows(2) {
254            if window[0] >= window[1] {
255                panic!("Heights must be strictly increasing, but found: {window:?}");
256            }
257        }
258    };
259
260    // Define consensus version heights container used for testing.
261    let mut test_consensus_heights = TEST_CONSENSUS_VERSION_HEIGHTS;
262
263    // If version heights have been specified, verify and return them.
264    match consensus_version_heights {
265        Some(height_string) => {
266            let parsing_error = format!("Expected exactly {NUM_CONSENSUS_VERSIONS} ConsensusVersion heights.");
267            // Parse the heights from the environment variable.
268            let parsed_test_consensus_heights: [u32; NUM_CONSENSUS_VERSIONS] = height_string
269                .replace(" ", "")
270                .split(",")
271                .map(|height| height.parse::<u32>().expect("Heights should be valid u32 values."))
272                .collect::<Vec<u32>>()
273                .try_into()
274                .expect(&parsing_error);
275            // Set the parsed heights in the test consensus heights.
276            for (i, height) in parsed_test_consensus_heights.into_iter().enumerate() {
277                test_consensus_heights[i] = (TEST_CONSENSUS_VERSION_HEIGHTS[i].0, height);
278            }
279            // Verify and return the parsed test consensus heights.
280            verify_consensus_heights(&test_consensus_heights);
281            test_consensus_heights
282        }
283        None => {
284            // Verify and return the default test consensus heights.
285            verify_consensus_heights(&test_consensus_heights);
286            test_consensus_heights
287        }
288    }
289}
290
291/// Returns the consensus configuration value for the specified height.
292///
293/// Arguments:
294/// - `$network`: The network to use the constant of.
295/// - `$constant`: The constant to search a value of.
296/// - `$seek_height`: The block height to search the value for.
297#[macro_export]
298macro_rules! consensus_config_value {
299    ($network:ident, $constant:ident, $seek_height:expr) => {
300        // Search the consensus version enacted at the specified height.
301        $network::CONSENSUS_VERSION($seek_height).map_or(None, |seek_version| {
302            // Search the consensus value for the specified version.
303            // NOTE: calling `consensus_config_value_by_version!` here would require callers to import both macros.
304            match $network::$constant.binary_search_by(|(version, _)| version.cmp(&seek_version)) {
305                // If a value was found for this consensus version, return it.
306                Ok(index) => Some($network::$constant[index].1),
307                // If the specified version was not found exactly, determine whether to return an appropriate value anyway.
308                Err(index) => {
309                    // This constant is not yet in effect at this consensus version.
310                    if index == 0 {
311                        None
312                    // Return the appropriate value belonging to the consensus version *lower* than the sought version.
313                    } else {
314                        Some($network::$constant[index - 1].1)
315                    }
316                }
317            }
318        })
319    };
320}
321
322/// Returns the consensus configuration value for the specified ConsensusVersion.
323///
324/// Arguments:
325/// - `$network`: The network to use the constant of.
326/// - `$constant`: The constant to search a value of.
327/// - `$seek_version`: The ConsensusVersion to search the value for.
328#[macro_export]
329macro_rules! consensus_config_value_by_version {
330    ($network:ident, $constant:ident, $seek_version:expr) => {
331        // Search the consensus value for the specified version.
332        match $network::$constant.binary_search_by(|(version, _)| version.cmp(&$seek_version)) {
333            // If a value was found for this consensus version, return it.
334            Ok(index) => Some($network::$constant[index].1),
335            // If the specified version was not found exactly, determine whether to return an appropriate value anyway.
336            Err(index) => {
337                // This constant is not yet in effect at this consensus version.
338                if index == 0 {
339                    None
340                // Return the appropriate value belonging to the consensus version *lower* than the sought version.
341                } else {
342                    Some($network::$constant[index - 1].1)
343                }
344            }
345        }
346    };
347}
348
349/// Returns the Varuna version for the specified consensus version.
350pub fn varuna_version_from_consensus(consensus_version: ConsensusVersion) -> VarunaVersion {
351    // If new varuna versions are added, test_varuna_version_from_consensus below must be updated accordingly.
352    if consensus_version >= ConsensusVersion::V4 { VarunaVersion::V2 } else { VarunaVersion::V1 }
353}
354
355#[cfg(test)]
356mod tests {
357    use super::*;
358    use crate::{CanaryV0, MainnetV0, Network, TestnetV0};
359
360    /// Ensure that the consensus constants are defined and correct at genesis.
361    /// It is possible this invariant no longer holds in the future, e.g. due to pruning or novel types of constants.
362    fn consensus_constants_at_genesis<N: Network>() {
363        let height = N::_CONSENSUS_VERSION_HEIGHTS.first().unwrap().1;
364        assert_eq!(height, 0);
365        let consensus_version = N::_CONSENSUS_VERSION_HEIGHTS.first().unwrap().0;
366        assert_eq!(consensus_version, ConsensusVersion::V1);
367        assert_eq!(consensus_version as usize, 1);
368    }
369
370    /// Ensure that the consensus *versions* are unique, incrementing and start with 1.
371    fn consensus_versions<N: Network>() {
372        let mut previous_version = N::_CONSENSUS_VERSION_HEIGHTS.first().unwrap().0;
373        // Ensure that the consensus versions start with 1.
374        assert_eq!(previous_version as usize, 1);
375        // Ensure that the consensus versions are unique and incrementing by 1.
376        for (version, _) in N::_CONSENSUS_VERSION_HEIGHTS.iter().skip(1) {
377            assert_eq!(*version as usize, previous_version as usize + 1);
378            previous_version = *version;
379        }
380        // Ensure that the consensus versions are unique and incrementing.
381        let mut previous_version = N::MAX_CERTIFICATES.first().unwrap().0;
382        for (version, _) in N::MAX_CERTIFICATES.iter().skip(1) {
383            assert!(*version > previous_version);
384            previous_version = *version;
385        }
386        let mut previous_version = N::TRANSACTION_SPEND_LIMIT.first().unwrap().0;
387        for (version, _) in N::TRANSACTION_SPEND_LIMIT.iter().skip(1) {
388            assert!(*version > previous_version);
389            previous_version = *version;
390        }
391        let mut previous_version = N::CREDITS_PER_SECOND_OF_RUNTIME.first().unwrap().0;
392        for (version, _) in N::CREDITS_PER_SECOND_OF_RUNTIME.iter().skip(1) {
393            assert!(*version > previous_version);
394            previous_version = *version;
395        }
396        let mut previous_version = N::MAX_ARRAY_ELEMENTS.first().unwrap().0;
397        for (version, _) in N::MAX_ARRAY_ELEMENTS.iter().skip(1) {
398            assert!(*version > previous_version);
399            previous_version = *version;
400        }
401        let mut previous_version = N::MAX_PROGRAM_SIZE.first().unwrap().0;
402        for (version, _) in N::MAX_PROGRAM_SIZE.iter().skip(1) {
403            assert!(*version > previous_version);
404            previous_version = *version;
405        }
406        let mut previous_version = N::MAX_TRANSACTION_SIZE.first().unwrap().0;
407        for (version, _) in N::MAX_TRANSACTION_SIZE.iter().skip(1) {
408            assert!(*version > previous_version);
409            previous_version = *version;
410        }
411        let mut previous_version = N::MAX_WRITES.first().unwrap().0;
412        for (version, _) in N::MAX_WRITES.iter().skip(1) {
413            assert!(*version > previous_version);
414            previous_version = *version;
415        }
416        let mut previous_version = N::ANCHOR_TIMES.first().unwrap().0;
417        for (version, _) in N::ANCHOR_TIMES.iter().skip(1) {
418            assert!(*version > previous_version);
419            previous_version = *version;
420        }
421    }
422
423    /// Ensure that consensus *heights* are unique and incrementing.
424    fn consensus_constants_increasing_heights<N: Network>() {
425        let mut previous_height = N::CONSENSUS_VERSION_HEIGHTS().first().unwrap().1;
426        for (version, height) in N::CONSENSUS_VERSION_HEIGHTS().iter().skip(1) {
427            assert!(*height > previous_height);
428            previous_height = *height;
429            // Ensure that N::CONSENSUS_VERSION returns the expected value.
430            assert_eq!(N::CONSENSUS_VERSION(*height).unwrap(), *version);
431            // Ensure that N::CONSENSUS_HEIGHT returns the expected value.
432            assert_eq!(N::CONSENSUS_HEIGHT(*version).unwrap(), *height);
433        }
434    }
435
436    /// Ensure that version of all consensus-relevant constants are present in the consensus version heights.
437    fn consensus_constants_valid_heights<N: Network>() {
438        for (version, value) in N::MAX_CERTIFICATES.iter() {
439            // Ensure that the height at which an update occurs are present in CONSENSUS_VERSION_HEIGHTS.
440            let height = N::CONSENSUS_VERSION_HEIGHTS().iter().find(|(c_version, _)| *c_version == *version).unwrap().1;
441            // Double-check that consensus_config_value returns the correct value.
442            assert_eq!(consensus_config_value!(N, MAX_CERTIFICATES, height).unwrap(), *value);
443        }
444        for (version, value) in N::TRANSACTION_SPEND_LIMIT.iter() {
445            // Ensure that the height at which an update occurs are present in CONSENSUS_VERSION_HEIGHTS.
446            let height = N::CONSENSUS_VERSION_HEIGHTS().iter().find(|(c_version, _)| *c_version == *version).unwrap().1;
447            // Double-check that consensus_config_value returns the correct value.
448            assert_eq!(consensus_config_value!(N, TRANSACTION_SPEND_LIMIT, height).unwrap(), *value);
449        }
450        for (version, value) in N::CREDITS_PER_SECOND_OF_RUNTIME.iter() {
451            // Ensure that the height at which an update occurs are present in CONSENSUS_VERSION_HEIGHTS.
452            let height = N::CONSENSUS_VERSION_HEIGHTS().iter().find(|(c_version, _)| *c_version == *version).unwrap().1;
453            // Double-check that consensus_config_value returns the correct value.
454            assert_eq!(consensus_config_value!(N, CREDITS_PER_SECOND_OF_RUNTIME, height).unwrap(), *value);
455        }
456        for (version, value) in N::MAX_ARRAY_ELEMENTS.iter() {
457            // Ensure that the height at which an update occurs are present in CONSENSUS_VERSION_HEIGHTS.
458            let height = N::CONSENSUS_VERSION_HEIGHTS().iter().find(|(c_version, _)| *c_version == *version).unwrap().1;
459            // Double-check that consensus_config_value returns the correct value.
460            assert_eq!(consensus_config_value!(N, MAX_ARRAY_ELEMENTS, height).unwrap(), *value);
461        }
462        for (version, value) in N::MAX_PROGRAM_SIZE.iter() {
463            // Ensure that the height at which an update occurs are present in CONSENSUS_VERSION_HEIGHTS.
464            let height = N::CONSENSUS_VERSION_HEIGHTS().iter().find(|(c_version, _)| *c_version == *version).unwrap().1;
465            // Double-check that consensus_config_value returns the correct value.
466            assert_eq!(consensus_config_value!(N, MAX_PROGRAM_SIZE, height).unwrap(), *value);
467        }
468        for (version, value) in N::MAX_TRANSACTION_SIZE.iter() {
469            // Ensure that the height at which an update occurs are present in CONSENSUS_VERSION_HEIGHTS.
470            let height = N::CONSENSUS_VERSION_HEIGHTS().iter().find(|(c_version, _)| *c_version == *version).unwrap().1;
471            // Double-check that consensus_config_value returns the correct value.
472            assert_eq!(consensus_config_value!(N, MAX_TRANSACTION_SIZE, height).unwrap(), *value);
473        }
474        for (version, value) in N::MAX_WRITES.iter() {
475            // Ensure that the height at which an update occurs are present in CONSENSUS_VERSION_HEIGHTS.
476            let height = N::CONSENSUS_VERSION_HEIGHTS().iter().find(|(c_version, _)| *c_version == *version).unwrap().1;
477            // Double-check that consensus_config_value returns the correct value.
478            assert_eq!(consensus_config_value!(N, MAX_WRITES, height).unwrap(), *value);
479        }
480        for (version, value) in N::ANCHOR_TIMES.iter() {
481            let height = N::CONSENSUS_VERSION_HEIGHTS().iter().find(|(c_version, _)| c_version == version).unwrap().1;
482            assert_eq!(consensus_config_value!(N, ANCHOR_TIMES, height).unwrap(), *value);
483        }
484    }
485
486    /// Ensure that consensus_config_value returns a valid value for all consensus versions.
487    fn consensus_config_returns_some<N: Network>() {
488        for (_, height) in N::CONSENSUS_VERSION_HEIGHTS().iter() {
489            assert!(consensus_config_value!(N, MAX_CERTIFICATES, *height).is_some());
490            assert!(consensus_config_value!(N, TRANSACTION_SPEND_LIMIT, *height).is_some());
491            assert!(consensus_config_value!(N, CREDITS_PER_SECOND_OF_RUNTIME, *height).is_some());
492            assert!(consensus_config_value!(N, MAX_ARRAY_ELEMENTS, *height).is_some());
493            assert!(consensus_config_value!(N, MAX_PROGRAM_SIZE, *height).is_some());
494            assert!(consensus_config_value!(N, MAX_TRANSACTION_SIZE, *height).is_some());
495            assert!(consensus_config_value!(N, MAX_WRITES, *height).is_some());
496            assert!(consensus_config_value!(N, ANCHOR_TIMES, *height).is_some());
497        }
498    }
499
500    /// Ensure that `MAX_CERTIFICATES` increases and is correctly defined.
501    /// See the constant declaration for an explanation why.
502    fn max_certificates_increasing<N: Network>() {
503        let mut previous_value = N::MAX_CERTIFICATES.first().unwrap().1;
504        for (_, value) in N::MAX_CERTIFICATES.iter().skip(1) {
505            assert!(*value >= previous_value);
506            previous_value = *value;
507        }
508    }
509
510    /// Ensure that `MAX_ARRAY_ELEMENTS` increases and is correctly defined.
511    /// See the constant declaration for an explanation why.
512    fn max_array_elements_increasing<N: Network>() {
513        let mut previous_value = N::MAX_ARRAY_ELEMENTS.first().unwrap().1;
514        for (_, value) in N::MAX_ARRAY_ELEMENTS.iter().skip(1) {
515            assert!(*value >= previous_value);
516            previous_value = *value;
517        }
518    }
519
520    /// Ensure that `MAX_TRANSACTION_SIZE` is at least 28KB greater than `MAX_PROGRAM_SIZE` for all consensus versions.
521    /// This overhead accounts for proofs, signatures, and other transaction metadata.
522    fn transaction_size_exceeds_program_size<N: Network>() {
523        const MIN_OVERHEAD: usize = 28_000; // 28 kB minimum overhead
524
525        for (_, height) in N::CONSENSUS_VERSION_HEIGHTS().iter() {
526            let max_program_size = consensus_config_value!(N, MAX_PROGRAM_SIZE, *height).unwrap();
527            let max_transaction_size = consensus_config_value!(N, MAX_TRANSACTION_SIZE, *height).unwrap();
528
529            assert!(
530                max_transaction_size >= max_program_size + MIN_OVERHEAD,
531                "At height {height}: MAX_TRANSACTION_SIZE ({max_transaction_size}) must be at least {MIN_OVERHEAD} bytes greater than MAX_PROGRAM_SIZE ({max_program_size})"
532            );
533        }
534    }
535
536    /// Ensure that `MAX_PROGRAM_SIZE` and `MAX_TRANSACTION_SIZE` are defined in lockstep:
537    /// the same number of entries, keyed by the same consensus versions in the same order, with the
538    /// transaction size strictly exceeding the program size at every version. The latest transaction
539    /// size must likewise exceed the latest program size, since a transaction must hold a program
540    /// plus its proofs, signatures, and metadata.
541    fn program_and_transaction_size_aligned<N: Network>() {
542        // Ensure both constants define the same number of entries.
543        assert_eq!(
544            N::MAX_PROGRAM_SIZE.len(),
545            N::MAX_TRANSACTION_SIZE.len(),
546            "MAX_PROGRAM_SIZE and MAX_TRANSACTION_SIZE must define the same number of entries"
547        );
548        // Ensure both constants are keyed by the same consensus versions, in the same order, and that
549        // the transaction size exceeds the program size at each corresponding version.
550        for (index, (program_version, program_size)) in N::MAX_PROGRAM_SIZE.iter().enumerate() {
551            let (transaction_version, transaction_size) = &N::MAX_TRANSACTION_SIZE[index];
552            assert_eq!(
553                program_version, transaction_version,
554                "MAX_PROGRAM_SIZE and MAX_TRANSACTION_SIZE must be keyed by the same consensus version at index {index}, but found {program_version} and {transaction_version}"
555            );
556            assert!(
557                transaction_size > program_size,
558                "At consensus version {program_version}: MAX_TRANSACTION_SIZE ({transaction_size}) must be greater than MAX_PROGRAM_SIZE ({program_size})"
559            );
560        }
561        // Ensure the latest transaction size exceeds the latest program size.
562        assert!(
563            N::LATEST_MAX_TRANSACTION_SIZE() > N::LATEST_MAX_PROGRAM_SIZE(),
564            "LATEST_MAX_TRANSACTION_SIZE ({}) must be greater than LATEST_MAX_PROGRAM_SIZE ({})",
565            N::LATEST_MAX_TRANSACTION_SIZE(),
566            N::LATEST_MAX_PROGRAM_SIZE()
567        );
568    }
569
570    /// Ensure that the number of constant definitions is the same across networks.
571    fn constants_equal_length<N1: Network, N2: Network, N3: Network>() {
572        // If we can construct an array, that means the underlying types must be the same.
573        let _ = [N1::CONSENSUS_VERSION_HEIGHTS, N2::CONSENSUS_VERSION_HEIGHTS, N3::CONSENSUS_VERSION_HEIGHTS];
574        let _ = [N1::MAX_CERTIFICATES, N2::MAX_CERTIFICATES, N3::MAX_CERTIFICATES];
575        let _ = [N1::TRANSACTION_SPEND_LIMIT, N2::TRANSACTION_SPEND_LIMIT, N3::TRANSACTION_SPEND_LIMIT];
576        let _ =
577            [N1::CREDITS_PER_SECOND_OF_RUNTIME, N2::CREDITS_PER_SECOND_OF_RUNTIME, N3::CREDITS_PER_SECOND_OF_RUNTIME];
578        let _ = [N1::MAX_ARRAY_ELEMENTS, N2::MAX_ARRAY_ELEMENTS, N3::MAX_ARRAY_ELEMENTS];
579        let _ = [N1::MAX_PROGRAM_SIZE, N2::MAX_PROGRAM_SIZE, N3::MAX_PROGRAM_SIZE];
580        let _ = [N1::MAX_TRANSACTION_SIZE, N2::MAX_TRANSACTION_SIZE, N3::MAX_TRANSACTION_SIZE];
581        let _ = [N1::MAX_WRITES, N2::MAX_WRITES, N3::MAX_WRITES];
582        let _ = [N1::ANCHOR_TIMES, N2::ANCHOR_TIMES, N3::ANCHOR_TIMES];
583    }
584
585    /// Ensure that `LATEST_MAX_*` functions return valid values without panicking.
586    /// These functions use `.expect()` internally, so this test verifies the arrays are non-empty.
587    fn latest_max_functions_are_safe<N: Network>() {
588        // Verify LATEST_MAX_CERTIFICATES returns a positive value.
589        assert!(N::LATEST_MAX_CERTIFICATES() > 0, "LATEST_MAX_CERTIFICATES must be positive");
590        // Verify LATEST_MAX_PROGRAM_SIZE returns a positive value.
591        assert!(N::LATEST_MAX_PROGRAM_SIZE() > 0, "LATEST_MAX_PROGRAM_SIZE must be positive");
592        // Verify LATEST_MAX_TRANSACTION_SIZE returns a positive value.
593        assert!(N::LATEST_MAX_TRANSACTION_SIZE() > 0, "LATEST_MAX_TRANSACTION_SIZE must be positive");
594        // Verify LATEST_MAX_WRITES returns a positive value.
595        assert!(N::LATEST_MAX_WRITES() > 0, "LATEST_MAX_WRITES must be positive");
596    }
597
598    #[test]
599    #[allow(clippy::assertions_on_constants)]
600    fn test_consensus_constants() {
601        consensus_constants_at_genesis::<MainnetV0>();
602        consensus_constants_at_genesis::<TestnetV0>();
603        consensus_constants_at_genesis::<CanaryV0>();
604
605        consensus_versions::<MainnetV0>();
606        consensus_versions::<TestnetV0>();
607        consensus_versions::<CanaryV0>();
608
609        consensus_constants_increasing_heights::<MainnetV0>();
610        consensus_constants_increasing_heights::<TestnetV0>();
611        consensus_constants_increasing_heights::<CanaryV0>();
612
613        consensus_constants_valid_heights::<MainnetV0>();
614        consensus_constants_valid_heights::<TestnetV0>();
615        consensus_constants_valid_heights::<CanaryV0>();
616
617        consensus_config_returns_some::<MainnetV0>();
618        consensus_config_returns_some::<TestnetV0>();
619        consensus_config_returns_some::<CanaryV0>();
620
621        max_certificates_increasing::<MainnetV0>();
622        max_certificates_increasing::<TestnetV0>();
623        max_certificates_increasing::<CanaryV0>();
624
625        max_array_elements_increasing::<MainnetV0>();
626        max_array_elements_increasing::<TestnetV0>();
627        max_array_elements_increasing::<CanaryV0>();
628
629        transaction_size_exceeds_program_size::<MainnetV0>();
630        transaction_size_exceeds_program_size::<TestnetV0>();
631        transaction_size_exceeds_program_size::<CanaryV0>();
632
633        program_and_transaction_size_aligned::<MainnetV0>();
634        program_and_transaction_size_aligned::<TestnetV0>();
635        program_and_transaction_size_aligned::<CanaryV0>();
636
637        latest_max_functions_are_safe::<MainnetV0>();
638        latest_max_functions_are_safe::<TestnetV0>();
639        latest_max_functions_are_safe::<CanaryV0>();
640
641        constants_equal_length::<MainnetV0, TestnetV0, CanaryV0>();
642    }
643
644    /// Ensure (de-)serialization works correctly.
645    #[test]
646    fn test_to_bytes() {
647        let version = ConsensusVersion::V8;
648        let bytes = version.to_bytes_le().unwrap();
649        let result = ConsensusVersion::from_bytes_le(&bytes).unwrap();
650        assert_eq!(result, version);
651
652        let version = ConsensusVersion::latest();
653        let bytes = version.to_bytes_le().unwrap();
654        let result = ConsensusVersion::from_bytes_le(&bytes).unwrap();
655        assert_eq!(result, version);
656
657        let invalid_bytes = u16::MAX.to_bytes_le().unwrap();
658        let result = ConsensusVersion::from_bytes_le(&invalid_bytes);
659        assert!(result.is_err());
660    }
661
662    #[test]
663    fn test_reward_anchor_time() {
664        assert_eq!(MainnetV0::REWARD_ANCHOR_TIME, MainnetV0::ANCHOR_TIMES.first().unwrap().1);
665        assert_eq!(TestnetV0::REWARD_ANCHOR_TIME, TestnetV0::ANCHOR_TIMES.first().unwrap().1);
666        assert_eq!(CanaryV0::REWARD_ANCHOR_TIME, CanaryV0::ANCHOR_TIMES.first().unwrap().1);
667    }
668
669    #[test]
670    fn test_varuna_version_from_consensus() {
671        // First boundary: V4
672        assert_eq!(varuna_version_from_consensus(ConsensusVersion::V3), VarunaVersion::V1);
673        assert_eq!(varuna_version_from_consensus(ConsensusVersion::V4), VarunaVersion::V2);
674    }
675}