snarkvm_console_network/
lib.rs

1// Copyright 2024 Aleo Network Foundation
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
16#![forbid(unsafe_code)]
17#![allow(clippy::too_many_arguments)]
18#![warn(clippy::cast_possible_truncation)]
19
20#[macro_use]
21extern crate lazy_static;
22
23pub use snarkvm_console_network_environment as environment;
24pub use snarkvm_console_network_environment::*;
25
26mod helpers;
27pub use helpers::*;
28
29mod canary_v0;
30pub use canary_v0::*;
31
32mod mainnet_v0;
33pub use mainnet_v0::*;
34
35mod testnet_v0;
36pub use testnet_v0::*;
37
38pub mod prelude {
39    pub use crate::{ConsensusVersion, Network, consensus_config_value, environment::prelude::*};
40}
41
42use crate::environment::prelude::*;
43use snarkvm_algorithms::{
44    AlgebraicSponge,
45    crypto_hash::PoseidonSponge,
46    snark::varuna::{CircuitProvingKey, CircuitVerifyingKey, VarunaHidingMode},
47    srs::{UniversalProver, UniversalVerifier},
48};
49use snarkvm_console_algorithms::{BHP512, BHP1024, Poseidon2, Poseidon4};
50use snarkvm_console_collections::merkle_tree::{MerklePath, MerkleTree};
51use snarkvm_console_types::{Field, Group, Scalar};
52use snarkvm_curves::PairingEngine;
53
54use indexmap::IndexMap;
55use once_cell::sync::OnceCell;
56use std::sync::Arc;
57
58/// A helper type for the BHP Merkle tree.
59pub type BHPMerkleTree<N, const DEPTH: u8> = MerkleTree<N, BHP1024<N>, BHP512<N>, DEPTH>;
60/// A helper type for the Poseidon Merkle tree.
61pub type PoseidonMerkleTree<N, const DEPTH: u8> = MerkleTree<N, Poseidon4<N>, Poseidon2<N>, DEPTH>;
62
63/// Helper types for the Varuna parameters.
64type Fq<N> = <<N as Environment>::PairingCurve as PairingEngine>::Fq;
65pub type FiatShamir<N> = PoseidonSponge<Fq<N>, 2, 1>;
66pub type FiatShamirParameters<N> = <FiatShamir<N> as AlgebraicSponge<Fq<N>, 2>>::Parameters;
67
68/// Helper types for the Varuna proving and verifying key.
69pub(crate) type VarunaProvingKey<N> = CircuitProvingKey<<N as Environment>::PairingCurve, VarunaHidingMode>;
70pub(crate) type VarunaVerifyingKey<N> = CircuitVerifyingKey<<N as Environment>::PairingCurve>;
71
72/// The different consensus versions.
73/// Documentation for what is changed at each version can be found in `N::CONSENSUS_VERSION`
74#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd)]
75pub enum ConsensusVersion {
76    V1 = 1,
77    V2 = 2,
78    V3 = 3,
79    V4 = 4,
80}
81
82pub trait Network:
83    'static
84    + Environment
85    + Copy
86    + Clone
87    + Debug
88    + Eq
89    + PartialEq
90    + core::hash::Hash
91    + Serialize
92    + DeserializeOwned
93    + for<'a> Deserialize<'a>
94    + Send
95    + Sync
96{
97    /// The network ID.
98    const ID: u16;
99    /// The network name.
100    const NAME: &'static str;
101    /// The network edition.
102    const EDITION: u16;
103
104    /// The function name for the inclusion circuit.
105    const INCLUSION_FUNCTION_NAME: &'static str;
106
107    /// The fixed timestamp of the genesis block.
108    const GENESIS_TIMESTAMP: i64;
109    /// The genesis block coinbase target.
110    const GENESIS_COINBASE_TARGET: u64;
111    /// The genesis block proof target.
112    const GENESIS_PROOF_TARGET: u64;
113    /// The maximum number of solutions that can be included per block as a power of 2.
114    const MAX_SOLUTIONS_AS_POWER_OF_TWO: u8 = 2; // 4 solutions
115    /// The maximum number of solutions that can be included per block.
116    const MAX_SOLUTIONS: usize = 1 << Self::MAX_SOLUTIONS_AS_POWER_OF_TWO; // 4 solutions
117
118    /// The starting supply of Aleo credits.
119    const STARTING_SUPPLY: u64 = 1_500_000_000_000_000; // 1.5B credits
120    /// The cost in microcredits per byte for the deployment transaction.
121    const DEPLOYMENT_FEE_MULTIPLIER: u64 = 1_000; // 1 millicredit per byte
122    /// The constant that divides the storage polynomial.
123    const EXECUTION_STORAGE_FEE_SCALING_FACTOR: u64 = 5000;
124    /// The maximum size execution transactions can be before a quadratic storage penalty applies.
125    const EXECUTION_STORAGE_PENALTY_THRESHOLD: u64 = 5000;
126    /// The cost in microcredits per constraint for the deployment transaction.
127    const SYNTHESIS_FEE_MULTIPLIER: u64 = 25; // 25 microcredits per constraint
128    /// The maximum number of variables in a deployment.
129    const MAX_DEPLOYMENT_VARIABLES: u64 = 1 << 20; // 1,048,576 variables
130    /// The maximum number of constraints in a deployment.
131    const MAX_DEPLOYMENT_CONSTRAINTS: u64 = 1 << 20; // 1,048,576 constraints
132    /// The maximum number of microcredits that can be spent as a fee.
133    const MAX_FEE: u64 = 1_000_000_000_000_000;
134    /// The maximum number of microcredits that can be spent on a finalize block.
135    const TRANSACTION_SPEND_LIMIT: u64 = 100_000_000;
136
137    /// The anchor height, defined as the expected number of blocks to reach the coinbase target.
138    const ANCHOR_HEIGHT: u32 = Self::ANCHOR_TIME as u32 / Self::BLOCK_TIME as u32;
139    /// The anchor time in seconds.
140    const ANCHOR_TIME: u16 = 25;
141    /// The expected time per block in seconds.
142    const BLOCK_TIME: u16 = 10;
143    /// The number of blocks per epoch.
144    const NUM_BLOCKS_PER_EPOCH: u32 = 3600 / Self::BLOCK_TIME as u32; // 360 blocks == ~1 hour
145
146    /// The maximum number of entries in data.
147    const MAX_DATA_ENTRIES: usize = 32;
148    /// The maximum recursive depth of an entry.
149    /// Note: This value must be strictly less than u8::MAX.
150    const MAX_DATA_DEPTH: usize = 32;
151    /// The maximum number of fields in data (must not exceed u16::MAX).
152    #[allow(clippy::cast_possible_truncation)]
153    const MAX_DATA_SIZE_IN_FIELDS: u32 = ((128 * 1024 * 8) / Field::<Self>::SIZE_IN_DATA_BITS) as u32;
154
155    /// The minimum number of entries in a struct.
156    const MIN_STRUCT_ENTRIES: usize = 1; // This ensures the struct is not empty.
157    /// The maximum number of entries in a struct.
158    const MAX_STRUCT_ENTRIES: usize = Self::MAX_DATA_ENTRIES;
159
160    /// The minimum number of elements in an array.
161    const MIN_ARRAY_ELEMENTS: usize = 1; // This ensures the array is not empty.
162    /// The maximum number of elements in an array.
163    const MAX_ARRAY_ELEMENTS: usize = Self::MAX_DATA_ENTRIES;
164
165    /// The minimum number of entries in a record.
166    const MIN_RECORD_ENTRIES: usize = 1; // This accounts for 'record.owner'.
167    /// The maximum number of entries in a record.
168    const MAX_RECORD_ENTRIES: usize = Self::MIN_RECORD_ENTRIES.saturating_add(Self::MAX_DATA_ENTRIES);
169
170    /// The maximum program size by number of characters.
171    const MAX_PROGRAM_SIZE: usize = 100_000; // 100 KB
172
173    /// The maximum number of mappings in a program.
174    const MAX_MAPPINGS: usize = 31;
175    /// The maximum number of functions in a program.
176    const MAX_FUNCTIONS: usize = 31;
177    /// The maximum number of structs in a program.
178    const MAX_STRUCTS: usize = 10 * Self::MAX_FUNCTIONS;
179    /// The maximum number of records in a program.
180    const MAX_RECORDS: usize = 10 * Self::MAX_FUNCTIONS;
181    /// The maximum number of closures in a program.
182    const MAX_CLOSURES: usize = 2 * Self::MAX_FUNCTIONS;
183    /// The maximum number of operands in an instruction.
184    const MAX_OPERANDS: usize = Self::MAX_INPUTS;
185    /// The maximum number of instructions in a closure or function.
186    const MAX_INSTRUCTIONS: usize = u16::MAX as usize;
187    /// The maximum number of commands in finalize.
188    const MAX_COMMANDS: usize = u16::MAX as usize;
189    /// The maximum number of write commands in finalize.
190    const MAX_WRITES: u16 = 16;
191
192    /// The maximum number of inputs per transition.
193    const MAX_INPUTS: usize = 16;
194    /// The maximum number of outputs per transition.
195    const MAX_OUTPUTS: usize = 16;
196
197    /// The maximum program depth.
198    const MAX_PROGRAM_DEPTH: usize = 64;
199    /// The maximum number of imports.
200    const MAX_IMPORTS: usize = 64;
201
202    /// The maximum number of bytes in a transaction.
203    // Note: This value must **not** be decreased as it would invalidate existing transactions.
204    const MAX_TRANSACTION_SIZE: usize = 128_000; // 128 kB
205
206    /// The state root type.
207    type StateRoot: Bech32ID<Field<Self>>;
208    /// The block hash type.
209    type BlockHash: Bech32ID<Field<Self>>;
210    /// The ratification ID type.
211    type RatificationID: Bech32ID<Field<Self>>;
212    /// The transaction ID type.
213    type TransactionID: Bech32ID<Field<Self>>;
214    /// The transition ID type.
215    type TransitionID: Bech32ID<Field<Self>>;
216    /// The transmission checksum type.
217    type TransmissionChecksum: IntegerType;
218
219    /// A list of (consensus_version, block_height) pairs indicating when each consensus version takes effect.
220    /// Documentation for what is changed at each version can be found in `N::CONSENSUS_VERSION`
221    const CONSENSUS_VERSION_HEIGHTS: [(ConsensusVersion, u32); 4];
222    ///  A list of (consensus_version, size) pairs indicating the maximum number of validators in a committee.
223    //  Note: This value must **not** decrease without considering the impact on serialization.
224    //  Decreasing this value will break backwards compatibility of serialization without explicit
225    //  declaration of migration based on round number rather than block height.
226    //  Increasing this value will require a migration to prevent forking during network upgrades.
227    const MAX_CERTIFICATES: [(ConsensusVersion, u16); 2];
228
229    /// Returns the consensus version which is active at the given height.
230    ///
231    /// V1: The initial genesis consensus version.
232    ///
233    /// V2: Update to the block reward and execution cost algorithms.
234    ///
235    /// V3: Update to the number of validators and finalize scope RNG seed.
236    #[allow(non_snake_case)]
237    fn CONSENSUS_VERSION(seek_height: u32) -> anyhow::Result<ConsensusVersion> {
238        match Self::CONSENSUS_VERSION_HEIGHTS.binary_search_by(|(_, height)| height.cmp(&seek_height)) {
239            // If a consensus version was found at this height, return it.
240            Ok(index) => Ok(Self::CONSENSUS_VERSION_HEIGHTS[index].0),
241            // If the specified height was not found, determine whether to return an appropriate version.
242            Err(index) => {
243                if index == 0 {
244                    Err(anyhow!("Expected consensus version 1 to exist at height 0."))
245                } else {
246                    // Return the appropriate version belonging to the height *lower* than the sought height.
247                    Ok(Self::CONSENSUS_VERSION_HEIGHTS[index - 1].0)
248                }
249            }
250        }
251    }
252    /// Returns the height at which a specified consensus version becomes active.
253    #[allow(non_snake_case)]
254    fn CONSENSUS_HEIGHT(version: ConsensusVersion) -> Result<u32> {
255        Ok(Self::CONSENSUS_VERSION_HEIGHTS.get(version as usize - 1).ok_or(anyhow!("Invalid consensus version"))?.1)
256    }
257    /// Returns the last `MAX_CERTIFICATES` value.
258    #[allow(non_snake_case)]
259    fn LATEST_MAX_CERTIFICATES() -> Result<u16> {
260        Self::MAX_CERTIFICATES.last().map_or(Err(anyhow!("No MAX_CERTIFICATES defined.")), |(_, value)| Ok(*value))
261    }
262
263    /// Returns the genesis block bytes.
264    fn genesis_bytes() -> &'static [u8];
265
266    /// Returns the restrictions list as a JSON-compatible string.
267    fn restrictions_list_as_str() -> &'static str;
268
269    /// Returns the proving key for the given function name in `credits.aleo`.
270    fn get_credits_proving_key(function_name: String) -> Result<&'static Arc<VarunaProvingKey<Self>>>;
271
272    /// Returns the verifying key for the given function name in `credits.aleo`.
273    fn get_credits_verifying_key(function_name: String) -> Result<&'static Arc<VarunaVerifyingKey<Self>>>;
274
275    /// Returns the `proving key` for the inclusion circuit.
276    fn inclusion_proving_key() -> &'static Arc<VarunaProvingKey<Self>>;
277
278    /// Returns the `verifying key` for the inclusion circuit.
279    fn inclusion_verifying_key() -> &'static Arc<VarunaVerifyingKey<Self>>;
280
281    /// Returns the powers of `G`.
282    fn g_powers() -> &'static Vec<Group<Self>>;
283
284    /// Returns the scalar multiplication on the generator `G`.
285    fn g_scalar_multiply(scalar: &Scalar<Self>) -> Group<Self>;
286
287    /// Returns the Varuna universal prover.
288    fn varuna_universal_prover() -> &'static UniversalProver<Self::PairingCurve>;
289
290    /// Returns the Varuna universal verifier.
291    fn varuna_universal_verifier() -> &'static UniversalVerifier<Self::PairingCurve>;
292
293    /// Returns the sponge parameters for Varuna.
294    fn varuna_fs_parameters() -> &'static FiatShamirParameters<Self>;
295
296    /// Returns the encryption domain as a constant field element.
297    fn encryption_domain() -> Field<Self>;
298
299    /// Returns the graph key domain as a constant field element.
300    fn graph_key_domain() -> Field<Self>;
301
302    /// Returns the serial number domain as a constant field element.
303    fn serial_number_domain() -> Field<Self>;
304
305    /// Returns a BHP commitment with an input hasher of 256-bits and randomizer.
306    fn commit_bhp256(input: &[bool], randomizer: &Scalar<Self>) -> Result<Field<Self>>;
307
308    /// Returns a BHP commitment with an input hasher of 512-bits and randomizer.
309    fn commit_bhp512(input: &[bool], randomizer: &Scalar<Self>) -> Result<Field<Self>>;
310
311    /// Returns a BHP commitment with an input hasher of 768-bits and randomizer.
312    fn commit_bhp768(input: &[bool], randomizer: &Scalar<Self>) -> Result<Field<Self>>;
313
314    /// Returns a BHP commitment with an input hasher of 1024-bits and randomizer.
315    fn commit_bhp1024(input: &[bool], randomizer: &Scalar<Self>) -> Result<Field<Self>>;
316
317    /// Returns a Pedersen commitment for the given (up to) 64-bit input and randomizer.
318    fn commit_ped64(input: &[bool], randomizer: &Scalar<Self>) -> Result<Field<Self>>;
319
320    /// Returns a Pedersen commitment for the given (up to) 128-bit input and randomizer.
321    fn commit_ped128(input: &[bool], randomizer: &Scalar<Self>) -> Result<Field<Self>>;
322
323    /// Returns a BHP commitment with an input hasher of 256-bits and randomizer.
324    fn commit_to_group_bhp256(input: &[bool], randomizer: &Scalar<Self>) -> Result<Group<Self>>;
325
326    /// Returns a BHP commitment with an input hasher of 512-bits and randomizer.
327    fn commit_to_group_bhp512(input: &[bool], randomizer: &Scalar<Self>) -> Result<Group<Self>>;
328
329    /// Returns a BHP commitment with an input hasher of 768-bits and randomizer.
330    fn commit_to_group_bhp768(input: &[bool], randomizer: &Scalar<Self>) -> Result<Group<Self>>;
331
332    /// Returns a BHP commitment with an input hasher of 1024-bits and randomizer.
333    fn commit_to_group_bhp1024(input: &[bool], randomizer: &Scalar<Self>) -> Result<Group<Self>>;
334
335    /// Returns a Pedersen commitment for the given (up to) 64-bit input and randomizer.
336    fn commit_to_group_ped64(input: &[bool], randomizer: &Scalar<Self>) -> Result<Group<Self>>;
337
338    /// Returns a Pedersen commitment for the given (up to) 128-bit input and randomizer.
339    fn commit_to_group_ped128(input: &[bool], randomizer: &Scalar<Self>) -> Result<Group<Self>>;
340
341    /// Returns the BHP hash with an input hasher of 256-bits.
342    fn hash_bhp256(input: &[bool]) -> Result<Field<Self>>;
343
344    /// Returns the BHP hash with an input hasher of 512-bits.
345    fn hash_bhp512(input: &[bool]) -> Result<Field<Self>>;
346
347    /// Returns the BHP hash with an input hasher of 768-bits.
348    fn hash_bhp768(input: &[bool]) -> Result<Field<Self>>;
349
350    /// Returns the BHP hash with an input hasher of 1024-bits.
351    fn hash_bhp1024(input: &[bool]) -> Result<Field<Self>>;
352
353    /// Returns the Keccak hash with a 256-bit output.
354    fn hash_keccak256(input: &[bool]) -> Result<Vec<bool>>;
355
356    /// Returns the Keccak hash with a 384-bit output.
357    fn hash_keccak384(input: &[bool]) -> Result<Vec<bool>>;
358
359    /// Returns the Keccak hash with a 512-bit output.
360    fn hash_keccak512(input: &[bool]) -> Result<Vec<bool>>;
361
362    /// Returns the Pedersen hash for a given (up to) 64-bit input.
363    fn hash_ped64(input: &[bool]) -> Result<Field<Self>>;
364
365    /// Returns the Pedersen hash for a given (up to) 128-bit input.
366    fn hash_ped128(input: &[bool]) -> Result<Field<Self>>;
367
368    /// Returns the Poseidon hash with an input rate of 2.
369    fn hash_psd2(input: &[Field<Self>]) -> Result<Field<Self>>;
370
371    /// Returns the Poseidon hash with an input rate of 4.
372    fn hash_psd4(input: &[Field<Self>]) -> Result<Field<Self>>;
373
374    /// Returns the Poseidon hash with an input rate of 8.
375    fn hash_psd8(input: &[Field<Self>]) -> Result<Field<Self>>;
376
377    /// Returns the SHA-3 hash with a 256-bit output.
378    fn hash_sha3_256(input: &[bool]) -> Result<Vec<bool>>;
379
380    /// Returns the SHA-3 hash with a 384-bit output.
381    fn hash_sha3_384(input: &[bool]) -> Result<Vec<bool>>;
382
383    /// Returns the SHA-3 hash with a 512-bit output.
384    fn hash_sha3_512(input: &[bool]) -> Result<Vec<bool>>;
385
386    /// Returns the extended Poseidon hash with an input rate of 2.
387    fn hash_many_psd2(input: &[Field<Self>], num_outputs: u16) -> Vec<Field<Self>>;
388
389    /// Returns the extended Poseidon hash with an input rate of 4.
390    fn hash_many_psd4(input: &[Field<Self>], num_outputs: u16) -> Vec<Field<Self>>;
391
392    /// Returns the extended Poseidon hash with an input rate of 8.
393    fn hash_many_psd8(input: &[Field<Self>], num_outputs: u16) -> Vec<Field<Self>>;
394
395    /// Returns the BHP hash with an input hasher of 256-bits.
396    fn hash_to_group_bhp256(input: &[bool]) -> Result<Group<Self>>;
397
398    /// Returns the BHP hash with an input hasher of 512-bits.
399    fn hash_to_group_bhp512(input: &[bool]) -> Result<Group<Self>>;
400
401    /// Returns the BHP hash with an input hasher of 768-bits.
402    fn hash_to_group_bhp768(input: &[bool]) -> Result<Group<Self>>;
403
404    /// Returns the BHP hash with an input hasher of 1024-bits.
405    fn hash_to_group_bhp1024(input: &[bool]) -> Result<Group<Self>>;
406
407    /// Returns the Pedersen hash for a given (up to) 64-bit input.
408    fn hash_to_group_ped64(input: &[bool]) -> Result<Group<Self>>;
409
410    /// Returns the Pedersen hash for a given (up to) 128-bit input.
411    fn hash_to_group_ped128(input: &[bool]) -> Result<Group<Self>>;
412
413    /// Returns the Poseidon hash with an input rate of 2 on the affine curve.
414    fn hash_to_group_psd2(input: &[Field<Self>]) -> Result<Group<Self>>;
415
416    /// Returns the Poseidon hash with an input rate of 4 on the affine curve.
417    fn hash_to_group_psd4(input: &[Field<Self>]) -> Result<Group<Self>>;
418
419    /// Returns the Poseidon hash with an input rate of 8 on the affine curve.
420    fn hash_to_group_psd8(input: &[Field<Self>]) -> Result<Group<Self>>;
421
422    /// Returns the Poseidon hash with an input rate of 2 on the scalar field.
423    fn hash_to_scalar_psd2(input: &[Field<Self>]) -> Result<Scalar<Self>>;
424
425    /// Returns the Poseidon hash with an input rate of 4 on the scalar field.
426    fn hash_to_scalar_psd4(input: &[Field<Self>]) -> Result<Scalar<Self>>;
427
428    /// Returns the Poseidon hash with an input rate of 8 on the scalar field.
429    fn hash_to_scalar_psd8(input: &[Field<Self>]) -> Result<Scalar<Self>>;
430
431    /// Returns a Merkle tree with a BHP leaf hasher of 1024-bits and a BHP path hasher of 512-bits.
432    fn merkle_tree_bhp<const DEPTH: u8>(leaves: &[Vec<bool>]) -> Result<BHPMerkleTree<Self, DEPTH>>;
433
434    /// Returns a Merkle tree with a Poseidon leaf hasher with input rate of 4 and a Poseidon path hasher with input rate of 2.
435    fn merkle_tree_psd<const DEPTH: u8>(leaves: &[Vec<Field<Self>>]) -> Result<PoseidonMerkleTree<Self, DEPTH>>;
436
437    /// Returns `true` if the given Merkle path is valid for the given root and leaf.
438    #[allow(clippy::ptr_arg)]
439    fn verify_merkle_path_bhp<const DEPTH: u8>(
440        path: &MerklePath<Self, DEPTH>,
441        root: &Field<Self>,
442        leaf: &Vec<bool>,
443    ) -> bool;
444
445    /// Returns `true` if the given Merkle path is valid for the given root and leaf.
446    #[allow(clippy::ptr_arg)]
447    fn verify_merkle_path_psd<const DEPTH: u8>(
448        path: &MerklePath<Self, DEPTH>,
449        root: &Field<Self>,
450        leaf: &Vec<Field<Self>>,
451    ) -> bool;
452}
453
454/// Returns the consensus configuration value for the specified height.
455///
456/// Arguments:
457/// - `$network`: The network to use the constant of.
458/// - `$constant`: The constant to search a value of.
459/// - `$seek_height`: The block height to search the value for.
460#[macro_export]
461macro_rules! consensus_config_value {
462    ($network:ident, $constant:ident, $seek_height:expr) => {
463        // Search the consensus version enacted at the specified height.
464        $network::CONSENSUS_VERSION($seek_height).map_or(None, |seek_version| {
465            // Search the consensus value for the specified version.
466            match $network::$constant.binary_search_by(|(version, _)| version.cmp(&seek_version)) {
467                // If a value was found for this consensus version, return it.
468                Ok(index) => Some($network::$constant[index].1),
469                // If the specified version was not found exactly, determine whether to return an appropriate value anyway.
470                Err(index) => {
471                    // This constant is not yet in effect at this consensus version.
472                    if index == 0 {
473                        None
474                    // Return the appropriate value belonging to the consensus version *lower* than the sought version.
475                    } else {
476                        Some($network::$constant[index - 1].1)
477                    }
478                }
479            }
480        })
481    };
482}
483
484#[cfg(test)]
485mod tests {
486    use super::*;
487
488    /// Ensure that the consensus constants are defined and correct at genesis.
489    /// It is possible this invariant no longer holds in the future, e.g. due to pruning or novel types of constants.
490    fn consensus_constants_at_genesis<N: Network>() {
491        let height = N::CONSENSUS_VERSION_HEIGHTS.first().unwrap().1;
492        assert_eq!(height, 0);
493        let consensus_version = N::CONSENSUS_VERSION_HEIGHTS.first().unwrap().0;
494        assert_eq!(consensus_version, ConsensusVersion::V1);
495        assert_eq!(consensus_version as usize, 1);
496    }
497
498    /// Ensure that the consensus *versions* are unique, incrementing and start with 1.
499    fn consensus_versions<N: Network>() {
500        let mut previous_version = N::CONSENSUS_VERSION_HEIGHTS.first().unwrap().0;
501        // Ensure that the consensus versions start with 1.
502        assert_eq!(previous_version as usize, 1);
503        // Ensure that the consensus versions are unique and incrementing by 1.
504        for (version, _) in N::CONSENSUS_VERSION_HEIGHTS.iter().skip(1) {
505            assert_eq!(*version as usize, previous_version as usize + 1);
506            previous_version = *version;
507        }
508        // Ensure that the consensus versions are unique and incrementing.
509        let mut previous_version = N::MAX_CERTIFICATES.first().unwrap().0;
510        for (version, _) in N::MAX_CERTIFICATES.iter().skip(1) {
511            assert!(*version > previous_version);
512            previous_version = *version;
513        }
514    }
515
516    /// Ensure that consensus *heights* are unique and incrementing.
517    fn consensus_constants_increasing_heights<N: Network>() {
518        let mut previous_height = N::CONSENSUS_VERSION_HEIGHTS.first().unwrap().1;
519        for (version, height) in N::CONSENSUS_VERSION_HEIGHTS.iter().skip(1) {
520            assert!(*height > previous_height);
521            previous_height = *height;
522            // Ensure that N::CONSENSUS_VERSION returns the expected value.
523            assert_eq!(N::CONSENSUS_VERSION(*height).unwrap(), *version);
524            // Ensure that N::CONSENSUS_HEIGHT returns the expected value.
525            assert_eq!(N::CONSENSUS_HEIGHT(*version).unwrap(), *height);
526        }
527    }
528
529    /// Ensure that version of all consensus-relevant constants are present in the consensus version heights.
530    fn consensus_constants_valid_heights<N: Network>() {
531        for (version, value) in N::MAX_CERTIFICATES.iter() {
532            // Ensure that the height at which an update occurs are present in CONSENSUS_VERSION_HEIGHTS.
533            let height = N::CONSENSUS_VERSION_HEIGHTS.iter().find(|(c_version, _)| *c_version == *version).unwrap().1;
534            // Double-check that consensus_config_value returns the correct value.
535            assert_eq!(consensus_config_value!(N, MAX_CERTIFICATES, height).unwrap(), *value);
536        }
537    }
538
539    /// Ensure that `MAX_CERTIFICATES` increases and is correctly defined.
540    /// See the constant declaration for an explanation why.
541    fn max_certificates_increasing<N: Network>() {
542        let mut previous_value = N::MAX_CERTIFICATES.first().unwrap().1;
543        for (_, value) in N::MAX_CERTIFICATES.iter().skip(1) {
544            assert!(*value >= previous_value);
545            previous_value = *value;
546        }
547    }
548
549    /// Ensure that the number of constant definitions is the same across networks.
550    fn constants_equal_length<N1: Network, N2: Network, N3: Network>() {
551        // If we can construct an array, that means the underlying types must be the same.
552        let _ = [N1::CONSENSUS_VERSION_HEIGHTS, N2::CONSENSUS_VERSION_HEIGHTS, N3::CONSENSUS_VERSION_HEIGHTS];
553        let _ = [N1::MAX_CERTIFICATES, N2::MAX_CERTIFICATES, N3::MAX_CERTIFICATES];
554    }
555
556    #[test]
557    #[allow(clippy::assertions_on_constants)]
558    fn test_consensus_constants() {
559        consensus_constants_at_genesis::<MainnetV0>();
560        consensus_constants_at_genesis::<TestnetV0>();
561        consensus_constants_at_genesis::<CanaryV0>();
562
563        consensus_versions::<MainnetV0>();
564        consensus_versions::<TestnetV0>();
565        consensus_versions::<CanaryV0>();
566
567        consensus_constants_increasing_heights::<MainnetV0>();
568        consensus_constants_increasing_heights::<TestnetV0>();
569        consensus_constants_increasing_heights::<CanaryV0>();
570
571        consensus_constants_valid_heights::<MainnetV0>();
572        consensus_constants_valid_heights::<TestnetV0>();
573        consensus_constants_valid_heights::<CanaryV0>();
574
575        max_certificates_increasing::<MainnetV0>();
576        max_certificates_increasing::<TestnetV0>();
577        max_certificates_increasing::<CanaryV0>();
578
579        constants_equal_length::<MainnetV0, TestnetV0, CanaryV0>();
580    }
581}