Persistent Merkle Tree in Rust
Go to file
Magamedrasul Ibragimov deac77c2b2 docs: update readme with Config 2023-02-13 16:32:40 +04:00
.github/workflows chore: update workflow (add caching) 2022-12-05 14:17:52 +03:00
src feat: add Config associated type to Database trait 2023-02-10 14:52:45 +04:00
tests feat: add Config associated type to Database trait 2023-02-10 14:52:45 +04: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 docs: update readme with Config 2023-02-13 16:32:40 +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);

#[derive(Default)]
struct MemoryDBConfig;

impl Database for MemoryDB {
    type Config = MemoryDBConfig;

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

    fn load(_db_config: MemoryDBConfig) -> Result<Self> {
        Err(Box::new(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(())
    }

    fn put_batch(&mut self, subtree: HashMap<DBKey, Value>) -> Result<()> {
        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();
}