pmtree/README.md

95 lines
2.1 KiB
Markdown
Raw Permalink Normal View History

2022-10-19 12:18:34 +00:00
<p align="center">
2022-10-30 20:35:36 +00:00
<img src="./pmtree.png" width="150">
</p>
<p align="center">
<img src="https://github.com/Rate-Limiting-Nullifier/pmtree/workflows/Build-Test-Fmt/badge.svg" width="140">
2022-10-19 12:18:34 +00:00
</p>
2022-10-11 17:10:32 +00:00
<h1 align="center">pmtree</h1>
<h3 align="center">Persistent Merkle Tree (optimized & sparse & fixed-size) in Rust</h3>
2022-10-11 17:10:32 +00:00
## How to use
```toml
[dependencies]
pmtree = { git = "https://github.com/Rate-Limiting-Nullifier/pmtree" }
2022-10-11 17:21:26 +00:00
```
2022-12-10 14:19:00 +00:00
## Example
2022-10-19 12:18:34 +00:00
2022-12-10 14:19:00 +00:00
In-Memory DB (HashMap) + Keccak
```rust
struct MemoryDB(HashMap<DBKey, Value>);
struct MyKeccak(Keccak);
2023-02-13 12:32:40 +00:00
#[derive(Default)]
struct MemoryDBConfig;
2022-12-10 14:19:00 +00:00
impl Database for MemoryDB {
2023-02-13 12:32:40 +00:00
type Config = MemoryDBConfig;
2023-04-18 08:52:38 +00:00
fn new(_db_config: MemoryDBConfig) -> PmtreeResult<Self> {
2022-12-10 14:19:00 +00:00
Ok(MemoryDB(HashMap::new()))
}
2023-04-18 08:52:38 +00:00
fn load(_db_config: MemoryDBConfig) -> PmtreeResult<Self> {
Err(DatabaseError(DatabaseErrorKind::CannotLoadDatabase))
2022-12-10 14:19:00 +00:00
}
2023-04-18 08:52:38 +00:00
fn get(&self, key: DBKey) -> PmtreeResult<Option<Value>> {
2022-12-10 14:19:00 +00:00
Ok(self.0.get(&key).cloned())
}
2023-04-18 08:52:38 +00:00
fn put(&mut self, key: DBKey, value: Value) -> PmtreeResult<()> {
2022-12-10 14:19:00 +00:00
self.0.insert(key, value);
Ok(())
}
2023-02-02 17:13:04 +00:00
2023-04-18 08:52:38 +00:00
fn put_batch(&mut self, subtree: HashMap<DBKey, Value>) -> PmtreeResult<()> {
2023-02-02 17:13:04 +00:00
self.0.extend(subtree.into_iter());
Ok(())
}
2022-12-10 14:19:00 +00:00
}
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() {
2023-02-13 12:32:40 +00:00
let mut mt = MerkleTree::<MemoryDB, MyKeccak>::new(2, MemoryDBConfig).unwrap();
2022-12-10 14:19:00 +00:00
assert_eq!(mt.capacity(), 4);
assert_eq!(mt.depth(), 2);
2022-10-28 13:54:54 +00:00
2022-12-10 14:19:00 +00:00
mt.update_next(hex!(
"c1ba1812ff680ce84c1d5b4f1087eeb08147a4d510f3496b2849df3a73f5af95"
))
.unwrap();
}
2022-10-28 13:54:54 +00:00
```