MultiSignerERC7913.sol 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.4.0) (utils/cryptography/signers/MultiSignerERC7913.sol)
  3. pragma solidity ^0.8.26;
  4. import {AbstractSigner} from "./AbstractSigner.sol";
  5. import {SignatureChecker} from "../SignatureChecker.sol";
  6. import {EnumerableSet} from "../../structs/EnumerableSet.sol";
  7. /**
  8. * @dev Implementation of {AbstractSigner} using multiple ERC-7913 signers with a threshold-based
  9. * signature verification system.
  10. *
  11. * This contract allows managing a set of authorized signers and requires a minimum number of
  12. * signatures (threshold) to approve operations. It uses ERC-7913 formatted signers, which
  13. * makes it natively compatible with ECDSA and ERC-1271 signers.
  14. *
  15. * Example of usage:
  16. *
  17. * ```solidity
  18. * contract MyMultiSignerAccount is Account, MultiSignerERC7913, Initializable {
  19. * function initialize(bytes[] memory signers, uint64 threshold) public initializer {
  20. * _addSigners(signers);
  21. * _setThreshold(threshold);
  22. * }
  23. *
  24. * function addSigners(bytes[] memory signers) public onlyEntryPointOrSelf {
  25. * _addSigners(signers);
  26. * }
  27. *
  28. * function removeSigners(bytes[] memory signers) public onlyEntryPointOrSelf {
  29. * _removeSigners(signers);
  30. * }
  31. *
  32. * function setThreshold(uint64 threshold) public onlyEntryPointOrSelf {
  33. * _setThreshold(threshold);
  34. * }
  35. * }
  36. * ```
  37. *
  38. * IMPORTANT: Failing to properly initialize the signers and threshold either during construction
  39. * (if used standalone) or during initialization (if used as a clone) may leave the contract
  40. * either front-runnable or unusable.
  41. */
  42. abstract contract MultiSignerERC7913 is AbstractSigner {
  43. using EnumerableSet for EnumerableSet.BytesSet;
  44. using SignatureChecker for *;
  45. EnumerableSet.BytesSet private _signers;
  46. uint64 private _threshold;
  47. /// @dev Emitted when a signer is added.
  48. event ERC7913SignerAdded(bytes indexed signers);
  49. /// @dev Emitted when a signers is removed.
  50. event ERC7913SignerRemoved(bytes indexed signers);
  51. /// @dev Emitted when the threshold is updated.
  52. event ERC7913ThresholdSet(uint64 threshold);
  53. /// @dev The `signer` already exists.
  54. error MultiSignerERC7913AlreadyExists(bytes signer);
  55. /// @dev The `signer` does not exist.
  56. error MultiSignerERC7913NonexistentSigner(bytes signer);
  57. /// @dev The `signer` is less than 20 bytes long.
  58. error MultiSignerERC7913InvalidSigner(bytes signer);
  59. /// @dev The `threshold` is zero.
  60. error MultiSignerERC7913ZeroThreshold();
  61. /// @dev The `threshold` is unreachable given the number of `signers`.
  62. error MultiSignerERC7913UnreachableThreshold(uint64 signers, uint64 threshold);
  63. constructor(bytes[] memory signers_, uint64 threshold_) {
  64. _addSigners(signers_);
  65. _setThreshold(threshold_);
  66. }
  67. /**
  68. * @dev Returns a slice of the set of authorized signers.
  69. *
  70. * Using `start = 0` and `end = type(uint64).max` will return the entire set of signers.
  71. *
  72. * WARNING: Depending on the `start` and `end`, this operation can copy a large amount of data to memory, which
  73. * can be expensive. This is designed for view accessors queried without gas fees. Using it in state-changing
  74. * functions may become uncallable if the slice grows too large.
  75. */
  76. function getSigners(uint64 start, uint64 end) public view virtual returns (bytes[] memory) {
  77. return _signers.values(start, end);
  78. }
  79. /// @dev Returns the number of authorized signers
  80. function getSignerCount() public view virtual returns (uint256) {
  81. return _signers.length();
  82. }
  83. /// @dev Returns whether the `signer` is an authorized signer.
  84. function isSigner(bytes memory signer) public view virtual returns (bool) {
  85. return _signers.contains(signer);
  86. }
  87. /// @dev Returns the minimum number of signers required to approve a multisignature operation.
  88. function threshold() public view virtual returns (uint64) {
  89. return _threshold;
  90. }
  91. /**
  92. * @dev Adds the `newSigners` to those allowed to sign on behalf of this contract.
  93. * Internal version without access control.
  94. *
  95. * Requirements:
  96. *
  97. * * Each of `newSigners` must be at least 20 bytes long. Reverts with {MultiSignerERC7913InvalidSigner} if not.
  98. * * Each of `newSigners` must not be authorized. See {isSigner}. Reverts with {MultiSignerERC7913AlreadyExists} if so.
  99. */
  100. function _addSigners(bytes[] memory newSigners) internal virtual {
  101. for (uint256 i = 0; i < newSigners.length; ++i) {
  102. bytes memory signer = newSigners[i];
  103. require(signer.length >= 20, MultiSignerERC7913InvalidSigner(signer));
  104. require(_signers.add(signer), MultiSignerERC7913AlreadyExists(signer));
  105. emit ERC7913SignerAdded(signer);
  106. }
  107. }
  108. /**
  109. * @dev Removes the `oldSigners` from the authorized signers. Internal version without access control.
  110. *
  111. * Requirements:
  112. *
  113. * * Each of `oldSigners` must be authorized. See {isSigner}. Otherwise {MultiSignerERC7913NonexistentSigner} is thrown.
  114. * * See {_validateReachableThreshold} for the threshold validation.
  115. */
  116. function _removeSigners(bytes[] memory oldSigners) internal virtual {
  117. for (uint256 i = 0; i < oldSigners.length; ++i) {
  118. bytes memory signer = oldSigners[i];
  119. require(_signers.remove(signer), MultiSignerERC7913NonexistentSigner(signer));
  120. emit ERC7913SignerRemoved(signer);
  121. }
  122. _validateReachableThreshold();
  123. }
  124. /**
  125. * @dev Sets the signatures `threshold` required to approve a multisignature operation.
  126. * Internal version without access control.
  127. *
  128. * Requirements:
  129. *
  130. * * See {_validateReachableThreshold} for the threshold validation.
  131. */
  132. function _setThreshold(uint64 newThreshold) internal virtual {
  133. require(newThreshold > 0, MultiSignerERC7913ZeroThreshold());
  134. _threshold = newThreshold;
  135. _validateReachableThreshold();
  136. emit ERC7913ThresholdSet(newThreshold);
  137. }
  138. /**
  139. * @dev Validates the current threshold is reachable.
  140. *
  141. * Requirements:
  142. *
  143. * * The {getSignerCount} must be greater or equal than to the {threshold}. Throws
  144. * {MultiSignerERC7913UnreachableThreshold} if not.
  145. */
  146. function _validateReachableThreshold() internal view virtual {
  147. uint256 signersLength = _signers.length();
  148. uint64 currentThreshold = threshold();
  149. require(
  150. signersLength >= currentThreshold,
  151. MultiSignerERC7913UnreachableThreshold(
  152. uint64(signersLength), // Safe cast. Economically impossible to overflow.
  153. currentThreshold
  154. )
  155. );
  156. }
  157. /**
  158. * @dev Decodes, validates the signature and checks the signers are authorized.
  159. * See {_validateSignatures} and {_validateThreshold} for more details.
  160. *
  161. * Example of signature encoding:
  162. *
  163. * ```solidity
  164. * // Encode signers (verifier || key)
  165. * bytes memory signer1 = abi.encodePacked(verifier1, key1);
  166. * bytes memory signer2 = abi.encodePacked(verifier2, key2);
  167. *
  168. * // Order signers by their id
  169. * if (keccak256(signer1) > keccak256(signer2)) {
  170. * (signer1, signer2) = (signer2, signer1);
  171. * (signature1, signature2) = (signature2, signature1);
  172. * }
  173. *
  174. * // Assign ordered signers and signatures
  175. * bytes[] memory signers = new bytes[](2);
  176. * bytes[] memory signatures = new bytes[](2);
  177. * signers[0] = signer1;
  178. * signatures[0] = signature1;
  179. * signers[1] = signer2;
  180. * signatures[1] = signature2;
  181. *
  182. * // Encode the multi signature
  183. * bytes memory signature = abi.encode(signers, signatures);
  184. * ```
  185. *
  186. * Requirements:
  187. *
  188. * * The `signature` must be encoded as `abi.encode(signers, signatures)`.
  189. */
  190. function _rawSignatureValidation(
  191. bytes32 hash,
  192. bytes calldata signature
  193. ) internal view virtual override returns (bool) {
  194. if (signature.length == 0) return false; // For ERC-7739 compatibility
  195. (bytes[] memory signers, bytes[] memory signatures) = abi.decode(signature, (bytes[], bytes[]));
  196. return _validateThreshold(signers) && _validateSignatures(hash, signers, signatures);
  197. }
  198. /**
  199. * @dev Validates the signatures using the signers and their corresponding signatures.
  200. * Returns whether the signers are authorized and the signatures are valid for the given hash.
  201. *
  202. * IMPORTANT: Sorting the signers by their `keccak256` hash will improve the gas efficiency of this function.
  203. * See {SignatureChecker-areValidSignaturesNow-bytes32-bytes[]-bytes[]} for more details.
  204. *
  205. * Requirements:
  206. *
  207. * * The `signatures` and `signers` arrays must be equal in length. Returns false otherwise.
  208. */
  209. function _validateSignatures(
  210. bytes32 hash,
  211. bytes[] memory signers,
  212. bytes[] memory signatures
  213. ) internal view virtual returns (bool valid) {
  214. for (uint256 i = 0; i < signers.length; ++i) {
  215. if (!isSigner(signers[i])) {
  216. return false;
  217. }
  218. }
  219. return hash.areValidSignaturesNow(signers, signatures);
  220. }
  221. /**
  222. * @dev Validates that the number of signers meets the {threshold} requirement.
  223. * Assumes the signers were already validated. See {_validateSignatures} for more details.
  224. */
  225. function _validateThreshold(bytes[] memory validatingSigners) internal view virtual returns (bool) {
  226. return validatingSigners.length >= threshold();
  227. }
  228. }