#merkle-tree #db #value #key-value #default #pmtree

vacp2p_pmtree

Rust中的持久化Merkle树

3个稳定版本

2.0.2 2024年5月17日
1.0.0 2023年7月28日

#1447 in 数据库接口

Download history 63/week @ 2024-04-15 261/week @ 2024-05-13 42/week @ 2024-05-20 1/week @ 2024-05-27 28/week @ 2024-06-03 44/week @ 2024-06-10 9/week @ 2024-06-17 8/week @ 2024-06-24 12/week @ 2024-07-01 18/week @ 2024-07-08 18/week @ 2024-07-15 4/week @ 2024-07-22 67/week @ 2024-07-29

每月 109 次下载
2 个Crate中使用(通过 zerokit_utils

MIT/Apache

115KB
368

pmtree

Rust中的持久化Merkle树(优化 & 稀疏 & 固定大小)

如何使用

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

示例

内存数据库(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();
}

依赖关系

~1.5MB
~27K SLoC