Skip to main content

snarkvm_console_network/
mainnet_v0.rs

1// Copyright (c) 2019-2026 Provable Inc.
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::*;
17use snarkvm_console_algorithms::{
18    BHP256,
19    BHP512,
20    BHP768,
21    BHP1024,
22    Blake2Xs,
23    Keccak256,
24    Keccak384,
25    Keccak512,
26    Pedersen64,
27    Pedersen128,
28    Poseidon2,
29    Poseidon4,
30    Poseidon8,
31    Sha3_256,
32    Sha3_384,
33    Sha3_512,
34};
35
36lazy_static! {
37    /// The group bases for the Aleo signature and encryption schemes.
38    pub static ref GENERATOR_G: Vec<Group<MainnetV0 >> = MainnetV0::new_bases("AleoAccountEncryptionAndSignatureScheme0");
39
40    /// The Varuna sponge parameters.
41    pub static ref VARUNA_FS_PARAMETERS: FiatShamirParameters<MainnetV0> = FiatShamir::<MainnetV0>::sample_parameters();
42
43    /// The commitment domain as a constant field element.
44    static ref COMMITMENT_DOMAIN: Field<MainnetV0> = Field::<MainnetV0>::new_domain_separator("AleoCommitment0");
45    /// The encryption domain as a constant field element.
46    pub static ref ENCRYPTION_DOMAIN: Field<MainnetV0> = Field::<MainnetV0>::new_domain_separator("AleoSymmetricEncryption0");
47    /// The graph key domain as a constant field element.
48    pub static ref GRAPH_KEY_DOMAIN: Field<MainnetV0> = Field::<MainnetV0>::new_domain_separator("AleoGraphKey0");
49    /// The serial number domain as a constant field element.
50    pub static ref SERIAL_NUMBER_DOMAIN: Field<MainnetV0> = Field::<MainnetV0>::new_domain_separator("AleoSerialNumber0");
51
52    /// The BHP hash function, which can take an input of up to 256 bits.
53    pub static ref BHP_256: BHP256<MainnetV0> = BHP256::<MainnetV0>::setup("AleoBHP256").expect("Failed to setup BHP256");
54    /// The BHP hash function, which can take an input of up to 512 bits.
55    pub static ref BHP_512: BHP512<MainnetV0> = BHP512::<MainnetV0>::setup("AleoBHP512").expect("Failed to setup BHP512");
56    /// The BHP hash function, which can take an input of up to 768 bits.
57    pub static ref BHP_768: BHP768<MainnetV0> = BHP768::<MainnetV0>::setup("AleoBHP768").expect("Failed to setup BHP768");
58    /// The BHP hash function, which can take an input of up to 1024 bits.
59    pub static ref BHP_1024: BHP1024<MainnetV0> = BHP1024::<MainnetV0>::setup("AleoBHP1024").expect("Failed to setup BHP1024");
60
61    /// The Pedersen hash function, which can take an input of up to 64 bits.
62    pub static ref PEDERSEN_64: Pedersen64<MainnetV0> = Pedersen64::<MainnetV0>::setup("AleoPedersen64");
63    /// The Pedersen hash function, which can take an input of up to 128 bits.
64    pub static ref PEDERSEN_128: Pedersen128<MainnetV0> = Pedersen128::<MainnetV0>::setup("AleoPedersen128");
65
66    /// The Poseidon hash function, using a rate of 2.
67    pub static ref POSEIDON_2: Poseidon2<MainnetV0> = Poseidon2::<MainnetV0>::setup("AleoPoseidon2").expect("Failed to setup Poseidon2");
68    /// The Poseidon hash function, using a rate of 4.
69    pub static ref POSEIDON_4: Poseidon4<MainnetV0> = Poseidon4::<MainnetV0>::setup("AleoPoseidon4").expect("Failed to setup Poseidon4");
70    /// The Poseidon hash function, using a rate of 8.
71    pub static ref POSEIDON_8: Poseidon8<MainnetV0> = Poseidon8::<MainnetV0>::setup("AleoPoseidon8").expect("Failed to setup Poseidon8");
72
73    /// The Poseidon leaf hasher for dynamic records, using a rate of 8.
74    pub static ref DYNAMIC_RECORD_LEAF_HASHER: Poseidon8<MainnetV0> = Poseidon8::<MainnetV0>::setup("DynamicRecordLeafHasher").expect("Failed to setup DynamicRecordLeafHasher");
75    /// The Poseidon path hasher for dynamic records, using a rate of 2.
76    pub static ref DYNAMIC_RECORD_PATH_HASHER: Poseidon2<MainnetV0> = Poseidon2::<MainnetV0>::setup("DynamicRecordPathHasher").expect("Failed to setup DynamicRecordPathHasher");
77
78    pub static ref CREDITS_V0_PROVING_KEYS: IndexMap<String, Arc<VarunaProvingKey<Console>>> = {
79        let mut map = IndexMap::new();
80        snarkvm_parameters::insert_credit_v0_keys!(map, VarunaProvingKey<Console>, Prover);
81        map
82    };
83    pub static ref CREDITS_V0_VERIFYING_KEYS: IndexMap<String, Arc<VarunaVerifyingKey<Console>>> = {
84        let mut map = IndexMap::new();
85        snarkvm_parameters::insert_credit_v0_keys!(map, VarunaVerifyingKey<Console>, Verifier);
86        map
87    };
88
89    pub static ref CREDITS_PROVING_KEYS: IndexMap<String, Arc<VarunaProvingKey<Console>>> = {
90        let mut map = IndexMap::new();
91        snarkvm_parameters::insert_credit_keys!(map, VarunaProvingKey<Console>, Prover);
92        map
93    };
94    pub static ref CREDITS_VERIFYING_KEYS: IndexMap<String, Arc<VarunaVerifyingKey<Console>>> = {
95        let mut map = IndexMap::new();
96        snarkvm_parameters::insert_credit_keys!(map, VarunaVerifyingKey<Console>, Verifier);
97        map
98    };
99}
100
101pub const TRANSACTION_PREFIX: &str = "at";
102
103#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
104pub struct MainnetV0;
105
106impl MainnetV0 {
107    /// Initializes a new instance of group bases from a given input domain message.
108    fn new_bases(message: &str) -> Vec<Group<Self>> {
109        // Hash the given message to a point on the curve, to initialize the starting base.
110        let (base, _, _) = Blake2Xs::hash_to_curve::<<Self as Environment>::Affine>(message);
111
112        // Compute the bases up to the size of the scalar field (in bits).
113        let mut g = Group::<Self>::new(base);
114        let mut g_bases = Vec::with_capacity(Scalar::<Self>::size_in_bits());
115        for _ in 0..Scalar::<Self>::size_in_bits() {
116            g_bases.push(g);
117            g = g.double();
118        }
119        g_bases
120    }
121}
122
123impl Environment for MainnetV0 {
124    type Affine = <Console as Environment>::Affine;
125    type BigInteger = <Console as Environment>::BigInteger;
126    type Field = <Console as Environment>::Field;
127    type PairingCurve = <Console as Environment>::PairingCurve;
128    type Projective = <Console as Environment>::Projective;
129    type Scalar = <Console as Environment>::Scalar;
130
131    /// The coefficient `A` of the twisted Edwards curve.
132    const EDWARDS_A: Self::Field = Console::EDWARDS_A;
133    /// The coefficient `D` of the twisted Edwards curve.
134    const EDWARDS_D: Self::Field = Console::EDWARDS_D;
135    /// The coefficient `A` of the Montgomery curve.
136    const MONTGOMERY_A: Self::Field = Console::MONTGOMERY_A;
137    /// The coefficient `B` of the Montgomery curve.
138    const MONTGOMERY_B: Self::Field = Console::MONTGOMERY_B;
139}
140
141impl Network for MainnetV0 {
142    /// The block hash type.
143    type BlockHash = AleoID<Field<Self>, { hrp2!("ab") }>;
144    /// The ratification ID type.
145    type RatificationID = AleoID<Field<Self>, { hrp2!("ar") }>;
146    /// The state root type.
147    type StateRoot = AleoID<Field<Self>, { hrp2!("sr") }>;
148    /// The transaction ID type.
149    type TransactionID = AleoID<Field<Self>, { hrp2!(TRANSACTION_PREFIX) }>;
150    /// The transition ID type.
151    type TransitionID = AleoID<Field<Self>, { hrp2!("au") }>;
152    /// The transmission checksum type.
153    type TransmissionChecksum = u128;
154
155    /// The genesis block coinbase target.
156    #[cfg(not(feature = "test"))]
157    const GENESIS_COINBASE_TARGET: u64 = (1u64 << 29).saturating_sub(1);
158    /// The genesis block coinbase target.
159    /// This is deliberately set to a low value (32) for testing purposes only.
160    #[cfg(feature = "test")]
161    const GENESIS_COINBASE_TARGET: u64 = (1u64 << 5).saturating_sub(1);
162    /// The genesis block proof target.
163    #[cfg(not(feature = "test"))]
164    const GENESIS_PROOF_TARGET: u64 = 1u64 << 27;
165    /// The genesis block proof target.
166    /// This is deliberately set to a low value (8) for testing purposes only.
167    #[cfg(feature = "test")]
168    const GENESIS_PROOF_TARGET: u64 = 1u64 << 3;
169    /// The fixed timestamp of the genesis block.
170    const GENESIS_TIMESTAMP: i64 = 1725462000 /* 2024-09-04 11:00:00 UTC */;
171    /// The network ID.
172    const ID: u16 = 0;
173    /// The function name for the inclusion circuit.
174    const INCLUSION_FUNCTION_NAME: &'static str = snarkvm_parameters::mainnet::NETWORK_INCLUSION_FUNCTION_NAME;
175    /// A list of (consensus_version, size) pairs indicating the maximum number of certificates in a batch.
176    #[cfg(not(any(test, feature = "test")))]
177    const MAX_CERTIFICATES: [(ConsensusVersion, u16); 6] = [
178        (ConsensusVersion::V1, 16),
179        (ConsensusVersion::V3, 25),
180        (ConsensusVersion::V5, 30),
181        (ConsensusVersion::V6, 35),
182        (ConsensusVersion::V9, 40),
183        (ConsensusVersion::V20, 40),
184    ];
185    /// A list of (consensus_version, size) pairs indicating the maximum number of certificates in a batch.
186    #[cfg(any(test, feature = "test"))]
187    const MAX_CERTIFICATES: [(ConsensusVersion, u16); 6] = [
188        (ConsensusVersion::V1, 100),
189        (ConsensusVersion::V3, 101),
190        (ConsensusVersion::V5, 102),
191        (ConsensusVersion::V6, 103),
192        (ConsensusVersion::V9, 104),
193        (ConsensusVersion::V20, 105),
194    ];
195    /// The (long) network name.
196    const NAME: &'static str = "Aleo Mainnet (v0)";
197    /// The short network name.
198    const SHORT_NAME: &'static str = "mainnet";
199    /// A list of (consensus_version, block_height) pairs indicating when each consensus version takes effect.
200    /// Documentation for what is changed at each version can be found in `ConsensusVersion`.
201    /// Do not read this directly outside of tests, use `N::CONSENSUS_VERSION_HEIGHTS()` instead.
202    const _CONSENSUS_VERSION_HEIGHTS: [(ConsensusVersion, u32); NUM_CONSENSUS_VERSIONS] =
203        MAINNET_V0_CONSENSUS_VERSION_HEIGHTS;
204
205    /// Returns the block height where the the inclusion proof will be updated.
206    #[allow(non_snake_case)]
207    fn INCLUSION_UPGRADE_HEIGHT() -> Result<u32> {
208        Self::CONSENSUS_HEIGHT(ConsensusVersion::V8)
209    }
210
211    /// Returns the genesis block bytes.
212    fn genesis_bytes() -> &'static [u8] {
213        snarkvm_parameters::mainnet::GenesisBytes::load_bytes()
214    }
215
216    /// Returns the restrictions list as a JSON-compatible string.
217    fn restrictions_list_as_str() -> &'static str {
218        snarkvm_parameters::mainnet::RESTRICTIONS_LIST
219    }
220
221    /// Returns the proving key for the given function name in the v0 version of `credits.aleo`.
222    fn get_credits_v0_proving_key(function_name: String) -> Result<&'static Arc<VarunaProvingKey<Self>>> {
223        CREDITS_V0_PROVING_KEYS
224            .get(&function_name)
225            .ok_or_else(|| anyhow!("Proving key (v0) for credits.aleo/{function_name}' not found"))
226    }
227
228    /// Returns the verifying key for the given function name in the v0 version of `credits.aleo`.
229    fn get_credits_v0_verifying_key(function_name: String) -> Result<&'static Arc<VarunaVerifyingKey<Self>>> {
230        CREDITS_V0_VERIFYING_KEYS
231            .get(&function_name)
232            .ok_or_else(|| anyhow!("Verifying key (v0) for credits_v0.aleo/{function_name}' not found"))
233    }
234
235    /// Returns the proving key for the given function name in `credits.aleo`.
236    fn get_credits_proving_key(function_name: String) -> Result<&'static Arc<VarunaProvingKey<Self>>> {
237        CREDITS_PROVING_KEYS
238            .get(&function_name)
239            .ok_or_else(|| anyhow!("Proving key for credits.aleo/{function_name}' not found"))
240    }
241
242    /// Returns the verifying key for the given function name in `credits.aleo`.
243    fn get_credits_verifying_key(function_name: String) -> Result<&'static Arc<VarunaVerifyingKey<Self>>> {
244        CREDITS_VERIFYING_KEYS
245            .get(&function_name)
246            .ok_or_else(|| anyhow!("Verifying key for credits.aleo/{function_name}' not found"))
247    }
248
249    #[cfg(not(feature = "wasm"))]
250    /// Returns the `proving key` for the inclusion_v0 circuit.
251    fn inclusion_v0_proving_key() -> &'static Arc<VarunaProvingKey<Self>> {
252        static INSTANCE: OnceLock<Arc<VarunaProvingKey<Console>>> = OnceLock::new();
253        INSTANCE.get_or_init(|| {
254            // Skipping the first byte, which is the encoded version.
255            Arc::new(
256                CircuitProvingKey::from_bytes_le(&snarkvm_parameters::mainnet::INCLUSION_V0_PROVING_KEY[1..])
257                    .expect("Failed to load inclusion_v0 proving key."),
258            )
259        })
260    }
261
262    #[cfg(feature = "wasm")]
263    /// Returns the `proving key` for the inclusion_v0 circuit.
264    fn inclusion_v0_proving_key(inclusion_key_bytes: Option<Vec<u8>>) -> &'static Arc<VarunaProvingKey<Self>> {
265        static INSTANCE: OnceLock<Arc<VarunaProvingKey<Console>>> = OnceLock::new();
266        INSTANCE.get_or_init(|| {
267            inclusion_key_bytes
268                .map(|bytes| {
269                    snarkvm_parameters::mainnet::InclusionV0Prover::verify_bytes(&bytes)
270                        .expect("Bytes provided did not match expected inclusion checksum.");
271                    Arc::new(
272                        CircuitProvingKey::from_bytes_le(&bytes[1..]).expect("Failed to load inclusion proving key."),
273                    )
274                })
275                .unwrap_or_else(|| {
276                    Arc::new(
277                        CircuitProvingKey::from_bytes_le(&snarkvm_parameters::mainnet::INCLUSION_V0_PROVING_KEY[1..])
278                            .expect("Failed to load inclusion proving key."),
279                    )
280                })
281        })
282    }
283
284    /// Returns the `verifying key` for the inclusion_v0 circuit.
285    fn inclusion_v0_verifying_key() -> &'static Arc<VarunaVerifyingKey<Self>> {
286        static INSTANCE: OnceLock<Arc<VarunaVerifyingKey<Console>>> = OnceLock::new();
287        INSTANCE.get_or_init(|| {
288            // Skipping the first byte, which is the encoded version.
289            Arc::new(
290                CircuitVerifyingKey::from_bytes_le(&snarkvm_parameters::mainnet::INCLUSION_V0_VERIFYING_KEY[1..])
291                    .expect("Failed to load inclusion_v0 verifying key."),
292            )
293        })
294    }
295
296    #[cfg(not(feature = "wasm"))]
297    /// Returns the `proving key` for the inclusion circuit.
298    fn inclusion_proving_key() -> &'static Arc<VarunaProvingKey<Self>> {
299        static INSTANCE: OnceLock<Arc<VarunaProvingKey<Console>>> = OnceLock::new();
300        INSTANCE.get_or_init(|| {
301            // Skipping the first byte, which is the encoded version.
302            Arc::new(
303                CircuitProvingKey::from_bytes_le(&snarkvm_parameters::mainnet::INCLUSION_PROVING_KEY[1..])
304                    .expect("Failed to load inclusion proving key."),
305            )
306        })
307    }
308
309    #[cfg(feature = "wasm")]
310    /// Returns the `proving key` for the inclusion circuit.
311    fn inclusion_proving_key(inclusion_key_bytes: Option<Vec<u8>>) -> &'static Arc<VarunaProvingKey<Self>> {
312        static INSTANCE: OnceLock<Arc<VarunaProvingKey<Console>>> = OnceLock::new();
313        INSTANCE.get_or_init(|| {
314            inclusion_key_bytes
315                .map(|bytes| {
316                    snarkvm_parameters::mainnet::InclusionProver::verify_bytes(&bytes)
317                        .expect("Bytes provided did not match expected inclusion checksum.");
318                    Arc::new(
319                        CircuitProvingKey::from_bytes_le(&bytes[1..]).expect("Failed to load inclusion proving key."),
320                    )
321                })
322                .unwrap_or_else(|| {
323                    Arc::new(
324                        CircuitProvingKey::from_bytes_le(&snarkvm_parameters::mainnet::INCLUSION_PROVING_KEY[1..])
325                            .expect("Failed to load inclusion proving key."),
326                    )
327                })
328        })
329    }
330
331    /// Returns the `verifying key` for the inclusion circuit.
332    fn inclusion_verifying_key() -> &'static Arc<VarunaVerifyingKey<Self>> {
333        static INSTANCE: OnceLock<Arc<VarunaVerifyingKey<Console>>> = OnceLock::new();
334        INSTANCE.get_or_init(|| {
335            // Skipping the first byte, which is the encoded version.
336            Arc::new(
337                CircuitVerifyingKey::from_bytes_le(&snarkvm_parameters::mainnet::INCLUSION_VERIFYING_KEY[1..])
338                    .expect("Failed to load inclusion verifying key."),
339            )
340        })
341    }
342
343    #[cfg(not(feature = "wasm"))]
344    /// Returns the `proving key` for the credits.aleo credits record translation circuit.
345    fn translation_credits_proving_key() -> &'static Arc<VarunaProvingKey<Self>> {
346        static INSTANCE: OnceLock<Arc<VarunaProvingKey<Console>>> = OnceLock::new();
347        INSTANCE.get_or_init(|| {
348            // Skipping the first byte, which is the encoded version.
349            Arc::new(
350                CircuitProvingKey::from_bytes_le(&snarkvm_parameters::mainnet::TRANSLATION_CREDITS_PROVING_KEY[1..])
351                    .expect("Failed to load translation credits proving key."),
352            )
353        })
354    }
355
356    #[cfg(feature = "wasm")]
357    /// Returns the `proving key` for the translation credits circuit.
358    fn translation_credits_proving_key(
359        translation_credits_key_bytes: Option<Vec<u8>>,
360    ) -> &'static Arc<VarunaProvingKey<Self>> {
361        static INSTANCE: OnceLock<Arc<VarunaProvingKey<Console>>> = OnceLock::new();
362        INSTANCE.get_or_init(|| {
363            translation_credits_key_bytes
364                .map(|bytes| {
365                    snarkvm_parameters::mainnet::TranslationCreditsProver::verify_bytes(&bytes)
366                        .expect("Bytes provided did not match expected translation credits checksum.");
367                    Arc::new(
368                        CircuitProvingKey::from_bytes_le(&bytes[1..])
369                            .expect("Failed to load translation credits proving key."),
370                    )
371                })
372                .unwrap_or_else(|| {
373                    Arc::new(
374                        CircuitProvingKey::from_bytes_le(
375                            &snarkvm_parameters::mainnet::TRANSLATION_CREDITS_PROVING_KEY[1..],
376                        )
377                        .expect("Failed to load translation credits proving key."),
378                    )
379                })
380        })
381    }
382
383    /// Returns the `verifying key` for the translation circuit.
384    fn translation_credits_verifying_key() -> &'static Arc<VarunaVerifyingKey<Self>> {
385        static INSTANCE: OnceLock<Arc<VarunaVerifyingKey<Console>>> = OnceLock::new();
386        INSTANCE.get_or_init(|| {
387            Arc::new(
388                CircuitVerifyingKey::from_bytes_le(
389                    &snarkvm_parameters::mainnet::TRANSLATION_CREDITS_VERIFYING_KEY[1..],
390                )
391                .expect("Failed to load translation verifying key."),
392            )
393        })
394    }
395
396    /// Returns the powers of `G`.
397    fn g_powers() -> &'static Vec<Group<Self>> {
398        &GENERATOR_G
399    }
400
401    /// Returns the scalar multiplication on the generator `G`.
402    fn g_scalar_multiply(scalar: &Scalar<Self>) -> Group<Self> {
403        GENERATOR_G
404            .iter()
405            .zip_eq(&scalar.to_bits_le())
406            .filter_map(|(base, bit)| match bit {
407                true => Some(base),
408                false => None,
409            })
410            .sum()
411    }
412
413    /// Returns the Varuna universal prover.
414    fn varuna_universal_prover() -> &'static UniversalProver<Self::PairingCurve> {
415        static INSTANCE: OnceLock<UniversalProver<<Console as Environment>::PairingCurve>> = OnceLock::new();
416        INSTANCE.get_or_init(|| {
417            snarkvm_algorithms::polycommit::kzg10::UniversalParams::load()
418                .expect("Failed to load universal SRS (KZG10).")
419                .to_universal_prover()
420                .expect("Failed to convert universal SRS (KZG10) to the prover.")
421        })
422    }
423
424    /// Returns the Varuna universal verifier.
425    fn varuna_universal_verifier() -> &'static UniversalVerifier<Self::PairingCurve> {
426        static INSTANCE: OnceLock<UniversalVerifier<<Console as Environment>::PairingCurve>> = OnceLock::new();
427        INSTANCE.get_or_init(|| {
428            snarkvm_algorithms::polycommit::kzg10::UniversalParams::load()
429                .expect("Failed to load universal SRS (KZG10).")
430                .to_universal_verifier()
431                .expect("Failed to convert universal SRS (KZG10) to the verifier.")
432        })
433    }
434
435    /// Returns the sponge parameters used for the sponge in the Varuna SNARK.
436    fn varuna_fs_parameters() -> &'static FiatShamirParameters<Self> {
437        &VARUNA_FS_PARAMETERS
438    }
439
440    /// Returns the commitment domain as a constant field element.
441    fn commitment_domain() -> Field<Self> {
442        *COMMITMENT_DOMAIN
443    }
444
445    /// Returns the encryption domain as a constant field element.
446    fn encryption_domain() -> Field<Self> {
447        *ENCRYPTION_DOMAIN
448    }
449
450    /// Returns the graph key domain as a constant field element.
451    fn graph_key_domain() -> Field<Self> {
452        *GRAPH_KEY_DOMAIN
453    }
454
455    /// Returns the serial number domain as a constant field element.
456    fn serial_number_domain() -> Field<Self> {
457        *SERIAL_NUMBER_DOMAIN
458    }
459
460    /// Returns a BHP commitment with an input hasher of 256-bits and randomizer.
461    fn commit_bhp256(input: &[bool], randomizer: &Scalar<Self>) -> Result<Field<Self>> {
462        BHP_256.commit(input, randomizer)
463    }
464
465    /// Returns a BHP commitment with an input hasher of 512-bits and randomizer.
466    fn commit_bhp512(input: &[bool], randomizer: &Scalar<Self>) -> Result<Field<Self>> {
467        BHP_512.commit(input, randomizer)
468    }
469
470    /// Returns a BHP commitment with an input hasher of 768-bits and randomizer.
471    fn commit_bhp768(input: &[bool], randomizer: &Scalar<Self>) -> Result<Field<Self>> {
472        BHP_768.commit(input, randomizer)
473    }
474
475    /// Returns a BHP commitment with an input hasher of 1024-bits and randomizer.
476    fn commit_bhp1024(input: &[bool], randomizer: &Scalar<Self>) -> Result<Field<Self>> {
477        BHP_1024.commit(input, randomizer)
478    }
479
480    /// Returns a Pedersen commitment for the given (up to) 64-bit input and randomizer.
481    fn commit_ped64(input: &[bool], randomizer: &Scalar<Self>) -> Result<Field<Self>> {
482        PEDERSEN_64.commit(input, randomizer)
483    }
484
485    /// Returns a Pedersen commitment for the given (up to) 128-bit input and randomizer.
486    fn commit_ped128(input: &[bool], randomizer: &Scalar<Self>) -> Result<Field<Self>> {
487        PEDERSEN_128.commit(input, randomizer)
488    }
489
490    /// Returns a BHP commitment with an input hasher of 256-bits and randomizer.
491    fn commit_to_group_bhp256(input: &[bool], randomizer: &Scalar<Self>) -> Result<Group<Self>> {
492        BHP_256.commit_uncompressed(input, randomizer)
493    }
494
495    /// Returns a BHP commitment with an input hasher of 512-bits and randomizer.
496    fn commit_to_group_bhp512(input: &[bool], randomizer: &Scalar<Self>) -> Result<Group<Self>> {
497        BHP_512.commit_uncompressed(input, randomizer)
498    }
499
500    /// Returns a BHP commitment with an input hasher of 768-bits and randomizer.
501    fn commit_to_group_bhp768(input: &[bool], randomizer: &Scalar<Self>) -> Result<Group<Self>> {
502        BHP_768.commit_uncompressed(input, randomizer)
503    }
504
505    /// Returns a BHP commitment with an input hasher of 1024-bits and randomizer.
506    fn commit_to_group_bhp1024(input: &[bool], randomizer: &Scalar<Self>) -> Result<Group<Self>> {
507        BHP_1024.commit_uncompressed(input, randomizer)
508    }
509
510    /// Returns a Pedersen commitment for the given (up to) 64-bit input and randomizer.
511    fn commit_to_group_ped64(input: &[bool], randomizer: &Scalar<Self>) -> Result<Group<Self>> {
512        PEDERSEN_64.commit_uncompressed(input, randomizer)
513    }
514
515    /// Returns a Pedersen commitment for the given (up to) 128-bit input and randomizer.
516    fn commit_to_group_ped128(input: &[bool], randomizer: &Scalar<Self>) -> Result<Group<Self>> {
517        PEDERSEN_128.commit_uncompressed(input, randomizer)
518    }
519
520    /// Returns the BHP hash with an input hasher of 256-bits.
521    fn hash_bhp256(input: &[bool]) -> Result<Field<Self>> {
522        BHP_256.hash(input)
523    }
524
525    /// Returns the BHP hash with an input hasher of 512-bits.
526    fn hash_bhp512(input: &[bool]) -> Result<Field<Self>> {
527        BHP_512.hash(input)
528    }
529
530    /// Returns the BHP hash with an input hasher of 768-bits.
531    fn hash_bhp768(input: &[bool]) -> Result<Field<Self>> {
532        BHP_768.hash(input)
533    }
534
535    /// Returns the BHP hash with an input hasher of 1024-bits.
536    fn hash_bhp1024(input: &[bool]) -> Result<Field<Self>> {
537        BHP_1024.hash(input)
538    }
539
540    /// Returns the Keccak hash with a 256-bit output.
541    fn hash_keccak256(input: &[bool]) -> Result<Vec<bool>> {
542        Keccak256::default().hash(input)
543    }
544
545    /// Returns the Keccak hash with a 384-bit output.
546    fn hash_keccak384(input: &[bool]) -> Result<Vec<bool>> {
547        Keccak384::default().hash(input)
548    }
549
550    /// Returns the Keccak hash with a 512-bit output.
551    fn hash_keccak512(input: &[bool]) -> Result<Vec<bool>> {
552        Keccak512::default().hash(input)
553    }
554
555    /// Returns the Pedersen hash for a given (up to) 64-bit input.
556    fn hash_ped64(input: &[bool]) -> Result<Field<Self>> {
557        PEDERSEN_64.hash(input)
558    }
559
560    /// Returns the Pedersen hash for a given (up to) 128-bit input.
561    fn hash_ped128(input: &[bool]) -> Result<Field<Self>> {
562        PEDERSEN_128.hash(input)
563    }
564
565    /// Returns the Poseidon hash with an input rate of 2.
566    fn hash_psd2(input: &[Field<Self>]) -> Result<Field<Self>> {
567        POSEIDON_2.hash(input)
568    }
569
570    /// Returns the Poseidon hash with an input rate of 4.
571    fn hash_psd4(input: &[Field<Self>]) -> Result<Field<Self>> {
572        POSEIDON_4.hash(input)
573    }
574
575    /// Returns the Poseidon hash with an input rate of 8.
576    fn hash_psd8(input: &[Field<Self>]) -> Result<Field<Self>> {
577        POSEIDON_8.hash(input)
578    }
579
580    /// Returns the SHA-3 hash with a 256-bit output.
581    fn hash_sha3_256(input: &[bool]) -> Result<Vec<bool>> {
582        Sha3_256::default().hash(input)
583    }
584
585    /// Returns the SHA-3 hash with a 384-bit output.
586    fn hash_sha3_384(input: &[bool]) -> Result<Vec<bool>> {
587        Sha3_384::default().hash(input)
588    }
589
590    /// Returns the SHA-3 hash with a 512-bit output.
591    fn hash_sha3_512(input: &[bool]) -> Result<Vec<bool>> {
592        Sha3_512::default().hash(input)
593    }
594
595    /// Returns the extended Poseidon hash with an input rate of 2.
596    fn hash_many_psd2(input: &[Field<Self>], num_outputs: u16) -> Vec<Field<Self>> {
597        POSEIDON_2.hash_many(input, num_outputs)
598    }
599
600    /// Returns the extended Poseidon hash with an input rate of 4.
601    fn hash_many_psd4(input: &[Field<Self>], num_outputs: u16) -> Vec<Field<Self>> {
602        POSEIDON_4.hash_many(input, num_outputs)
603    }
604
605    /// Returns the extended Poseidon hash with an input rate of 8.
606    fn hash_many_psd8(input: &[Field<Self>], num_outputs: u16) -> Vec<Field<Self>> {
607        POSEIDON_8.hash_many(input, num_outputs)
608    }
609
610    /// Returns the BHP hash with an input hasher of 256-bits.
611    fn hash_to_group_bhp256(input: &[bool]) -> Result<Group<Self>> {
612        BHP_256.hash_uncompressed(input)
613    }
614
615    /// Returns the BHP hash with an input hasher of 512-bits.
616    fn hash_to_group_bhp512(input: &[bool]) -> Result<Group<Self>> {
617        BHP_512.hash_uncompressed(input)
618    }
619
620    /// Returns the BHP hash with an input hasher of 768-bits.
621    fn hash_to_group_bhp768(input: &[bool]) -> Result<Group<Self>> {
622        BHP_768.hash_uncompressed(input)
623    }
624
625    /// Returns the BHP hash with an input hasher of 1024-bits.
626    fn hash_to_group_bhp1024(input: &[bool]) -> Result<Group<Self>> {
627        BHP_1024.hash_uncompressed(input)
628    }
629
630    /// Returns the Pedersen hash for a given (up to) 64-bit input.
631    fn hash_to_group_ped64(input: &[bool]) -> Result<Group<Self>> {
632        PEDERSEN_64.hash_uncompressed(input)
633    }
634
635    /// Returns the Pedersen hash for a given (up to) 128-bit input.
636    fn hash_to_group_ped128(input: &[bool]) -> Result<Group<Self>> {
637        PEDERSEN_128.hash_uncompressed(input)
638    }
639
640    /// Returns the Poseidon hash with an input rate of 2 on the affine curve.
641    fn hash_to_group_psd2(input: &[Field<Self>]) -> Result<Group<Self>> {
642        POSEIDON_2.hash_to_group(input)
643    }
644
645    /// Returns the Poseidon hash with an input rate of 4 on the affine curve.
646    fn hash_to_group_psd4(input: &[Field<Self>]) -> Result<Group<Self>> {
647        POSEIDON_4.hash_to_group(input)
648    }
649
650    /// Returns the Poseidon hash with an input rate of 8 on the affine curve.
651    fn hash_to_group_psd8(input: &[Field<Self>]) -> Result<Group<Self>> {
652        POSEIDON_8.hash_to_group(input)
653    }
654
655    /// Returns the Poseidon hash with an input rate of 2 on the scalar field.
656    fn hash_to_scalar_psd2(input: &[Field<Self>]) -> Result<Scalar<Self>> {
657        POSEIDON_2.hash_to_scalar(input)
658    }
659
660    /// Returns the Poseidon hash with an input rate of 4 on the scalar field.
661    fn hash_to_scalar_psd4(input: &[Field<Self>]) -> Result<Scalar<Self>> {
662        POSEIDON_4.hash_to_scalar(input)
663    }
664
665    /// Returns the Poseidon hash with an input rate of 8 on the scalar field.
666    fn hash_to_scalar_psd8(input: &[Field<Self>]) -> Result<Scalar<Self>> {
667        POSEIDON_8.hash_to_scalar(input)
668    }
669
670    /// Returns a Merkle tree with a BHP leaf hasher of 1024-bits and a BHP path hasher of 512-bits.
671    fn merkle_tree_bhp<const DEPTH: u8>(leaves: &[Vec<bool>]) -> Result<BHPMerkleTree<Self, DEPTH>> {
672        MerkleTree::new(&*BHP_1024, &*BHP_512, leaves)
673    }
674
675    /// Recreates a Merkle tree with a BHP leaf hasher of 1024-bits and a BHP path hasher of
676    /// 512-bits from the given state, e.g. one that was previously cached on disk.
677    fn merkle_tree_bhp_from_state<const DEPTH: u8>(
678        state: MerkleTreeState<'_, Self>,
679    ) -> Result<BHPMerkleTree<Self, DEPTH>> {
680        MerkleTree::from_state(&*BHP_1024, &*BHP_512, state)
681    }
682
683    /// Returns a Merkle tree with a Poseidon leaf hasher with input rate of 4 and a Poseidon path hasher with input rate of 2.
684    fn merkle_tree_psd<const DEPTH: u8>(leaves: &[Vec<Field<Self>>]) -> Result<PoseidonMerkleTree<Self, DEPTH>> {
685        MerkleTree::new(&*POSEIDON_4, &*POSEIDON_2, leaves)
686    }
687
688    /// Returns `true` if the given Merkle path is valid for the given root and leaf.
689    fn verify_merkle_path_bhp<const DEPTH: u8>(
690        path: &MerklePath<Self, DEPTH>,
691        root: &Field<Self>,
692        leaf: &Vec<bool>,
693    ) -> bool {
694        path.verify(&*BHP_1024, &*BHP_512, root, leaf)
695    }
696
697    /// Returns `true` if the given Merkle path is valid for the given root and leaf.
698    fn verify_merkle_path_psd<const DEPTH: u8>(
699        path: &MerklePath<Self, DEPTH>,
700        root: &Field<Self>,
701        leaf: &Vec<Field<Self>>,
702    ) -> bool {
703        path.verify(&*POSEIDON_4, &*POSEIDON_2, root, leaf)
704    }
705
706    /// Returns the Poseidon leaf hasher for dynamic records (rate 8).
707    fn dynamic_record_leaf_hasher() -> &'static Poseidon8<Self> {
708        &DYNAMIC_RECORD_LEAF_HASHER
709    }
710
711    /// Returns the Poseidon path hasher for dynamic records (rate 2).
712    fn dynamic_record_path_hasher() -> &'static Poseidon2<Self> {
713        &DYNAMIC_RECORD_PATH_HASHER
714    }
715}
716
717#[cfg(test)]
718mod tests {
719    use super::*;
720
721    type CurrentNetwork = MainnetV0;
722
723    #[test]
724    fn test_g_scalar_multiply() {
725        // Compute G^r.
726        let scalar = Scalar::rand(&mut TestRng::default());
727        let group = CurrentNetwork::g_scalar_multiply(&scalar);
728        assert_eq!(group, CurrentNetwork::g_powers()[0] * scalar);
729    }
730}