Skip to content

Commit f130873

Browse files
authored
bug: BytesUtils.compare() Arithmetic Overflow (#420)
fixed overflow in `compare()` and added test case
1 parent 5030285 commit f130873

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

contracts/test/TestBytesUtils.sol

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,10 @@ contract TestBytesUtils {
134134
longChar.compare(otherLongChar) < 0 == true,
135135
"Compare long char with difference at start"
136136
);
137+
require(
138+
abi.encodePacked(type(int256).min).compare(abi.encodePacked(type(int256).max)) > 0,
139+
"Compare maximum difference"
140+
);
137141
}
138142

139143
function testSubstring() public pure {

contracts/utils/BytesUtils.sol

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -123,15 +123,18 @@ library BytesUtils {
123123
b := mload(otherptr)
124124
}
125125
if (a != b) {
126-
// Mask out irrelevant bytes and check again
127-
uint256 mask;
128-
if (shortest - idx >= 32) {
129-
mask = type(uint256).max;
130-
} else {
131-
mask = ~(2 ** (8 * (idx + 32 - shortest)) - 1);
126+
uint256 rest = shortest - idx;
127+
if (rest < 32) {
128+
// shift out the irrelevant bits
129+
rest = (32 - rest) << 3; // bits to drop
130+
a >>= rest;
131+
b >>= rest;
132+
}
133+
if (a < b) {
134+
return -1;
135+
} else if (a > b) {
136+
return 1;
132137
}
133-
int256 diff = int256(a & mask) - int256(b & mask);
134-
if (diff != 0) return diff;
135138
}
136139
selfptr += 32;
137140
otherptr += 32;

0 commit comments

Comments
 (0)