From ba729845f13ee2102516df8f617d6757cfd8c900 Mon Sep 17 00:00:00 2001 From: cedoor Date: Wed, 20 Mar 2024 10:13:20 +0000 Subject: [PATCH 1/2] refactor(imt.sol): use if instead of while to increment depth A new insertion can increase tree's depth by at most 1. We can be sure that the while loop isn't executed twice. re #213 --- packages/imt.sol/contracts/internal/InternalLeanIMT.sol | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/imt.sol/contracts/internal/InternalLeanIMT.sol b/packages/imt.sol/contracts/internal/InternalLeanIMT.sol index 572dbde29..3658057ad 100644 --- a/packages/imt.sol/contracts/internal/InternalLeanIMT.sol +++ b/packages/imt.sol/contracts/internal/InternalLeanIMT.sol @@ -46,7 +46,7 @@ library InternalLeanIMT { revert LeafAlreadyExists(); } - while (2 ** self.depth < self.size + 1) { + if (2 ** self.depth < self.size + 1) { self.depth += 1; } From 21df170d6d969d8dcfa763bc1aeb1390c320a627 Mon Sep 17 00:00:00 2001 From: cedoor Date: Wed, 20 Mar 2024 10:36:06 +0000 Subject: [PATCH 2/2] docs(imt.sol): add more comments to code re #213 --- packages/imt.sol/contracts/internal/InternalLeanIMT.sol | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/imt.sol/contracts/internal/InternalLeanIMT.sol b/packages/imt.sol/contracts/internal/InternalLeanIMT.sol index 3658057ad..00ee1909b 100644 --- a/packages/imt.sol/contracts/internal/InternalLeanIMT.sol +++ b/packages/imt.sol/contracts/internal/InternalLeanIMT.sol @@ -46,6 +46,9 @@ library InternalLeanIMT { revert LeafAlreadyExists(); } + // A new insertion can increase a tree's depth by at most 1, + // and only if the number of leaves supported by the current + // depth is less than the number of leaves to be supported after insertion. if (2 ** self.depth < self.size + 1) { self.depth += 1; } @@ -103,6 +106,8 @@ library InternalLeanIMT { currentLevel = leaves; // Calculate the depth of the tree after adding the new values. + // Unlike the 'insert' function, we need a while here as + // N insertions can increase the tree's depth more than once. while (2 ** self.depth < self.size + leaves.length) { self.depth += 1; }