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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
use crate::{
    Error, PoseidonLeaf, Scalar, FULL_ROUNDS, MDS_MATRIX, MERKLE_ARITY, PARTIAL_ROUNDS,
    ROUND_CONSTANTS, WIDTH,
};
use std::ops;

/// The `Poseidon` structure will accept a number of inputs equal to the arity.
///
/// The leaves must implement [`ops::Mul`] against a [`Scalar`], because the MDS matrix and the
/// round constants are set, by default, as scalars.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Poseidon<T: PoseidonLeaf> {
    constants_offset: usize,
    present_elements: u64,
    pos: usize,
    leaves: [T; WIDTH],
}

impl<T: PoseidonLeaf> Default for Poseidon<T> {
    fn default() -> Self {
        Poseidon {
            present_elements: 0u64,
            constants_offset: 0,
            pos: 1,
            leaves: [T::from(0u64); WIDTH],
        }
    }
}

impl<T: PoseidonLeaf> Poseidon<T> {
    /// The poseidon width will be defined by `arity + 1`, because the first element will be a set of bitflags defining which element is present or absent. The absent elements will be represented by `0`, and the present ones by `1`, considering inverse order.
    ///
    /// For example: given we have an arity of `8`, and  if we have two present elements, three absent, and three present, we will have the first element as `0xe3`, or `(11100011)`.
    ///
    /// Every time we push an element, we set the related bitflag with the proper state.
    ///
    /// The returned `usize` represents the leaf position for the insert operation
    pub fn push(&mut self, leaf: T) -> Result<usize, Error> {
        // Cannot input more elements than the defined arity
        if self.pos > MERKLE_ARITY {
            return Err(Error::FullBuffer);
        }

        self.insert_unchecked(self.pos - 1, leaf);
        self.pos += 1;

        Ok(self.pos - 2)
    }

    /// Insert the provided leaf in the defined position.
    ///
    /// # Panics
    ///
    /// Panics if `index` is out of bounds.
    pub(crate) fn insert_unchecked(&mut self, index: usize, leaf: T) {
        let mut mask = 1u64;
        mask <<= index;
        self.present_elements |= mask;

        // Set current element, and increase the pointer
        self.leaves[index + 1] = leaf;
    }

    /// Removes an item that is indexed by `index`.
    ///
    /// Internally, the buffer is stored in form of `index + 1`, because of the leading bitflags
    /// element.
    ///
    /// # Example
    /// ```
    /// use dusk_poseidon_merkle::*;
    ///
    /// let mut h = Poseidon::default();
    ///
    /// assert!(h.remove(0).is_err());
    ///
    /// let idx = h.push(Scalar::one()).unwrap();
    /// assert_eq!(0, idx);
    ///
    /// h.remove(0).unwrap();
    /// ```
    pub fn remove(&mut self, index: usize) -> Result<T, Error> {
        let index = index + 1;
        if index >= self.pos {
            return Err(Error::IndexOutOfBounds);
        }

        Ok(self.remove_unchecked(index))
    }

    /// Removes the first equivalence of the item from the leafs set and returns it.
    pub fn remove_item(&mut self, item: &T) -> Option<T> {
        self.leaves
            .iter()
            .enumerate()
            .fold(None, |mut acc, (i, s)| {
                if acc.is_none() && i > 0 && s == item {
                    acc.replace(i);
                }

                acc
            })
            .map(|idx| self.remove_unchecked(idx))
    }

    /// Set the provided index as absent for the hash calculation.
    ///
    /// # Panics
    ///
    /// Panics if `index` is out of bounds.
    pub fn remove_unchecked(&mut self, index: usize) -> T {
        let leaf = self.leaves[index];
        self.leaves[index] = T::from(0u64);

        let mut mask = 1u64;
        mask <<= index;
        self.present_elements &= !mask;

        leaf
    }

    /// Replace the leaves with the provided optional items.
    ///
    /// # Panics
    ///
    /// Panics if the provided slice is bigger than the arity.
    pub fn replace(&mut self, buf: &[Option<T>]) {
        self.reset();
        buf.iter().enumerate().for_each(|(i, scalar)| {
            if let Some(s) = scalar {
                self.insert_unchecked(i, *s);
            }
        });
    }

