tiny_merkle/
proof.rs

1use alloc::vec::Vec;
2
3use crate::hash::Hasher;
4
5/// Position of a leaf in the tree.
6#[derive(Debug, Clone, PartialEq)]
7pub enum Position {
8	Left,
9	Right,
10}
11
12#[cfg(feature = "std")]
13impl core::fmt::Display for Position {
14	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
15		match self {
16			Position::Left => write!(f, "Left"),
17			Position::Right => write!(f, "Right"),
18		}
19	}
20}
21
22/// pair of hash and position
23#[derive(Debug, Clone)]
24pub struct Pair<H>
25where
26	H: Hasher,
27{
28	pub data: H::Hash,
29	pub position: Position,
30}
31
32/// Merkle proof for a leaf.
33#[derive(Clone)]
34pub struct MerkleProof<H>
35where
36	H: Hasher,
37{
38	pub proofs: Vec<Pair<H>>,
39}
40
41#[cfg(feature = "std")]
42impl<H> core::fmt::Debug for MerkleProof<H>
43where
44	H: Hasher + core::fmt::Debug,
45	H::Hash: core::fmt::Debug,
46{
47	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
48		write!(f, "MerkleProof {{ proofs: {:?} }}", self.proofs)
49	}
50}
51
52#[cfg(all(test, feature = "std"))]
53mod tests {
54	use super::*;
55	use crate::{merkle::tests::KeccakHasher, MerkleTree};
56	use alloc::format;
57	#[allow(unused_imports)]
58	use alloc::vec;
59
60	#[test]
61	fn test_debug() {
62		let leaves = ["a", "b", "c", "d", "e", "f"]
63			.iter()
64			.map(|x| KeccakHasher::hash(x.as_bytes()))
65			.collect::<Vec<_>>();
66		let mtree = MerkleTree::<KeccakHasher>::from_leaves(leaves, None);
67		let _root = mtree.root();
68
69		// verify the proof of the first leaf
70		let leaf = KeccakHasher::hash("a".as_bytes());
71		let proof = mtree.proof(leaf).unwrap();
72		// assert!(mtree.verify(&leaf, &root, &proof));
73		format!("{:?}", proof);
74	}
75}