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
#![feature(external_doc)]
#![deny(missing_docs)]
#![doc(include = "../README.md")]

use std::ops;

use lazy_static::*;
#[cfg(feature = "big-merkle")]
use serde::{Deserialize, Serialize};

pub use crate::poseidon::Poseidon;
pub use curve25519_dalek::scalar::Scalar;
pub use error::Error;
pub use merkle::MerkleTree;
pub use proof::Proof;

#[cfg(feature = "big-merkle")]
pub use big_merkle::{BigMerkleTree, BigProof, MerkleCoord, MerkleRange};

mod error;
mod merkle;
mod poseidon;
mod proof;

#[cfg(feature = "big-merkle")]
mod big_merkle;

include!("constants.rs");

lazy_static! {
    static ref ROUND_CONSTANTS: [Scalar; 960] = {
        let bytes = include_bytes!("../assets/ark.bin");
        unsafe { std::ptr::read(bytes.as_ptr() as *const _) }
    };
    static ref MDS_MATRIX: [[Scalar; WIDTH]; WIDTH] = {
        let bytes = include_bytes!("../assets/mds.bin");
        assert_eq!(bytes.len(), (WIDTH * WIDTH) << 5);
        unsafe { std::ptr::read(bytes.as_ptr() as *const _) }
    };
}

/// The items for the [`MerkleTree`] and [`Poseidon`] must implement this trait
///
/// The implementation must be serializable for the [`BigMerkleTree`] storage
#[cfg(feature = "big-merkle")]
pub trait PoseidonLeaf:
    Copy
    + From<u64>
    + From<Scalar>
    + From<[u8; 32]>
    + PartialEq
    + ops::MulAssign
    + ops::AddAssign
    + Serialize
    + for<'d> Deserialize<'d>
    + Send
    + Sync
{
}

/// The items for the [`MerkleTree`] and [`Poseidon`] must implement this trait
#[cfg(not(feature = "big-merkle"))]
pub trait PoseidonLeaf:
    Copy + From<u64> + From<Scalar> + PartialEq + ops::MulAssign + ops::AddAssign
{
}

impl PoseidonLeaf for Scalar {}

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

    #[test]
    fn constants_consistency() {
        // Grant we have enough constants for the sbox rounds
        assert!(WIDTH * (FULL_ROUNDS + PARTIAL_ROUNDS) <= ROUND_CONSTANTS.len());

        // Sanity check for the arity
        assert!(MERKLE_ARITY > 1);

        // Sanity check for the height
        assert!(MERKLE_HEIGHT > 1);

        // Enforce a relation between the provided MDS matrix and the arity of the merkle tree
        assert_eq!(WIDTH, MERKLE_ARITY + 1);

        // Enforce at least one level for the merkle tree
        assert!(MERKLE_WIDTH > MERKLE_ARITY);

        // Grant the defined arity is consistent with the defined width
        assert_eq!(
            MERKLE_ARITY.pow(std::cmp::max(2, MERKLE_HEIGHT as u32)),
            MERKLE_WIDTH
        );
    }
}