next_index: u32 // Next available leaf index (0-1023)filled_subtrees: Map<u32, u256> // Last hash at each level (sparse optimization)roots: Map<u32, u256> // Ring buffer of recent rootscurrent_root_index: u32 // Current position in ring buffercommitments: Map<u256, bool> // Commitment uniqueness check
fn _insert(ref self: ContractState, leaf: u256) -> u32 { let current_index = self.next_index.read(); assert(current_index < 1024, 'Pool: tree full'); let mut current_hash = leaf; let mut current_level_index = current_index; let mut i: u32 = 0; while i < TREE_DEPTH { if current_level_index % 2 == 0 { // Left child: store current hash, pair with zero self.filled_subtrees.write(i, current_hash); let zero_hash = self._get_zero_value(i); current_hash = bn254_hash_pair(current_hash, zero_hash); } else { // Right child: pair with stored left sibling let left = self.filled_subtrees.read(i); current_hash = bn254_hash_pair(left, current_hash); } current_level_index = current_level_index / 2; i += 1; }; // Store new root in ring buffer let new_root_index = (self.current_root_index.read() + 1) % ROOT_HISTORY_SIZE; self.roots.write(new_root_index, current_hash); self.current_root_index.write(new_root_index); let leaf_index = current_index; self.next_index.write(current_index + 1); leaf_index}
Read current leaf index (next_index)
Starting from level 0, compute parent hashes:
If index is even: store hash, pair with zero on right
If index is odd: pair stored left sibling with current hash
fn _is_known_root(self: @ContractState, root: u256) -> bool { if root == 0 { return false; } let current = self.current_root_index.read(); let mut i: u32 = 0; let mut found = false; while i < ROOT_HISTORY_SIZE { let idx = if current >= i { current - i } else { ROOT_HISTORY_SIZE - (i - current) }; if self.roots.read(idx) == root { found = true; break; } i += 1; }; found}
Root History Window: 30 roots ≈ 30 deposits of latency tolerance. If a user generates a proof using root R, they have ~30 deposits to submit it before R expires.