MultiSignerERC7913.sol 9.0 KB

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