You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

254 lines
7.8 KiB

  1. // merkletree.rs implements a simple binary insert-only merkletree in which the leafs positions is
  2. // determined by the leaf value binary representation. Inspired by
  3. // https://docs.iden3.io/publications/pdfs/Merkle-Tree.pdf (which can be found implemented in
  4. // https://github.com/vocdoni/arbo).
  5. use ark_ff::{BigInteger, PrimeField};
  6. use ark_serialize::CanonicalSerialize;
  7. use ark_std::log2;
  8. use ark_std::marker::PhantomData;
  9. use sha3::{Digest, Keccak256};
  10. // abstraction to set the hash function used
  11. pub trait Hash<F>: Clone {
  12. fn hash(_in: &[F]) -> F;
  13. }
  14. #[derive(Clone, Copy, Debug)]
  15. pub struct Keccak256Hash<F: PrimeField> {
  16. phantom: PhantomData<F>,
  17. }
  18. impl<F: PrimeField> Hash<F> for Keccak256Hash<F> {
  19. fn hash(_in: &[F]) -> F {
  20. let mut buf = vec![];
  21. _in.serialize_uncompressed(&mut buf).unwrap();
  22. let mut h = Keccak256::default();
  23. h.update(buf);
  24. let r = h.finalize();
  25. let out = F::from_le_bytes_mod_order(&r);
  26. out
  27. }
  28. }
  29. #[derive(Clone, Debug)]
  30. pub struct Node<F: PrimeField, H: Hash<F>> {
  31. phantom: PhantomData<H>,
  32. hash: F,
  33. left: Option<Box<Node<F, H>>>,
  34. right: Option<Box<Node<F, H>>>,
  35. value: Option<F>,
  36. }
  37. impl<F: PrimeField, H: Hash<F>> Node<F, H> {
  38. pub fn new_leaf(v: F) -> Self {
  39. let h = H::hash(&[v]);
  40. Self {
  41. phantom: PhantomData::<H>,
  42. hash: h,
  43. left: None,
  44. right: None,
  45. value: Some(v),
  46. }
  47. }
  48. pub fn new_node(l: Self, r: Self) -> Self {
  49. let left = Box::new(l);
  50. let right = Box::new(r);
  51. let hash = H::hash(&[left.hash, right.hash]);
  52. Self {
  53. phantom: PhantomData::<H>,
  54. hash,
  55. left: Some(left),
  56. right: Some(right),
  57. value: None,
  58. }
  59. }
  60. }
  61. pub struct MerkleTree<F: PrimeField, H: Hash<F>> {
  62. pub root: Node<F, H>,
  63. nlevels: u32,
  64. }
  65. impl<F: PrimeField, H: Hash<F>> MerkleTree<F, H> {
  66. pub fn commit(values: &[F]) -> (F, Self) {
  67. // for the moment assume that values length is a power of 2.
  68. if (values.len() != 0) && (values.len() & (values.len() - 1) != 0) {
  69. panic!("values.len() should be a power of 2");
  70. }
  71. // prepare the leafs
  72. let mut leaf_nodes: Vec<Node<F, H>> = Vec::new();
  73. for i in 0..values.len() {
  74. let node = Node::<F, H>::new_leaf(values[i]);
  75. leaf_nodes.push(node);
  76. }
  77. // go up from the leafs to the root
  78. let top_nodes = Self::up_from_nodes(leaf_nodes);
  79. (
  80. top_nodes[0].hash,
  81. Self {
  82. root: top_nodes[0].clone(),
  83. nlevels: log2(values.len()),
  84. },
  85. )
  86. }
  87. fn up_from_nodes(nodes: Vec<Node<F, H>>) -> Vec<Node<F, H>> {
  88. if nodes.len() == 0 {
  89. return [Node::<F, H> {
  90. phantom: PhantomData::<H>,
  91. hash: F::from(0_u32),
  92. left: None,
  93. right: None,
  94. value: None,
  95. }]
  96. .to_vec();
  97. }
  98. if nodes.len() == 1 {
  99. return nodes;
  100. }
  101. let mut next_level_nodes: Vec<Node<F, H>> = Vec::new();
  102. for i in (0..nodes.len()).step_by(2) {
  103. let node = Node::<F, H>::new_node(nodes[i].clone(), nodes[i + 1].clone());
  104. next_level_nodes.push(node);
  105. }
  106. return Self::up_from_nodes(next_level_nodes);
  107. }
  108. fn get_path(num_levels: u32, value: F) -> Vec<bool> {
  109. let value_bytes = value.into_bigint().to_bytes_le();
  110. let mut path = Vec::new();
  111. for i in 0..num_levels {
  112. path.push(value_bytes[(i / 8) as usize] & (1 << (i % 8)) != 0);
  113. }
  114. path
  115. }
  116. pub fn open(&self, index: F) -> Vec<F> {
  117. // start from root, and go down to the index, while getting the siblings at each level
  118. let path = Self::get_path(self.nlevels, index);
  119. // reverse path as we're going from up to down
  120. let path_inv = path.iter().copied().rev().collect();
  121. let mut siblings: Vec<F> = Vec::new();
  122. siblings = Self::go_down(path_inv, self.root.clone(), siblings);
  123. return siblings;
  124. }
  125. fn go_down(path: Vec<bool>, node: Node<F, H>, mut siblings: Vec<F>) -> Vec<F> {
  126. if !node.value.is_none() {
  127. return siblings;
  128. }
  129. if !path[0] {
  130. siblings.push(node.right.unwrap().hash);
  131. return Self::go_down(path[1..].to_vec(), *node.left.unwrap(), siblings);
  132. } else {
  133. siblings.push(node.left.unwrap().hash);
  134. return Self::go_down(path[1..].to_vec(), *node.right.unwrap(), siblings);
  135. }
  136. }
  137. pub fn verify(root: F, index: F, value: F, siblings: Vec<F>) -> bool {
  138. let mut h = H::hash(&[value]);
  139. let path = Self::get_path(siblings.len() as u32, index);
  140. for i in 0..siblings.len() {
  141. if !path[i] {
  142. h = H::hash(&[h, siblings[siblings.len() - 1 - i]]);
  143. } else {
  144. h = H::hash(&[siblings[siblings.len() - 1 - i], h]);
  145. }
  146. }
  147. if h == root {
  148. return true;
  149. }
  150. false
  151. }
  152. }
  153. #[cfg(test)]
  154. mod tests {
  155. use super::*;
  156. use ark_std::UniformRand;
  157. pub type Fr = ark_bn254::Fr; // scalar field
  158. #[test]
  159. fn test_path() {
  160. assert_eq!(
  161. MerkleTree::<Fr, Keccak256Hash<Fr>>::get_path(8, Fr::from(0_u32)),
  162. [false, false, false, false, false, false, false, false]
  163. );
  164. assert_eq!(
  165. MerkleTree::<Fr, Keccak256Hash<Fr>>::get_path(8, Fr::from(1_u32)),
  166. [true, false, false, false, false, false, false, false]
  167. );
  168. assert_eq!(
  169. MerkleTree::<Fr, Keccak256Hash<Fr>>::get_path(8, Fr::from(2_u32)),
  170. [false, true, false, false, false, false, false, false]
  171. );
  172. assert_eq!(
  173. MerkleTree::<Fr, Keccak256Hash<Fr>>::get_path(8, Fr::from(3_u32)),
  174. [true, true, false, false, false, false, false, false]
  175. );
  176. assert_eq!(
  177. MerkleTree::<Fr, Keccak256Hash<Fr>>::get_path(8, Fr::from(254_u32)),
  178. [false, true, true, true, true, true, true, true]
  179. );
  180. assert_eq!(
  181. MerkleTree::<Fr, Keccak256Hash<Fr>>::get_path(8, Fr::from(255_u32)),
  182. [true, true, true, true, true, true, true, true]
  183. );
  184. }
  185. #[test]
  186. fn test_new_empty_tree() {
  187. let (root, mt) = MerkleTree::<Fr, Keccak256Hash<Fr>>::commit(&[]);
  188. assert_eq!(mt.root.hash, Fr::from(0_u32));
  189. assert_eq!(root, Fr::from(0_u32));
  190. }
  191. #[test]
  192. fn test_proof() {
  193. type MT = MerkleTree<Fr, Keccak256Hash<Fr>>;
  194. let values = [
  195. Fr::from(0_u32),
  196. Fr::from(1_u32),
  197. Fr::from(2_u32),
  198. Fr::from(3_u32),
  199. Fr::from(200_u32),
  200. Fr::from(201_u32),
  201. Fr::from(202_u32),
  202. Fr::from(203_u32),
  203. ];
  204. let (root, mt) = MT::commit(&values);
  205. assert_eq!(
  206. root.to_string(),
  207. "6195952497672867974990959901930625199810318409246598214215524466855665265259"
  208. );
  209. let index = 3;
  210. let index_F = Fr::from(index as u32);
  211. let siblings = mt.open(index_F);
  212. assert!(MT::verify(root, index_F, values[index], siblings));
  213. }
  214. #[test]
  215. fn test_proofs() {
  216. type MT = MerkleTree<Fr, Keccak256Hash<Fr>>;
  217. let mut rng = ark_std::test_rng();
  218. let n_values = 64;
  219. let mut values: Vec<Fr> = Vec::new();
  220. for _i in 0..n_values {
  221. let v = Fr::rand(&mut rng);
  222. values.push(v);
  223. }
  224. let (root, mt) = MT::commit(&values);
  225. assert_eq!(mt.nlevels, 6);
  226. for i in 0..n_values {
  227. let i_Fr = Fr::from(i as u32);
  228. let siblings = mt.open(i_Fr);
  229. assert!(MT::verify(root, i_Fr, values[i], siblings));
  230. }
  231. }
  232. }