From e422e5824f763592f8d0be83088c0d1204413275 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eduardo=20Leegwater=20Sim=C3=B5es?= Date: Mon, 9 Sep 2024 14:45:50 +0200 Subject: [PATCH] dusk-merkle: add bounds check at `Tree::insert` A panic on an out of bounds insertion is expected in the merkle tree, however, the panic message is a bit cryptic. This commit adds a bounds check (`index < capacity`) and improves the error message such that it is clear to whomever calls it. Resolves: #91 --- dusk-merkle/CHANGELOG.md | 5 +++++ dusk-merkle/src/tree.rs | 20 +++++++++++++++----- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/dusk-merkle/CHANGELOG.md b/dusk-merkle/CHANGELOG.md index b661377..823008b 100644 --- a/dusk-merkle/CHANGELOG.md +++ b/dusk-merkle/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## Added + +- Add bounds check on `Tree::insert`, improving panic message [#91] + ## [0.5.2] - 2023-10-27 ### Fixed @@ -102,6 +106,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fix `CheckBytes` derivation in `Node` [#15] +[#91]: https://github.com/dusk-network/merkle/issues/91 [#73]: https://github.com/dusk-network/merkle/issues/73 [#62]: https://github.com/dusk-network/merkle/issues/62 [#58]: https://github.com/dusk-network/merkle/issues/58 diff --git a/dusk-merkle/src/tree.rs b/dusk-merkle/src/tree.rs index 662cc86..eeaf7d9 100644 --- a/dusk-merkle/src/tree.rs +++ b/dusk-merkle/src/tree.rs @@ -37,10 +37,18 @@ where /// Insert an `item` at the given `position` in the tree. /// /// # Panics - /// If `position >= capacity`. - pub fn insert(&mut self, position: u64, item: impl Into) { - self.root.insert(0, position, item); - self.positions.insert(position); + /// If `index >= capacity`. + pub fn insert(&mut self, index: u64, item: impl Into) { + let capacity = self.capacity(); + + assert!( + index < capacity, + "index out of bounds: \ + the capacity is {capacity} but the index is {index}" + ); + + self.root.insert(0, index, item); + self.positions.insert(index); } /// Remove and return the item at the given `position` in the tree if it @@ -200,7 +208,9 @@ mod tests { } #[test] - #[should_panic] + #[should_panic( + expected = "index out of bounds: the capacity is 8 but the index is 8" + )] fn tree_insertion_out_of_bounds() { let mut tree = SumTree::new(); tree.insert(tree.capacity(), 42);