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

Add Math.modExp and a Panic library #3298

Merged
Show file tree
Hide file tree
Changes from 57 commits
Commits
Show all changes
60 commits
Select commit Hold shift + click to select a range
91e39eb
Added Wrapper Library for ModularExponentiation along with tests.
mw2000 Mar 27, 2022
712a0f3
Fixed linting issues.
mw2000 Mar 27, 2022
77f33ea
Added function to Math.sol and migrated tests.
mw2000 Apr 9, 2022
4683f26
Merge branch 'master' into modular-exponentiation-precompile-wrapper-…
mw2000 Dec 23, 2022
7489ce4
Merge remote-tracking branch 'origin/master' into modular-exponentiat…
mw2000 Jun 8, 2023
d576641
Added tests
mw2000 Jun 9, 2023
0d78d29
Fixed lint
mw2000 Jun 9, 2023
5d99ed8
Added changeset
mw2000 Jun 9, 2023
acb16f2
Merge branch 'master' into modular-exponentiation-precompile-wrapper-…
mw2000 Jun 9, 2023
d7e81cf
Fixed codespell error
mw2000 Jun 9, 2023
85187dd
Fixed function calling in tests
mw2000 Jun 10, 2023
d458765
Merge branch 'master' into modular-exponentiation-precompile-wrapper-…
mw2000 Jun 11, 2023
01badeb
Update contracts/utils/math/Math.sol
Amxx Jun 12, 2023
a1c1439
Added a restriction to e
mw2000 Jun 25, 2023
d81d69d
Merge branch 'modular-exponentiation-precompile-wrapper-#1985' of htt…
mw2000 Jun 25, 2023
6e8cced
Merge branch 'master' into modular-exponentiation-precompile-wrapper-…
mw2000 Jun 25, 2023
fd7b8de
All args should be non-zero
mw2000 Jun 25, 2023
26a036e
Seperating the e and m != 0 out
mw2000 Jun 25, 2023
4ba0a29
Fixed test when m = 1
mw2000 Nov 8, 2023
988c950
Merge branch 'master' into modular-exponentiation-precompile-wrapper-…
mw2000 Nov 8, 2023
c08ac50
Added last bracket.
mw2000 Nov 8, 2023
98f7994
Fixed lint issues
mw2000 Nov 8, 2023
f634aab
Merge branch 'master' into modular-exponentiation-precompile-wrapper-…
mw2000 Dec 24, 2023
66a0c1f
Added custom errors + tests for it
mw2000 Dec 24, 2023
eecd818
Added comments for errors
mw2000 Dec 24, 2023
1583160
Added a not to be reverted for custom error
mw2000 Dec 24, 2023
19ead8e
Merge branch 'master' into modular-exponentiation-precompile-wrapper-…
Amxx Jan 25, 2024
8cf355f
better fuzzing for modexp
Amxx Jan 25, 2024
113e85e
cleanup tests
Amxx Jan 25, 2024
4e1cf0d
Update .changeset/shiny-poets-whisper.md
Amxx Jan 25, 2024
6d7c154
return 0 instead of reverting in case of error
Amxx Jan 25, 2024
84b285d
fallback to revert
Amxx Jan 25, 2024
9e73f46
simplification
Amxx Jan 25, 2024
76c9afa
cleanup
Amxx Jan 25, 2024
1ff0776
Refactor fuzz test
ernestognw Jan 29, 2024
f84b1b6
Lint
ernestognw Jan 29, 2024
fe32a38
mulDiv fuzzing with no external
Amxx Jan 29, 2024
4accc2e
modExp in assembly to avoid memory leaks
Amxx Jan 31, 2024
cfd80e9
optimise and mark as memory-safe
Amxx Jan 31, 2024
526d6b9
add note about using Ferma's little theorem to compute inverse in big…
Amxx Jan 31, 2024
3718090
Add utils/Panic.sol library
Amxx Feb 1, 2024
cd2f2e9
add missing files
Amxx Feb 1, 2024
104002e
fix lint
Amxx Feb 1, 2024
d149ea6
mark constants as internal
Amxx Feb 1, 2024
05aa60e
slither disable
Amxx Feb 1, 2024
f352681
add unit testing for Panic
Amxx Feb 1, 2024
32ea4bb
Update test/utils/Panic.test.js
Amxx Feb 1, 2024
2e962c8
fix lint
Amxx Feb 1, 2024
275c959
Update Panic.sol
Amxx Feb 1, 2024
24cd52a
Implement tryMod
ernestognw Feb 2, 2024
50374a1
Implement review suggestions
ernestognw Feb 2, 2024
ee91836
fix tryModExp behavior and test
Amxx Feb 2, 2024
d13e52d
better vm.expectRevert check
Amxx Feb 2, 2024
969e259
use stdErrors for forge-std
Amxx Feb 2, 2024
e64c3f9
remove unecessary import
Amxx Feb 2, 2024
06220be
add a mock to force import libraries
Amxx Feb 2, 2024
9137bae
rename panic codes following libsolutil
Amxx Feb 2, 2024
81e8ba0
fix lint
Amxx Feb 2, 2024
2b72050
Merge branch 'master' into modular-exponentiation-precompile-wrapper-…
Amxx Feb 2, 2024
2fc20d4
Nits
ernestognw Feb 2, 2024
File filter

