Persistent Merkle Tree in Rust
Go to file
rymnc c34635f53a
chore: release v2.0.2
2024-05-17 14:34:23 +05:30
.github/workflows chore: update workflow (add caching) 2022-12-05 14:17:52 +03:00
src add constructor 2024-05-17 16:00:58 +07:00
tests fix: rename to vacp2p_pmtree 2023-07-28 14:10:10 +05:30
.gitignore init: add rust lib template 2022-10-11 19:48:08 +03:00
Cargo.toml chore: release v2.0.2 2024-05-17 14:34:23 +05:30
LICENSE-APACHE chore: add APACHE-2.0 License (dual) 2023-02-24 15:31:42 +04:00
LICENSE-MIT chore: rename LICENSE file to LICENSE-MIT 2023-02-24 15:30:51 +04:00
README.md fix: custom error enum 2023-04-18 14:22:38 +05:30
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) -> 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();
}