Skip to content

Commit

Permalink
Merge branch 'master' into feat/update-erc1363-error-signatures
Browse files Browse the repository at this point in the history
  • Loading branch information
vittominacori committed May 7, 2024
2 parents 1bee601 + 52c36d4 commit ab4a759
Show file tree
Hide file tree
Showing 15 changed files with 301 additions and 14 deletions.
5 changes: 5 additions & 0 deletions .changeset/chilly-humans-warn.md
@@ -0,0 +1,5 @@
---
'openzeppelin-solidity': patch
---

`ProxyAdmin`: Fixed documentation for `UPGRADE_INTERFACE_VERSION` getter.
5 changes: 5 additions & 0 deletions .changeset/cold-cheetahs-check.md
@@ -0,0 +1,5 @@
---
'openzeppelin-solidity': minor
---

`CircularBuffer`: Add a data structure that stores the last `N` values pushed to it.
5 changes: 5 additions & 0 deletions .changeset/spotty-falcons-explain.md
@@ -0,0 +1,5 @@
---
'openzeppelin-solidity': minor
---

`Math`, `SignedMath`: Add a branchless `ternary` function that computes`cond ? a : b` in constant gas cost.
6 changes: 3 additions & 3 deletions .github/workflows/checks.yml
Expand Up @@ -93,9 +93,9 @@ jobs:
uses: ./.github/actions/setup
- name: Run coverage
run: npm run coverage
- uses: codecov/codecov-action@v3
with:
token: ${{ secrets.CODECOV_TOKEN }}
- uses: codecov/codecov-action@v4
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}

harnesses:
runs-on: ubuntu-latest
Expand Down
2 changes: 2 additions & 0 deletions contracts/mocks/Stateless.sol
Expand Up @@ -10,6 +10,7 @@ import {AuthorityUtils} from "../access/manager/AuthorityUtils.sol";
import {Base64} from "../utils/Base64.sol";
import {BitMaps} from "../utils/structs/BitMaps.sol";
import {Checkpoints} from "../utils/structs/Checkpoints.sol";
import {CircularBuffer} from "../utils/structs/CircularBuffer.sol";
import {Clones} from "../proxy/Clones.sol";
import {Create2} from "../utils/Create2.sol";
import {DoubleEndedQueue} from "../utils/structs/DoubleEndedQueue.sol";
Expand All @@ -24,6 +25,7 @@ import {ERC721Holder} from "../token/ERC721/utils/ERC721Holder.sol";
import {Math} from "../utils/math/Math.sol";
import {MerkleProof} from "../utils/cryptography/MerkleProof.sol";
import {MessageHashUtils} from "../utils/cryptography/MessageHashUtils.sol";
import {Panic} from "../utils/Panic.sol";
import {Packing} from "../utils/Packing.sol";
import {SafeCast} from "../utils/math/SafeCast.sol";
import {SafeERC20} from "../token/ERC20/utils/SafeERC20.sol";
Expand Down
8 changes: 4 additions & 4 deletions contracts/proxy/transparent/ProxyAdmin.sol
Expand Up @@ -12,10 +12,10 @@ import {Ownable} from "../../access/Ownable.sol";
*/
contract ProxyAdmin is Ownable {
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgrade(address)`
* and `upgradeAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeAndCall(address,bytes)` is present, and the second argument must
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgrade(address,address)`
* and `upgradeAndCall(address,address,bytes)` are present, and `upgrade` must be used if no function should be called,
* while `upgradeAndCall` will invoke the `receive` function if the third argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeAndCall(address,address,bytes)` is present, and the third argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
Expand Down
3 changes: 3 additions & 0 deletions contracts/utils/Arrays.sol
Expand Up @@ -455,6 +455,7 @@ library Arrays {
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(address[] storage array, uint256 len) internal {
/// @solidity memory-safe-assembly
assembly {
sstore(array.slot, len)
}
Expand All @@ -466,6 +467,7 @@ library Arrays {
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
/// @solidity memory-safe-assembly
assembly {
sstore(array.slot, len)
}
Expand All @@ -477,6 +479,7 @@ library Arrays {
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(uint256[] storage array, uint256 len) internal {
/// @solidity memory-safe-assembly
assembly {
sstore(array.slot, len)
}
Expand Down
3 changes: 3 additions & 0 deletions contracts/utils/README.adoc
Expand Up @@ -21,6 +21,7 @@ Miscellaneous contracts and libraries containing utility functions you can use t
* {EnumerableMap}: A type like Solidity's https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`], but with key-value _enumeration_: this will let you know how many entries a mapping has, and iterate over them (which is not possible with `mapping`).
* {EnumerableSet}: Like {EnumerableMap}, but for https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets]. Can be used to store privileged accounts, issued IDs, etc.
* {DoubleEndedQueue}: An implementation of a https://en.wikipedia.org/wiki/Double-ended_queue[double ended queue] whose values can be removed added or remove from both sides. Useful for FIFO and LIFO structures.
* {CircularBuffer}: A data structure to store the last N values pushed to it.
* {Checkpoints}: A data structure to store values mapped to an strictly increasing key. Can be used for storing and accessing values over time.
* {MerkleTree}: A library with https://wikipedia.org/wiki/Merkle_Tree[Merkle Tree] data structures and helper functions.
* {Create2}: Wrapper around the https://blog.openzeppelin.com/getting-the-most-out-of-create2/[`CREATE2` EVM opcode] for safe use without having to deal with low-level assembly.
Expand Down Expand Up @@ -95,6 +96,8 @@ Ethereum contracts have no native concept of an interface, so applications must

