Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support Saturation Arithmetic Operations #5029

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/six-zebras-guess.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'openzeppelin-solidity': minor
---

`Math`, `SignedMath`: Add saturating arithmetic operations, such as `saturatingAdd`, `saturatingSub` and `saturatingMul`.
74 changes: 60 additions & 14 deletions contracts/utils/math/Math.sol
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,36 @@ library Math {
Expand // Away from zero
}

/**
* @dev Unsigned saturating addition, bounds to `2 ** 256 - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
uint256 c = a + b;
// equivalent to: c < a ? type(uint256).max : c
return c | (0 - SafeCast.toUint(c < a));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That may be cheaper than the ternary alternative, but its also way less readable. @ernestognw wdyt ?

Copy link
Contributor Author

@Lohann Lohann May 31, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I designed all methods in this PR by first write everything in pure assembly using https://www.evm.codes/playground to find the most efficient solution possible, then I write the solidity code that generate the equivalent code. For this one specifically this is the most optimized way I've found:

PUSH2 0xdead  // b
PUSH2 0xbeef  // a b

// c = a + b
DUP2          // b a b
ADD           // c b

// overflow = c > b    
SWAP1         // b c
DUP2          // c b c
LT            // overflow c

// limit = 0 - overflow
PUSH0         // 0 overflow c
SUB           // limit c

// result = overflow ? limit : c
OR            // result

// total gas used starting from DUP2 = 23 gas

}
}

/**
* @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
success = c >= a;
// equivalent to: c >= a ? c : 0
result = SafeCast.toUint(success) * c;
}
}

/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// equivalent to: a > b ? a - b : 0
return (a - b) * SafeCast.toUint(a > b);
}
}

Expand All @@ -33,8 +55,25 @@ library Math {
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
success = a >= b;
// equivalent to: success ? (a - b) : 0
result = SafeCast.toUint(success) * (a - b);
}
}

/**
* @dev Unsigned saturating multiplication, bounds to `2 ** 256 - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use of assembly may be efficient, but readability is not great. I'd be more confortable with that function being

(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I had to use assembly because c / a reverts, even inside a unchecked statement, while in pure evm a division by zero always result in zero.

unchecked {
uint256 c = a * b;
bool success;
assembly {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
return c | (SafeCast.toUint(success) - 1);
}
}

Expand All @@ -43,13 +82,14 @@ library Math {
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
assembly {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = SafeCast.toUint(success) * c;
}
}

Expand All @@ -58,8 +98,11 @@ library Math {
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
success = b > 0;
assembly {
// In EVM any value divided by zero is zero.
result := div(a, b)
}
}
}

Expand All @@ -68,8 +111,11 @@ library Math {
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
success = b > 0;
assembly {
// In EVM a value modulus zero is equal to zero.
result := mod(a, b)
}
}
}

Expand Down
70 changes: 70 additions & 0 deletions contracts/utils/math/SignedMath.sol
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,74 @@ library SignedMath {
return uint256((n + mask) ^ mask);
}
}

/**
* @dev Signed saturating addition, computes `a + b` saturating at the numeric bounds instead of overflowing.
*/
function saturatingAdd(int256 a, int256 b) internal pure returns (int256) {
unchecked {
int256 c = a + b;
// Rationale:
// - overflow is only possible when both `a` and `b` are positive
// - underflow is only possible when both `a` and `b` are negative
//
// Lemma:
// (i) - if `a > (a + b)` is true, then `b` MUST be negative, otherwise overflow happened.
// (ii) - if `a > (a + b)` is false, then `b` MUST be non-negative, otherwise underflow happened.
//
// So the following statement will be true only if an overflow or underflow happened:
// statement: a > (a + b) == (b >= 0)
//
// We can use the sign of `b` to distinguish between overflow and underflow, as demonstrated below:
// | a > (a + b) | b >= 0 |
// | true | true | Lemma (i) thus Overflow
// | false | false | Lemma (ii) thus Underflow
// | true | false | Ok
// | false | true | Ok
bool sign = b >= 0;
bool overflow = a > c == sign;

// Efficient branchless method to retrieve the boundary limit:
// (1 << 255) == type(int256).min
// (1 << 255) - 1 == type(int256).max
uint256 limit = (SafeCast.toUint(overflow) << 255) - SafeCast.toUint(sign);

return ternary(overflow, int256(limit), c);
Comment on lines +92 to +100
Copy link
Contributor Author

@Lohann Lohann May 31, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For this one, this is the assembly implementation, it uses 64 gas (discounting the a and b push).

// b = type(int256).min
PUSH32 0x8000000000000000000000000000000000000000000000000000000000000000
// a = -1
PUSH32 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff

// c = a + b
DUP2        // b a b
DUP2        // a b a b
ADD         // c a b

// sign = b >= 0
SWAP2       // b a c
PUSH0       // 0 b a c
SGT         // (0 > b) a c
ISZERO      // sign a c

// overflow = (c < a) == sign
SWAP1       // a sign c
DUP3        // c a sign c
SLT         // (c < a) sign c
DUP2        // sign (c < a) sign c
EQ          // overflow sign c

// limit = (overflow << 255) - sign
SWAP1       // sign overflow c
DUP2        // overflow sign overflow c
PUSH1 0xff  // 255 overflow sign overflow c
SHL         // (overflow << 255) sign overflow c
SUB         // limit overflow c

// result = overflow ? limit : c
DUP3        // c limit overflow c
XOR         // (c ^ limit) overflow c
MUL         // ((c ^ limit) * overflow) c
XOR         // result

}
}

