Persistent Merkle Tree in Rust
Go to file
Magamedrasul Ibragimov 689a3e2ed4 chore: add frame for batch_insertions 2023-01-29 15:07:42 +04:00
.github/workflows chore: update workflow (add caching) 2022-12-05 14:17:52 +03:00
src chore: add frame for batch_insertions 2023-01-29 15:07:42 +04:00
tests refactor: remove useless prints 2022-12-10 16:41:07 +03:00
.gitignore init: add rust lib template 2022-10-11 19:48:08 +03:00
Cargo.toml chore: remove batch_insert feature & make it default 2023-01-27 15:07:35 +04:00
LICENSE.md chore: add LICENSE 2022-10-19 15:26:59 +03:00
README.md chore: remove batch_insert feature & make it default 2023-01-27 15:07:35 +04:00
pmtree.png docs: customize README 2022-10-30 23:35:36 +03:00

README.md

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);

impl Database for MemoryDB {
    fn new(_dbpath: &str) -> Result<Self> {
        Ok(MemoryDB(HashMap::new()))
    }

    fn load(_dbpath: &str) -> Result<Self> {
        Err(Error("Cannot load in-memory DB".to_string()))
    }

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

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

        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, "abacaba").unwrap();

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

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