Contract Name:
ManyChainMultiSig
Contract Source Code:
File 1 of 1 : ManyChainMultiSig
{{
"language": "Solidity",
"sources": {
"lib/openzeppelin-contracts/contracts/access/Ownable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor() {\n _transferOwnership(_msgSender());\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n _checkOwner();\n _;\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if the sender is not the owner.\n */\n function _checkOwner() internal view virtual {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby disabling any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n}\n"
},
"lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./Ownable.sol\";\n\n/**\n * @dev Contract module which provides access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership} and {acceptOwnership}.\n *\n * This module is used through inheritance. It will make available all functions\n * from parent (Ownable).\n */\nabstract contract Ownable2Step is Ownable {\n address private _pendingOwner;\n\n event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Returns the address of the pending owner.\n */\n function pendingOwner() public view virtual returns (address) {\n return _pendingOwner;\n }\n\n /**\n * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual override onlyOwner {\n _pendingOwner = newOwner;\n emit OwnershipTransferStarted(owner(), newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual override {\n delete _pendingOwner;\n super._transferOwnership(newOwner);\n }\n\n /**\n * @dev The new owner accepts the ownership transfer.\n */\n function acceptOwnership() public virtual {\n address sender = _msgSender();\n require(pendingOwner() == sender, \"Ownable2Step: caller is not the new owner\");\n _transferOwnership(sender);\n }\n}\n"
},
"lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n /**\n * @dev Returns the largest of two signed numbers.\n */\n function max(int256 a, int256 b) internal pure returns (int256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two signed numbers.\n */\n function min(int256 a, int256 b) internal pure returns (int256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two signed numbers without overflow.\n * The result is rounded towards zero.\n */\n function average(int256 a, int256 b) internal pure returns (int256) {\n // Formula from the book \"Hacker's Delight\"\n int256 x = (a & b) + ((a ^ b) >> 1);\n return x + (int256(uint256(x) >> 255) & (a ^ b));\n }\n\n /**\n * @dev Returns the absolute unsigned value of a signed value.\n */\n function abs(int256 n) internal pure returns (uint256) {\n unchecked {\n // must be unchecked in order to support `n = type(int256).min`\n return uint256(n >= 0 ? n : -n);\n }\n }\n}\n"
},
"lib/openzeppelin-contracts/contracts/utils/math/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n // The surrounding unchecked block does not change this fact.\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1, \"Math: mulDiv overflow\");\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10 ** 64) {\n value /= 10 ** 64;\n result += 64;\n }\n if (value >= 10 ** 32) {\n value /= 10 ** 32;\n result += 32;\n }\n if (value >= 10 ** 16) {\n value /= 10 ** 16;\n result += 16;\n }\n if (value >= 10 ** 8) {\n value /= 10 ** 8;\n result += 8;\n }\n if (value >= 10 ** 4) {\n value /= 10 ** 4;\n result += 4;\n }\n if (value >= 10 ** 2) {\n value /= 10 ** 2;\n result += 2;\n }\n if (value >= 10 ** 1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n}\n"
},
"lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.2) (utils/cryptography/MerkleProof.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev These functions deal with verification of Merkle Tree proofs.\n *\n * The tree and the proofs can be generated using our\n * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].\n * You will find a quickstart guide in the readme.\n *\n * WARNING: You should avoid using leaf values that are 64 bytes long prior to\n * hashing, or use a hash function other than keccak256 for hashing leaves.\n * This is because the concatenation of a sorted pair of internal nodes in\n * the merkle tree could be reinterpreted as a leaf value.\n * OpenZeppelin's JavaScript library generates merkle trees that are safe\n * against this attack out of the box.\n */\nlibrary MerkleProof {\n /**\n * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree\n * defined by `root`. For this, a `proof` must be provided, containing\n * sibling hashes on the branch from the leaf to the root of the tree. Each\n * pair of leaves and each pair of pre-images are assumed to be sorted.\n */\n function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {\n return processProof(proof, leaf) == root;\n }\n\n /**\n * @dev Calldata version of {verify}\n *\n * _Available since v4.7._\n */\n function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {\n return processProofCalldata(proof, leaf) == root;\n }\n\n /**\n * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up\n * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt\n * hash matches the root of the tree. When processing the proof, the pairs\n * of leafs & pre-images are assumed to be sorted.\n *\n * _Available since v4.4._\n */\n function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {\n bytes32 computedHash = leaf;\n for (uint256 i = 0; i < proof.length; i++) {\n computedHash = _hashPair(computedHash, proof[i]);\n }\n return computedHash;\n }\n\n /**\n * @dev Calldata version of {processProof}\n *\n * _Available since v4.7._\n */\n function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {\n bytes32 computedHash = leaf;\n for (uint256 i = 0; i < proof.length; i++) {\n computedHash = _hashPair(computedHash, proof[i]);\n }\n return computedHash;\n }\n\n /**\n * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by\n * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.\n *\n * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.\n *\n * _Available since v4.7._\n */\n function multiProofVerify(\n bytes32[] memory proof,\n bool[] memory proofFlags,\n bytes32 root,\n bytes32[] memory leaves\n ) internal pure returns (bool) {\n return processMultiProof(proof, proofFlags, leaves) == root;\n }\n\n /**\n * @dev Calldata version of {multiProofVerify}\n *\n * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.\n *\n * _Available since v4.7._\n */\n function multiProofVerifyCalldata(\n bytes32[] calldata proof,\n bool[] calldata proofFlags,\n bytes32 root,\n bytes32[] memory leaves\n ) internal pure returns (bool) {\n return processMultiProofCalldata(proof, proofFlags, leaves) == root;\n }\n\n /**\n * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction\n * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another\n * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false\n * respectively.\n *\n * CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree\n * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the\n * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).\n *\n * _Available since v4.7._\n */\n function processMultiProof(\n bytes32[] memory proof,\n bool[] memory proofFlags,\n bytes32[] memory leaves\n ) internal pure returns (bytes32 merkleRoot) {\n // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by\n // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the\n // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of\n // the merkle tree.\n uint256 leavesLen = leaves.length;\n uint256 proofLen = proof.length;\n uint256 totalHashes = proofFlags.length;\n\n // Check proof validity.\n require(leavesLen + proofLen - 1 == totalHashes, \"MerkleProof: invalid multiproof\");\n\n // The xxxPos values are \"pointers\" to the next value to consume in each array. All accesses are done using\n // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's \"pop\".\n bytes32[] memory hashes = new bytes32[](totalHashes);\n uint256 leafPos = 0;\n uint256 hashPos = 0;\n uint256 proofPos = 0;\n // At each step, we compute the next hash using two values:\n // - a value from the \"main queue\". If not all leaves have been consumed, we get the next leaf, otherwise we\n // get the next hash.\n // - depending on the flag, either another value from the \"main queue\" (merging branches) or an element from the\n // `proof` array.\n for (uint256 i = 0; i < totalHashes; i++) {\n bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];\n bytes32 b = proofFlags[i]\n ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])\n : proof[proofPos++];\n hashes[i] = _hashPair(a, b);\n }\n\n if (totalHashes > 0) {\n require(proofPos == proofLen, \"MerkleProof: invalid multiproof\");\n unchecked {\n return hashes[totalHashes - 1];\n }\n } else if (leavesLen > 0) {\n return leaves[0];\n } else {\n return proof[0];\n }\n }\n\n /**\n * @dev Calldata version of {processMultiProof}.\n *\n * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.\n *\n * _Available since v4.7._\n */\n function processMultiProofCalldata(\n bytes32[] calldata proof,\n bool[] calldata proofFlags,\n bytes32[] memory leaves\n ) internal pure returns (bytes32 merkleRoot) {\n // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by\n // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the\n // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of\n // the merkle tree.\n uint256 leavesLen = leaves.length;\n uint256 proofLen = proof.length;\n uint256 totalHashes = proofFlags.length;\n\n // Check proof validity.\n require(leavesLen + proofLen - 1 == totalHashes, \"MerkleProof: invalid multiproof\");\n\n // The xxxPos values are \"pointers\" to the next value to consume in each array. All accesses are done using\n // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's \"pop\".\n bytes32[] memory hashes = new bytes32[](totalHashes);\n uint256 leafPos = 0;\n uint256 hashPos = 0;\n uint256 proofPos = 0;\n // At each step, we compute the next hash using two values:\n // - a value from the \"main queue\". If not all leaves have been consumed, we get the next leaf, otherwise we\n // get the next hash.\n // - depending on the flag, either another value from the \"main queue\" (merging branches) or an element from the\n // `proof` array.\n for (uint256 i = 0; i < totalHashes; i++) {\n bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];\n bytes32 b = proofFlags[i]\n ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])\n : proof[proofPos++];\n hashes[i] = _hashPair(a, b);\n }\n\n if (totalHashes > 0) {\n require(proofPos == proofLen, \"MerkleProof: invalid multiproof\");\n unchecked {\n return hashes[totalHashes - 1];\n }\n } else if (leavesLen > 0) {\n return leaves[0];\n } else {\n return proof[0];\n }\n }\n\n function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {\n return a < b ? _efficientHash(a, b) : _efficientHash(b, a);\n }\n\n function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {\n /// @solidity memory-safe-assembly\n assembly {\n mstore(0x00, a)\n mstore(0x20, b)\n value := keccak256(0x00, 0x40)\n }\n }\n}\n"
},
"lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../Strings.sol\";\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n enum RecoverError {\n NoError,\n InvalidSignature,\n InvalidSignatureLength,\n InvalidSignatureS,\n InvalidSignatureV // Deprecated in v4.8\n }\n\n function _throwError(RecoverError error) private pure {\n if (error == RecoverError.NoError) {\n return; // no error: do nothing\n } else if (error == RecoverError.InvalidSignature) {\n revert(\"ECDSA: invalid signature\");\n } else if (error == RecoverError.InvalidSignatureLength) {\n revert(\"ECDSA: invalid signature length\");\n } else if (error == RecoverError.InvalidSignatureS) {\n revert(\"ECDSA: invalid signature 's' value\");\n }\n }\n\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature` or error string. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n *\n * Documentation for signature generation:\n * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\n * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\n *\n * _Available since v4.3._\n */\n function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {\n if (signature.length == 65) {\n bytes32 r;\n bytes32 s;\n uint8 v;\n // ecrecover takes the signature parameters, and the only way to get them\n // currently is to use assembly.\n /// @solidity memory-safe-assembly\n assembly {\n r := mload(add(signature, 0x20))\n s := mload(add(signature, 0x40))\n v := byte(0, mload(add(signature, 0x60)))\n }\n return tryRecover(hash, v, r, s);\n } else {\n return (address(0), RecoverError.InvalidSignatureLength);\n }\n }\n\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature`. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n */\n function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, signature);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n *\n * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]\n *\n * _Available since v4.3._\n */\n function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {\n bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);\n uint8 v = uint8((uint256(vs) >> 255) + 27);\n return tryRecover(hash, v, r, s);\n }\n\n /**\n * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\n *\n * _Available since v4.2._\n */\n function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, r, vs);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\n * `r` and `s` signature fields separately.\n *\n * _Available since v4.3._\n */\n function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {\n // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\n // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n //\n // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n // these malleable signatures as well.\n if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n return (address(0), RecoverError.InvalidSignatureS);\n }\n\n // If the signature is valid (and not malleable), return the signer address\n address signer = ecrecover(hash, v, r, s);\n if (signer == address(0)) {\n return (address(0), RecoverError.InvalidSignature);\n }\n\n return (signer, RecoverError.NoError);\n }\n\n /**\n * @dev Overload of {ECDSA-recover} that receives the `v`,\n * `r` and `s` signature fields separately.\n */\n function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, v, r, s);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n * produces hash corresponding to the one signed with the\n * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n * JSON-RPC method as part of EIP-191.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {\n // 32 is the length in bytes of hash,\n // enforced by the type signature above\n /// @solidity memory-safe-assembly\n assembly {\n mstore(0x00, \"\\x19Ethereum Signed Message:\\n32\")\n mstore(0x1c, hash)\n message := keccak256(0x00, 0x3c)\n }\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from `s`. This\n * produces hash corresponding to the one signed with the\n * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n * JSON-RPC method as part of EIP-191.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n\", Strings.toString(s.length), s));\n }\n\n /**\n * @dev Returns an Ethereum Signed Typed Data, created from a\n * `domainSeparator` and a `structHash`. This produces hash corresponding\n * to the one signed with the\n * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n * JSON-RPC method as part of EIP-712.\n *\n * See {recover}.\n */\n function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {\n /// @solidity memory-safe-assembly\n assembly {\n let ptr := mload(0x40)\n mstore(ptr, \"\\x19\\x01\")\n mstore(add(ptr, 0x02), domainSeparator)\n mstore(add(ptr, 0x22), structHash)\n data := keccak256(ptr, 0x42)\n }\n }\n\n /**\n * @dev Returns an Ethereum Signed Data with intended validator, created from a\n * `validator` and `data` according to the version 0 of EIP-191.\n *\n * See {recover}.\n */\n function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19\\x00\", validator, data));\n }\n}\n"
},
"lib/openzeppelin-contracts/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"lib/openzeppelin-contracts/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./math/Math.sol\";\nimport \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n unchecked {\n uint256 length = Math.log10(value) + 1;\n string memory buffer = new string(length);\n uint256 ptr;\n /// @solidity memory-safe-assembly\n assembly {\n ptr := add(buffer, add(32, length))\n }\n while (true) {\n ptr--;\n /// @solidity memory-safe-assembly\n assembly {\n mstore8(ptr, byte(mod(value, 10), _SYMBOLS))\n }\n value /= 10;\n if (value == 0) break;\n }\n return buffer;\n }\n }\n\n /**\n * @dev Converts a `int256` to its ASCII `string` decimal representation.\n */\n function toString(int256 value) internal pure returns (string memory) {\n return string(abi.encodePacked(value < 0 ? \"-\" : \"\", toString(SignedMath.abs(value))));\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n unchecked {\n return toHexString(value, Math.log256(value) + 1);\n }\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n\n /**\n * @dev Returns true if the two strings are equal.\n */\n function equal(string memory a, string memory b) internal pure returns (bool) {\n return keccak256(bytes(a)) == keccak256(bytes(b));\n }\n}\n"
},
"src/ManyChainMultiSig.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity =0.8.19;\n\nimport \"openzeppelin-contracts/utils/cryptography/MerkleProof.sol\";\nimport \"openzeppelin-contracts/access/Ownable2Step.sol\";\nimport \"openzeppelin-contracts/utils/cryptography/ECDSA.sol\";\n\n// Should be used as the first 32 bytes of the pre-image of the leaf that holds a\n// op. This value is for domain separation of the different values stored in the\n// Merkle tree.\nbytes32 constant MANY_CHAIN_MULTI_SIG_DOMAIN_SEPARATOR_OP =\n keccak256(\"MANY_CHAIN_MULTI_SIG_DOMAIN_SEPARATOR_OP\");\n\n// Should be used as the first 32 bytes of the pre-image of the leaf that holds the\n// root metadata. This value is for domain separation of the different values stored in the\n// Merkle tree.\nbytes32 constant MANY_CHAIN_MULTI_SIG_DOMAIN_SEPARATOR_METADATA =\n keccak256(\"MANY_CHAIN_MULTI_SIG_DOMAIN_SEPARATOR_METADATA\");\n\n/// @notice This is a multi-sig contract that supports signing many transactions (called \"ops\" in\n/// the context of this contract to prevent confusion with transactions on the underlying chain)\n/// targeting many chains with a single set of signatures. Authorized ops along with some metadata\n/// are stored in a Merkle tree, which is generated offchain. Each op has an associated chain id,\n/// ManyChainMultiSig contract address and nonce. The nonce enables us to enforce the\n/// (per-ManyChainMultiSig contract instance) ordering of ops.\n///\n/// At any time, this contract stores at most one Merkle root. In the typical case, all ops\n/// in the Merkle tree are expected to be executed before another root is set. Since the Merkle root\n/// itself reveals ~ no information about the tree's contents, we take two measures to improve\n/// transparency. First, we attach an expiration time to each Merkle root after which it cannot\n/// be used any more. Second, we embed metadata in the tree itself that has to be proven/revealed\n/// to the contract when a new root is set; the metadata contains the range of nonces (and thus\n/// number of ops) in the tree intended for the ManyChainMultiSig contract instance on which the\n/// root is being set.\n///\n/// Once a root is registered, *anyone* is allowed to furnish proofs of op inclusion in the Merkle\n/// tree and execute the corresponding op. The contract enforces that ops are executed in the\n/// correct order and with the correct arguments. A notable exception to this is the gas limit of\n/// the call, which can be freely determined by the executor. We expect (transitive) callees to\n/// implement standard behavior of simply reverting if insufficient gas is provided. In particular,\n/// this means callees should not have non-reverting gas-dependent branches.\n///\n/// Note: In the typical case, we expect the time from a root being set to all of the ops\n/// therein having been executed to be on the order of a couple of minutes.\ncontract ManyChainMultiSig is Ownable2Step {\n receive() external payable {}\n\n uint8 public constant NUM_GROUPS = 32;\n uint8 public constant MAX_NUM_SIGNERS = 200;\n\n struct Signer {\n address addr;\n uint8 index; // index of signer in s_config.signers\n uint8 group; // 0 <= group < NUM_GROUPS. Each signer can only be in one group.\n }\n\n // s_signers is used to easily validate the existence of the signer by its address. We still\n // have signers stored in s_config in order to easily deactivate them when a new config is set.\n mapping(address => Signer) s_signers;\n\n // Signing groups are arranged in a tree. Each group is an interior node and has its own quorum.\n // Signers are the leaves of the tree. A signer/leaf node is successful iff it furnishes a valid\n // signature. A group/interior node is successful iff a quorum of its children are successful.\n // setRoot succeeds only if the root group is successful.\n // Here is an example:\n //\n // ┌──────┐\n // ┌─►│2-of-3│◄───────┐\n // │ └──────┘ │\n // │ ▲ │\n // │ │ │\n // ┌──┴───┐ ┌──┴───┐ ┌───┴────┐\n // ┌──►│1-of-2│ │2-of-2│ │signer A│\n // │ └──────┘ └──────┘ └────────┘\n // │ ▲ ▲ ▲\n // │ │ │ │ ┌──────┐\n // │ │ │ └─────┤1-of-2│◄─┐\n // │ │ │ └──────┘ │\n // ┌───────┴┐ ┌────┴───┐ ┌┴───────┐ ▲ │\n // │signer B│ │signer C│ │signer D│ │ │\n // └────────┘ └────────┘ └────────┘ │ │\n // │ │\n // ┌──────┴─┐ ┌────┴───┐\n // │signer E│ │signer F│\n // └────────┘ └────────┘\n //\n // - If signers [A, B] sign, they can set a root.\n // - If signers [B, D, E] sign, they can set a root.\n // - If signers [B, D, E, F] sign, they can set a root. (Either E's or F's signature was\n // superfluous.)\n // - If signers [B, C, D] sign, they cannot set a root, because the 2-of-2 group on the second\n // level isn't successful and therefore the root group isn't successful either.\n //\n // To map this tree to a Config, we:\n // - create an entry in signers for each signer (sorted by address in ascending order)\n // - assign the root group to index 0 and have it be its own parent\n // - assign an index to each non-root group, such that each group's parent has a lower index\n // than the group itself\n // For example, we could transform the above tree structure into:\n // groupQuorums = [2, 1, 2, 1] + [0, 0, ...] (rightpad with 0s to NUM_GROUPS)\n // groupParents = [0, 0, 0, 2] + [0, 0, ...] (rightpad with 0s to NUM_GROUPS)\n // and assuming that address(A) < address(C) < address(E) < address(F) < address(D) < address(B)\n // signers = [\n // {addr: address(A), index: 0, group: 0}, {addr: address(C), index: 1, group: 1},\n // {addr: address(E), index: 2, group: 3}, {addr: address(F), index: 3, group: 3},\n // {addr: address(D), index: 4, group: 2}, {addr: address(B), index: 5, group: 1},\n // ]\n struct Config {\n Signer[] signers;\n // groupQuorums[i] stores the quorum for the i-th signer group. Any group with\n // groupQuorums[i] = 0 is considered disabled. The i-th group is successful if\n // it is enabled and at least groupQuorums[i] of its children are successful.\n uint8[NUM_GROUPS] groupQuorums;\n // groupParents[i] stores the parent group of the i-th signer group. We ensure that the\n // groups form a tree structure (where the root/0-th signer group points to itself as\n // parent) by enforcing\n // - (i != 0) implies (groupParents[i] < i)\n // - groupParents[0] == 0\n uint8[NUM_GROUPS] groupParents;\n }\n\n Config s_config;\n\n // Remember signedHashes that this contract has seen. Each signedHash can only be set once.\n mapping(bytes32 => bool) s_seenSignedHashes;\n\n // MerkleRoots are a bit tricky since they reveal almost no information about the contents of\n // the tree they authenticate. To mitigate this, we enforce that this contract can only execute\n // ops from a single root at any given point in time. We further associate an expiry\n // with each root to ensure that messages are executed in a timely manner. setRoot and various\n // execute calls are expected to happen in quick succession. We put the expiring root and\n // opCount in same struct in order to reduce gas costs of reading and writing.\n struct ExpiringRootAndOpCount {\n bytes32 root;\n // We prefer using block.timestamp instead of block.number, as a single\n // root may target many chains. We assume that block.timestamp can\n // be manipulated by block producers but only within relatively tight\n // bounds (a few minutes at most).\n uint32 validUntil;\n // each ManyChainMultiSig instance has it own independent opCount.\n uint40 opCount;\n }\n\n ExpiringRootAndOpCount s_expiringRootAndOpCount;\n\n /// @notice Each root also authenticates metadata about itself (stored as one of the leaves)\n /// which must be revealed when the root is set.\n ///\n /// @dev We need to be careful that abi.encode(MANY_CHAIN_MULTI_SIG_DOMAIN_SEPARATOR_METADATA, RootMetadata)\n /// is greater than 64 bytes to prevent collisions with internal nodes in the Merkle tree. See\n /// openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol:15 for details.\n struct RootMetadata {\n // chainId and multiSig uniquely identify a ManyChainMultiSig contract instance that the\n // root is destined for.\n // uint256 since it is unclear if we can represent chainId as uint64. There is a proposal (\n // https://ethereum-magicians.org/t/eip-2294-explicit-bound-to-chain-id/11090) to\n // bound chainid to 64 bits, but it is still unresolved.\n uint256 chainId;\n address multiSig;\n // opCount before adding this root\n uint40 preOpCount;\n // opCount after executing all ops in this root\n uint40 postOpCount;\n // override whatever root was already stored in this contract even if some of its\n // ops weren't executed.\n // Important: it is strongly recommended that offchain code set this to false by default.\n // Be careful setting this to true as it may break assumptions about what transactions from\n // the previous root have already been executed.\n bool overridePreviousRoot;\n }\n\n RootMetadata s_rootMetadata;\n\n /// @notice An ECDSA signature.\n struct Signature {\n uint8 v;\n bytes32 r;\n bytes32 s;\n }\n\n /// @notice setRoot Sets a new expiring root.\n ///\n /// @param root is the new expiring root.\n /// @param validUntil is the time by which root is valid\n /// @param metadata is the authenticated metadata about the root, which is stored as one of\n /// the leaves.\n /// @param metadataProof is the MerkleProof of inclusion of the metadata in the Merkle tree.\n /// @param signatures the ECDSA signatures on (root, validUntil).\n ///\n /// @dev the message (root, validUntil) should be signed by a sufficient set of signers.\n /// This signature authenticates also the metadata.\n ///\n /// @dev this method can be executed by anyone who has the root and valid signatures.\n /// as we validate the correctness of signatures, this imposes no risk.\n function setRoot(\n bytes32 root,\n uint32 validUntil,\n RootMetadata calldata metadata,\n bytes32[] calldata metadataProof,\n Signature[] calldata signatures\n ) external {\n bytes32 signedHash = ECDSA.toEthSignedMessageHash(keccak256(abi.encode(root, validUntil)));\n\n // Each (root, validUntil) tuple can only bet set once. For example, this prevents a\n // scenario where there are two signed roots with overridePreviousRoot = true and\n // an adversary keeps alternatively calling setRoot(root1), setRoot(root2),\n // setRoot(root1), ...\n if (s_seenSignedHashes[signedHash]) {\n revert SignedHashAlreadySeen();\n }\n\n // verify ECDSA signatures on (root, validUntil) and ensure that the root group is successful\n {\n // verify sigs and count number of signers in each group\n Signer memory signer;\n address prevAddress = address(0x0);\n uint8[NUM_GROUPS] memory groupVoteCounts; // number of votes per group\n for (uint256 i = 0; i < signatures.length; i++) {\n Signature calldata sig = signatures[i];\n address signerAddress = ECDSA.recover(signedHash, sig.v, sig.r, sig.s);\n // the off-chain system is required to sort the signatures by the\n // signer address in an increasing order\n if (prevAddress >= signerAddress) {\n revert SignersAddressesMustBeStrictlyIncreasing();\n }\n prevAddress = signerAddress;\n\n signer = s_signers[signerAddress];\n if (signer.addr != signerAddress) {\n revert InvalidSigner();\n }\n uint8 group = signer.group;\n while (true) {\n groupVoteCounts[group]++;\n if (groupVoteCounts[group] != s_config.groupQuorums[group]) {\n // bail out unless we just hit the quorum. we only hit each quorum once,\n // so we never move on to the parent of a group more than once.\n break;\n }\n if (group == 0) {\n // reached root\n break;\n }\n\n group = s_config.groupParents[group];\n }\n }\n // the group at the root of the tree (with index 0) determines whether the vote passed,\n // we cannot proceed if it isn't configured with a valid (non-zero) quorum\n if (s_config.groupQuorums[0] == 0) {\n revert MissingConfig();\n }\n // did the root group reach its quorum?\n if (groupVoteCounts[0] < s_config.groupQuorums[0]) {\n revert InsufficientSigners();\n }\n }\n\n if (validUntil < block.timestamp) {\n revert ValidUntilHasAlreadyPassed();\n }\n\n {\n // verify metadataProof\n bytes32 hashedLeaf =\n keccak256(abi.encode(MANY_CHAIN_MULTI_SIG_DOMAIN_SEPARATOR_METADATA, metadata));\n if (!MerkleProof.verify(metadataProof, root, hashedLeaf)) {\n revert ProofCannotBeVerified();\n }\n }\n\n if (block.chainid != metadata.chainId) {\n revert WrongChainId();\n }\n\n if (address(this) != metadata.multiSig) {\n revert WrongMultiSig();\n }\n\n uint40 opCount = s_expiringRootAndOpCount.opCount;\n\n // don't allow a new root to be set if there are still outstanding ops that have not been\n // executed, unless overridePreviousRoot is set\n if (opCount != s_rootMetadata.postOpCount && !metadata.overridePreviousRoot) {\n revert PendingOps();\n }\n\n // the signers are responsible for tracking opCount offchain and ensuring that\n // preOpCount equals to opCount\n if (opCount != metadata.preOpCount) {\n revert WrongPreOpCount();\n }\n\n if (metadata.preOpCount > metadata.postOpCount) {\n revert WrongPostOpCount();\n }\n\n // done with validation, persist in in contract state\n s_seenSignedHashes[signedHash] = true;\n s_expiringRootAndOpCount = ExpiringRootAndOpCount({\n root: root,\n validUntil: validUntil,\n opCount: metadata.preOpCount\n });\n s_rootMetadata = metadata;\n emit NewRoot(root, validUntil, metadata);\n }\n\n /// @notice an op to be executed by the ManyChainMultiSig contract\n ///\n /// @dev We need to be careful that abi.encode(LEAF_OP_DOMAIN_SEPARATOR, RootMetadata)\n /// is greater than 64 bytes to prevent collisions with internal nodes in the Merkle tree. See\n /// openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol:15 for details.\n struct Op {\n uint256 chainId;\n address multiSig;\n uint40 nonce;\n address to;\n uint256 value;\n bytes data;\n }\n\n /// @notice Execute the received op after verifying the proof of its inclusion in the\n /// current Merkle tree. The op should be the next op according to the order\n /// enforced by the merkle tree whose root is stored in s_expiringRootAndOpCount, i.e., the\n /// nonce of the op should be equal to s_expiringRootAndOpCount.opCount.\n ///\n /// @param op is Op to be executed\n /// @param proof is the MerkleProof for the op's inclusion in the MerkleTree which its\n /// root is the s_expiringRootAndOpCount.root.\n ///\n /// @dev ANYONE can call this function! That's intentional. Callers can only execute verified,\n /// ordered ops in the Merkle tree.\n ///\n /// @dev we perform a raw call to each target. Raw calls to targets that don't have associated\n /// contract code will always succeed regardless of data.\n ///\n /// @dev the gas limit of the call can be freely determined by the caller of this function.\n /// We expect callees to revert if they run out of gas.\n function execute(Op calldata op, bytes32[] calldata proof) external payable {\n ExpiringRootAndOpCount memory currentExpiringRootAndOpCount = s_expiringRootAndOpCount;\n\n if (s_rootMetadata.postOpCount <= currentExpiringRootAndOpCount.opCount) {\n revert PostOpCountReached();\n }\n\n if (op.chainId != block.chainid) {\n revert WrongChainId();\n }\n\n if (op.multiSig != address(this)) {\n revert WrongMultiSig();\n }\n\n if (block.timestamp > currentExpiringRootAndOpCount.validUntil) {\n revert RootExpired();\n }\n\n if (op.nonce != currentExpiringRootAndOpCount.opCount) {\n revert WrongNonce();\n }\n\n // verify that the op exists in the merkle tree\n bytes32 hashedLeaf = keccak256(abi.encode(MANY_CHAIN_MULTI_SIG_DOMAIN_SEPARATOR_OP, op));\n if (!MerkleProof.verify(proof, currentExpiringRootAndOpCount.root, hashedLeaf)) {\n revert ProofCannotBeVerified();\n }\n\n // increase the counter *before* execution to prevent reentrancy issues\n s_expiringRootAndOpCount.opCount = currentExpiringRootAndOpCount.opCount + 1;\n\n _execute(op.to, op.value, op.data);\n emit OpExecuted(op.nonce, op.to, op.data, op.value);\n }\n\n /// @notice sets a new s_config. If clearRoot is true, then it also invalidates\n /// s_expiringRootAndOpCount.root.\n ///\n /// @param signerAddresses holds the addresses of the active signers. The addresses must be in\n /// ascending order.\n /// @param signerGroups maps each signer to its group\n /// @param groupQuorums holds the required number of valid signatures in each group.\n /// A group i is called successful group if at least groupQuorum[i] distinct signers provide a\n /// valid signature.\n /// @param groupParents holds each group's parent. The groups must be arranged in a tree s.t.\n /// group 0 is the root of the tree and the i-th group's parent has index j less than i.\n /// Iff setRoot is called with a set of signatures that causes the root group to be successful,\n /// setRoot allows a root to be set.\n /// @param clearRoot, if set to true, invalidates the current root. This option is needed to\n /// invalidate the current root, so to prevent further ops from being executed. This\n /// might be used when the current root was signed under a loser group configuration or when\n /// some previous signers aren't trusted any more.\n function setConfig(\n address[] calldata signerAddresses,\n uint8[] calldata signerGroups,\n uint8[NUM_GROUPS] calldata groupQuorums,\n uint8[NUM_GROUPS] calldata groupParents,\n bool clearRoot\n ) external onlyOwner {\n if (signerAddresses.length == 0 || signerAddresses.length > MAX_NUM_SIGNERS) {\n revert OutOfBoundsNumOfSigners();\n }\n\n if (signerAddresses.length != signerGroups.length) {\n revert SignerGroupsLengthMismatch();\n }\n\n {\n // validate group structure\n // counts the number of children of each group\n uint8[NUM_GROUPS] memory groupChildrenCounts;\n // first, we count the signers as children\n for (uint256 i = 0; i < signerGroups.length; i++) {\n if (signerGroups[i] >= NUM_GROUPS) {\n revert OutOfBoundsGroup();\n }\n groupChildrenCounts[signerGroups[i]]++;\n }\n // second, we iterate backwards so as to check each group and propagate counts from\n // child group to parent groups up the tree to the root\n for (uint256 j = 0; j < NUM_GROUPS; j++) {\n uint256 i = NUM_GROUPS - 1 - j;\n // ensure we have a well-formed group tree. the root should have itself as parent\n if ((i != 0 && groupParents[i] >= i) || (i == 0 && groupParents[i] != 0)) {\n revert GroupTreeNotWellFormed();\n }\n bool disabled = groupQuorums[i] == 0;\n if (disabled) {\n // a disabled group shouldn't have any children\n if (0 < groupChildrenCounts[i]) {\n revert SignerInDisabledGroup();\n }\n } else {\n // ensure that the group quorum can be met\n if (groupChildrenCounts[i] < groupQuorums[i]) {\n revert OutOfBoundsGroupQuorum();\n }\n groupChildrenCounts[groupParents[i]]++;\n // the above line clobbers groupChildrenCounts[0] in last iteration, don't use it after the loop ends\n }\n }\n }\n\n Signer[] memory oldSigners = s_config.signers;\n // remove any old signer addresses\n for (uint256 i = 0; i < oldSigners.length; i++) {\n address oldSignerAddress = oldSigners[i].addr;\n delete s_signers[oldSignerAddress];\n s_config.signers.pop();\n }\n\n // we cannot just write s_config = Config({...}) because solc doesn't support that\n assert(s_config.signers.length == 0);\n s_config.groupQuorums = groupQuorums;\n s_config.groupParents = groupParents;\n\n // add new signers' addresses, we require that the signers' list be a strictly monotone\n // increasing sequence\n address prevSigner = address(0x0);\n for (uint256 i = 0; i < signerAddresses.length; i++) {\n if (prevSigner >= signerAddresses[i]) {\n revert SignersAddressesMustBeStrictlyIncreasing();\n }\n Signer memory signer =\n Signer({addr: signerAddresses[i], index: uint8(i), group: signerGroups[i]});\n s_signers[signerAddresses[i]] = signer;\n s_config.signers.push(signer);\n prevSigner = signerAddresses[i];\n }\n\n if (clearRoot) {\n // clearRoot is equivalent to overriding with a completely empty root\n uint40 opCount = s_expiringRootAndOpCount.opCount;\n s_expiringRootAndOpCount =\n ExpiringRootAndOpCount({root: 0, validUntil: 0, opCount: opCount});\n s_rootMetadata = RootMetadata({\n chainId: block.chainid,\n multiSig: address(this),\n preOpCount: opCount,\n postOpCount: opCount,\n overridePreviousRoot: true\n });\n }\n emit ConfigSet(s_config, clearRoot);\n }\n\n /// @notice Execute an op's call. Performs a raw call that always succeeds if the\n /// target isn't a contract.\n function _execute(address target, uint256 value, bytes calldata data) internal virtual {\n (bool success, bytes memory ret) = target.call{value: value}(data);\n if (!success) {\n revert CallReverted(ret);\n }\n }\n\n /*\n * Getters\n */\n\n function getConfig() public view returns (Config memory) {\n return s_config;\n }\n\n function getOpCount() public view returns (uint40) {\n return s_expiringRootAndOpCount.opCount;\n }\n\n function getRoot() public view returns (bytes32 root, uint32 validUntil) {\n ExpiringRootAndOpCount memory currentRootAndOpCount = s_expiringRootAndOpCount;\n return (currentRootAndOpCount.root, currentRootAndOpCount.validUntil);\n }\n\n function getRootMetadata() public view returns (RootMetadata memory) {\n return s_rootMetadata;\n }\n\n /*\n * Events and Errors\n */\n\n /// @notice Emitted when a new root is set.\n event NewRoot(bytes32 indexed root, uint32 validUntil, RootMetadata metadata);\n\n /// @notice Emitted when a new config is set.\n event ConfigSet(Config config, bool isRootCleared);\n\n /// @notice Emitted when an op gets successfully executed.\n event OpExecuted(uint40 indexed nonce, address to, bytes data, uint256 value);\n\n /// @notice Thrown when number of signers is 0 or greater than MAX_NUM_SIGNERS.\n error OutOfBoundsNumOfSigners();\n\n /// @notice Thrown when signerAddresses and signerGroups have different lengths.\n error SignerGroupsLengthMismatch();\n\n /// @notice Thrown when number of some signer's group is greater than (NUM_GROUPS-1).\n error OutOfBoundsGroup();\n\n /// @notice Thrown when the group tree isn't well-formed.\n error GroupTreeNotWellFormed();\n\n /// @notice Thrown when the quorum of some group is larger than the number of signers in it.\n error OutOfBoundsGroupQuorum();\n\n /// @notice Thrown when a disabled group contains a signer.\n error SignerInDisabledGroup();\n\n /// @notice Thrown when the signers' addresses are not a strictly increasing monotone sequence.\n /// Prevents signers from including more than one signature.\n error SignersAddressesMustBeStrictlyIncreasing();\n\n /// @notice Thrown when the signature corresponds to invalid signer.\n error InvalidSigner();\n\n /// @notice Thrown when there is no sufficient set of valid signatures provided to make the\n /// root group successful.\n error InsufficientSigners();\n\n /// @notice Thrown when attempt to set metadata or execute op for another chain.\n error WrongChainId();\n\n /// @notice Thrown when the multiSig address in metadata or op is\n /// incompatible with the address of this contract.\n error WrongMultiSig();\n\n /// @notice Thrown when the preOpCount <= postOpCount invariant is violated.\n error WrongPostOpCount();\n\n /// @notice Thrown when attempting to set a new root while there are still pending ops\n /// from the previous root without explicitly overriding it.\n error PendingOps();\n\n /// @notice Thrown when preOpCount in metadata is incompatible with the current opCount.\n error WrongPreOpCount();\n\n /// @notice Thrown when the provided merkle proof cannot be verified.\n error ProofCannotBeVerified();\n\n /// @notice Thrown when attempt to execute an op after\n /// s_expiringRootAndOpCount.validUntil has passed.\n error RootExpired();\n\n /// @notice Thrown when attempt to bypass the enforced ops' order in the merkle tree or\n /// re-execute an op.\n error WrongNonce();\n\n /// @notice Thrown when attempting to execute an op even though opCount equals\n /// metadata.postOpCount.\n error PostOpCountReached();\n\n /// @notice Thrown when the underlying call in _execute() reverts.\n error CallReverted(bytes error);\n\n /// @notice Thrown when attempt to set past validUntil for the root.\n error ValidUntilHasAlreadyPassed();\n\n /// @notice Thrown when setRoot() is called before setting a config.\n error MissingConfig();\n\n /// @notice Thrown when attempt to set the same (root, validUntil) in setRoot().\n error SignedHashAlreadySeen();\n}\n"
}
},
"settings": {
"evmVersion": "paris",
"libraries": {},
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"enabled": true,
"runs": 200
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"abi"
]
}
},
"remappings": [
"ds-test/=lib/forge-std/lib/ds-test/src/",
"forge-std/=lib/forge-std/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
"safe-contracts/=lib/safe-contracts/contracts/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"openzeppelin/=lib/openzeppelin-contracts/contracts/"
],
"viaIR": false
}
}}