Generates a proof for a given index. Returns the leaf as well.
(&self, index: u32)
| 57 | |
| 58 | /// Generates a proof for a given index. Returns the leaf as well. |
| 59 | pub fn generate_proof(&self, index: u32) -> ([u8; 32], MMRInclusionProof) { |
| 60 | if self.nodes[0].len() == 0 { |
| 61 | panic!("MMR is empty"); |
| 62 | } |
| 63 | if self.nodes[0].len() <= index as usize { |
| 64 | panic!("Index out of bounds"); |
| 65 | } |
| 66 | let mut proof: Vec<[u8; 32]> = vec![]; |
| 67 | let mut current_index = index; |
| 68 | let mut current_level = 0; |
| 69 | // Returns the subtree proof for the subroot. |
| 70 | while !(current_index == self.nodes[current_level].len() as u32 - 1 |
| 71 | && self.nodes[current_level].len() % 2 == 1) |
| 72 | { |
| 73 | let sibling_index = if current_index % 2 == 0 { |
| 74 | current_index + 1 |
| 75 | } else { |
| 76 | current_index - 1 |
| 77 | }; |
| 78 | proof.push(self.nodes[current_level][sibling_index as usize]); |
| 79 | current_index = current_index / 2; |
| 80 | current_level += 1; |
| 81 | } |
| 82 | let (subroot_idx, internal_idx) = self.get_helpers_from_index(index); |
| 83 | let mmr_proof = MMRInclusionProof::new(subroot_idx, internal_idx, proof); |
| 84 | (self.nodes[0][index as usize], mmr_proof) |
| 85 | } |
| 86 | |
| 87 | /// Given an index, returns the subroot index (which subtree the index is in), subtree size, and internal index (of the subtree that the index belongs to). |
| 88 | fn get_helpers_from_index(&self, index: u32) -> (usize, u32) { |