{{DoubleEndedQueue}}

{{CircularBuffer}}

{{Checkpoints}}

{{MerkleTree}}
Expand Down
26 changes: 21 additions & 5 deletions contracts/utils/math/Math.sol
Expand Up @@ -73,18 +73,34 @@ library Math {
}
}

/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}

/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
return ternary(a > b, a, b);
}

/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
return ternary(a < b, a, b);
}

/**
Expand Down Expand Up @@ -114,7 +130,7 @@ library Math {
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return a == 0 ? 0 : (a - 1) / b + 1;
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}

Expand Down Expand Up @@ -147,7 +163,7 @@ library Math {

// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= prod1) {
Panic.panic(denominator == 0 ? Panic.DIVISION_BY_ZERO : Panic.UNDER_OVERFLOW);
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}

///////////////////////////////////////////////
Expand Down Expand Up @@ -268,7 +284,7 @@ library Math {
}

if (gcd != 1) return 0; // No inverse exists.
return x < 0 ? (n - uint256(-x)) : uint256(x); // Wrap the result if it's negative.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}

Expand Down
22 changes: 20 additions & 2 deletions contracts/utils/math/SignedMath.sol
Expand Up @@ -3,22 +3,40 @@

pragma solidity ^0.8.20;

import {SafeCast} from "./SafeCast.sol";

/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}

/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
return ternary(a > b, a, b);
}

/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
return ternary(a < b, a, b);
}

/**
Expand Down
130 changes: 130 additions & 0 deletions contracts/utils/structs/CircularBuffer.sol
@@ -0,0 +1,130 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {Math} from "../math/Math.sol";
import {Arrays} from "../Arrays.sol";
import {Panic} from "../Panic.sol";

/**
* @dev A fixed-size buffer for keeping `bytes32` items in storage.
*
* This data structure allows for pushing elements to it, and when its length exceeds the specified fixed size,
* new items take the place of the oldest element in the buffer, keeping at most `N` elements in the
* structure.
*
* Elements can't be removed but the data structure can be cleared. See {clear}.
*
* Complexity:
* - insertion ({push}): O(1)
* - lookup ({last}): O(1)
* - inclusion ({includes}): O(N) (worst case)
* - reset ({clear}): O(1)
*
* * The struct is called `Bytes32CircularBuffer`. Other types can be cast to and from `bytes32`. This data structure
* can only be used in storage, and not in memory.
*
* Example usage:
*
* ```solidity
* contract Example {
* // Add the library methods
* using CircularBuffer for CircularBuffer.Bytes32CircularBuffer;
*
* // Declare a buffer storage variable
* CircularBuffer.Bytes32CircularBuffer private myBuffer;
* }
* ```
*/
library CircularBuffer {
/**
* @dev Counts the number of items that have been pushed to the buffer. The residuo modulo _data.length indicates
* where the next value should be stored.
*
* Struct members have an underscore prefix indicating that they are "private" and should not be read or written to
* directly. Use the functions provided below instead. Modifying the struct manually may violate assumptions and
* lead to unexpected behavior.
*
* The last item is at data[(index - 1) % data.length] and the last item is at data[index % data.length]. This
* range can wrap around.
*/
struct Bytes32CircularBuffer {
uint256 _count;
bytes32[] _data;
}

/**
* @dev Initialize a new CircularBuffer of given size.
*
* If the CircularBuffer was already setup and used, calling that function again will reset it to a blank state.
*
* NOTE: The size of the buffer will affect the execution of {includes} function, as it has a complexity of O(N).
* Consider a large buffer size may render the function unusable.
*/
function setup(Bytes32CircularBuffer storage self, uint256 size) internal {
clear(self);
Arrays.unsafeSetLength(self._data, size);
}

/**
* @dev Clear all data in the buffer without resetting memory, keeping the existing size.
*/
function clear(Bytes32CircularBuffer storage self) internal {
self._count = 0;
}

/**
* @dev Push a new value to the buffer. If the buffer is already full, the new value replaces the oldest value in
* the buffer.
*/
function push(Bytes32CircularBuffer storage self, bytes32 value) internal {
uint256 index = self._count++;
uint256 modulus = self._data.length;
Arrays.unsafeAccess(self._data, index % modulus).value = value;
}

/**
* @dev Number of values currently in the buffer. This value is 0 for an empty buffer, and cannot exceed the size of
* the buffer.
*/
function count(Bytes32CircularBuffer storage self) internal view returns (uint256) {
return Math.min(self._count, self._data.length);
}

/**
* @dev Length of the buffer. This is the maximum number of elements kepts in the buffer.
*/
function length(Bytes32CircularBuffer storage self) internal view returns (uint256) {
return self._data.length;
}

/**
* @dev Getter for the i-th value in the buffer, from the end.
*
* Reverts with {Panic-ARRAY_OUT_OF_BOUNDS} if trying to access an element that was not pushed, or that was
* dropped to make room for newer elements.
*/
function last(Bytes32CircularBuffer storage self, uint256 i) internal view returns (bytes32) {
uint256 index = self._count;
uint256 modulus = self._data.length;
uint256 total = Math.min(index, modulus); // count(self)
if (i >= total) {
Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS);
}
return Arrays.unsafeAccess(self._data, (index - i - 1) % modulus).value;
}

