This project implements a Merkle Tree in Rust using SHA-256 hashing (via the sha2 crate`.
It supports:
- Building a Merkle tree from a list of input values
- Automatic leaf duplication for odd counts
- SHA-256 hashing for leaves and parent nodes
- Recursive Merkle tree construction
- ASCII tree visualization
A Merkle Tree is a binary tree where:
- Every leaf node contains the hash of some input data.
- Each internal node contains the hash of the concatenation of its two child nodes.
- The root hash cryptographically represents the entire dataset.
Merkle Trees are widely used in:
- Blockchain systems
- Distributed databases
- File integrity verification
- Peer-to-peer networks
Pass a Vec<T> and the tree takes care of hashing, balancing, and node creation.
All leaf and parent nodes use the hash algorithm provided by the sha2 crate.
If the number of leaves is odd, the last leaf is duplicated to maintain a complete binary structure.
The ASCII printing function produces output like this:
└── 3af...91bc
├── 19c...a23f
│ ├── 98f...1ac3
│ └── 11b...98dd
└── 4b9...de20
├── 77c...8120
└── 6ea...9f11
Clean and easy to understand.
let mut data = vec![
"a".to_owned(),
"b".to_owned(),
"c".to_owned(),
"d".to_owned(),
"e".to_owned(),
"f".to_owned(),
"g".to_owned(),
"h".to_owned(),
];let mut merkle_tree = MerkleTree::new();
merkle_tree.create(&mut data);print_tree(Some(merkle_tree.root));├── src
│ ├── main.rs
│
├── Cargo.toml
└── README.md
Add this to your Cargo.toml:
[dependencies]
sha2 = "0.10"Represents a node in the tree:
struct MerkelNode {
data: String,
left: Option<Box<MerkelNode>>,
right: Option<Box<MerkelNode>>,
}Handles constructing the entire tree and storing the root.
Utility function that computes a SHA-256 hash of any input convertible to bytes.
Pretty-prints the tree using ASCII symbols (├──, └──, │).
cargo run
You will see:
- The computed Merkle root
- The full tree printed in readable ASCII form
- Merkle proof generation & verification
- JSON or binary serialization
- Colorized tree output
- Parallel hashing for performance
- Avoid unnecessary cloning of nodes
This project is open-source and free to use.