Skip to content

Commit

Permalink
fix gas loop optimization in MerkleProof.sol (OpenZeppelin#5028)
Browse files Browse the repository at this point in the history
  • Loading branch information
CarsonCase committed May 9, 2024
1 parent 52c36d4 commit c9b7c9b
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions contracts/utils/cryptography/MerkleProof.sol
Expand Up @@ -50,8 +50,11 @@ library MerkleProof {
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
for (uint256 i; i < proof.length; ) {
computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
unchecked {
++i;
}
}
return computedHash;
}
Expand All @@ -61,8 +64,11 @@ library MerkleProof {
*/
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
for (uint256 i; i < proof.length; ) {
computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
unchecked {
++i;
}
}
return computedHash;
}
Expand Down Expand Up @@ -135,12 +141,15 @@ library MerkleProof {
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < totalHashes; i++) {
for (uint256 i; i < totalHashes; ) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = Hashes.commutativeKeccak256(a, b);
unchecked {
++i;
}
}

if (totalHashes > 0) {
Expand Down Expand Up @@ -191,12 +200,15 @@ library MerkleProof {
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < totalHashes; i++) {
for (uint256 i; i < totalHashes; ) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = Hashes.commutativeKeccak256(a, b);
unchecked {
++i;
}
}

if (totalHashes > 0) {
Expand Down

0 comments on commit c9b7c9b

Please sign in to comment.