5 unstable releases
0.3.0 | Feb 2, 2024 |
---|---|
0.2.0 | Dec 6, 2023 |
0.1.2 | Dec 2, 2023 |
0.1.1 | Nov 30, 2023 |
0.1.0 | Nov 22, 2023 |
#62 in #merkle
28KB
556 lines
MerkleTree for Ethereum
Contents
Usage
Add the following to your Cargo.toml
:
[dependencies]
tiny-merkle = "0.2"
tiny-keccak = { version = "2.0.2", features = ["keccak"] }
Construct tree, generate proof, and verify proof:
use tiny_merkle::MerkleTree;
use tiny_keccak::{Hasher, Keccak};
#[derive(Clone, Debug)]
pub struct KeccakHasher;
impl tiny_merkle::Hasher for KeccakHasher {
type Hash = [u8; 32];
fn hash(value: &[u8]) -> Self::Hash {
keccak256(value)
}
}
fn keccak256(data: &[u8]) -> [u8; 32] {
let mut hasher = Keccak::v256();
let mut hash = [0_u8; 32];
hasher.update(data);
hasher.finalize(&mut hash);
hash
}
fn main() {
let data_raw = vec!["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"];
let leaves = data_raw.iter().map(|s| keccak256(&s.as_bytes())).collect::<Vec<_>>();
let tree = MerkleTree::<KeccakHasher>::from_leaves(leaves.clone(), Some(tiny_merkle::MerkleOptions::default().with_sort(true)));
println!("root: {}", hex::encode(tree.root()));
let proof = tree.proof(&leaves[0]).unwrap();
let ok = tree.verify(&leaves[0], &tree.root(), &proof);
println!("verify: {}", ok);
}
Diagrams
▾ Visualization of Merkle Tree
▾ Visualization of Merkle Tree Proof
▾ Visualization of Invalid Merkle Tree Proofs
▾ Visualization of Bitcoin Merkle Tree
License
This project is licensed under the MIT License - see the LICENSE.md file for details
Dependencies
~0–265KB