arkworks-rs / crypto-primitives

Interfaces and implementations of cryptographic primitives, along with R1CS constraints for them
https://www.arkworks.rs
Apache License 2.0
179 stars 88 forks source link

Add `TreeHash` API for use specifically within a Merkle Tree #37

Closed Pratyush closed 3 years ago

Pratyush commented 3 years ago

This is not a blocker for this API, but maybe instead of trying to design a general API for hashing two inputs into one, we should have specialized traits for hashing in the context of a Merkle tree. For example:

pub trait TreeHash {
    type Parameters;
    type InputOutput;
    const ARITY; // We can set this to just 2 for the time being.

    fn setup() -> Self::Parameters;

    /// Panics if .
    fn hash_inner_node(params: &Self::Parameters, hashes: &[Self::InputOutput]) -> Self::InputOutput;

    /// Hash the bottom layer. First, use  to hash the leaf object, and then
    /// convert the output of  to . (maybe by internally re-hashing.)
    fn hash_leaf<LeafHash: CRH>(
        params: &Self::Parameters, 
        leaf_hash_params: &LeafHash::Parameters, 
        leaf: &[u8]
    ) -> Self::InputOutput {
        // hash the leaf using LeafHash, convert the output to bytes,
        // and then internally handle the conversion to .
        // For example, if  is , then use .
        // Else, if it's bytes, then there's no need to convert.
        // We can add specializations using  to avoid the conversion when 
        // , or when  is some known hash, 
        // like  or something.
    }
}

For pedersen::CRH, bowe_hopwood::CRH, and blake2s/sha256::CRH, the InputOutput type would be Vec<u8>, while for poseidon::CRH, it would be Vec<F> (or maybe [F; 2], or whatever the output size is). This way, the Merkle tree doesn't incur the overhead of converting into bytes at each step, and we've also made it very clear that these hashes are for use in a Merkle tree, and not (necessarily) outside that.

What do you think? @ValarDragon @tsunrise?

Originally posted by @Pratyush in https://github.com/arkworks-rs/crypto-primitives/issues/30#issuecomment-819369640

burdges commented 3 years ago

Arity is only rarely even on SNARK friendly hashes, right?