Filter by extension

Filter by extension

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

`Math`: Add `modExp` function that exposes the `EIP-198` precompile.
5 changes: 5 additions & 0 deletions .changeset/silver-swans-promise.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'openzeppelin-solidity': minor
---

`Panic`: Add a library for reverting with panic codes.
5 changes: 5 additions & 0 deletions .changeset/smart-bugs-switch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'openzeppelin-solidity': minor
---

`Math`: MathOverflowedMulDiv error was replaced with native panic codes.
40 changes: 40 additions & 0 deletions contracts/mocks/_import.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {Address} from "../utils/Address.sol";
import {Arrays} from "../utils/Arrays.sol";
import {Base64} from "../utils/Base64.sol";
import {BitMaps} from "../utils/structs/BitMaps.sol";
import {Checkpoints} from "../utils/structs/Checkpoints.sol";
import {Context} from "../utils/Context.sol";
import {Create2} from "../utils/Create2.sol";
import {DoubleEndedQueue} from "../utils/structs/DoubleEndedQueue.sol";
import {ECDSA} from "../utils/cryptography/ECDSA.sol";
import {EIP712} from "../utils/cryptography/EIP712.sol";
import {EnumerableMap} from "../utils/structs/EnumerableMap.sol";
import {EnumerableSet} from "../utils/structs/EnumerableSet.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";
import {ERC165Checker} from "../utils/introspection/ERC165Checker.sol";
import {IERC165} from "../utils/introspection/IERC165.sol";
import {Math} from "../utils/math/Math.sol";
import {MerkleProof} from "../utils/cryptography/MerkleProof.sol";
import {MessageHashUtils} from "../utils/cryptography/MessageHashUtils.sol";
import {Multicall} from "../utils/Multicall.sol";
import {Nonces} from "../utils/Nonces.sol";
import {Panic} from "../utils/Panic.sol";
import {Pausable} from "../utils/Pausable.sol";
import {ReentrancyGuard} from "../utils/ReentrancyGuard.sol";
import {SafeCast} from "../utils/math/SafeCast.sol";
import {ShortStrings} from "../utils/ShortStrings.sol";
import {SignatureChecker} from "../utils/cryptography/SignatureChecker.sol";
import {SignedMath} from "../utils/math/SignedMath.sol";
import {StorageSlot} from "../utils/StorageSlot.sol";
import {Strings} from "../utils/Strings.sol";
import {Time} from "../utils/types/Time.sol";

abstract contract ExposeImports {
// This will be transpiled, causing all the imports above to be transpiled when running the upgradeable tests.
// This trick is necessary for testing libraries such as Panic.sol (which are not imported by any other transpiled
// contracts and would otherwise not be exposed).
}
41 changes: 41 additions & 0 deletions contracts/utils/Panic.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

