tiny-merkle 0.3.0

A tiny merkle tree library for Ethereum
Documentation

MerkleTree for Ethereum

Build status Crates.io Documentation

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