#merkle-tree #keccak256 #merkle-proof #merkle-root #blockchain

merkletreerust

🌳 The simple and easy implementation of Merkle Tree

4 releases

0.1.7 Feb 21, 2023
0.1.6 Feb 21, 2023
0.1.5 Feb 7, 2023
0.1.4 Feb 7, 2023

#7 in #keccak256

23 downloads per month

MIT license

23KB
375 lines


merkletree.js logo


MerkleTreeRust

Install

# Cargo.toml

[dependencies]
merkletreerust = "*"

Getting started

Construct tree, generate proof

use merkeltreerust::merkeltree::MerkelTree;
use merkeltreerust::option::Options;
use merkeltreerust::buffer::Buffer;
use merkeltreerust::error::MerkelTreeError;
use tiny_keccak::{Hasher, Keccak};

let whitelist_address: Vec<Buffer> = vec![
    "0x6dC0c0be4c8B2dFE750156dc7d59FaABFb5B923D".parse::<Buffer>()?,
    "0xa8d17cc9caf29af964d19267ddeb4dff122697b0".parse::<Buffer>()?
];

let options = Options { duplicate_odd: false, sort_pairs: true, sort_leaves: true, sort: true, hash_leaves: true };
let hash_fn = |buf: &[u8]| {
    let mut k256 = Keccak::v256();
    let mut result = [0; 32];
    k256.update(buf);
    k256.finalize(&mut result);
    result.to_vec()
};
let merkle_tree = MerkelTree::new(whitelist_address, hash_fn, options);

let root = merkle_tree.get_root()?.to_hex();
let leaf = "0x6dC0c0be4c8B2dFE750156dc7d59FaABFb5B923D";
let proof = merkle_tree.get_hex_proof(leaf.parse::<Buffer>()?)?;

println!("root: {:?}", root);
println!("leaf: {:?}", leaf);
println!("proof: {:?}", proof);

Output:

root:0xdb44a1f32851683f64d15a563ecd3686b67de2075821b6196dbaf7d25604592f
leaf:0x6dC0c0be4c8B2dFE750156dc7d59FaABFb5B923D
proof:["0x7fa4f9a213fc25511745e0fe7627ab0d7145664238bd854fb781559c2ddbf9c4"]

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

Dependencies

~76KB