Skip to content

Commit

Permalink
avoid some mloads; change concat branch logic
Browse files Browse the repository at this point in the history
  • Loading branch information
dmfxyz committed Apr 15, 2022
1 parent c0f5dff commit 407430c
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 13 deletions.
8 changes: 4 additions & 4 deletions .gas-snapshot
@@ -1,4 +1,4 @@
StandardizedInputTest:testMerkleGenerateProofStandard() (gas: 768014)
StandardizedInputTest:testMerkleVerifyProofStandard() (gas: 865050)
StandardizedInputTest:testXorkleGenerateProofStandard() (gas: 708635)
StandardizedInputTest:testXorkleVerifyProofStandard() (gas: 794182)
StandardizedInputTest:testMerkleGenerateProofStandard() (gas: 762582)
StandardizedInputTest:testMerkleVerifyProofStandard() (gas: 858691)
StandardizedInputTest:testXorkleGenerateProofStandard() (gas: 705651)
StandardizedInputTest:testXorkleVerifyProofStandard() (gas: 790745)
Binary file modified reports/murky_gas_report.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions src/Merkle.sol
Expand Up @@ -15,8 +15,8 @@ contract Merkle is MurkyBase {
/// ascending sort and concat prior to hashing
function hashLeafPairs(bytes32 left, bytes32 right) public pure override returns (bytes32 _hash) {
assembly {
switch gt(left, right)
case 1 {
switch lt(left, right)
case 0 {
mstore(0x0, right)
mstore(0x20, left)
}
Expand Down
15 changes: 8 additions & 7 deletions src/common/MurkyBase.sol
Expand Up @@ -20,8 +20,9 @@ abstract contract MurkyBase {
function verifyProof(bytes32 root, bytes32[] memory proof, bytes32 valueToProve) public pure returns (bool) {
// proof length must be less than max array size
bytes32 rollingHash = valueToProve;
uint256 length = proof.length;
unchecked {
for(uint i = 0; i < proof.length; ++i){
for(uint i = 0; i < length; ++i){
rollingHash = hashLeafPairs(rollingHash, proof[i]);
}
}
Expand Down Expand Up @@ -72,18 +73,18 @@ abstract contract MurkyBase {
function hashLevel(bytes32[] memory data) internal pure returns (bytes32[] memory) {
bytes32[] memory result;

// TODO: can store data.length to avoid mload calls
if (data.length % 2 == 1){
result = new bytes32[](data.length / 2 + 1);
result[result.length - 1] = hashLeafPairs(data[data.length - 1], bytes32(0));
uint256 length = data.length;
if (length % 2 == 1){
result = new bytes32[](length / 2 + 1);
result[result.length - 1] = hashLeafPairs(data[length - 1], bytes32(0));
} else {
result = new bytes32[](data.length / 2);
result = new bytes32[](length / 2);
}

// pos is upper bounded by data.length / 2, so safe even if array is at max size
unchecked {
uint256 pos = 0;
for (uint256 i = 0; i < data.length-1; i+=2){
for (uint256 i = 0; i < length-1; i+=2){
result[pos] = hashLeafPairs(data[i], data[i+1]);
++pos;
}
Expand Down

0 comments on commit 407430c

Please sign in to comment.