Skip to content

Commit

Permalink
fix: overflowing subtractions when accessing op stack underflow
Browse files Browse the repository at this point in the history
  • Loading branch information
jan-ferdinand committed Oct 19, 2023
1 parent 49424a6 commit 2aa72e7
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions triton-vm/src/op_stack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,14 @@ impl OpStack {
/// The first element of the op-stack underflow memory, or 0 if the op-stack underflow memory
/// is empty.
pub(crate) fn first_underflow_element(&self) -> BFieldElement {
let top_of_stack_index = self.stack.len() - 1;
let underflow_start = top_of_stack_index - OpStackElement::COUNT;
self.stack.get(underflow_start).copied().unwrap_or_default()
let default = BFieldElement::zero();
let Some(top_of_stack_index) = self.stack.len().checked_sub(1) else {
return default;
};
let Some(underflow_start) = top_of_stack_index.checked_sub(OpStackElement::COUNT) else {
return default;
};
self.stack.get(underflow_start).copied().unwrap_or(default)
}
}

Expand Down Expand Up @@ -392,6 +397,16 @@ mod tests {
assert!(op_stack.is_too_shallow());
}

#[test]
fn trying_to_access_first_underflow_element_never_panics() {
let mut op_stack = OpStack::new(Default::default());
let way_too_long = 2 * op_stack.stack.len();
for _ in 0..way_too_long {
let _ = op_stack.pop();
let _ = op_stack.first_underflow_element();
}
}

#[test]
fn canonicalize_empty_underflow_io_sequence() {
let mut sequence = vec![];
Expand Down

0 comments on commit 2aa72e7

Please sign in to comment.