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