/**
* @dev Signed saturating subtraction, computes `a - b` saturating at the numeric bounds instead of overflowing.
*/
function saturatingSub(int256 a, int256 b) internal pure returns (int256) {
unchecked {
int256 c = a - b;
// Rationale:
// - overflow is only possible when `a` is zero or positive and `b` is negative
// - underflow is only possible when `a` is negative and `b` is positive
//
// Lemma:
// (i) - if `a >= (a - b)` is true, then `b` MUST be non-negative, otherwise overflow happened.
// (ii) - if `a >= (a - b)` is false, then `b` MUST be negative, otherwise underflow happened.
//
// So the following statement will be true only if an overflow or underflow happened:
// statement: a >= (a - b) == (b < 0)
//
// We can use the sign of `b` to distinguish between overflow and underflow, as demonstrated below:
// | a >= (a - b) | b < 0 |
// | true | true | Lemma (i) thus Overflow
// | false | false | Lemma (ii) thus Underflow
// | true | false | Ok
// | false | true | Ok
bool sign = b < 0;
bool overflow = a >= c == sign;

// Efficient branchless method to retrieve the boundary limit:
// (1 << 255) == type(int256).min
// (1 << 255) - 1 == type(int256).max
uint256 limit = (SafeCast.toUint(overflow) << 255) - SafeCast.toUint(sign);

return ternary(overflow, int256(limit), c);
}
}
}
2 changes: 1 addition & 1 deletion test/utils/math/Math.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ 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 {
function testTernary(bool f, uint256 a, uint256 b) public {
assertEq(Math.ternary(f, a, b), f ? a : b);
}

Expand Down
54 changes: 54 additions & 0 deletions test/utils/math/Math.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,21 @@ describe('Math', function () {
});
});

describe('saturatingAdd', function () {
it('adds correctly', async function () {
const a = 5678n;
const b = 1234n;
await testCommutative(this.mock.$saturatingAdd, a, b, a + b);
await testCommutative(this.mock.$saturatingAdd, a, 0n, a);
await testCommutative(this.mock.$saturatingAdd, ethers.MaxUint256, 0n, ethers.MaxUint256);
});

it('bounds on addition overflow', async function () {
await testCommutative(this.mock.$saturatingAdd, ethers.MaxUint256, 1n, ethers.MaxUint256);
expect(await this.mock.$saturatingAdd(ethers.MaxUint256, ethers.MaxUint256)).to.equal(ethers.MaxUint256);
});
});