/**
* @dev Helper library for emitting standardized panic codes.
*
* Follows the list from libsolutil: https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h
*/
// slither-disable-next-line unused-state
library Panic {
ernestognw marked this conversation as resolved.
Show resolved Hide resolved
/// @dev generic / unspecified error
uint256 internal constant Generic = 0x00;

Check failure on line 13 in contracts/utils/Panic.sol

View workflow job for this annotation

GitHub Actions / lint

Constant name must be in capitalized SNAKE_CASE
/// @dev used by the assert() builtin
uint256 internal constant Assert = 0x01;

Check failure on line 15 in contracts/utils/Panic.sol

View workflow job for this annotation

GitHub Actions / lint

Constant name must be in capitalized SNAKE_CASE
/// @dev arithmetic underflow or overflow
uint256 internal constant UnderOverflow = 0x11;

Check failure on line 17 in contracts/utils/Panic.sol

View workflow job for this annotation

GitHub Actions / lint

Constant name must be in capitalized SNAKE_CASE
/// @dev division or modulo by zero
uint256 internal constant DivisionByZero = 0x12;

Check failure on line 19 in contracts/utils/Panic.sol

View workflow job for this annotation

GitHub Actions / lint

Constant name must be in capitalized SNAKE_CASE
/// @dev enum conversion error
uint256 internal constant EnumConversionError = 0x21;

Check failure on line 21 in contracts/utils/Panic.sol

View workflow job for this annotation

GitHub Actions / lint

Constant name must be in capitalized SNAKE_CASE
/// @dev invalid encoding in storage
uint256 internal constant StorageEncodingError = 0x22;

Check failure on line 23 in contracts/utils/Panic.sol

View workflow job for this annotation

GitHub Actions / lint

Constant name must be in capitalized SNAKE_CASE
/// @dev empty array pop
uint256 internal constant EmptyArrayPop = 0x31;

Check failure on line 25 in contracts/utils/Panic.sol

View workflow job for this annotation

GitHub Actions / lint

Constant name must be in capitalized SNAKE_CASE
/// @dev array out of bounds access
uint256 internal constant ArrayOutOfBounds = 0x32;

Check failure on line 27 in contracts/utils/Panic.sol

View workflow job for this annotation

GitHub Actions / lint

Constant name must be in capitalized SNAKE_CASE
/// @dev resource error (too large allocation or too large array)
uint256 internal constant ResourceError = 0x41;

Check failure on line 29 in contracts/utils/Panic.sol

View workflow job for this annotation

GitHub Actions / lint

Constant name must be in capitalized SNAKE_CASE
/// @dev calling invalid internal function
uint256 internal constant InvalidInternalFunction = 0x51;

Check failure on line 31 in contracts/utils/Panic.sol

View workflow job for this annotation

GitHub Actions / lint

Constant name must be in capitalized SNAKE_CASE

function panic(uint256 code) internal pure {
Copy link
Member

Choose a reason for hiding this comment

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

Right now anyone can call Panic.code(0xff) when 0xff is not in the "official" list (I'm not sure what "official" even means in this context).

I'm not sure how frequently Solidity adds (or changes) the panic codes, but imagine the following situation:

  • We release this Panic library
  • Some protocol start using Panic.code(0x420)
  • Solidity releases a new panic code in 0.9.0 using the same code (0x420)

Wouldn't it be bad that the same revert code has different meanings?

Copy link
Member

Choose a reason for hiding this comment

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

Alternatively we can generate this library procedurally wth the codes, such that users can do:

Panic.ASSERTION_ERROR();

Copy link
Collaborator

Choose a reason for hiding this comment

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

I'm not too worried about users emitting random panic code ... but I'm not fundamentally opposed to making panic(uint256) private and having functions like

function TooMuchMemoryAllocated() internal pure { _panic(0x41); }

We would have to make them CamelCase though.

Copy link
Collaborator

Choose a reason for hiding this comment

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

The thing, if new panic code are ever added, the current version would allow users to use them without us having to do a release.
I'm also thinking, what if some L2 whant to use specific panic codes for some crosschain stuff. We won't want to add them to the library, but users will want to emit them.

Copy link
Member

Choose a reason for hiding this comment

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

We would have to make them CamelCase though.

Agree with this syntax.

The thing, if new panic code are ever added, the current version would allow users to use them without us having to do a release.

Right, good point. If the goal is to provide a workaround then I would be fine if we release the panic(uint256) function, although I'd suggest naming it _panic(uint256) and making it internal instead.

I know this is kind of the same thing but I feel the design of the library API is more friendly if we keep each panic code function and also the custom _panic for the following reasons:

  • The developers will have defined functions out of the box without the need to check the internal constants.
  • When using functions in editors like VSCode, the NatSpec shows up. Developers will have each panic code explained in their IDEs (I think this doesn't happen with the constants)
  • I realized it doesn't make sense for a protocol to rely on external contracts returning a panic code, it's easily exploitable and not 100% reliable anyway. It's worth keeping it but underscoring _panic helps signaling that the function is not intended for direct access but as a fallback for custom use cases.

Would you agree with this?

Copy link
Collaborator

@Amxx Amxx Feb 2, 2024

Choose a reason for hiding this comment

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

The linter rules are not ok with that, and I think we should follow them:

  • Constant must be SNAKE_CASE
  • Library internal functions should not have leading underscore

The developers will have defined functions out of the box without the need to check the internal constants.

I'm not sure that is a good point. When testing panic code with hardhat you do

expect(...).to.be.revertedWithPanic(PANIC_CODE.ARITHMETIC_UNDER_OR_OVERFLOW)

you don't to

expect(...).to.be.revertedWithPanicArithmeticUnderOrOverflow();

Copy link
Collaborator

@Amxx Amxx Feb 2, 2024

Choose a reason for hiding this comment

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

I think the current version is simple and effective. It's targetting advanced users anyway.

Copy link
Member

Choose a reason for hiding this comment

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

I'm not sure that is a good point. When testing panic code with hardhat you do

expect(...).to.be.revertedWithPanic(PANIC_CODE.ARITHMETIC_UNDER_OR_OVERFLOW)

Fair

I think the cureent version is simple and effective. It's targetting advanced users anyway.

We should document the function then. Currently it allows panicking with anything it I think it needs some usage instructions in both the contracts NatSpec and the panic funciton itself

/// @solidity memory-safe-assembly
assembly {
mstore(0x00, shl(0xe0, 0x4e487b71))
mstore(0x04, code)
revert(0x00, 0x24)
}
}
}
75 changes: 68 additions & 7 deletions contracts/utils/math/Math.sol
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@

pragma solidity ^0.8.20;

import {Address} from "../Address.sol";
import {Panic} from "../Panic.sol";

/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();

enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Expand Down Expand Up @@ -107,7 +105,7 @@ library Math {
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
Panic.panic(Panic.DivisionByZero);
}

// The following calculation ensures accurate ceiling division without overflow.
Expand Down Expand Up @@ -149,7 +147,7 @@ library Math {

// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
Panic.panic(denominator == 0 ? Panic.DivisionByZero : Panic.UnderOverflow);
}

///////////////////////////////////////////////
Expand Down Expand Up @@ -226,6 +224,9 @@ library Math {
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Ferma's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
Expand Down Expand Up @@ -275,6 +276,66 @@ library Math {
}
}

/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
Copy link
Member

Choose a reason for hiding this comment

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

A potential threat here is that in chains where this precompile is not available, then the result length will be 0.

I guess that's the most reliable way to protect against but I don't think it's worth the check.

I added a not specifying that developers need to make sure if the precompile is available.

if (!success) {
if (m == 0) {
Panic.panic(Panic.DivisionByZero);
} else {
revert Address.FailedInnerCall();
}
}
return result;
}

/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked has failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
ernestognw marked this conversation as resolved.
Show resolved Hide resolved
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)

