2 releases
0.1.1 | Aug 16, 2023 |
---|---|
0.1.0 | Aug 16, 2023 |
#23 in #constructing
320KB
381 lines
Ethereum Merkle Tree Library (eth-merkle-tree-rs
)
A Rust library and command-line interface (CLI) for working with Ethereum's Merkle tree structure.
Table of Contents
Installation
To include eth-merkle-tree-rs
in your project, add it to your Cargo.toml
:
[dependencies.lib]
petgraph = "0.6"
hex = "0.4"
rust-crypto = "0.2"
[dependencies.bin]
petgraph = "0.6"
hex = "0.4"
rust-crypto = "0.2"
structopt = "0.3"
csv = "1.1"
colored = "2.0"
Library Usage
Constructing the Merkle Tree
use eth_merkle_tree::tree::MerkleTree;
let data = vec![
String::from("0x901Ab22EdCA65188686C9742F2C88c946698bc90, 100"),
String::from("0x7b95d138cD923476b6e697391DD2aA01D15BAB27, 100"),
];
let tree = MerkleTree::new(data).expect("Tree creation error.");
let root = tree.root.expect("Unable to access root");
println!("Root: {}", root.data);
or
use eth_merkle_tree::tree::MerkleTree;
let data = vec![
String::from("0x901Ab22EdCA65188686C9742F2C88c946698bc90"),
String::from("0x7b95d138cD923476b6e697391DD2aA01D15BAB27"),
];
let tree = MerkleTree::new(data).expect("Tree creation error.");
let root = tree.root.expect("Unable to access root");
println!("Root: {}", root.data);
Visualizing the Tree
Can visualize the tree structure using the provided visualization tools:
Note: To visualize the Merkle Tree, ensure that Graphviz is installed on your system.
use eth_merkle_tree::graph::visualizer::graphviz;
graphviz(&tree).expect("Visualization Error!");
CLI Usage
The library also comes with a command-line interface for interacting with Merkle trees.
Visualize the Tree
To visualize the tree, use the -v or --visualize flag:
$ emtr -- ./example.txt -v
Generate a Merkle Proof
To generate a Merkle proof for a specific leaf:
$ emtr -- ./example.txt --proof 0x901Ab22EdCA65188686C9742F2C88c946698bc90
Validating a proof in Solidity
Once the proof has been generated, it can be validated in Solidity using MerkleProof as in the following example:
pragma solidity >=0.8.0 <0.9.0;
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
contract Verifier {
bytes32 private root;
constructor(bytes32 _root) {
root = _root;
}
function verify(
bytes32[] memory proof,
address addr,
uint256 amount
) public view {
bytes32 leaf = keccak256(abi.encode(addr, amount));
require(MerkleProof.verify(proof, root, leaf), "Invalid proof");
}
function verify(
bytes32[] memory proof,
address addr
) public view {
bytes32 leaf = keccak256(abi.encodePacked(addr));
require(MerkleProof.verify(proof, root, leaf), "Invalid proof");
}
}
License
This project is licensed under the MIT License. See the LICENSE file for details.
Dependencies
~10–21MB
~207K SLoC