describe('trySub', function () {
it('subtracts correctly', async function () {
const a = 5678n;
Expand All @@ -67,6 +82,25 @@ describe('Math', function () {
});
});

describe('saturatingSub', function () {
it('subtracts correctly', async function () {
const a = 5678n;
const b = 1234n;
expect(await this.mock.$saturatingSub(a, b)).to.equal(a - b);
expect(await this.mock.$saturatingSub(a, a)).to.equal(0n);
expect(await this.mock.$saturatingSub(a, 0n)).to.equal(a);
expect(await this.mock.$saturatingSub(0n, a)).to.equal(0n);
expect(await this.mock.$saturatingSub(ethers.MaxUint256, 1n)).to.equal(ethers.MaxUint256 - 1n);
});

it('bounds on subtraction overflow', async function () {
expect(await this.mock.$saturatingSub(0n, 1n)).to.equal(0n);
expect(await this.mock.$saturatingSub(1n, 2n)).to.equal(0n);
expect(await this.mock.$saturatingSub(1n, ethers.MaxUint256)).to.equal(0n);
expect(await this.mock.$saturatingSub(ethers.MaxUint256 - 1n, ethers.MaxUint256)).to.equal(0n);
});
});

describe('tryMul', function () {
it('multiplies correctly', async function () {
const a = 1234n;
Expand All @@ -87,6 +121,26 @@ describe('Math', function () {
});
});

describe('saturatingMul', function () {
it('multiplies correctly', async function () {
const a = 1234n;
const b = 5678n;
await testCommutative(this.mock.$saturatingMul, a, b, a * b);
});

it('multiplies by zero correctly', async function () {
const a = 0n;
const b = 5678n;
await testCommutative(this.mock.$saturatingMul, a, b, 0n);
});

it('bounds on multiplication overflow', async function () {
const a = ethers.MaxUint256;
const b = 2n;
await testCommutative(this.mock.$saturatingMul, a, b, ethers.MaxUint256);
});
});

describe('tryDiv', function () {
it('divides correctly', async function () {
const a = 5678n;
Expand Down
2 changes: 1 addition & 1 deletion test/utils/math/SignedMath.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ 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 {
function testTernary(bool f, int256 a, int256 b) public {
assertEq(SignedMath.ternary(f, a, b), f ? a : b);
}

Expand Down
81 changes: 81 additions & 0 deletions test/utils/math/SignedMath.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,85 @@ describe('SignedMath', function () {
});
}
});

describe('saturatingAdd', function () {
it('adds correctly', async function () {
expect(await this.mock.$saturatingAdd(0n, 0)).to.equal(0n);
const a = 5678n;
const b = 1234n;
await testCommutative(this.mock.$saturatingAdd, a, b, a + b);
await testCommutative(this.mock.$saturatingAdd, 0, 1n, 1n);
await testCommutative(this.mock.$saturatingAdd, 0, -1n, -1n);
await testCommutative(this.mock.$saturatingAdd, 1n, -1n, 0n);
expect(await this.mock.$saturatingAdd(1n, 1n)).to.equal(2n);
expect(await this.mock.$saturatingAdd(-1n, -1n)).to.equal(-2n);

await testCommutative(this.mock.$saturatingAdd, ethers.MaxInt256, 0n, ethers.MaxInt256);
await testCommutative(this.mock.$saturatingAdd, ethers.MaxInt256, -1n, ethers.MaxInt256 - 1n);
await testCommutative(this.mock.$saturatingAdd, ethers.MaxInt256, -2n, ethers.MaxInt256 - 2n);

await testCommutative(this.mock.$saturatingAdd, ethers.MinInt256, 0n, ethers.MinInt256);
await testCommutative(this.mock.$saturatingAdd, ethers.MinInt256, 1n, ethers.MinInt256 + 1n);
await testCommutative(this.mock.$saturatingAdd, ethers.MinInt256, 2n, ethers.MinInt256 + 2n);

await testCommutative(this.mock.$saturatingAdd, ethers.MinInt256, ethers.MaxInt256, -1n);
});

it('bounds on addition overflow', async function () {
await testCommutative(this.mock.$saturatingAdd, ethers.MaxInt256, 1n, ethers.MaxInt256);
await testCommutative(this.mock.$saturatingAdd, ethers.MaxInt256, 2n, ethers.MaxInt256);
await testCommutative(this.mock.$saturatingAdd, ethers.MaxInt256, ethers.MaxInt256, ethers.MaxInt256);
});

it('bounds on addition underflow', async function () {
await testCommutative(this.mock.$saturatingAdd, ethers.MinInt256, -1n, ethers.MinInt256);
await testCommutative(this.mock.$saturatingAdd, ethers.MinInt256, -2n, ethers.MinInt256);
await testCommutative(this.mock.$saturatingAdd, ethers.MinInt256, ethers.MinInt256, ethers.MinInt256);
});
});

describe('saturatingSub', function () {
it('subtracts correctly', async function () {
const a = 5678n;
const b = 1234n;
expect(await this.mock.$saturatingSub(a, b)).to.equal(a - b);

expect(await this.mock.$saturatingSub(0n, 1n)).to.equal(-1n);
expect(await this.mock.$saturatingSub(0n, 0)).to.equal(0n);
expect(await this.mock.$saturatingSub(0n, -1n)).to.equal(1n);

expect(await this.mock.$saturatingSub(1n, 1n)).to.equal(0n);
expect(await this.mock.$saturatingSub(1n, 0n)).to.equal(1n);
expect(await this.mock.$saturatingSub(1n, -1n)).to.equal(2n);

expect(await this.mock.$saturatingSub(-1n, 0n)).to.equal(-1n);
expect(await this.mock.$saturatingSub(-1n, 1n)).to.equal(-2n);
expect(await this.mock.$saturatingSub(-1n, -1n)).to.equal(0n);

expect(await this.mock.$saturatingSub(0n, ethers.MaxInt256)).to.equal(0n - ethers.MaxInt256);
expect(await this.mock.$saturatingSub(1n, ethers.MaxInt256)).to.equal(1n - ethers.MaxInt256);
expect(await this.mock.$saturatingSub(-1n, ethers.MinInt256)).to.equal(-1n - ethers.MinInt256);
expect(await this.mock.$saturatingSub(-2n, ethers.MinInt256)).to.equal(-2n - ethers.MinInt256);
expect(await this.mock.$saturatingSub(ethers.MinInt256, 0n)).to.equal(ethers.MinInt256 - 0n);
expect(await this.mock.$saturatingSub(ethers.MinInt256, -1n)).to.equal(ethers.MinInt256 + 1n);
expect(await this.mock.$saturatingSub(ethers.MinInt256, ethers.MinInt256)).to.equal(0n);
expect(await this.mock.$saturatingSub(ethers.MaxInt256, ethers.MaxInt256)).to.equal(0n);
expect(await this.mock.$saturatingSub(ethers.MaxInt256, 0n)).to.equal(ethers.MaxInt256);
expect(await this.mock.$saturatingSub(ethers.MinInt256, 0n)).to.equal(ethers.MinInt256);
});

it('bounds on subtraction overflow', async function () {
expect(await this.mock.$saturatingSub(0n, ethers.MinInt256)).to.equal(ethers.MaxInt256);
expect(await this.mock.$saturatingSub(ethers.MaxInt256, -1n)).to.equal(ethers.MaxInt256);
expect(await this.mock.$saturatingSub(ethers.MaxInt256, ethers.MinInt256)).to.equal(ethers.MaxInt256);
expect(await this.mock.$saturatingSub(1n << 254n, -(1n << 254n))).to.equal(ethers.MaxInt256);
});

it('bounds on subtraction underflow', async function () {
expect(await this.mock.$saturatingSub(ethers.MinInt256, 1n)).to.equal(ethers.MinInt256);
expect(await this.mock.$saturatingSub(-1n, ethers.MaxInt256)).to.equal(ethers.MinInt256);
expect(await this.mock.$saturatingSub(-2n, ethers.MaxInt256)).to.equal(ethers.MinInt256);
expect(await this.mock.$saturatingSub(ethers.MinInt256, ethers.MaxInt256)).to.equal(ethers.MinInt256);
});
});
});