success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}

/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
Expand Down
4 changes: 2 additions & 2 deletions scripts/generate/templates/Checkpoints.t.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,14 @@ function _bound${capitalize(opts.keyTypeName)}(
${opts.keyTypeName} x,
${opts.keyTypeName} min,
${opts.keyTypeName} max
) internal view returns (${opts.keyTypeName}) {
) internal pure returns (${opts.keyTypeName}) {
return SafeCast.to${capitalize(opts.keyTypeName)}(bound(uint256(x), uint256(min), uint256(max)));
}

function _prepareKeys(
${opts.keyTypeName}[] memory keys,
${opts.keyTypeName} maxSpread
) internal view {
) internal pure {
${opts.keyTypeName} lastKey = 0;
for (uint256 i = 0; i < keys.length; ++i) {
${opts.keyTypeName} key = _bound${capitalize(opts.keyTypeName)}(keys[i], lastKey, lastKey + maxSpread);
Expand Down
37 changes: 37 additions & 0 deletions test/utils/Panic.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const { ethers } = require('hardhat');
const { expect } = require('chai');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');
const { PANIC_CODES } = require('@nomicfoundation/hardhat-chai-matchers/panic');

async function fixture() {
return { mock: await ethers.deployContract('$Panic') };
}

describe('Panic', function () {
beforeEach(async function () {
Object.assign(this, await loadFixture(fixture));
});

for (const [name, code] of Object.entries({
Generic: 0x0,
Assert: PANIC_CODES.ASSERTION_ERROR,
UnderOverflow: PANIC_CODES.ARITHMETIC_UNDER_OR_OVERFLOW,
DivisionByZero: PANIC_CODES.DIVISION_BY_ZERO,
EnumConversionError: PANIC_CODES.ENUM_CONVERSION_OUT_OF_BOUNDS,
StorageEncodingError: PANIC_CODES.INCORRECTLY_ENCODED_STORAGE_BYTE_ARRAY,
EmptyArrayPop: PANIC_CODES.POP_ON_EMPTY_ARRAY,
ArrayOutOfBounds: PANIC_CODES.ARRAY_ACCESS_OUT_OF_BOUNDS,
ResourceError: PANIC_CODES.TOO_MUCH_MEMORY_ALLOCATED,
InvalidInternalFunction: PANIC_CODES.ZERO_INITIALIZED_VARIABLE,
})) {
describe(name, function () {
it('exposes panic code as constant', async function () {
expect(await this.mock.getFunction(`$${name}`)()).to.equal(code);
});

it(`throw panic code ${ethers.toBeHex(code)}`, async function () {
await expect(this.mock.$panic(code)).to.be.revertedWithPanic(code);
});
});
}
});
50 changes: 36 additions & 14 deletions test/utils/math/Math.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

pragma solidity ^0.8.20;

import {Test} from "forge-std/Test.sol";
import {Test, stdError} from "forge-std/Test.sol";

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

Expand Down Expand Up @@ -186,7 +186,7 @@ contract MathTest is Test {
// Full precision for q * d
(uint256 qdHi, uint256 qdLo) = _mulHighLow(q, d);
// Add remainder of x * y / d (computed as rem = (x * y % d))
(uint256 qdRemLo, uint256 c) = _addCarry(qdLo, _mulmod(x, y, d));
(uint256 qdRemLo, uint256 c) = _addCarry(qdLo, mulmod(x, y, d));
uint256 qdRemHi = qdHi + c;

// Full precision check that x * y = q * d + rem
Expand All @@ -201,14 +201,42 @@ contract MathTest is Test {
vm.assume(xyHi >= d);

// we are outside the scope of {testMulDiv}, we expect muldiv to revert
try this.muldiv(x, y, d) returns (uint256) {
fail();
} catch {}
vm.expectRevert(d == 0 ? stdError.divisionError : stdError.arithmeticError);
Math.mulDiv(x, y, d);
}

// External call
function muldiv(uint256 x, uint256 y, uint256 d) external pure returns (uint256) {
return Math.mulDiv(x, y, d);
// MOD EXP
function testModExp(uint256 b, uint256 e, uint256 m) public {
if (m == 0) {
vm.expectRevert(stdError.divisionError);
}
uint256 result = Math.modExp(b, e, m);
assertLt(result, m);
assertEq(result, _nativeModExp(b, e, m));
}

function testTryModExp(uint256 b, uint256 e, uint256 m) public {
(bool success, uint256 result) = Math.tryModExp(b, e, m);
assertEq(success, m != 0);
if (success) {
assertLt(result, m);
assertEq(result, _nativeModExp(b, e, m));
} else {
assertEq(result, 0);
}
}

function _nativeModExp(uint256 b, uint256 e, uint256 m) private pure returns (uint256) {
if (m == 1) return 0;
uint256 r = 1;
while (e > 0) {
if (e % 2 > 0) {
r = mulmod(r, b, m);
}
b = mulmod(b, b, m);
e >>= 1;
}
return r;
}

// Helpers
Expand All @@ -217,12 +245,6 @@ contract MathTest is Test {
return Math.Rounding(r);
}

function _mulmod(uint256 x, uint256 y, uint256 z) private pure returns (uint256 r) {
assembly {
r := mulmod(x, y, z)
}
}

function _mulHighLow(uint256 x, uint256 y) private pure returns (uint256 high, uint256 low) {
(uint256 x0, uint256 x1) = (x & type(uint128).max, x >> 128);
(uint256 y0, uint256 y1) = (y & type(uint128).max, y >> 128);
Expand Down
Loading
Loading