diff --git a/README.md b/README.md index c4200b3d..2bc3e3a8 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,10 @@ tokens utils ├─ SSTORE2 — "Library for cheaper reads and writes to persistent storage" ├─ CREATE3 — "Deploy to deterministic addresses without an initcode factor" +├─ LibString — "Library for creating string representations of uint values" ├─ SafeCastLib — "Safe unsigned integer casting lib that reverts on overflow" +├─ SignedWadMath — "Signed integer 18 decimal fixed point arithmetic library" +├─ MerkleProofLib — "Efficient merkle tree inclusion proof verification library" ├─ ReentrancyGuard — "Gas optimized reentrancy protection for smart contracts" ├─ FixedPointMathLib — "Arithmetic library with operations for fixed-point numbers" ├─ Bytes32AddressLib — "Library for converting between addresses and bytes32 values" diff --git a/src/test/LibString.t.sol b/src/test/LibString.t.sol new file mode 100644 index 00000000..51a1e8f0 --- /dev/null +++ b/src/test/LibString.t.sol @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.8.0; + +import {DSTestPlus} from "./utils/DSTestPlus.sol"; + +import {LibString} from "../utils/LibString.sol"; + +contract LibStringTest is DSTestPlus { + function testToString() public { + assertEq(LibString.toString(0), "0"); + assertEq(LibString.toString(1), "1"); + assertEq(LibString.toString(17), "17"); + assertEq(LibString.toString(99999999), "99999999"); + assertEq(LibString.toString(99999999999), "99999999999"); + assertEq(LibString.toString(2342343923423), "2342343923423"); + assertEq(LibString.toString(98765685434567), "98765685434567"); + } + + function testDifferentiallyFuzzToString(uint256 value, bytes calldata brutalizeWith) + public + brutalizeMemory(brutalizeWith) + { + string memory libString = LibString.toString(value); + string memory oz = toStringOZ(value); + + assertEq(bytes(libString).length, bytes(oz).length); + assertEq(libString, oz); + } + + function testToStringOverwrite() public { + string memory str = LibString.toString(1); + + bytes32 data; + bytes32 expected; + + assembly { + // Imagine a high level allocation writing something to the current free memory. + // Should have sufficient higher order bits for this to be visible + mstore(mload(0x40), not(0)) + // Correctly allocate 32 more bytes, to avoid more interference + mstore(0x40, add(mload(0x40), 32)) + data := mload(add(str, 32)) + + // the expected value should be the uft-8 encoding of 1 (49), + // followed by clean bits. We achieve this by taking the value and + // shifting left to the end of the 32 byte word + expected := shl(248, 49) + } + + assertEq(data, expected); + } + + function testToStringDirty() public { + uint256 freememptr; + // Make the next 4 bytes of the free memory dirty + assembly { + let dirty := not(0) + freememptr := mload(0x40) + mstore(freememptr, dirty) + mstore(add(freememptr, 32), dirty) + mstore(add(freememptr, 64), dirty) + mstore(add(freememptr, 96), dirty) + mstore(add(freememptr, 128), dirty) + } + string memory str = LibString.toString(1); + uint256 len; + bytes32 data; + bytes32 expected; + assembly { + freememptr := str + len := mload(str) + data := mload(add(str, 32)) + // the expected value should be the uft-8 encoding of 1 (49), + // followed by clean bits. We achieve this by taking the value and + // shifting left to the end of the 32 byte word + expected := shl(248, 49) + } + emit log_named_uint("str: ", freememptr); + emit log_named_uint("len: ", len); + emit log_named_bytes32("data: ", data); + assembly { + freememptr := mload(0x40) + } + emit log_named_uint("memptr: ", freememptr); + + assertEq(data, expected); + } +} + +function toStringOZ(uint256 value) pure returns (string memory) { + if (value == 0) { + return "0"; + } + uint256 temp = value; + uint256 digits; + while (temp != 0) { + digits++; + temp /= 10; + } + bytes memory buffer = new bytes(digits); + while (value != 0) { + digits -= 1; + buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); + value /= 10; + } + return string(buffer); +} diff --git a/src/test/MerkleProofLib.t.sol b/src/test/MerkleProofLib.t.sol new file mode 100644 index 00000000..52796798 --- /dev/null +++ b/src/test/MerkleProofLib.t.sol @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.8.0; + +import {DSTestPlus} from "./utils/DSTestPlus.sol"; + +import {MerkleProofLib} from "../utils/MerkleProofLib.sol"; + +contract MerkleProofLibTest is DSTestPlus { + function testVerifyEmptyMerkleProofSuppliedLeafAndRootSame() public { + bytes32[] memory proof; + assertBoolEq(this.verify(proof, 0x00, 0x00), true); + } + + function testVerifyEmptyMerkleProofSuppliedLeafAndRootDifferent() public { + bytes32[] memory proof; + bytes32 leaf = "a"; + assertBoolEq(this.verify(proof, 0x00, leaf), false); + } + + function testValidProofSupplied() public { + // Merkle tree created from leaves ['a', 'b', 'c']. + // Leaf is 'a'. + bytes32[] memory proof = new bytes32[](2); + proof[0] = 0xb5553de315e0edf504d9150af82dafa5c4667fa618ed0a6f19c69b41166c5510; + proof[1] = 0x0b42b6393c1f53060fe3ddbfcd7aadcca894465a5a438f69c87d790b2299b9b2; + bytes32 root = 0x5842148bc6ebeb52af882a317c765fccd3ae80589b21a9b8cbf21abb630e46a7; + bytes32 leaf = 0x3ac225168df54212a25c1c01fd35bebfea408fdac2e31ddd6f80a4bbf9a5f1cb; + assertBoolEq(this.verify(proof, root, leaf), true); + } + + function testVerifyInvalidProofSupplied() public { + // Merkle tree created from leaves ['a', 'b', 'c']. + // Leaf is 'a'. + // Proof is same as testValidProofSupplied but last byte of first element is modified. + bytes32[] memory proof = new bytes32[](2); + proof[0] = 0xb5553de315e0edf504d9150af82dafa5c4667fa618ed0a6f19c69b41166c5511; + proof[1] = 0x0b42b6393c1f53060fe3ddbfcd7aadcca894465a5a438f69c87d790b2299b9b2; + bytes32 root = 0x5842148bc6ebeb52af882a317c765fccd3ae80589b21a9b8cbf21abb630e46a7; + bytes32 leaf = 0x3ac225168df54212a25c1c01fd35bebfea408fdac2e31ddd6f80a4bbf9a5f1cb; + assertBoolEq(this.verify(proof, root, leaf), false); + } + + function verify( + bytes32[] calldata proof, + bytes32 root, + bytes32 leaf + ) external pure returns (bool) { + return MerkleProofLib.verify(proof, root, leaf); + } +} diff --git a/src/test/SignedWadMath.t.sol b/src/test/SignedWadMath.t.sol new file mode 100644 index 00000000..ec5b6f3b --- /dev/null +++ b/src/test/SignedWadMath.t.sol @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.8.0; + +import {DSTestPlus} from "./utils/DSTestPlus.sol"; + +import {wadMul, wadDiv} from "../utils/SignedWadMath.sol"; + +contract SignedWadMathTest is DSTestPlus { + function testWadMul( + uint256 x, + uint256 y, + bool negX, + bool negY + ) public { + x = bound(x, 0, 99999999999999e18); + y = bound(x, 0, 99999999999999e18); + + int256 xPrime = negX ? -int256(x) : int256(x); + int256 yPrime = negY ? -int256(y) : int256(y); + + assertEq(wadMul(xPrime, yPrime), (xPrime * yPrime) / 1e18); + } + + function testFailWadMulOverflow(int256 x, int256 y) public pure { + // Ignore cases where x * y does not overflow. + unchecked { + if ((x * y) / x == y) revert(); + } + + wadMul(x, y); + } + + function testWadDiv( + uint256 x, + uint256 y, + bool negX, + bool negY + ) public { + x = bound(x, 0, 99999999e18); + y = bound(x, 1, 99999999e18); + + int256 xPrime = negX ? -int256(x) : int256(x); + int256 yPrime = negY ? -int256(y) : int256(y); + + assertEq(wadDiv(xPrime, yPrime), (xPrime * 1e18) / yPrime); + } + + function testFailWadDivOverflow(int256 x, int256 y) public pure { + // Ignore cases where x * WAD does not overflow or y is 0. + unchecked { + if (y == 0 || (x * 1e18) / 1e18 == x) revert(); + } + + wadDiv(x, y); + } + + function testFailWadDivZeroDenominator(int256 x) public pure { + wadDiv(x, 0); + } +} diff --git a/src/utils/FixedPointMathLib.sol b/src/utils/FixedPointMathLib.sol index 33fbaf87..9b5fe975 100644 --- a/src/utils/FixedPointMathLib.sol +++ b/src/utils/FixedPointMathLib.sol @@ -219,4 +219,20 @@ library FixedPointMathLib { } } } + + function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) { + assembly { + // Divide x by y. Note this will return + // 0 instead of reverting if y is zero. + r := div(x, y) + } + } + + function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) { + assembly { + // Add 1 to x * y if x % y > 0. Note this will + // return 0 instead of reverting if y is zero. + z := add(gt(mod(x, y), 0), div(x, y)) + } + } } diff --git a/src/utils/LibString.sol b/src/utils/LibString.sol new file mode 100644 index 00000000..bcd8b57a --- /dev/null +++ b/src/utils/LibString.sol @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.8.0; + +/// @notice Efficient library for creating string representations of integers. +/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/LibString.sol) +library LibString { + function toString(uint256 value) internal pure returns (string memory str) { + assembly { + // The maximum value of a uint256 contains 78 digits (1 byte per digit), but we allocate 160 bytes + // to keep the free memory pointer word aligned. We'll need 1 word for the length, 1 word for the + // trailing zeros padding, and 3 other words for a max of 78 digits. In total: 5 * 32 = 160 bytes. + let newFreeMemoryPointer := add(mload(0x40), 160) + + // Update the free memory pointer to avoid overriding our string. + mstore(0x40, newFreeMemoryPointer) + + // Assign str to the end of the zone of newly allocated memory. + str := sub(newFreeMemoryPointer, 32) + + // Clean the last word of memory it may not be overwritten. + mstore(str, 0) + + // Cache the end of the memory to calculate the length later. + let end := str + + // We write the string from rightmost digit to leftmost digit. + // The following is essentially a do-while loop that also handles the zero case. + // prettier-ignore + for { let temp := value } 1 {} { + // Move the pointer 1 byte to the left. + str := sub(str, 1) + + // Write the character to the pointer. + // The ASCII index of the '0' character is 48. + mstore8(str, add(48, mod(temp, 10))) + + // Keep dividing temp until zero. + temp := div(temp, 10) + + // prettier-ignore + if iszero(temp) { break } + } + + // Compute and cache the final total length of the string. + let length := sub(end, str) + + // Move the pointer 32 bytes leftwards to make room for the length. + str := sub(str, 32) + + // Store the string's length at the start of memory allocated for our string. + mstore(str, length) + } + } +} diff --git a/src/utils/MerkleProofLib.sol b/src/utils/MerkleProofLib.sol new file mode 100644 index 00000000..5909020a --- /dev/null +++ b/src/utils/MerkleProofLib.sol @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.8.0; + +/// @notice Gas optimized merkle proof verification library. +/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/MerkleProofLib.sol) +library MerkleProofLib { + function verify( + bytes32[] calldata proof, + bytes32 root, + bytes32 leaf + ) internal pure returns (bool isValid) { + assembly { + if proof.length { + // Left shifting by 5 is like multiplying by 32. + let end := add(proof.offset, shl(5, proof.length)) + + // Initialize offset to the offset of the proof in calldata. + let offset := proof.offset + + // Iterate over proof elements to compute root hash. + // prettier-ignore + for {} 1 {} { + // Slot where the leaf should be put in scratch space. If + // leaf > calldataload(offset): slot 32, otherwise: slot 0. + let leafSlot := shl(5, gt(leaf, calldataload(offset))) + + // Store elements to hash contiguously in scratch space. + // The xor puts calldataload(offset) in whichever slot leaf + // is not occupying, so 0 if leafSlot is 32, and 32 otherwise. + mstore(leafSlot, leaf) + mstore(xor(leafSlot, 32), calldataload(offset)) + + // Reuse leaf to store the hash to reduce stack operations. + leaf := keccak256(0, 64) // Hash both slots of scratch space. + + offset := add(offset, 32) // Shift 1 word per cycle. + + // prettier-ignore + if iszero(lt(offset, end)) { break } + } + } + + isValid := eq(leaf, root) // The proof is valid if the roots match. + } + } +} diff --git a/src/utils/SignedWadMath.sol b/src/utils/SignedWadMath.sol new file mode 100644 index 00000000..c743a58f --- /dev/null +++ b/src/utils/SignedWadMath.sol @@ -0,0 +1,197 @@ +// SPDX-License-Identifier: MIT +pragma solidity >=0.8.0; + +/// @notice Signed 18 decimal fixed point (wad) arithmetic library. +/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SignedWadMath.sol) + +/// @dev Will not revert on overflow, only use where overflow is not possible. +function toWadUnsafe(uint256 x) pure returns (int256 r) { + assembly { + // Multiply x by 1e18. + r := mul(x, 1000000000000000000) + } +} + +/// @dev Will not revert on overflow, only use where overflow is not possible. +function unsafeWadMul(int256 x, int256 y) pure returns (int256 r) { + assembly { + // Multiply x by y and divide by 1e18. + r := sdiv(mul(x, y), 1000000000000000000) + } +} + +/// @dev Will return 0 instead of reverting if y is zero and will +/// not revert on overflow, only use where overflow is not possible. +function unsafeWadDiv(int256 x, int256 y) pure returns (int256 r) { + assembly { + // Multiply x by 1e18 and divide it by y. + r := sdiv(mul(x, 1000000000000000000), y) + } +} + +function wadMul(int256 x, int256 y) pure returns (int256 r) { + assembly { + // Store x * y in r for now. + r := mul(x, y) + + // Equivalent to require(x == 0 || (x * y) / x == y) + if iszero(or(iszero(x), eq(sdiv(r, x), y))) { + revert(0, 0) + } + + // Scale the result down by 1e18. + r := sdiv(r, 1000000000000000000) + } +} + +function wadDiv(int256 x, int256 y) pure returns (int256 r) { + assembly { + // Store x * 1e18 in r for now. + r := mul(x, 1000000000000000000) + + // Equivalent to require(y != 0 && ((x * 1e18) / 1e18 == x)) + if iszero(and(iszero(iszero(y)), eq(sdiv(r, 1000000000000000000), x))) { + revert(0, 0) + } + + // Divide r by y. + r := sdiv(r, y) + } +} + +function wadExp(int256 x) pure returns (int256 r) { + unchecked { + // When the result is < 0.5 we return zero. This happens when + // x <= floor(log(0.5e18) * 1e18) ~ -42e18 + if (x <= -42139678854452767551) return 0; + + // When the result is > (2**255 - 1) / 1e18 we can not represent it as an + // int. This happens when x >= floor(log((2**255 - 1) / 1e18) * 1e18) ~ 135. + if (x >= 135305999368893231589) revert("EXP_OVERFLOW"); + + // x is now in the range (-42, 136) * 1e18. Convert to (-42, 136) * 2**96 + // for more intermediate precision and a binary basis. This base conversion + // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78. + x = (x << 78) / 5**18; + + // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers + // of two such that exp(x) = exp(x') * 2**k, where k is an integer. + // Solving this gives k = round(x / log(2)) and x' = x - k * log(2). + int256 k = ((x << 96) / 54916777467707473351141471128 + 2**95) >> 96; + x = x - k * 54916777467707473351141471128; + + // k is in the range [-61, 195]. + + // Evaluate using a (6, 7)-term rational approximation. + // p is made monic, we'll multiply by a scale factor later. + int256 y = x + 1346386616545796478920950773328; + y = ((y * x) >> 96) + 57155421227552351082224309758442; + int256 p = y + x - 94201549194550492254356042504812; + p = ((p * y) >> 96) + 28719021644029726153956944680412240; + p = p * x + (4385272521454847904659076985693276 << 96); + + // We leave p in 2**192 basis so we don't need to scale it back up for the division. + int256 q = x - 2855989394907223263936484059900; + q = ((q * x) >> 96) + 50020603652535783019961831881945; + q = ((q * x) >> 96) - 533845033583426703283633433725380; + q = ((q * x) >> 96) + 3604857256930695427073651918091429; + q = ((q * x) >> 96) - 14423608567350463180887372962807573; + q = ((q * x) >> 96) + 26449188498355588339934803723976023; + + assembly { + // Div in assembly because solidity adds a zero check despite the unchecked. + // The q polynomial won't have zeros in the domain as all its roots are complex. + // No scaling is necessary because p is already 2**96 too large. + r := sdiv(p, q) + } + + // r should be in the range (0.09, 0.25) * 2**96. + + // We now need to multiply r by: + // * the scale factor s = ~6.031367120. + // * the 2**k factor from the range reduction. + // * the 1e18 / 2**96 factor for base conversion. + // We do this all at once, with an intermediate result in 2**213 + // basis, so the final right shift is always by a positive amount. + r = int256((uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)); + } +} + +function wadLn(int256 x) pure returns (int256 r) { + unchecked { + require(x > 0, "UNDEFINED"); + + // We want to convert x from 10**18 fixed point to 2**96 fixed point. + // We do this by multiplying by 2**96 / 10**18. But since + // ln(x * C) = ln(x) + ln(C), we can simply do nothing here + // and add ln(2**96 / 10**18) at the end. + + assembly { + r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) + r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) + r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) + r := or(r, shl(4, lt(0xffff, shr(r, x)))) + r := or(r, shl(3, lt(0xff, shr(r, x)))) + r := or(r, shl(2, lt(0xf, shr(r, x)))) + r := or(r, shl(1, lt(0x3, shr(r, x)))) + r := or(r, lt(0x1, shr(r, x))) + } + + // Reduce range of x to (1, 2) * 2**96 + // ln(2^k * x) = k * ln(2) + ln(x) + int256 k = r - 96; + x <<= uint256(159 - k); + x = int256(uint256(x) >> 159); + + // Evaluate using a (8, 8)-term rational approximation. + // p is made monic, we will multiply by a scale factor later. + int256 p = x + 3273285459638523848632254066296; + p = ((p * x) >> 96) + 24828157081833163892658089445524; + p = ((p * x) >> 96) + 43456485725739037958740375743393; + p = ((p * x) >> 96) - 11111509109440967052023855526967; + p = ((p * x) >> 96) - 45023709667254063763336534515857; + p = ((p * x) >> 96) - 14706773417378608786704636184526; + p = p * x - (795164235651350426258249787498 << 96); + + // We leave p in 2**192 basis so we don't need to scale it back up for the division. + // q is monic by convention. + int256 q = x + 5573035233440673466300451813936; + q = ((q * x) >> 96) + 71694874799317883764090561454958; + q = ((q * x) >> 96) + 283447036172924575727196451306956; + q = ((q * x) >> 96) + 401686690394027663651624208769553; + q = ((q * x) >> 96) + 204048457590392012362485061816622; + q = ((q * x) >> 96) + 31853899698501571402653359427138; + q = ((q * x) >> 96) + 909429971244387300277376558375; + assembly { + // Div in assembly because solidity adds a zero check despite the unchecked. + // The q polynomial is known not to have zeros in the domain. + // No scaling required because p is already 2**96 too large. + r := sdiv(p, q) + } + + // r is in the range (0, 0.125) * 2**96 + + // Finalization, we need to: + // * multiply by the scale factor s = 5.549… + // * add ln(2**96 / 10**18) + // * add k * ln(2) + // * multiply by 10**18 / 2**96 = 5**18 >> 78 + + // mul s * 5e18 * 2**96, base is now 5**18 * 2**192 + r *= 1677202110996718588342820967067443963516166; + // add ln(2) * k * 5e18 * 2**192 + r += 16597577552685614221487285958193947469193820559219878177908093499208371 * k; + // add ln(2**96 / 10**18) * 5e18 * 2**192 + r += 600920179829731861736702779321621459595472258049074101567377883020018308; + // base conversion: mul 2**18 / 2**192 + r >>= 174; + } +} + +/// @dev Will return 0 instead of reverting if y is zero. +function unsafeDiv(int256 x, int256 y) pure returns (int256 r) { + assembly { + // Divide x by y. + r := sdiv(x, y) + } +}