1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
// Copyright (C) 2019-2022 Aleo Systems Inc.
// This file is part of the snarkVM library.

// The snarkVM library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The snarkVM library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with the snarkVM library. If not, see <https://www.gnu.org/licenses/>.

use super::*;

impl<E: Environment, const RATE: usize> HashToScalar for Poseidon<E, RATE> {
    type Input = Field<E>;
    type Scalar = Scalar<E>;

    /// Returns a scalar from hashing the input.
    /// This method uses truncation (up to data bits) to project onto the scalar field.
    #[inline]
    fn hash_to_scalar(&self, input: &[Self::Input]) -> Self::Scalar {
        // Hash the input to the base field.
        let output = self.hash(input);

        // Truncate the output to the size in data bits (1 bit less than the MODULUS) of the scalar.
        // Slicing here is safe as the base field is larger than the scalar field.
        Scalar::from_bits_le(&output.to_bits_le()[..E::ScalarField::size_in_data_bits()])
    }
}

#[cfg(all(test, console))]
mod tests {
    use super::*;
    use snarkvm_circuit_types::environment::Circuit;

    use anyhow::Result;

    const DOMAIN: &str = "PoseidonCircuit0";
    const ITERATIONS: usize = 10;
    const RATE: usize = 4;

    fn check_hash_to_scalar(
        mode: Mode,
        num_inputs: usize,
        num_constants: u64,
        num_public: u64,
        num_private: u64,
        num_constraints: u64,
        rng: &mut TestRng,
    ) -> Result<()> {
        use console::HashToScalar as H;

        let native = console::Poseidon::<<Circuit as Environment>::Network, RATE>::setup(DOMAIN)?;
        let poseidon = Poseidon::<Circuit, RATE>::constant(native.clone());

        for i in 0..ITERATIONS {
            // Prepare the preimage.
            let native_input = (0..num_inputs).map(|_| Uniform::rand(rng)).collect::<Vec<_>>();
            let input = native_input.iter().map(|v| Field::<Circuit>::new(mode, *v)).collect::<Vec<_>>();

            // Compute the native hash to scalar.
            let expected = native.hash_to_scalar(&native_input)?;

            // Compute the circuit hash.
            Circuit::scope(format!("Poseidon {mode} {i}"), || {
                let candidate = poseidon.hash_to_scalar(&input);
                assert_eq!(expected, candidate.eject_value());
                let case = format!("(mode = {mode}, num_inputs = {num_inputs})");
                assert_scope!(case, num_constants, num_public, num_private, num_constraints);
            });
            Circuit::reset();
        }
        Ok(())
    }

    #[test]
    fn test_hash_to_scalar_constant() -> Result<()> {
        let mut rng = TestRng::default();

        for num_inputs in 0..=RATE {
            check_hash_to_scalar(Mode::Constant, num_inputs, 254, 0, 0, 0, &mut rng)?;
        }
        Ok(())
    }

    #[test]
    fn test_hash_to_scalar_public() -> Result<()> {
        let mut rng = TestRng::default();

        check_hash_to_scalar(Mode::Public, 0, 254, 0, 0, 0, &mut rng)?;
        check_hash_to_scalar(Mode::Public, 1, 1, 0, 588, 589, &mut rng)?;
        check_hash_to_scalar(Mode::Public, 2, 1, 0, 593, 594, &mut rng)?;
        check_hash_to_scalar(Mode::Public, 3, 1, 0, 598, 599, &mut rng)?;
        check_hash_to_scalar(Mode::Public, 4, 1, 0, 603, 604, &mut rng)?;
        check_hash_to_scalar(Mode::Public, 5, 1, 0, 958, 959, &mut rng)?;
        check_hash_to_scalar(Mode::Public, 6, 1, 0, 958, 959, &mut rng)?;
        check_hash_to_scalar(Mode::Public, 7, 1, 0, 958, 959, &mut rng)?;
        check_hash_to_scalar(Mode::Public, 8, 1, 0, 958, 959, &mut rng)?;
        check_hash_to_scalar(Mode::Public, 9, 1, 0, 1313, 1314, &mut rng)?;
        check_hash_to_scalar(Mode::Public, 10, 1, 0, 1313, 1314, &mut rng)
    }

    #[test]
    fn test_hash_to_scalar_private() -> Result<()> {
        let mut rng = TestRng::default();

        check_hash_to_scalar(Mode::Private, 0, 254, 0, 0, 0, &mut rng)?;
        check_hash_to_scalar(Mode::Private, 1, 1, 0, 588, 589, &mut rng)?;
        check_hash_to_scalar(Mode::Private, 2, 1, 0, 593, 594, &mut rng)?;
        check_hash_to_scalar(Mode::Private, 3, 1, 0, 598, 599, &mut rng)?;
        check_hash_to_scalar(Mode::Private, 4, 1, 0, 603, 604, &mut rng)?;
        check_hash_to_scalar(Mode::Private, 5, 1, 0, 958, 959, &mut rng)?;
        check_hash_to_scalar(Mode::Private, 6, 1, 0, 958, 959, &mut rng)?;
        check_hash_to_scalar(Mode::Private, 7, 1, 0, 958, 959, &mut rng)?;
        check_hash_to_scalar(Mode::Private, 8, 1, 0, 958, 959, &mut rng)?;
        check_hash_to_scalar(Mode::Private, 9, 1, 0, 1313, 1314, &mut rng)?;
        check_hash_to_scalar(Mode::Private, 10, 1, 0, 1313, 1314, &mut rng)
    }
}