tiny-merkle

Crates.iotiny-merkle
lib.rstiny-merkle
version0.3.0
sourcesrc
created_at2023-11-22 14:42:43.592569
updated_at2024-02-02 07:50:34.007769
descriptionA tiny merkle tree library for Ethereum
homepage
repositoryhttps://github.com/chiaos/merkletree
max_upload_size
id1045227
size73,588
chaio-l-cd (chiaos)

documentation

README


merkletree.js logo


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

Merkle Tree

▾ Visualization of Merkle Tree Proof

Merkle Tree Proof

▾ Visualization of Invalid Merkle Tree Proofs

Merkle Tree Proof

▾ Visualization of Bitcoin Merkle Tree

Merkle Tree Proof

License

This project is licensed under the MIT License - see the LICENSE.md file for details

Commit count: 8

cargo fmt