    /// Restore the initial state
    pub fn reset(&mut self) {
        self.present_elements = 0;
        self.constants_offset = 0;
        self.pos = 1;
        self.leaves.iter_mut().for_each(|l| *l = T::from(0u64));
    }

    /// The absent elements will be considered as zeroes in the permutation.
    ///
    /// The number of rounds is divided into two equal parts for the full rounds, plus the partial rounds.
    ///
    /// The returned element is the second poseidon leaf, for the first is initially the bitflags scheme.
    pub fn hash(&mut self) -> T
    where
        Scalar: ops::Mul<T, Output = T>,
    {
        // The first element is a set of bitflags to differentiate zeroed leaves from absent
        // ones
        //
        // This avoids collisions
        self.leaves[0] = T::from(self.present_elements);

        // This counter is incremented when a round constants is read. Therefore, the round constants never
        // repeat
        for _ in 0..FULL_ROUNDS / 2 {
            self.full_round();
        }

        for _ in 0..PARTIAL_ROUNDS {
            self.partial_round();
        }

        for _ in 0..FULL_ROUNDS / 2 {
            self.full_round();
        }

        // The first bitflags element is discarded, so we can use the first actual leaf as a result
        // of the hash
        self.leaves[1]
    }

    /// The full round function will add the round constants and apply the S-Box to all poseidon leaves, including the bitflags first element.
    ///
    /// After that, the poseidon elements will be set to the result of the product between the poseidon leaves and the constant MDS matrix.
    pub fn full_round(&mut self)
    where
        Scalar: ops::Mul<T, Output = T>,
    {
        // Every element of the merkle tree, plus the bitflag, is incremented by the round constants
        self.add_round_constants();

        // Apply the quintic S-Box to all elements
        self.leaves.iter_mut().for_each(|l| quintic_s_box(l));

        // Multiply the elements by the constant MDS matrix
        self.product_mds();
    }

    /// The partial round is the same as the full round, with the difference that we apply the S-Box only to the first bitflags poseidon leaf.
    pub fn partial_round(&mut self)
    where
        Scalar: ops::Mul<T, Output = T>,
    {
        // Every element of the merkle tree, plus the bitflag, is incremented by the round constants
        self.add_round_constants();

        // Apply the quintic S-Box to the bitflags element
        quintic_s_box(&mut self.leaves[0]);

        // Multiply the elements by the constant MDS matrix
        self.product_mds();
    }

    /// For every leaf, add the round constants with index defined by the constants offset, and increment the
    /// offset
    fn add_round_constants(&mut self) {
        let mut constants_offset = self.constants_offset;

        self.leaves.iter_mut().for_each(|l| {
            *l += T::from(ROUND_CONSTANTS[constants_offset]);
            constants_offset += 1;
        });

        self.constants_offset = constants_offset;
    }

    /// Set the provided leaves with the result of the product between the leaves and the constant
    /// MDS matrix
    fn product_mds(&mut self)
    where
        Scalar: ops::Mul<T, Output = T>,
    {
        let mut result = [T::from(0u64); WIDTH];

        for j in 0..WIDTH {
            for k in 0..WIDTH {
                result[j] += MDS_MATRIX[j][k] * self.leaves[k];
            }
        }

        self.leaves.copy_from_slice(&result);
    }
}

/// Apply the quintic S-Box (s^5) to a given item
fn quintic_s_box<T>(l: &mut T)
where
    T: Copy + ops::MulAssign,
{
    let c = *l;
    for _ in 0..4 {
        *l *= c;
    }
}

#[cfg(test)]
mod tests {
    use crate::*;

    #[test]
    fn reset() {
        let mut h = Poseidon::default();
        for _ in 0..MERKLE_ARITY {
            h.push(Scalar::one()).unwrap();
        }
        h.hash();
        h.reset();

        assert_eq!(Poseidon::default(), h);
    }

    #[test]
    fn hash_det() {
        let mut h = Poseidon::default();
        h.push(Scalar::one()).unwrap();

        let mut h2 = h.clone();
        let result = h.hash();

        assert_eq!(result, h2.hash());
    }
}