Skip to content

Commit

Permalink
MMR append change loops to pop from span
Browse files Browse the repository at this point in the history
  • Loading branch information
fmkra committed Mar 22, 2024
1 parent 1e2bc3f commit c65b8e3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 18 deletions.
32 changes: 14 additions & 18 deletions src/data_structures/mmr/mmr.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -49,32 +49,28 @@ impl MMRImpl of MMRTrait {

self.last_pos += 1;

// TODO: why number of new peaks is equal to number of trailing ones
let new_peaks_count = trailing_ones(leaf_count);
let mut new_peak = hash;
let mut i = 0;
let mut preserved_peaks = peaks.slice(0, peaks_count - new_peaks_count);
let mut merged_peaks = peaks.slice(peaks_count - new_peaks_count, new_peaks_count);

let mut last_peak = hash;
loop {
if i == new_peaks_count {
break ();
}

new_peak = PoseidonHasher::hash_double(*peaks.at(peaks.len() - i - 1), new_peak);

i += 1;
match merged_peaks.pop_back() {
Option::Some(x) => { last_peak = PoseidonHasher::hash_double(*x, last_peak); },
Option::None => { break; }
};
self.last_pos += 1;
};

let mut new_peaks = ArrayTrait::new();
let mut i = 0;
loop {
if i == peaks_count - new_peaks_count {
break ();
}
new_peaks.append(*peaks.at(i));

i += 1;
match preserved_peaks.pop_front() {
Option::Some(x) => { new_peaks.append(*x); },
Option::None => { break; }
};
};
new_peaks.append(new_peak);
new_peaks.append(last_peak);

let new_root = compute_root(self.last_pos.into(), new_peaks.span());
self.root = new_root;
Expand All @@ -98,7 +94,7 @@ impl MMRImpl of MMRTrait {
if !peaks.valid(*self.last_pos, *self.root) {
return Result::Err('Invalid peaks');
}

let (peak_index, peak_height) = get_peak_info(*self.last_pos, index);

if proof.len() != peak_height {
Expand Down
4 changes: 4 additions & 0 deletions src/data_structures/mmr/utils.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,17 @@ fn count_ones(n: u32) -> u32 {
// @notice Convert a leaf index to an Merkle Mountain Range tree index
// @param n The leaf index
// @return The MMR index
// Explanation of why this formula is correct
// https://mmr.herodotus.dev/mmr-size-vs-leaf-count#leaf-count-to-mmr-size-algorithm
fn leaf_index_to_mmr_index(n: u32) -> u32 {
2 * n - 1 - count_ones(n - 1)
}

// @notice Convert a Merkle Mountain Range tree size to number of leaves
// @param n MMR size
// @result Number of leaves
// Explanation of why this algorithm is correct
// https://mmr.herodotus.dev/mmr-size-vs-leaf-count#mmr-size-to-leaf-count-algorithm
fn mmr_size_to_leaf_count(n: u32) -> u32 {
let mut mmr_size = n;
let bits = bit_length(mmr_size + 1);
Expand Down

0 comments on commit c65b8e3

Please sign in to comment.