commit
79be2062a7
@ -0,0 +1,5 @@ |
||||
--- |
||||
'openzeppelin-solidity': patch |
||||
--- |
||||
|
||||
`ProxyAdmin`: Fixed documentation for `UPGRADE_INTERFACE_VERSION` getter. |
@ -0,0 +1,5 @@ |
||||
--- |
||||
'openzeppelin-solidity': minor |
||||
--- |
||||
|
||||
`RSA`: Library to verify signatures according to RFC 8017 Signature Verification Operation |
@ -0,0 +1,5 @@ |
||||
--- |
||||
'openzeppelin-solidity': minor |
||||
--- |
||||
|
||||
`GovernorCountingFractional`: Add a governor counting module that allows distributing voting power amongst 3 options (For, Against, Abstain). |
@ -0,0 +1,5 @@ |
||||
--- |
||||
'openzeppelin-solidity': minor |
||||
--- |
||||
|
||||
`Strings`: Added a utility function for converting an address to checksummed string. |
@ -0,0 +1,5 @@ |
||||
--- |
||||
'openzeppelin-solidity': minor |
||||
--- |
||||
|
||||
`AccessManager`: Allow the `onlyAuthorized` modifier to restrict functions added to the manager. |
@ -0,0 +1,5 @@ |
||||
--- |
||||
'openzeppelin-solidity': minor |
||||
--- |
||||
|
||||
`Create2`: Bubbles up returndata from a deployed contract that reverted during construction. |
@ -0,0 +1,5 @@ |
||||
--- |
||||
'openzeppelin-solidity': minor |
||||
--- |
||||
|
||||
`P256`: Library for verification and public key recovery of P256 (aka secp256r1) signatures. |
@ -0,0 +1,193 @@ |
||||
// SPDX-License-Identifier: MIT |
||||
|
||||
pragma solidity ^0.8.20; |
||||
|
||||
import {Governor} from "../Governor.sol"; |
||||
import {GovernorCountingSimple} from "./GovernorCountingSimple.sol"; |
||||
import {Math} from "../../utils/math/Math.sol"; |
||||
|
||||
/** |
||||
* @dev Extension of {Governor} for fractional voting. |
||||
* |
||||
* Similar to {GovernorCountingSimple}, this contract is a votes counting module for {Governor} that supports 3 options: |
||||
* Against, For, Abstain. Additionally, it includes a fourth option: Fractional, which allows voters to split their voting |
||||
* power amongst the other 3 options. |
||||
* |
||||
* Votes cast with the Fractional support must be accompanied by a `params` argument that is three packed `uint128` values |
||||
* representing the weight the delegate assigns to Against, For, and Abstain respectively. For those votes cast for the other |
||||
* 3 options, the `params` argument must be empty. |
||||
* |
||||
* This is mostly useful when the delegate is a contract that implements its own rules for voting. These delegate-contracts |
||||
* can cast fractional votes according to the preferences of multiple entities delegating their voting power. |
||||
* |
||||
* Some example use cases include: |
||||
* |
||||
* * Voting from tokens that are held by a DeFi pool |
||||
* * Voting from an L2 with tokens held by a bridge |
||||
* * Voting privately from a shielded pool using zero knowledge proofs. |
||||
* |
||||
* Based on ScopeLift's GovernorCountingFractional[https://github.com/ScopeLift/flexible-voting/blob/e5de2efd1368387b840931f19f3c184c85842761/src/GovernorCountingFractional.sol] |
||||
*/ |
||||
abstract contract GovernorCountingFractional is Governor { |
||||
using Math for *; |
||||
|
||||
uint8 internal constant VOTE_TYPE_FRACTIONAL = 255; |
||||
|
||||
struct ProposalVote { |
||||
uint256 againstVotes; |
||||
uint256 forVotes; |
||||
uint256 abstainVotes; |
||||
mapping(address voter => uint256) usedVotes; |
||||
} |
||||
|
||||
/** |
||||
* @dev Mapping from proposal ID to vote tallies for that proposal. |
||||
*/ |
||||
mapping(uint256 => ProposalVote) private _proposalVotes; |
||||
|
||||
/** |
||||
* @dev A fractional vote params uses more votes than are available for that user. |
||||
*/ |
||||
error GovernorExceedRemainingWeight(address voter, uint256 usedVotes, uint256 remainingWeight); |
||||
|
||||
/** |
||||
* @dev See {IGovernor-COUNTING_MODE}. |
||||
*/ |
||||
// solhint-disable-next-line func-name-mixedcase |
||||
function COUNTING_MODE() public pure virtual override returns (string memory) { |
||||
return "support=bravo,fractional&quorum=for,abstain¶ms=fractional"; |
||||
} |
||||
|
||||
/** |
||||
* @dev See {IGovernor-hasVoted}. |
||||
*/ |
||||
function hasVoted(uint256 proposalId, address account) public view virtual override returns (bool) { |
||||
return usedVotes(proposalId, account) > 0; |
||||
} |
||||
|
||||
/** |
||||
* @dev Get the number of votes already cast by `account` for a proposal with `proposalId`. Useful for |
||||
* integrations that allow delegates to cast rolling, partial votes. |
||||
*/ |
||||
function usedVotes(uint256 proposalId, address account) public view virtual returns (uint256) { |
||||
return _proposalVotes[proposalId].usedVotes[account]; |
||||
} |
||||
|
||||
/** |
||||
* @dev Get current distribution of votes for a given proposal. |
||||
*/ |
||||
function proposalVotes( |
||||
uint256 proposalId |
||||
) public view virtual returns (uint256 againstVotes, uint256 forVotes, uint256 abstainVotes) { |
||||
ProposalVote storage proposalVote = _proposalVotes[proposalId]; |
||||
return (proposalVote.againstVotes, proposalVote.forVotes, proposalVote.abstainVotes); |
||||
} |
||||
|
||||
/** |
||||
* @dev See {Governor-_quorumReached}. |
||||
*/ |
||||
function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) { |
||||
ProposalVote storage proposalVote = _proposalVotes[proposalId]; |
||||
return quorum(proposalSnapshot(proposalId)) <= proposalVote.forVotes + proposalVote.abstainVotes; |
||||
} |
||||
|
||||
/** |
||||
* @dev See {Governor-_voteSucceeded}. In this module, forVotes must be > againstVotes. |
||||
*/ |
||||
function _voteSucceeded(uint256 proposalId) internal view virtual override returns (bool) { |
||||
ProposalVote storage proposalVote = _proposalVotes[proposalId]; |
||||
return proposalVote.forVotes > proposalVote.againstVotes; |
||||
} |
||||
|
||||
/** |
||||
* @dev See {Governor-_countVote}. Function that records the delegate's votes. |
||||
* |
||||
* Executing this function consumes (part of) the delegate's weight on the proposal. This weight can be |
||||
* distributed amongst the 3 options (Against, For, Abstain) by specifying a fractional `support`. |
||||
* |
||||
* This counting module supports two vote casting modes: nominal and fractional. |
||||
* |
||||
* - Nominal: A nominal vote is cast by setting `support` to one of the 3 bravo options (Against, For, Abstain). |
||||
* - Fractional: A fractional vote is cast by setting `support` to `type(uint8).max` (255). |
||||
* |
||||
* Casting a nominal vote requires `params` to be empty and consumes the delegate's full remaining weight on the |
||||
* proposal for the specified `support` option. This is similar to the {GovernorCountingSimple} module and follows |
||||
* the `VoteType` enum from Governor Bravo. As a consequence, no vote weight remains unspent so no further voting |
||||
* is possible (for this `proposalId` and this `account`). |
||||
* |
||||
* Casting a fractional vote consumes a fraction of the delegate's remaining weight on the proposal according to the |
||||
* weights the delegate assigns to each support option (Against, For, Abstain respectively). The sum total of the |
||||
* three decoded vote weights _must_ be less than or equal to the delegate's remaining weight on the proposal (i.e. |
||||
* their checkpointed total weight minus votes already cast on the proposal). This format can be produced using: |
||||
* |
||||
* `abi.encodePacked(uint128(againstVotes), uint128(forVotes), uint128(abstainVotes))` |
||||
* |
||||
* NOTE: Consider that fractional voting restricts the number of casted vote (in each category) to 128 bits. |
||||
* Depending on how many decimals the underlying token has, a single voter may require to split their vote into |
||||
* multiple vote operations. For precision higher than ~30 decimals, large token holders may require an |
||||
* potentially large number of calls to cast all their votes. The voter has the possibility to cast all the |
||||
* remaining votes in a single operation using the traditional "bravo" vote. |
||||
*/ |
||||
// slither-disable-next-line cyclomatic-complexity |
||||
function _countVote( |
||||
uint256 proposalId, |
||||
address account, |
||||
uint8 support, |
||||
uint256 totalWeight, |
||||
bytes memory params |
||||
) internal virtual override returns (uint256) { |
||||
// Compute number of remaining votes. Returns 0 on overflow. |
||||
(, uint256 remainingWeight) = totalWeight.trySub(usedVotes(proposalId, account)); |
||||
if (remainingWeight == 0) { |
||||
revert GovernorAlreadyCastVote(account); |
||||
} |
||||
|
||||
uint256 againstVotes = 0; |
||||
uint256 forVotes = 0; |
||||
uint256 abstainVotes = 0; |
||||
uint256 usedWeight; |
||||
|
||||
// For clarity of event indexing, fractional voting must be clearly advertised in the "support" field. |
||||
// |
||||
// Supported `support` value must be: |
||||
// - "Full" voting: `support = 0` (Against), `1` (For) or `2` (Abstain), with empty params. |
||||
// - "Fractional" voting: `support = 255`, with 48 bytes params. |
||||
if (support == uint8(GovernorCountingSimple.VoteType.Against)) { |
||||
if (params.length != 0) revert GovernorInvalidVoteParams(); |
||||
usedWeight = againstVotes = remainingWeight; |
||||
} else if (support == uint8(GovernorCountingSimple.VoteType.For)) { |
||||
if (params.length != 0) revert GovernorInvalidVoteParams(); |
||||
usedWeight = forVotes = remainingWeight; |
||||
} else if (support == uint8(GovernorCountingSimple.VoteType.Abstain)) { |
||||
if (params.length != 0) revert GovernorInvalidVoteParams(); |
||||
usedWeight = abstainVotes = remainingWeight; |
||||
} else if (support == VOTE_TYPE_FRACTIONAL) { |
||||
// The `params` argument is expected to be three packed `uint128`: |
||||
// `abi.encodePacked(uint128(againstVotes), uint128(forVotes), uint128(abstainVotes))` |
||||
if (params.length != 0x30) revert GovernorInvalidVoteParams(); |
||||
|
||||
assembly ("memory-safe") { |
||||
againstVotes := shr(128, mload(add(params, 0x20))) |
||||
forVotes := shr(128, mload(add(params, 0x30))) |
||||
abstainVotes := shr(128, mload(add(params, 0x40))) |
||||
usedWeight := add(add(againstVotes, forVotes), abstainVotes) // inputs are uint128: cannot overflow |
||||
} |
||||
|
||||
// check parsed arguments are valid |
||||
if (usedWeight > remainingWeight) { |
||||
revert GovernorExceedRemainingWeight(account, usedWeight, remainingWeight); |
||||
} |
||||
} else { |
||||
revert GovernorInvalidVoteType(); |
||||
} |
||||
|
||||
// update votes tracking |
||||
ProposalVote storage details = _proposalVotes[proposalId]; |
||||
if (againstVotes > 0) details.againstVotes += againstVotes; |
||||
if (forVotes > 0) details.forVotes += forVotes; |
||||
if (abstainVotes > 0) details.abstainVotes += abstainVotes; |
||||
details.usedVotes[account] += usedWeight; |
||||
|
||||
return usedWeight; |
||||
} |
||||
} |
@ -0,0 +1,21 @@ |
||||
// SPDX-License-Identifier: MIT |
||||
|
||||
pragma solidity ^0.8.20; |
||||
|
||||
import {AccessManager} from "../access/manager/AccessManager.sol"; |
||||
import {StorageSlot} from "../utils/StorageSlot.sol"; |
||||
|
||||
contract AccessManagerMock is AccessManager { |
||||
event CalledRestricted(address caller); |
||||
event CalledUnrestricted(address caller); |
||||
|
||||
constructor(address initialAdmin) AccessManager(initialAdmin) {} |
||||
|
||||
function fnRestricted() public onlyAuthorized { |
||||
emit CalledRestricted(msg.sender); |
||||
} |
||||
|
||||
function fnUnrestricted() public { |
||||
emit CalledUnrestricted(msg.sender); |
||||
} |
||||
} |
@ -0,0 +1,34 @@ |
||||
// SPDX-License-Identifier: MIT |
||||
|
||||
pragma solidity ^0.8.20; |
||||
|
||||
contract ConstructorMock { |
||||
bool foo; |
||||
|
||||
enum RevertType { |
||||
None, |
||||
RevertWithoutMessage, |
||||
RevertWithMessage, |
||||
RevertWithCustomError, |
||||
Panic |
||||
} |
||||
|
||||
error CustomError(); |
||||
|
||||
constructor(RevertType error) { |
||||
// After transpilation to upgradeable contract, the constructor will become an initializer |
||||
// To silence the `... can be restricted to view` warning, we write to state |
||||
foo = true; |
||||
|
||||
if (error == RevertType.RevertWithoutMessage) { |
||||
revert(); |
||||
} else if (error == RevertType.RevertWithMessage) { |
||||
revert("ConstructorMock: reverting"); |
||||
} else if (error == RevertType.RevertWithCustomError) { |
||||
revert CustomError(); |
||||
} else if (error == RevertType.Panic) { |
||||
uint256 a = uint256(0) / uint256(0); |
||||
a; |
||||
} |
||||
} |
||||
} |
@ -0,0 +1,14 @@ |
||||
// SPDX-License-Identifier: MIT |
||||
|
||||
pragma solidity ^0.8.20; |
||||
|
||||
import {Governor} from "../../governance/Governor.sol"; |
||||
import {GovernorSettings} from "../../governance/extensions/GovernorSettings.sol"; |
||||
import {GovernorCountingFractional} from "../../governance/extensions/GovernorCountingFractional.sol"; |
||||
import {GovernorVotesQuorumFraction} from "../../governance/extensions/GovernorVotesQuorumFraction.sol"; |
||||
|
||||
abstract contract GovernorFractionalMock is GovernorSettings, GovernorVotesQuorumFraction, GovernorCountingFractional { |
||||
function proposalThreshold() public view override(Governor, GovernorSettings) returns (uint256) { |
||||
return super.proposalThreshold(); |
||||
} |
||||
} |
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,316 @@ |
||||
// SPDX-License-Identifier: MIT |
||||
pragma solidity ^0.8.20; |
||||
|
||||
import {Math} from "../math/Math.sol"; |
||||
import {Errors} from "../Errors.sol"; |
||||
|
||||
/** |
||||
* @dev Implementation of secp256r1 verification and recovery functions. |
||||
* |
||||
* The secp256r1 curve (also known as P256) is a NIST standard curve with wide support in modern devices |
||||
* and cryptographic standards. Some notable examples include Apple's Secure Enclave and Android's Keystore |
||||
* as well as authentication protocols like FIDO2. |
||||
* |
||||
* Based on the original https://github.com/itsobvioustech/aa-passkeys-wallet/blob/main/src/Secp256r1.sol[implementation of itsobvioustech]. |
||||
* Heavily inspired in https://github.com/maxrobot/elliptic-solidity/blob/master/contracts/Secp256r1.sol[maxrobot] and |
||||
* https://github.com/tdrerup/elliptic-curve-solidity/blob/master/contracts/curves/EllipticCurve.sol[tdrerup] implementations. |
||||
*/ |
||||
library P256 { |
||||
struct JPoint { |
||||
uint256 x; |
||||
uint256 y; |
||||
uint256 z; |
||||
} |
||||
|
||||
/// @dev Generator (x component) |
||||
uint256 internal constant GX = 0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296; |
||||
/// @dev Generator (y component) |
||||
uint256 internal constant GY = 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5; |
||||
/// @dev P (size of the field) |
||||
uint256 internal constant P = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF; |
||||
/// @dev N (order of G) |
||||
uint256 internal constant N = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551; |
||||
/// @dev A parameter of the weierstrass equation |
||||
uint256 internal constant A = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC; |
||||
/// @dev B parameter of the weierstrass equation |
||||
uint256 internal constant B = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B; |
||||
|
||||
/// @dev (P + 1) / 4. Useful to compute sqrt |
||||
uint256 private constant P1DIV4 = 0x3fffffffc0000000400000000000000000000000400000000000000000000000; |
||||
|
||||
/// @dev N/2 for excluding higher order `s` values |
||||
uint256 private constant HALF_N = 0x7fffffff800000007fffffffffffffffde737d56d38bcf4279dce5617e3192a8; |
||||
|
||||
/** |
||||
* @dev Verifies a secp256r1 signature using the RIP-7212 precompile and falls back to the Solidity implementation |
||||
* if the precompile is not available. This version should work on all chains, but requires the deployment of more |
||||
* bytecode. |
||||
* |
||||
* @param h - hashed message |
||||
* @param r - signature half R |
||||
* @param s - signature half S |
||||
* @param qx - public key coordinate X |
||||
* @param qy - public key coordinate Y |
||||
* |
||||
* IMPORTANT: This function disallows signatures where the `s` value is above `N/2` to prevent malleability. |
||||
* To flip the `s` value, compute `s = N - s`. |
||||
*/ |
||||
function verify(bytes32 h, bytes32 r, bytes32 s, bytes32 qx, bytes32 qy) internal view returns (bool) { |
||||
(bool valid, bool supported) = _tryVerifyNative(h, r, s, qx, qy); |
||||
return supported ? valid : verifySolidity(h, r, s, qx, qy); |
||||
} |
||||
|
||||
/** |
||||
* @dev Same as {verify}, but it will revert if the required precompile is not available. |
||||
* |
||||
* Make sure any logic (code or precompile) deployed at that address is the expected one, |
||||
* otherwise the returned value may be misinterpreted as a positive boolean. |
||||
*/ |
||||
function verifyNative(bytes32 h, bytes32 r, bytes32 s, bytes32 qx, bytes32 qy) internal view returns (bool) { |
||||
(bool valid, bool supported) = _tryVerifyNative(h, r, s, qx, qy); |
||||
if (supported) { |
||||
return valid; |
||||
} else { |
||||
revert Errors.MissingPrecompile(address(0x100)); |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* @dev Same as {verify}, but it will return false if the required precompile is not available. |
||||
*/ |
||||
function _tryVerifyNative( |
||||
bytes32 h, |
||||
bytes32 r, |
||||
bytes32 s, |
||||
bytes32 qx, |
||||
bytes32 qy |
||||
) private view returns (bool valid, bool supported) { |
||||
if (!_isProperSignature(r, s) || !isValidPublicKey(qx, qy)) { |
||||
return (false, true); // signature is invalid, and its not because the precompile is missing |
||||
} |
||||
|
||||
(bool success, bytes memory returndata) = address(0x100).staticcall(abi.encode(h, r, s, qx, qy)); |
||||
return (success && returndata.length == 0x20) ? (abi.decode(returndata, (bool)), true) : (false, false); |
||||
} |
||||
|
||||
/** |
||||
* @dev Same as {verify}, but only the Solidity implementation is used. |
||||
*/ |
||||
function verifySolidity(bytes32 h, bytes32 r, bytes32 s, bytes32 qx, bytes32 qy) internal view returns (bool) { |
||||
if (!_isProperSignature(r, s) || !isValidPublicKey(qx, qy)) { |
||||
return false; |
||||
} |
||||
|
||||
JPoint[16] memory points = _preComputeJacobianPoints(uint256(qx), uint256(qy)); |
||||
uint256 w = Math.invModPrime(uint256(s), N); |
||||
uint256 u1 = mulmod(uint256(h), w, N); |
||||
uint256 u2 = mulmod(uint256(r), w, N); |
||||
(uint256 x, ) = _jMultShamir(points, u1, u2); |
||||
return ((x % N) == uint256(r)); |
||||
} |
||||
|
||||
/** |
||||
* @dev Public key recovery |
||||
* |
||||
* @param h - hashed message |
||||
* @param v - signature recovery param |
||||
* @param r - signature half R |
||||
* @param s - signature half S |
||||
* |
||||
* IMPORTANT: This function disallows signatures where the `s` value is above `N/2` to prevent malleability. |
||||
* To flip the `s` value, compute `s = N - s` and `v = 1 - v` if (`v = 0 | 1`). |
||||
*/ |
||||
function recovery(bytes32 h, uint8 v, bytes32 r, bytes32 s) internal view returns (bytes32, bytes32) { |
||||
if (!_isProperSignature(r, s) || v > 1) { |
||||
return (0, 0); |
||||
} |
||||
|
||||
uint256 rx = uint256(r); |
||||
uint256 ry2 = addmod(mulmod(addmod(mulmod(rx, rx, P), A, P), rx, P), B, P); // weierstrass equation y² = x³ + a.x + b |
||||
uint256 ry = Math.modExp(ry2, P1DIV4, P); // This formula for sqrt work because P ≡ 3 (mod 4) |
||||
if (mulmod(ry, ry, P) != ry2) return (0, 0); // Sanity check |
||||
if (ry % 2 != v % 2) ry = P - ry; |
||||
|
||||
JPoint[16] memory points = _preComputeJacobianPoints(rx, ry); |
||||
uint256 w = Math.invModPrime(uint256(r), N); |
||||
uint256 u1 = mulmod(N - (uint256(h) % N), w, N); |
||||
uint256 u2 = mulmod(uint256(s), w, N); |
||||
(uint256 x, uint256 y) = _jMultShamir(points, u1, u2); |
||||
return (bytes32(x), bytes32(y)); |
||||
} |
||||
|
||||
/** |
||||
* @dev Checks if (x, y) are valid coordinates of a point on the curve. |
||||
* In particular this function checks that x <= P and y <= P. |
||||
*/ |
||||
function isValidPublicKey(bytes32 x, bytes32 y) internal pure returns (bool result) { |
||||
assembly ("memory-safe") { |
||||
let p := P |
||||
let lhs := mulmod(y, y, p) // y^2 |
||||
let rhs := addmod(mulmod(addmod(mulmod(x, x, p), A, p), x, p), B, p) // ((x^2 + a) * x) + b = x^3 + ax + b |
||||
result := and(and(lt(x, p), lt(y, p)), eq(lhs, rhs)) // Should conform with the Weierstrass equation |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* @dev Checks if (r, s) is a proper signature. |
||||
* In particular, this checks that `s` is in the "lower-range", making the signature non-malleable. |
||||
*/ |
||||
function _isProperSignature(bytes32 r, bytes32 s) private pure returns (bool) { |
||||
return uint256(r) > 0 && uint256(r) < N && uint256(s) > 0 && uint256(s) <= HALF_N; |
||||
} |
||||
|
||||
/** |
||||
* @dev Reduce from jacobian to affine coordinates |
||||
* @param jx - jacobian coordinate x |
||||
* @param jy - jacobian coordinate y |
||||
* @param jz - jacobian coordinate z |
||||
* @return ax - affine coordinate x |
||||
* @return ay - affine coordinate y |
||||
*/ |
||||
function _affineFromJacobian(uint256 jx, uint256 jy, uint256 jz) private view returns (uint256 ax, uint256 ay) { |
||||
if (jz == 0) return (0, 0); |
||||
uint256 zinv = Math.invModPrime(jz, P); |
||||
uint256 zzinv = mulmod(zinv, zinv, P); |
||||
uint256 zzzinv = mulmod(zzinv, zinv, P); |
||||
ax = mulmod(jx, zzinv, P); |
||||
ay = mulmod(jy, zzzinv, P); |
||||
} |
||||
|
||||
/** |
||||
* @dev Point addition on the jacobian coordinates |
||||
* Reference: https://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#addition-add-1998-cmo-2 |
||||
*/ |
||||
function _jAdd( |
||||
JPoint memory p1, |
||||
uint256 x2, |
||||
uint256 y2, |
||||
uint256 z2 |
||||
) private pure returns (uint256 rx, uint256 ry, uint256 rz) { |
||||
assembly ("memory-safe") { |
||||
let p := P |
||||
let z1 := mload(add(p1, 0x40)) |
||||
let s1 := mulmod(mload(add(p1, 0x20)), mulmod(mulmod(z2, z2, p), z2, p), p) // s1 = y1*z2³ |
||||
let s2 := mulmod(y2, mulmod(mulmod(z1, z1, p), z1, p), p) // s2 = y2*z1³ |
||||
let r := addmod(s2, sub(p, s1), p) // r = s2-s1 |
||||
let u1 := mulmod(mload(p1), mulmod(z2, z2, p), p) // u1 = x1*z2² |
||||
let u2 := mulmod(x2, mulmod(z1, z1, p), p) // u2 = x2*z1² |
||||
let h := addmod(u2, sub(p, u1), p) // h = u2-u1 |
||||
let hh := mulmod(h, h, p) // h² |
||||
|
||||
// x' = r²-h³-2*u1*h² |
||||
rx := addmod( |
||||
addmod(mulmod(r, r, p), sub(p, mulmod(h, hh, p)), p), |
||||
sub(p, mulmod(2, mulmod(u1, hh, p), p)), |
||||
p |
||||
) |
||||
// y' = r*(u1*h²-x')-s1*h³ |
||||
ry := addmod( |
||||
mulmod(r, addmod(mulmod(u1, hh, p), sub(p, rx), p), p), |
||||
sub(p, mulmod(s1, mulmod(h, hh, p), p)), |
||||
p |
||||
) |
||||
// z' = h*z1*z2 |
||||
rz := mulmod(h, mulmod(z1, z2, p), p) |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* @dev Point doubling on the jacobian coordinates |
||||
* Reference: https://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-dbl-1998-cmo-2 |
||||
*/ |
||||
function _jDouble(uint256 x, uint256 y, uint256 z) private pure returns (uint256 rx, uint256 ry, uint256 rz) { |
||||
assembly ("memory-safe") { |
||||
let p := P |
||||
let yy := mulmod(y, y, p) |
||||
let zz := mulmod(z, z, p) |
||||
let s := mulmod(4, mulmod(x, yy, p), p) // s = 4*x*y² |
||||
let m := addmod(mulmod(3, mulmod(x, x, p), p), mulmod(A, mulmod(zz, zz, p), p), p) // m = 3*x²+a*z⁴ |
||||
let t := addmod(mulmod(m, m, p), sub(p, mulmod(2, s, p)), p) // t = m²-2*s |
||||
|
||||
// x' = t |
||||
rx := t |
||||
// y' = m*(s-t)-8*y⁴ |
||||
ry := addmod(mulmod(m, addmod(s, sub(p, t), p), p), sub(p, mulmod(8, mulmod(yy, yy, p), p)), p) |
||||
// z' = 2*y*z |
||||
rz := mulmod(2, mulmod(y, z, p), p) |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* @dev Compute P·u1 + Q·u2 using the precomputed points for P and Q (see {_preComputeJacobianPoints}). |
||||
* |
||||
* Uses Strauss Shamir trick for EC multiplication |
||||
* https://stackoverflow.com/questions/50993471/ec-scalar-multiplication-with-strauss-shamir-method |
||||
* we optimise on this a bit to do with 2 bits at a time rather than a single bit |
||||
* the individual points for a single pass are precomputed |
||||
* overall this reduces the number of additions while keeping the same number of doublings |
||||
*/ |
||||
function _jMultShamir(JPoint[16] memory points, uint256 u1, uint256 u2) private view returns (uint256, uint256) { |
||||
uint256 x = 0; |
||||
uint256 y = 0; |
||||
uint256 z = 0; |
||||
unchecked { |
||||
for (uint256 i = 0; i < 128; ++i) { |
||||
if (z > 0) { |
||||
(x, y, z) = _jDouble(x, y, z); |
||||
(x, y, z) = _jDouble(x, y, z); |
||||
} |
||||
// Read 2 bits of u1, and 2 bits of u2. Combining the two give a lookup index in the table. |
||||
uint256 pos = ((u1 >> 252) & 0xc) | ((u2 >> 254) & 0x3); |
||||
if (pos > 0) { |
||||
if (z == 0) { |
||||
(x, y, z) = (points[pos].x, points[pos].y, points[pos].z); |
||||
} else { |
||||
(x, y, z) = _jAdd(points[pos], x, y, z); |
||||
} |
||||
} |
||||
u1 <<= 2; |
||||
u2 <<= 2; |
||||
} |
||||
} |
||||
return _affineFromJacobian(x, y, z); |
||||
} |
||||
|
||||
/** |
||||
* @dev Precompute a matrice of useful jacobian points associated with a given P. This can be seen as a 4x4 matrix |
||||
* that contains combination of P and G (generator) up to 3 times each. See the table below: |
||||
* |
||||
* ┌────┬─────────────────────┐ |
||||
* │ i │ 0 1 2 3 │ |
||||
* ├────┼─────────────────────┤ |
||||
* │ 0 │ 0 p 2p 3p │ |
||||
* │ 4 │ g g+p g+2p g+3p │ |
||||
* │ 8 │ 2g 2g+p 2g+2p 2g+3p │ |
||||
* │ 12 │ 3g 3g+p 3g+2p 3g+3p │ |
||||
* └────┴─────────────────────┘ |
||||
*/ |
||||
function _preComputeJacobianPoints(uint256 px, uint256 py) private pure returns (JPoint[16] memory points) { |
||||
points[0x00] = JPoint(0, 0, 0); // 0,0 |
||||
points[0x01] = JPoint(px, py, 1); // 1,0 (p) |
||||
points[0x04] = JPoint(GX, GY, 1); // 0,1 (g) |
||||
points[0x02] = _jDoublePoint(points[0x01]); // 2,0 (2p) |
||||
points[0x08] = _jDoublePoint(points[0x04]); // 0,2 (2g) |
||||
points[0x03] = _jAddPoint(points[0x01], points[0x02]); // 3,0 (3p) |
||||
points[0x05] = _jAddPoint(points[0x01], points[0x04]); // 1,1 (p+g) |
||||
points[0x06] = _jAddPoint(points[0x02], points[0x04]); // 2,1 (2p+g) |
||||
points[0x07] = _jAddPoint(points[0x03], points[0x04]); // 3,1 (3p+g) |
||||
points[0x09] = _jAddPoint(points[0x01], points[0x08]); // 1,2 (p+2g) |
||||
points[0x0a] = _jAddPoint(points[0x02], points[0x08]); // 2,2 (2p+2g) |
||||
points[0x0b] = _jAddPoint(points[0x03], points[0x08]); // 3,2 (3p+2g) |
||||
points[0x0c] = _jAddPoint(points[0x04], points[0x08]); // 0,3 (g+2g) |
||||
points[0x0d] = _jAddPoint(points[0x01], points[0x0c]); // 1,3 (p+3g) |
||||
points[0x0e] = _jAddPoint(points[0x02], points[0x0c]); // 2,3 (2p+3g) |
||||
points[0x0f] = _jAddPoint(points[0x03], points[0x0C]); // 3,3 (3p+3g) |
||||
} |
||||
|
||||
function _jAddPoint(JPoint memory p1, JPoint memory p2) private pure returns (JPoint memory) { |
||||
(uint256 x, uint256 y, uint256 z) = _jAdd(p1, p2.x, p2.y, p2.z); |
||||
return JPoint(x, y, z); |
||||
} |
||||
|
||||
function _jDoublePoint(JPoint memory p) private pure returns (JPoint memory) { |
||||
(uint256 x, uint256 y, uint256 z) = _jDouble(p.x, p.y, p.z); |
||||
return JPoint(x, y, z); |
||||
} |
||||
} |
@ -0,0 +1,145 @@ |
||||
// SPDX-License-Identifier: MIT |
||||
pragma solidity ^0.8.20; |
||||
|
||||
import {Math} from "../math/Math.sol"; |
||||
|
||||
/** |
||||
* @dev RSA PKCS#1 v1.5 signature verification implementation according to https://datatracker.ietf.org/doc/html/rfc8017[RFC8017]. |
||||
* |
||||
* This library supports PKCS#1 v1.5 padding to avoid malleability via chosen plaintext attacks in practical implementations. |
||||
* The padding follows the EMSA-PKCS1-v1_5-ENCODE encoding definition as per section 9.2 of the RFC. This padding makes |
||||
* RSA semanticaly secure for signing messages. |
||||
* |
||||
* Inspired by https://github.com/adria0/SolRsaVerify[Adrià Massanet's work] |
||||
*/ |
||||
library RSA { |
||||
/** |
||||
* @dev Same as {pkcs1} but using SHA256 to calculate the digest of `data`. |
||||
*/ |
||||
function pkcs1Sha256( |
||||
bytes memory data, |
||||
bytes memory s, |
||||
bytes memory e, |
||||
bytes memory n |
||||
) internal view returns (bool) { |
||||
return pkcs1(sha256(data), s, e, n); |
||||
} |
||||
|
||||
/** |
||||
* @dev Verifies a PKCSv1.5 signature given a digest according the verification |
||||
* method described in https://datatracker.ietf.org/doc/html/rfc8017#section-8.2.2[section 8.2.2 of RFC8017]. |
||||
* |
||||
* IMPORTANT: Although this function allows for it, using n of length 1024 bits is considered unsafe. |
||||
* Consider using at least 2048 bits. |
||||
* |
||||
* WARNING: PKCS#1 v1.5 allows for replayability given the message may contain arbitrary optional parameters in the |
||||
* DigestInfo. Consider using an onchain nonce or unique identifier to include in the message to prevent replay attacks. |
||||
* |
||||
* @param digest the digest to verify |
||||
* @param s is a buffer containing the signature |
||||
* @param e is the exponent of the public key |
||||
* @param n is the modulus of the public key |
||||
*/ |
||||
function pkcs1(bytes32 digest, bytes memory s, bytes memory e, bytes memory n) internal view returns (bool) { |
||||
unchecked { |
||||
// cache and check length |
||||
uint256 length = n.length; |
||||
if ( |
||||
length < 0x40 || // PKCS#1 padding is slightly less than 0x40 bytes at the bare minimum |
||||
length != s.length // signature must have the same length as the finite field |
||||
) { |
||||
return false; |
||||
} |
||||
|
||||
// Verify that s < n to ensure there's only one valid signature for a given message |
||||
for (uint256 i = 0; i < length; i += 0x20) { |
||||
uint256 p = Math.min(i, length - 0x20); |
||||
bytes32 sp = _unsafeReadBytes32(s, p); |
||||
bytes32 np = _unsafeReadBytes32(n, p); |
||||
if (sp < np) { |
||||
// s < n in the upper bits (everything before is equal) → s < n globally: ok |
||||
break; |
||||
} else if (sp > np || p == length - 0x20) { |
||||
// s > n in the upper bits (everything before is equal) → s > n globally: fail |
||||
// or |
||||
// s = n and we are looking at the lower bits → s = n globally: fail |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
// RSAVP1 https://datatracker.ietf.org/doc/html/rfc8017#section-5.2.2 |
||||
// The previous check guarantees that n > 0. Therefore modExp cannot revert. |
||||
bytes memory buffer = Math.modExp(s, e, n); |
||||
|
||||
// Check that buffer is well encoded: |
||||
// buffer ::= 0x00 | 0x01 | PS | 0x00 | DigestInfo |
||||
// |
||||
// With |
||||
// - PS is padding filled with 0xFF |
||||
// - DigestInfo ::= SEQUENCE { |
||||
// digestAlgorithm AlgorithmIdentifier, |
||||
// [optional algorithm parameters] |
||||
// digest OCTET STRING |
||||
// } |
||||
|
||||
// Get AlgorithmIdentifier from the DigestInfo, and set the config accordingly |
||||
// - params: includes 00 + first part of DigestInfo |
||||
// - mask: filter to check the params |
||||
// - offset: length of the suffix (including digest) |
||||
bytes32 params; // 0x00 | DigestInfo |
||||
bytes32 mask; |
||||
uint256 offset; |
||||
|
||||
// Digest is expected at the end of the buffer. Therefore if NULL param is present, |
||||
// it should be at 32 (digest) + 2 bytes from the end. To those 34 bytes, we add the |
||||
// OID (9 bytes) and its length (2 bytes) to get the position of the DigestInfo sequence, |
||||
// which is expected to have a length of 0x31 when the NULL param is present or 0x2f if not. |
||||
if (bytes1(_unsafeReadBytes32(buffer, length - 50)) == 0x31) { |
||||
offset = 0x34; |
||||
// 00 (1 byte) | SEQUENCE length (0x31) = 3031 (2 bytes) | SEQUENCE length (0x0d) = 300d (2 bytes) | OBJECT_IDENTIFIER length (0x09) = 0609 (2 bytes) |
||||
// SHA256 OID = 608648016503040201 (9 bytes) | NULL = 0500 (2 bytes) (explicit) | OCTET_STRING length (0x20) = 0420 (2 bytes) |
||||
params = 0x003031300d060960864801650304020105000420000000000000000000000000; |
||||
mask = 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000; // (20 bytes) |
||||
} else if (bytes1(_unsafeReadBytes32(buffer, length - 48)) == 0x2F) { |
||||
offset = 0x32; |
||||
// 00 (1 byte) | SEQUENCE length (0x2f) = 302f (2 bytes) | SEQUENCE length (0x0b) = 300b (2 bytes) | OBJECT_IDENTIFIER length (0x09) = 0609 (2 bytes) |
||||
// SHA256 OID = 608648016503040201 (9 bytes) | NULL = <implicit> | OCTET_STRING length (0x20) = 0420 (2 bytes) |
||||
params = 0x00302f300b060960864801650304020104200000000000000000000000000000; |
||||
mask = 0xffffffffffffffffffffffffffffffffffff0000000000000000000000000000; // (18 bytes) |
||||
} else { |
||||
// unknown |
||||
return false; |
||||
} |
||||
|
||||
// Length is at least 0x40 and offset is at most 0x34, so this is safe. There is always some padding. |
||||
uint256 paddingEnd = length - offset; |
||||
|
||||
// The padding has variable (arbitrary) length, so we check it byte per byte in a loop. |
||||
// This is required to ensure non-malleability. Not checking would allow an attacker to |
||||
// use the padding to manipulate the message in order to create a valid signature out of |
||||
// multiple valid signatures. |
||||
for (uint256 i = 2; i < paddingEnd; ++i) { |
||||
if (bytes1(_unsafeReadBytes32(buffer, i)) != 0xFF) { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
// All the other parameters are small enough to fit in a bytes32, so we can check them directly. |
||||
return |
||||
bytes2(0x0001) == bytes2(_unsafeReadBytes32(buffer, 0x00)) && // 00 | 01 |
||||
// PS was checked in the loop |
||||
params == _unsafeReadBytes32(buffer, paddingEnd) & mask && // DigestInfo |
||||
// Optional parameters are not checked |
||||
digest == _unsafeReadBytes32(buffer, length - 0x20); // Digest |
||||
} |
||||
} |
||||
|
||||
/// @dev Reads a bytes32 from a bytes array without bounds checking. |
||||
function _unsafeReadBytes32(bytes memory array, uint256 offset) private pure returns (bytes32 result) { |
||||
// Memory safetiness is guaranteed as long as the provided `array` is a Solidity-allocated bytes array |
||||
// and `offset` is within bounds. This is the case for all calls to this private function from {pkcs1}. |
||||
assembly ("memory-safe") { |
||||
result := mload(add(add(array, 0x20), offset)) |
||||
} |
||||
} |
||||
} |
@ -0,0 +1,4 @@ |
||||
certora-cli==4.13.1 |
||||
# File uses a custom name (fv-requirements.txt) so that it isn't picked by Netlify's build |
||||
# whose latest Python version is 0.3.8, incompatible with most recent versions of Halmos |
||||
halmos==0.1.13 |
@ -0,0 +1 @@ |
||||
Subproject commit c0d865508c0fee0a11b97732c5e90f9cad6b65a5 |
@ -1 +0,0 @@ |
||||
certora-cli==4.13.1 |
@ -0,0 +1,18 @@ |
||||
#!/usr/bin/env bash |
||||
|
||||
set -euo pipefail |
||||
|
||||
export COVERAGE=true |
||||
export FOUNDRY_FUZZ_RUNS=10 |
||||
|
||||
# Hardhat coverage |
||||
hardhat coverage |
||||
|
||||
if [ "${CI:-"false"}" == "true" ]; then |
||||
# Foundry coverage |
||||
forge coverage --report lcov --ir-minimum |
||||
# Remove zero hits |
||||
sed -i '/,0/d' lcov.info |
||||
fi |
||||
|
||||
# Reports are then uploaded to Codecov automatically by workflow, and merged. |
@ -0,0 +1,86 @@ |
||||
const format = require('../format-lines'); |
||||
const { product } = require('../../helpers'); |
||||
const { SIZES } = require('./Packing.opts'); |
||||
|
||||
// TEMPLATE
|
||||
const header = `\
|
||||
pragma solidity ^0.8.20; |
||||
|
||||
/** |
||||
* @dev Helper library packing and unpacking multiple values into bytesXX. |
||||
* |
||||
* Example usage: |
||||
* |
||||
* \`\`\`solidity
|
||||
* library MyPacker { |
||||
* type MyType is bytes32; |
||||
* |
||||
* function _pack(address account, bytes4 selector, uint64 period) external pure returns (MyType) { |
||||
* bytes12 subpack = Packing.pack_4_8(selector, bytes8(period)); |
||||
* bytes32 pack = Packing.pack_20_12(bytes20(account), subpack); |
||||
* return MyType.wrap(pack); |
||||
* } |
||||
* |
||||
* function _unpack(MyType self) external pure returns (address, bytes4, uint64) { |
||||
* bytes32 pack = MyType.unwrap(self); |
||||
* return ( |
||||
* address(Packing.extract_32_20(pack, 0)), |
||||
* Packing.extract_32_4(pack, 20), |
||||
* uint64(Packing.extract_32_8(pack, 24)) |
||||
* ); |
||||
* } |
||||
* } |
||||
* \`\`\` |
||||
*/ |
||||
// solhint-disable func-name-mixedcase
|
||||
`;
|
||||
|
||||
const errors = `\
|
||||
error OutOfRangeAccess(); |
||||
`;
|
||||
|
||||
const pack = (left, right) => `\
|
||||
function pack_${left}_${right}(bytes${left} left, bytes${right} right) internal pure returns (bytes${ |
||||
left + right |
||||
} result) { |
||||
assembly ("memory-safe") { |
||||
result := or(left, shr(${8 * left}, right)) |
||||
} |
||||
} |
||||
`;
|
||||
|
||||
const extract = (outer, inner) => `\
|
||||
function extract_${outer}_${inner}(bytes${outer} self, uint8 offset) internal pure returns (bytes${inner} result) { |
||||
if (offset > ${outer - inner}) revert OutOfRangeAccess(); |
||||
assembly ("memory-safe") { |
||||
result := and(shl(mul(8, offset), self), shl(${256 - 8 * inner}, not(0))) |
||||
} |
||||
} |
||||
`;
|
||||
|
||||
const replace = (outer, inner) => `\
|
||||
function replace_${outer}_${inner}(bytes${outer} self, bytes${inner} value, uint8 offset) internal pure returns (bytes${outer} result) { |
||||
bytes${inner} oldValue = extract_${outer}_${inner}(self, offset); |
||||
assembly ("memory-safe") { |
||||
result := xor(self, shr(mul(8, offset), xor(oldValue, value))) |
||||
} |
||||
} |
||||
`;
|
||||
|
||||
// GENERATE
|
||||
module.exports = format( |
||||
header.trimEnd(), |
||||
'library Packing {', |
||||
format( |
||||
[].concat( |
||||
errors, |
||||
product(SIZES, SIZES) |
||||
.filter(([left, right]) => SIZES.includes(left + right)) |
||||
.map(([left, right]) => pack(left, right)), |
||||
product(SIZES, SIZES) |
||||
.filter(([outer, inner]) => outer > inner) |
||||
.flatMap(([outer, inner]) => [extract(outer, inner), replace(outer, inner)]), |
||||
), |
||||
).trimEnd(), |
||||
'}', |
||||
); |
@ -0,0 +1,3 @@ |
||||
module.exports = { |
||||
SIZES: [1, 2, 4, 6, 8, 12, 16, 20, 24, 28, 32], |
||||
}; |
@ -0,0 +1,48 @@ |
||||
const format = require('../format-lines'); |
||||
const { product } = require('../../helpers'); |
||||
const { SIZES } = require('./Packing.opts'); |
||||
|
||||
// TEMPLATE
|
||||
const header = `\
|
||||
pragma solidity ^0.8.20; |
||||
|
||||
import {Test} from "forge-std/Test.sol"; |
||||
import {Packing} from "@openzeppelin/contracts/utils/Packing.sol"; |
||||
`;
|
||||
|
||||
const testPack = (left, right) => `\
|
||||
function testPack(bytes${left} left, bytes${right} right) external { |
||||
assertEq(left, Packing.pack_${left}_${right}(left, right).extract_${left + right}_${left}(0)); |
||||
assertEq(right, Packing.pack_${left}_${right}(left, right).extract_${left + right}_${right}(${left})); |
||||
} |
||||
`;
|
||||
|
||||
const testReplace = (outer, inner) => `\
|
||||
function testReplace(bytes${outer} container, bytes${inner} newValue, uint8 offset) external { |
||||
offset = uint8(bound(offset, 0, ${outer - inner})); |
||||
|
||||
bytes${inner} oldValue = container.extract_${outer}_${inner}(offset); |
||||
|
||||
assertEq(newValue, container.replace_${outer}_${inner}(newValue, offset).extract_${outer}_${inner}(offset)); |
||||
assertEq(container, container.replace_${outer}_${inner}(newValue, offset).replace_${outer}_${inner}(oldValue, offset)); |
||||
} |
||||
`;
|
||||
|
||||
// GENERATE
|
||||
module.exports = format( |
||||
header, |
||||
'contract PackingTest is Test {', |
||||
format( |
||||
[].concat( |
||||
'using Packing for *;', |
||||
'', |
||||
product(SIZES, SIZES) |
||||
.filter(([left, right]) => SIZES.includes(left + right)) |
||||
.map(([left, right]) => testPack(left, right)), |
||||
product(SIZES, SIZES) |
||||
.filter(([outer, inner]) => outer > inner) |
||||
.map(([outer, inner]) => testReplace(outer, inner)), |
||||
), |
||||
).trimEnd(), |
||||
'}', |
||||
); |
@ -0,0 +1,248 @@ |
||||
const { ethers } = require('hardhat'); |
||||
const { expect } = require('chai'); |
||||
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers'); |
||||
|
||||
const { GovernorHelper } = require('../../helpers/governance'); |
||||
const { VoteType } = require('../../helpers/enums'); |
||||
const { zip } = require('../../helpers/iterate'); |
||||
const { sum } = require('../../helpers/math'); |
||||
|
||||
const TOKENS = [ |
||||
{ Token: '$ERC20Votes', mode: 'blocknumber' }, |
||||
{ Token: '$ERC20VotesTimestampMock', mode: 'timestamp' }, |
||||
]; |
||||
|
||||
const name = 'OZ-Governor'; |
||||
const version = '1'; |
||||
const tokenName = 'MockToken'; |
||||
const tokenSymbol = 'MTKN'; |
||||
const tokenSupply = ethers.parseEther('100'); |
||||
const votingDelay = 4n; |
||||
const votingPeriod = 16n; |
||||
const value = ethers.parseEther('1'); |
||||
|
||||
describe('GovernorCountingFractional', function () { |
||||
for (const { Token, mode } of TOKENS) { |
||||
const fixture = async () => { |
||||
const [owner, proposer, voter1, voter2, voter3, voter4, other] = await ethers.getSigners(); |
||||
const receiver = await ethers.deployContract('CallReceiverMock'); |
||||
|
||||
const token = await ethers.deployContract(Token, [tokenName, tokenSymbol, version]); |
||||
const mock = await ethers.deployContract('$GovernorFractionalMock', [ |
||||
name, // name
|
||||
votingDelay, // initialVotingDelay
|
||||
votingPeriod, // initialVotingPeriod
|
||||
0n, // initialProposalThreshold
|
||||
token, // tokenAddress
|
||||
10n, // quorumNumeratorValue
|
||||
]); |
||||
|
||||
await owner.sendTransaction({ to: mock, value }); |
||||
await token.$_mint(owner, tokenSupply); |
||||
|
||||
const helper = new GovernorHelper(mock, mode); |
||||
await helper.connect(owner).delegate({ token, to: voter1, value: ethers.parseEther('10') }); |
||||
await helper.connect(owner).delegate({ token, to: voter2, value: ethers.parseEther('7') }); |
||||
await helper.connect(owner).delegate({ token, to: voter3, value: ethers.parseEther('5') }); |
||||
await helper.connect(owner).delegate({ token, to: voter4, value: ethers.parseEther('2') }); |
||||
|
||||
return { owner, proposer, voter1, voter2, voter3, voter4, other, receiver, token, mock, helper }; |
||||
}; |
||||
|
||||
describe(`using ${Token}`, function () { |
||||
beforeEach(async function () { |
||||
Object.assign(this, await loadFixture(fixture)); |
||||
|
||||
// default proposal
|
||||
this.proposal = this.helper.setProposal( |
||||
[ |
||||
{ |
||||
target: this.receiver.target, |
||||
value, |
||||
data: this.receiver.interface.encodeFunctionData('mockFunction'), |
||||
}, |
||||
], |
||||
'<proposal description>', |
||||
); |
||||
}); |
||||
|
||||
it('deployment check', async function () { |
||||
expect(await this.mock.name()).to.equal(name); |
||||
expect(await this.mock.token()).to.equal(this.token); |
||||
expect(await this.mock.votingDelay()).to.equal(votingDelay); |
||||
expect(await this.mock.votingPeriod()).to.equal(votingPeriod); |
||||
expect(await this.mock.COUNTING_MODE()).to.equal( |
||||
'support=bravo,fractional&quorum=for,abstain¶ms=fractional', |
||||
); |
||||
}); |
||||
|
||||
it('nominal is unaffected', async function () { |
||||
await this.helper.connect(this.proposer).propose(); |
||||
await this.helper.waitForSnapshot(); |
||||
await this.helper.connect(this.voter1).vote({ support: VoteType.For, reason: 'This is nice' }); |
||||
await this.helper.connect(this.voter2).vote({ support: VoteType.For }); |
||||
await this.helper.connect(this.voter3).vote({ support: VoteType.Against }); |
||||
await this.helper.connect(this.voter4).vote({ support: VoteType.Abstain }); |
||||
await this.helper.waitForDeadline(); |
||||
await this.helper.execute(); |
||||
|
||||
expect(await this.mock.hasVoted(this.proposal.id, this.owner)).to.be.false; |
||||
expect(await this.mock.hasVoted(this.proposal.id, this.voter1)).to.be.true; |
||||
expect(await this.mock.hasVoted(this.proposal.id, this.voter2)).to.be.true; |
||||
expect(await ethers.provider.getBalance(this.mock)).to.equal(0n); |
||||
expect(await ethers.provider.getBalance(this.receiver)).to.equal(value); |
||||
}); |
||||
|
||||
describe('voting with a fraction of the weight', function () { |
||||
it('twice', async function () { |
||||
await this.helper.connect(this.proposer).propose(); |
||||
await this.helper.waitForSnapshot(); |
||||
|
||||
expect(await this.mock.proposalVotes(this.proposal.id)).to.deep.equal([0n, 0n, 0n]); |
||||
expect(await this.mock.hasVoted(this.proposal.id, this.voter2)).to.equal(false); |
||||
expect(await this.mock.usedVotes(this.proposal.id, this.voter2)).to.equal(0n); |
||||
|
||||
const steps = [ |
||||
['0', '2', '1'], |
||||
['1', '0', '1'], |
||||
].map(votes => votes.map(vote => ethers.parseEther(vote))); |
||||
|
||||
for (const votes of steps) { |
||||
const params = ethers.solidityPacked(['uint128', 'uint128', 'uint128'], votes); |
||||
await expect( |
||||
this.helper.connect(this.voter2).vote({ |
||||
support: VoteType.Parameters, |
||||
reason: 'no particular reason', |
||||
params, |
||||
}), |
||||
) |
||||
.to.emit(this.mock, 'VoteCastWithParams') |
||||
.withArgs( |
||||
this.voter2, |
||||
this.proposal.id, |
||||
VoteType.Parameters, |
||||
sum(...votes), |
||||
'no particular reason', |
||||
params, |
||||
); |
||||
} |
||||
|
||||
expect(await this.mock.proposalVotes(this.proposal.id)).to.deep.equal(zip(...steps).map(v => sum(...v))); |
||||
expect(await this.mock.hasVoted(this.proposal.id, this.voter2)).to.equal(true); |
||||
expect(await this.mock.usedVotes(this.proposal.id, this.voter2)).to.equal(sum(...[].concat(...steps))); |
||||
}); |
||||
|
||||
it('fractional then nominal', async function () { |
||||
await this.helper.connect(this.proposer).propose(); |
||||
await this.helper.waitForSnapshot(); |
||||
|
||||
expect(await this.mock.proposalVotes(this.proposal.id)).to.deep.equal([0n, 0n, 0n]); |
||||
expect(await this.mock.hasVoted(this.proposal.id, this.voter2)).to.equal(false); |
||||
expect(await this.mock.usedVotes(this.proposal.id, this.voter2)).to.equal(0n); |
||||
|
||||
const weight = ethers.parseEther('7'); |
||||
const fractional = ['1', '2', '1'].map(ethers.parseEther); |
||||
|
||||
const params = ethers.solidityPacked(['uint128', 'uint128', 'uint128'], fractional); |
||||
await expect( |
||||
this.helper.connect(this.voter2).vote({ |
||||
support: VoteType.Parameters, |
||||
reason: 'no particular reason', |
||||
params, |
||||
}), |
||||
) |
||||
.to.emit(this.mock, 'VoteCastWithParams') |
||||
.withArgs( |
||||
this.voter2, |
||||
this.proposal.id, |
||||
VoteType.Parameters, |
||||
sum(...fractional), |
||||
'no particular reason', |
||||
params, |
||||
); |
||||
|
||||
await expect(this.helper.connect(this.voter2).vote({ support: VoteType.Against })) |
||||
.to.emit(this.mock, 'VoteCast') |
||||
.withArgs(this.voter2, this.proposal.id, VoteType.Against, weight - sum(...fractional), ''); |
||||
|
||||
expect(await this.mock.proposalVotes(this.proposal.id)).to.deep.equal([ |
||||
weight - sum(...fractional.slice(1)), |
||||
...fractional.slice(1), |
||||
]); |
||||
expect(await this.mock.hasVoted(this.proposal.id, this.voter2)).to.equal(true); |
||||
expect(await this.mock.usedVotes(this.proposal.id, this.voter2)).to.equal(weight); |
||||
}); |
||||
|
||||
it('revert if params spend more than available', async function () { |
||||
await this.helper.connect(this.proposer).propose(); |
||||
await this.helper.waitForSnapshot(); |
||||
|
||||
const weight = ethers.parseEther('7'); |
||||
const fractional = ['0', '1000', '0'].map(ethers.parseEther); |
||||
|
||||
await expect( |
||||
this.helper.connect(this.voter2).vote({ |
||||
support: VoteType.Parameters, |
||||
reason: 'no particular reason', |
||||
params: ethers.solidityPacked(['uint128', 'uint128', 'uint128'], fractional), |
||||
}), |
||||
) |
||||
.to.be.revertedWithCustomError(this.mock, 'GovernorExceedRemainingWeight') |
||||
.withArgs(this.voter2, sum(...fractional), weight); |
||||
}); |
||||
|
||||
it('revert if no weight remaining', async function () { |
||||
await this.helper.connect(this.proposer).propose(); |
||||
await this.helper.waitForSnapshot(); |
||||
await this.helper.connect(this.voter2).vote({ support: VoteType.For }); |
||||
|
||||
await expect( |
||||
this.helper.connect(this.voter2).vote({ |
||||
support: VoteType.Parameters, |
||||
reason: 'no particular reason', |
||||
params: ethers.solidityPacked(['uint128', 'uint128', 'uint128'], [0n, 1n, 0n]), |
||||
}), |
||||
) |
||||
.to.be.revertedWithCustomError(this.mock, 'GovernorAlreadyCastVote') |
||||
.withArgs(this.voter2); |
||||
}); |
||||
|
||||
it('revert if params are not properly formatted #1', async function () { |
||||
await this.helper.connect(this.proposer).propose(); |
||||
await this.helper.waitForSnapshot(); |
||||
|
||||
await expect( |
||||
this.helper.connect(this.voter2).vote({ |
||||
support: VoteType.Parameters, |
||||
reason: 'no particular reason', |
||||
params: ethers.solidityPacked(['uint128', 'uint128'], [0n, 1n]), |
||||
}), |
||||
).to.be.revertedWithCustomError(this.mock, 'GovernorInvalidVoteParams'); |
||||
}); |
||||
|
||||
it('revert if params are not properly formatted #2', async function () { |
||||
await this.helper.connect(this.proposer).propose(); |
||||
await this.helper.waitForSnapshot(); |
||||
|
||||
await expect( |
||||
this.helper.connect(this.voter2).vote({ |
||||
support: VoteType.Against, |
||||
reason: 'no particular reason', |
||||
params: ethers.solidityPacked(['uint128', 'uint128', 'uint128'], [0n, 1n, 0n]), |
||||
}), |
||||
).to.be.revertedWithCustomError(this.mock, 'GovernorInvalidVoteParams'); |
||||
}); |
||||
|
||||
it('revert if vote type is invalid', async function () { |
||||
await this.helper.connect(this.proposer).propose(); |
||||
await this.helper.waitForSnapshot(); |
||||
|
||||
await expect(this.helper.connect(this.voter2).vote({ support: 128n })).to.be.revertedWithCustomError( |
||||
this.mock, |
||||
'GovernorInvalidVoteType', |
||||
); |
||||
}); |
||||
}); |
||||
}); |
||||
} |
||||
}); |
@ -0,0 +1,14 @@ |
||||
const { artifacts, ethers } = require('hardhat'); |
||||
const { setCode } = require('@nomicfoundation/hardhat-network-helpers'); |
||||
const { generators } = require('./random'); |
||||
|
||||
const forceDeployCode = (name, address = generators.address(), runner = ethers.provider) => |
||||
artifacts |
||||
.readArtifact(name) |
||||
.then(({ abi, deployedBytecode }) => |
||||
setCode(address, deployedBytecode).then(() => new ethers.Contract(address, abi, runner)), |
||||
); |
||||
|
||||
module.exports = { |
||||
forceDeployCode, |
||||
}; |
@ -0,0 +1,135 @@ |
||||
// SPDX-License-Identifier: MIT |
||||
|
||||
pragma solidity ^0.8.20; |
||||
|
||||
import {Test} from "forge-std/Test.sol"; |
||||
|
||||
import {P256} from "@openzeppelin/contracts/utils/cryptography/P256.sol"; |
||||
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; |
||||
|
||||
contract P256Test is Test { |
||||
/// forge-config: default.fuzz.runs = 512 |
||||
function testVerify(uint256 seed, bytes32 digest) public { |
||||
uint256 privateKey = bound(uint256(keccak256(abi.encode(seed))), 1, P256.N - 1); |
||||
|
||||
(bytes32 x, bytes32 y) = P256PublicKey.getPublicKey(privateKey); |
||||
(bytes32 r, bytes32 s) = vm.signP256(privateKey, digest); |
||||
s = _ensureLowerS(s); |
||||
assertTrue(P256.verify(digest, r, s, x, y)); |
||||
assertTrue(P256.verifySolidity(digest, r, s, x, y)); |
||||
} |
||||
|
||||
/// forge-config: default.fuzz.runs = 512 |
||||
function testRecover(uint256 seed, bytes32 digest) public { |
||||
uint256 privateKey = bound(uint256(keccak256(abi.encode(seed))), 1, P256.N - 1); |
||||
|
||||
(bytes32 x, bytes32 y) = P256PublicKey.getPublicKey(privateKey); |
||||
(bytes32 r, bytes32 s) = vm.signP256(privateKey, digest); |
||||
s = _ensureLowerS(s); |
||||
(bytes32 qx0, bytes32 qy0) = P256.recovery(digest, 0, r, s); |
||||
(bytes32 qx1, bytes32 qy1) = P256.recovery(digest, 1, r, s); |
||||
assertTrue((qx0 == x && qy0 == y) || (qx1 == x && qy1 == y)); |
||||
} |
||||
|
||||
function _ensureLowerS(bytes32 s) private pure returns (bytes32) { |
||||
uint256 _s = uint256(s); |
||||
unchecked { |
||||
return _s > P256.N / 2 ? bytes32(P256.N - _s) : s; |
||||
} |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* @dev Library to derive P256 public key from private key |
||||
* Should be removed if Foundry adds this functionality |
||||
* See https://github.com/foundry-rs/foundry/issues/7908 |
||||
*/ |
||||
library P256PublicKey { |
||||
function getPublicKey(uint256 privateKey) internal view returns (bytes32, bytes32) { |
||||
(uint256 x, uint256 y, uint256 z) = _jMult(P256.GX, P256.GY, 1, privateKey); |
||||
return _affineFromJacobian(x, y, z); |
||||
} |
||||
|
||||
function _jMult( |
||||
uint256 x, |
||||
uint256 y, |
||||
uint256 z, |
||||
uint256 k |
||||
) private pure returns (uint256 rx, uint256 ry, uint256 rz) { |
||||
unchecked { |
||||
for (uint256 i = 0; i < 256; ++i) { |
||||
if (rz > 0) { |
||||
(rx, ry, rz) = _jDouble(rx, ry, rz); |
||||
} |
||||
if (k >> 255 > 0) { |
||||
if (rz == 0) { |
||||
(rx, ry, rz) = (x, y, z); |
||||
} else { |
||||
(rx, ry, rz) = _jAdd(rx, ry, rz, x, y, z); |
||||
} |
||||
} |
||||
k <<= 1; |
||||
} |
||||
} |
||||
} |
||||
|
||||
/// From P256.sol |
||||
|
||||
function _affineFromJacobian(uint256 jx, uint256 jy, uint256 jz) private view returns (bytes32 ax, bytes32 ay) { |
||||
if (jz == 0) return (0, 0); |
||||
uint256 zinv = Math.invModPrime(jz, P256.P); |
||||
uint256 zzinv = mulmod(zinv, zinv, P256.P); |
||||
uint256 zzzinv = mulmod(zzinv, zinv, P256.P); |
||||
ax = bytes32(mulmod(jx, zzinv, P256.P)); |
||||
ay = bytes32(mulmod(jy, zzzinv, P256.P)); |
||||
} |
||||
|
||||
function _jDouble(uint256 x, uint256 y, uint256 z) private pure returns (uint256 rx, uint256 ry, uint256 rz) { |
||||
uint256 p = P256.P; |
||||
uint256 a = P256.A; |
||||
assembly ("memory-safe") { |
||||
let yy := mulmod(y, y, p) |
||||
let zz := mulmod(z, z, p) |
||||
let s := mulmod(4, mulmod(x, yy, p), p) // s = 4*x*y² |
||||
let m := addmod(mulmod(3, mulmod(x, x, p), p), mulmod(a, mulmod(zz, zz, p), p), p) // m = 3*x²+a*z⁴ |
||||
let t := addmod(mulmod(m, m, p), sub(p, mulmod(2, s, p)), p) // t = m²-2*s |
||||
|
||||
// x' = t |
||||
rx := t |
||||
// y' = m*(s-t)-8*y⁴ |
||||
ry := addmod(mulmod(m, addmod(s, sub(p, t), p), p), sub(p, mulmod(8, mulmod(yy, yy, p), p)), p) |
||||
// z' = 2*y*z |
||||
rz := mulmod(2, mulmod(y, z, p), p) |
||||
} |
||||
} |
||||
|
||||
function _jAdd( |
||||
uint256 x1, |
||||
uint256 y1, |
||||
uint256 z1, |
||||
uint256 x2, |
||||
uint256 y2, |
||||
uint256 z2 |
||||
) private pure returns (uint256 rx, uint256 ry, uint256 rz) { |
||||
uint256 p = P256.P; |
||||
assembly ("memory-safe") { |
||||
let zz1 := mulmod(z1, z1, p) // zz1 = z1² |
||||
let zz2 := mulmod(z2, z2, p) // zz2 = z2² |
||||
let u1 := mulmod(x1, zz2, p) // u1 = x1*z2² |
||||
let u2 := mulmod(x2, zz1, p) // u2 = x2*z1² |
||||
let s1 := mulmod(y1, mulmod(zz2, z2, p), p) // s1 = y1*z2³ |
||||
let s2 := mulmod(y2, mulmod(zz1, z1, p), p) // s2 = y2*z1³ |
||||
let h := addmod(u2, sub(p, u1), p) // h = u2-u1 |
||||
let hh := mulmod(h, h, p) // h² |
||||
let hhh := mulmod(h, hh, p) // h³ |
||||
let r := addmod(s2, sub(p, s1), p) // r = s2-s1 |
||||
|
||||
// x' = r²-h³-2*u1*h² |
||||
rx := addmod(addmod(mulmod(r, r, p), sub(p, hhh), p), sub(p, mulmod(2, mulmod(u1, hh, p), p)), p) |
||||
// y' = r*(u1*h²-x')-s1*h³ |
||||
ry := addmod(mulmod(r, addmod(mulmod(u1, hh, p), sub(p, rx), p), p), sub(p, mulmod(s1, hhh, p)), p) |
||||
// z' = h*z1*z2 |
||||
rz := mulmod(h, mulmod(z1, z2, p), p) |
||||
} |
||||
} |
||||
} |
@ -0,0 +1,156 @@ |
||||
const { ethers } = require('hardhat'); |
||||
const { expect } = require('chai'); |
||||
const { secp256r1 } = require('@noble/curves/p256'); |
||||
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers'); |
||||
|
||||
const N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n; |
||||
|
||||
// As in ECDSA, signatures are malleable and the tooling produce both high and low S values.
|
||||
// We need to ensure that the s value is in the lower half of the order of the curve.
|
||||
const ensureLowerOrderS = ({ s, recovery, ...rest }) => { |
||||
if (s > N / 2n) { |
||||
s = N - s; |
||||
recovery = 1 - recovery; |
||||
} |
||||
return { s, recovery, ...rest }; |
||||
}; |
||||
|
||||
const prepareSignature = ( |
||||
privateKey = secp256r1.utils.randomPrivateKey(), |
||||
messageHash = ethers.hexlify(ethers.randomBytes(0x20)), |
||||
) => { |
||||
const publicKey = [ |
||||
secp256r1.getPublicKey(privateKey, false).slice(0x01, 0x21), |
||||
secp256r1.getPublicKey(privateKey, false).slice(0x21, 0x41), |
||||
].map(ethers.hexlify); |
||||
const { r, s, recovery } = ensureLowerOrderS(secp256r1.sign(messageHash.replace(/0x/, ''), privateKey)); |
||||
const signature = [r, s].map(v => ethers.toBeHex(v, 0x20)); |
||||
|
||||
return { privateKey, publicKey, signature, recovery, messageHash }; |
||||
}; |
||||
|
||||
describe('P256', function () { |
||||
async function fixture() { |
||||
return { mock: await ethers.deployContract('$P256') }; |
||||
} |
||||
|
||||
beforeEach(async function () { |
||||
Object.assign(this, await loadFixture(fixture)); |
||||
}); |
||||
|
||||
describe('with signature', function () { |
||||
beforeEach(async function () { |
||||
Object.assign(this, prepareSignature()); |
||||
}); |
||||
|
||||
it('verify valid signature', async function () { |
||||
expect(await this.mock.$verify(this.messageHash, ...this.signature, ...this.publicKey)).to.be.true; |
||||
expect(await this.mock.$verifySolidity(this.messageHash, ...this.signature, ...this.publicKey)).to.be.true; |
||||
await expect(this.mock.$verifyNative(this.messageHash, ...this.signature, ...this.publicKey)) |
||||
.to.be.revertedWithCustomError(this.mock, 'MissingPrecompile') |
||||
.withArgs('0x0000000000000000000000000000000000000100'); |
||||
}); |
||||
|
||||
it('recover public key', async function () { |
||||
expect(await this.mock.$recovery(this.messageHash, this.recovery, ...this.signature)).to.deep.equal( |
||||
this.publicKey, |
||||
); |
||||
}); |
||||
|
||||
it('reject signature with flipped public key coordinates ([x,y] >> [y,x])', async function () { |
||||
// flip public key
|
||||
this.publicKey.reverse(); |
||||
|
||||
expect(await this.mock.$verify(this.messageHash, ...this.signature, ...this.publicKey)).to.be.false; |
||||
expect(await this.mock.$verifySolidity(this.messageHash, ...this.signature, ...this.publicKey)).to.be.false; |
||||
expect(await this.mock.$verifyNative(this.messageHash, ...this.signature, ...this.publicKey)).to.be.false; // Flipped public key is not in the curve
|
||||
}); |
||||
|
||||
it('reject signature with flipped signature values ([r,s] >> [s,r])', async function () { |
||||
// Preselected signature where `r < N/2` and `s < N/2`
|
||||
this.signature = [ |
||||
'0x45350225bad31e89db662fcc4fb2f79f349adbb952b3f652eed1f2aa72fb0356', |
||||
'0x513eb68424c42630012309eee4a3b43e0bdc019d179ef0e0c461800845e237ee', |
||||
]; |
||||
|
||||
// Corresponding hash and public key
|
||||
this.messageHash = '0x2ad1f900fe63745deeaedfdf396cb6f0f991c4338a9edf114d52f7d1812040a0'; |
||||
this.publicKey = [ |
||||
'0x9e30de165e521257996425d9bf12a7d366925614bf204eabbb78172b48e52e59', |
||||
'0x94bf0fe72f99654d7beae4780a520848e306d46a1275b965c4f4c2b8e9a2c08d', |
||||
]; |
||||
|
||||
// Make sure it works
|
||||
expect(await this.mock.$verify(this.messageHash, ...this.signature, ...this.publicKey)).to.be.true; |
||||
|
||||
// Flip signature
|
||||
this.signature.reverse(); |
||||
|
||||
expect(await this.mock.$verify(this.messageHash, ...this.signature, ...this.publicKey)).to.be.false; |
||||
expect(await this.mock.$verifySolidity(this.messageHash, ...this.signature, ...this.publicKey)).to.be.false; |
||||
await expect(this.mock.$verifyNative(this.messageHash, ...this.signature, ...this.publicKey)) |
||||
.to.be.revertedWithCustomError(this.mock, 'MissingPrecompile') |
||||
.withArgs('0x0000000000000000000000000000000000000100'); |
||||
expect(await this.mock.$recovery(this.messageHash, this.recovery, ...this.signature)).to.not.deep.equal( |
||||
this.publicKey, |
||||
); |
||||
}); |
||||
|
||||
it('reject signature with invalid message hash', async function () { |
||||
// random message hash
|
||||
this.messageHash = ethers.hexlify(ethers.randomBytes(32)); |
||||
|
||||
expect(await this.mock.$verify(this.messageHash, ...this.signature, ...this.publicKey)).to.be.false; |
||||
expect(await this.mock.$verifySolidity(this.messageHash, ...this.signature, ...this.publicKey)).to.be.false; |
||||
await expect(this.mock.$verifyNative(this.messageHash, ...this.signature, ...this.publicKey)) |
||||
.to.be.revertedWithCustomError(this.mock, 'MissingPrecompile') |
||||
.withArgs('0x0000000000000000000000000000000000000100'); |
||||
expect(await this.mock.$recovery(this.messageHash, this.recovery, ...this.signature)).to.not.deep.equal( |
||||
this.publicKey, |
||||
); |
||||
}); |
||||
|
||||
it('fail to recover signature with invalid recovery bit', async function () { |
||||
// flip recovery bit
|
||||
this.recovery = 1 - this.recovery; |
||||
|
||||
expect(await this.mock.$recovery(this.messageHash, this.recovery, ...this.signature)).to.not.deep.equal( |
||||
this.publicKey, |
||||
); |
||||
}); |
||||
}); |
||||
|
||||
// test cases for https://github.com/C2SP/wycheproof/blob/4672ff74d68766e7785c2cac4c597effccef2c5c/testvectors/ecdsa_secp256r1_sha256_p1363_test.json
|
||||
describe('wycheproof tests', function () { |
||||
for (const { key, tests } of require('./ecdsa_secp256r1_sha256_p1363_test.json').testGroups) { |
||||
// parse public key
|
||||
let [x, y] = [key.wx, key.wy].map(v => ethers.stripZerosLeft('0x' + v, 32)); |
||||
if (x.length > 66 || y.length > 66) continue; |
||||
x = ethers.zeroPadValue(x, 32); |
||||
y = ethers.zeroPadValue(y, 32); |
||||
|
||||
// run all tests for this key
|
||||
for (const { tcId, comment, msg, sig, result } of tests) { |
||||
// only keep properly formatted signatures
|
||||
if (sig.length != 128) continue; |
||||
|
||||
it(`${tcId}: ${comment}`, async function () { |
||||
// split signature, and reduce modulo N
|
||||
let [r, s] = Array(2) |
||||
.fill() |
||||
.map((_, i) => ethers.toBigInt('0x' + sig.substring(64 * i, 64 * (i + 1)))); |
||||
// move s to lower part of the curve if needed
|
||||
if (s <= N && s > N / 2n) s = N - s; |
||||
// prepare signature
|
||||
r = ethers.toBeHex(r, 32); |
||||
s = ethers.toBeHex(s, 32); |
||||
// hash
|
||||
const messageHash = ethers.sha256('0x' + msg); |
||||
|
||||
// check verify
|
||||
expect(await this.mock.$verify(messageHash, r, s, x, y)).to.equal(result == 'valid'); |
||||
}); |
||||
} |
||||
} |
||||
}); |
||||
}); |
@ -0,0 +1,17 @@ |
||||
const path = require('path'); |
||||
const fs = require('fs'); |
||||
|
||||
module.exports = function* parse(file) { |
||||
const cache = {}; |
||||
const data = fs.readFileSync(path.resolve(__dirname, file), 'utf8'); |
||||
for (const line of data.split('\r\n')) { |
||||
const groups = line.match(/^(?<key>\w+) = (?<value>\w+)(?<extra>.*)$/)?.groups; |
||||
if (groups) { |
||||
const { key, value, extra } = groups; |
||||
cache[key] = value; |
||||
if (groups.key === 'Result') { |
||||
yield Object.assign({ extra: extra.trim() }, cache); |
||||
} |
||||
} |
||||
} |
||||
}; |
@ -0,0 +1,97 @@ |
||||
const { ethers } = require('hardhat'); |
||||
const { expect } = require('chai'); |
||||
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers'); |
||||
|
||||
const parse = require('./RSA.helper'); |
||||
|
||||
async function fixture() { |
||||
return { mock: await ethers.deployContract('$RSA') }; |
||||
} |
||||
|
||||
describe('RSA', function () { |
||||
beforeEach(async function () { |
||||
Object.assign(this, await loadFixture(fixture)); |
||||
}); |
||||
|
||||
// Load test cases from file SigVer15_186-3.rsp from:
|
||||
// https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/dss/186-2rsatestvectors.zip
|
||||
describe('SigVer15_186-3.rsp tests', function () { |
||||
for (const test of parse('SigVer15_186-3.rsp')) { |
||||
const { length } = Buffer.from(test.S, 'hex'); |
||||
|
||||
/// For now, RSA only supports digest that are 32bytes long. If we ever extend that, we can use these hashing functions for @noble:
|
||||
// const { sha1 } = require('@noble/hashes/sha1');
|
||||
// const { sha224, sha256 } = require('@noble/hashes/sha256');
|
||||
// const { sha384, sha512 } = require('@noble/hashes/sha512');
|
||||
|
||||
if (test.SHAAlg === 'SHA256') { |
||||
const result = test.Result === 'P'; |
||||
|
||||
it(`signature length ${length} ${test.extra} ${result ? 'works' : 'fails'}`, async function () { |
||||
const data = '0x' + test.Msg; |
||||
const sig = '0x' + test.S; |
||||
const exp = '0x' + test.e; |
||||
const mod = '0x' + test.n; |
||||
|
||||
expect(await this.mock.$pkcs1(ethers.sha256(data), sig, exp, mod)).to.equal(result); |
||||
expect(await this.mock.$pkcs1Sha256(data, sig, exp, mod)).to.equal(result); |
||||
}); |
||||
} |
||||
} |
||||
}); |
||||
|
||||
describe('others tests', function () { |
||||
it('openssl', async function () { |
||||
const data = ethers.toUtf8Bytes('hello world'); |
||||
const sig = |
||||
'0x079bed733b48d69bdb03076cb17d9809072a5a765460bc72072d687dba492afe951d75b814f561f253ee5cc0f3d703b6eab5b5df635b03a5437c0a5c179309812f5b5c97650361c645bc99f806054de21eb187bc0a704ed38d3d4c2871a117c19b6da7e9a3d808481c46b22652d15b899ad3792da5419e50ee38759560002388'; |
||||
const exp = |
||||
'0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010001'; |
||||
const mod = |
||||
'0xdf3edde009b96bc5b03b48bd73fe70a3ad20eaf624d0dc1ba121a45cc739893741b7cf82acf1c91573ec8266538997c6699760148de57e54983191eca0176f518e547b85fe0bb7d9e150df19eee734cf5338219c7f8f7b13b39f5384179f62c135e544cb70be7505751f34568e06981095aeec4f3a887639718a3e11d48c240d'; |
||||
expect(await this.mock.$pkcs1Sha256(data, sig, exp, mod)).to.be.true; |
||||
}); |
||||
|
||||
// According to RFC4055, pg.5 and RFC8017, pg. 64, for SHA-1, and the SHA-2 family,
|
||||
// the algorithm parameter has to be NULL and both explicit NULL parameter and implicit
|
||||
// NULL parameter (ie, absent NULL parameter) are considered to be legal and equivalent.
|
||||
it('rfc8017 implicit null parameter', async function () { |
||||
const data = ethers.toUtf8Bytes('hello world!'); |
||||
const sig = |
||||
'0xa0073057133ff3758e7e111b4d7441f1d8cbe4b2dd5ee4316a14264290dee5ed7f175716639bd9bb43a14e4f9fcb9e84dedd35e2205caac04828b2c053f68176d971ea88534dd2eeec903043c3469fc69c206b2a8694fd262488441ed8852280c3d4994e9d42bd1d575c7024095f1a20665925c2175e089c0d731471f6cc145404edf5559fd2276e45e448086f71c78d0cc6628fad394a34e51e8c10bc39bfe09ed2f5f742cc68bee899d0a41e4c75b7b80afd1c321d89ccd9fe8197c44624d91cc935dfa48de3c201099b5b417be748aef29248527e8bbb173cab76b48478d4177b338fe1f1244e64d7d23f07add560d5ad50b68d6649a49d7bc3db686daaa7'; |
||||
const exp = '0x03'; |
||||
const mod = |
||||
'0xe932ac92252f585b3a80a4dd76a897c8b7652952fe788f6ec8dd640587a1ee5647670a8ad4c2be0f9fa6e49c605adf77b5174230af7bd50e5d6d6d6d28ccf0a886a514cc72e51d209cc772a52ef419f6a953f3135929588ebe9b351fca61ced78f346fe00dbb6306e5c2a4c6dfc3779af85ab417371cf34d8387b9b30ae46d7a5ff5a655b8d8455f1b94ae736989d60a6f2fd5cadbffbd504c5a756a2e6bb5cecc13bca7503f6df8b52ace5c410997e98809db4dc30d943de4e812a47553dce54844a78e36401d13f77dc650619fed88d8b3926e3d8e319c80c744779ac5d6abe252896950917476ece5e8fc27d5f053d6018d91b502c4787558a002b9283da7'; |
||||
expect(await this.mock.$pkcs1Sha256(data, sig, exp, mod)).to.be.true; |
||||
}); |
||||
|
||||
it('returns false for a very short n', async function () { |
||||
const data = ethers.toUtf8Bytes('hello world!'); |
||||
const sig = '0x0102'; |
||||
const exp = '0x03'; |
||||
const mod = '0x0405'; |
||||
expect(await this.mock.$pkcs1Sha256(data, sig, exp, mod)).to.be.false; |
||||
}); |
||||
|
||||
it('returns false for a signature with different length to n', async function () { |
||||
const data = ethers.toUtf8Bytes('hello world!'); |
||||
const sig = '0x00112233'; |
||||
const exp = '0x03'; |
||||
const mod = |
||||
'0xe932ac92252f585b3a80a4dd76a897c8b7652952fe788f6ec8dd640587a1ee5647670a8ad4c2be0f9fa6e49c605adf77b5174230af7bd50e5d6d6d6d28ccf0a886a514cc72e51d209cc772a52ef419f6a953f3135929588ebe9b351fca61ced78f346fe00dbb6306e5c2a4c6dfc3779af85ab417371cf34d8387b9b30ae46d7a5ff5a655b8d8455f1b94ae736989d60a6f2fd5cadbffbd504c5a756a2e6bb5cecc13bca7503f6df8b52ace5c410997e98809db4dc30d943de4e812a47553dce54844a78e36401d13f77dc650619fed88d8b3926e3d8e319c80c744779ac5d6abe252896950917476ece5e8fc27d5f053d6018d91b502c4787558a002b9283da7'; |
||||
expect(await this.mock.$pkcs1Sha256(data, sig, exp, mod)).to.be.false; |
||||
}); |
||||
|
||||
it('returns false if s >= n', async function () { |
||||
// this is the openssl example where sig has been replaced by sig + mod
|
||||
const data = ethers.toUtf8Bytes('hello world'); |
||||
const sig = |
||||
'0xe6dacb53450242618b3e502a257c08acb44b456c7931988da84f0cda8182b435d6d5453ac1e72b07c7dadf2747609b7d544d15f3f14081f9dbad9c48b7aa78d2bdafd81d630f19a0270d7911f4ec82b171e9a95889ffc9e740dc9fac89407a82d152ecb514967d4d9165e67ce0d7f39a3082657cdfca148a5fc2b3a7348c4795'; |
||||
const exp = |
||||
'0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010001'; |
||||
const mod = |
||||
'0xdf3edde009b96bc5b03b48bd73fe70a3ad20eaf624d0dc1ba121a45cc739893741b7cf82acf1c91573ec8266538997c6699760148de57e54983191eca0176f518e547b85fe0bb7d9e150df19eee734cf5338219c7f8f7b13b39f5384179f62c135e544cb70be7505751f34568e06981095aeec4f3a887639718a3e11d48c240d'; |
||||
expect(await this.mock.$pkcs1Sha256(data, sig, exp, mod)).to.be.false; |
||||
}); |
||||
}); |
||||
}); |
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Loading…
Reference in new issue