3 stable releases

2.0.2 May 17, 2024
1.0.0 Jul 28, 2023

#1179 in Cryptography

Download history 6/week @ 2024-07-20 63/week @ 2024-07-27 22/week @ 2024-08-03 26/week @ 2024-08-10 27/week @ 2024-08-17 24/week @ 2024-08-24 69/week @ 2024-08-31 64/week @ 2024-09-07 33/week @ 2024-09-14 48/week @ 2024-09-21 33/week @ 2024-09-28 13/week @ 2024-10-05 29/week @ 2024-10-12 10/week @ 2024-10-19 8/week @ 2024-10-26 5/week @ 2024-11-02

53 downloads per month
Used in 2 crates (via zerokit_utils)

MIT/Apache

115KB
368 lines

pmtree

Persistent Merkle Tree (optimized & sparse & fixed-size) in Rust

How to use

[dependencies]
pmtree = { git = "https://github.com/Rate-Limiting-Nullifier/pmtree" }

Example

In-Memory DB (HashMap) + Keccak

struct MemoryDB(HashMap<DBKey, Value>);
struct MyKeccak(Keccak);

#[derive(Default)]
struct MemoryDBConfig;

impl Database for MemoryDB {
    type Config = MemoryDBConfig;

    fn new(_db_config: MemoryDBConfig) -> PmtreeResult<Self> {
        Ok(MemoryDB(HashMap::new()))
    }

    fn load(_db_config: MemoryDBConfig) -> PmtreeResult<Self> {
        Err(DatabaseError(DatabaseErrorKind::CannotLoadDatabase))
    }

    fn get(&self, key: DBKey) -> PmtreeResult<Option<Value>> {
        Ok(self.0.get(&key).cloned())
    }

    fn put(&mut self, key: DBKey, value: Value) -> PmtreeResult<()> {
        self.0.insert(key, value);

        Ok(())
    }

    fn put_batch(&mut self, subtree: HashMap<DBKey, Value>) -> PmtreeResult<()> {
        self.0.extend(subtree.into_iter());

        Ok(())
    }
}

impl Hasher for MyKeccak {
    type Fr = [u8; 32];

    fn default_leaf() -> Self::Fr {
        [0; 32]
    }

    fn serialize(value: Self::Fr) -> Value {
        value.to_vec()
    }

    fn deserialize(value: Value) -> Self::Fr {
        value.try_into().unwrap()
    }

    fn hash(input: &[Self::Fr]) -> Self::Fr {
        let mut output = [0; 32];
        let mut hasher = Keccak::v256();
        for element in input {
            hasher.update(element);
        }
        hasher.finalize(&mut output);
        output
    }
}

fn main() {
    let mut mt = MerkleTree::<MemoryDB, MyKeccak>::new(2, MemoryDBConfig).unwrap();

    assert_eq!(mt.capacity(), 4);
    assert_eq!(mt.depth(), 2);

    mt.update_next(hex!(
        "c1ba1812ff680ce84c1d5b4f1087eeb08147a4d510f3496b2849df3a73f5af95"
    ))
    .unwrap();
}

Dependencies

~1.5MB
~27K SLoC