/**
* @dev Check if a given value is in the buffer.
*/
function includes(Bytes32CircularBuffer storage self, bytes32 value) internal view returns (bool) {
uint256 index = self._count;
uint256 modulus = self._data.length;
uint256 total = Math.min(index, modulus); // count(self)
for (uint256 i = 0; i < total; ++i) {
if (Arrays.unsafeAccess(self._data, (index - i - 1) % modulus).value == value) {
return true;
}
}
return false;
}
}
1 change: 1 addition & 0 deletions scripts/generate/templates/Arrays.js
Expand Up @@ -356,6 +356,7 @@ const unsafeSetLength = type => `
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(${type}[] storage array, uint256 len) internal {
/// @solidity memory-safe-assembly
assembly {
sstore(array.slot, len)
}
Expand Down
10 changes: 10 additions & 0 deletions test/utils/math/Math.t.sol
Expand Up @@ -7,6 +7,16 @@ import {Test, stdError} from "forge-std/Test.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

contract MathTest is Test {
function testSelect(bool f, uint256 a, uint256 b) public {
assertEq(Math.ternary(f, a, b), f ? a : b);
}

// MIN & MAX
function testMinMax(uint256 a, uint256 b) public {
assertEq(Math.min(a, b), a < b ? a : b);
assertEq(Math.max(a, b), a > b ? a : b);
}

// CEILDIV
function testCeilDiv(uint256 a, uint256 b) public {
vm.assume(b > 0);
Expand Down
10 changes: 10 additions & 0 deletions test/utils/math/SignedMath.t.sol
Expand Up @@ -8,6 +8,16 @@ import {Math} from "../../../contracts/utils/math/Math.sol";
import {SignedMath} from "../../../contracts/utils/math/SignedMath.sol";

contract SignedMathTest is Test {
function testSelect(bool f, int256 a, int256 b) public {
assertEq(SignedMath.ternary(f, a, b), f ? a : b);
}

// MIN & MAX
function testMinMax(int256 a, int256 b) public {
assertEq(SignedMath.min(a, b), a < b ? a : b);
assertEq(SignedMath.max(a, b), a > b ? a : b);
}

// MIN
function testMin(int256 a, int256 b) public {
int256 result = SignedMath.min(a, b);
Expand Down

0 comments on commit ab4a759

Please sign in to comment.