MultiSignerERC7913.sol 9.4 KB

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