MultiSignerERC7913Weighted.sol 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.4.0) (utils/cryptography/signers/MultiSignerERC7913Weighted.sol)
  3. pragma solidity ^0.8.26;
  4. import {SafeCast} from "../../math/SafeCast.sol";
  5. import {MultiSignerERC7913} from "./MultiSignerERC7913.sol";
  6. /**
  7. * @dev Extension of {MultiSignerERC7913} that supports weighted signatures.
  8. *
  9. * This contract allows assigning different weights to each signer, enabling more
  10. * flexible governance schemes. For example, some signers could have higher weight
  11. * than others, allowing for weighted voting or prioritized authorization.
  12. *
  13. * Example of usage:
  14. *
  15. * ```solidity
  16. * contract MyWeightedMultiSignerAccount is Account, MultiSignerERC7913Weighted, Initializable {
  17. * function initialize(bytes[] memory signers, uint64[] memory weights, uint64 threshold) public initializer {
  18. * _addSigners(signers);
  19. * _setSignerWeights(signers, weights);
  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. * function setSignerWeights(bytes[] memory signers, uint64[] memory weights) public onlyEntryPointOrSelf {
  36. * _setSignerWeights(signers, weights);
  37. * }
  38. * }
  39. * ```
  40. *
  41. * IMPORTANT: When setting a threshold value, ensure it matches the scale used for signer weights.
  42. * For example, if signers have weights like 1, 2, or 3, then a threshold of 4 would require at
  43. * least two signers (e.g., one with weight 1 and one with weight 3). See {signerWeight}.
  44. */
  45. abstract contract MultiSignerERC7913Weighted is MultiSignerERC7913 {
  46. using SafeCast for *;
  47. // Sum of all the extra weights of all signers. Storage packed with `MultiSignerERC7913._threshold`
  48. uint64 private _totalExtraWeight;
  49. // Mapping from signer to extraWeight (in addition to all authorized signers having weight 1)
  50. mapping(bytes signer => uint64) private _extraWeights;
  51. /**
  52. * @dev Emitted when a signer's weight is changed.
  53. *
  54. * NOTE: Not emitted in {_addSigners} or {_removeSigners}. Indexers must rely on {ERC7913SignerAdded}
  55. * and {ERC7913SignerRemoved} to index a default weight of 1. See {signerWeight}.
  56. */
  57. event ERC7913SignerWeightChanged(bytes indexed signer, uint64 weight);
  58. /// @dev Thrown when a signer's weight is invalid.
  59. error MultiSignerERC7913WeightedInvalidWeight(bytes signer, uint64 weight);
  60. /// @dev Thrown when the arrays lengths don't match. See {_setSignerWeights}.
  61. error MultiSignerERC7913WeightedMismatchedLength();
  62. constructor(bytes[] memory signers_, uint64[] memory weights_, uint64 threshold_) MultiSignerERC7913(signers_, 1) {
  63. _setSignerWeights(signers_, weights_);
  64. _setThreshold(threshold_);
  65. }
  66. /// @dev Gets the weight of a signer. Returns 0 if the signer is not authorized.
  67. function signerWeight(bytes memory signer) public view virtual returns (uint64) {
  68. unchecked {
  69. // Safe cast, _setSignerWeights guarantees 1+_extraWeights is a uint64
  70. return uint64(isSigner(signer).toUint() * (1 + _extraWeights[signer]));
  71. }
  72. }
  73. /// @dev Gets the total weight of all signers.
  74. function totalWeight() public view virtual returns (uint64) {
  75. return (getSignerCount() + _totalExtraWeight).toUint64();
  76. }
  77. /**
  78. * @dev Sets weights for multiple signers at once. Internal version without access control.
  79. *
  80. * Requirements:
  81. *
  82. * * `signers` and `weights` arrays must have the same length. Reverts with {MultiSignerERC7913WeightedMismatchedLength} on mismatch.
  83. * * Each signer must exist in the set of authorized signers. Otherwise reverts with {MultiSignerERC7913NonexistentSigner}
  84. * * Each weight must be greater than 0. Otherwise reverts with {MultiSignerERC7913WeightedInvalidWeight}
  85. * * See {_validateReachableThreshold} for the threshold validation.
  86. *
  87. * Emits {ERC7913SignerWeightChanged} for each signer.
  88. */
  89. function _setSignerWeights(bytes[] memory signers, uint64[] memory weights) internal virtual {
  90. require(signers.length == weights.length, MultiSignerERC7913WeightedMismatchedLength());
  91. uint256 extraWeightAdded = 0;
  92. uint256 extraWeightRemoved = 0;
  93. for (uint256 i = 0; i < signers.length; ++i) {
  94. bytes memory signer = signers[i];
  95. require(isSigner(signer), MultiSignerERC7913NonexistentSigner(signer));
  96. uint64 weight = weights[i];
  97. require(weight > 0, MultiSignerERC7913WeightedInvalidWeight(signer, weight));
  98. unchecked {
  99. uint64 oldExtraWeight = _extraWeights[signer];
  100. uint64 newExtraWeight = weight - 1;
  101. if (oldExtraWeight != newExtraWeight) {
  102. // Overflow impossible: weight values are bounded by uint64 and economic constraints
  103. extraWeightRemoved += oldExtraWeight;
  104. extraWeightAdded += _extraWeights[signer] = newExtraWeight;
  105. emit ERC7913SignerWeightChanged(signer, weight);
  106. }
  107. }
  108. }
  109. unchecked {
  110. // Safe from underflow: `extraWeightRemoved` is bounded by `_totalExtraWeight` by construction
  111. // and weight values are bounded by uint64 and economic constraints
  112. _totalExtraWeight = (uint256(_totalExtraWeight) + extraWeightAdded - extraWeightRemoved).toUint64();
  113. }
  114. _validateReachableThreshold();
  115. }
  116. /**
  117. * @dev See {MultiSignerERC7913-_addSigners}.
  118. *
  119. * In cases where {totalWeight} is almost `type(uint64).max` (due to a large `_totalExtraWeight`), adding new
  120. * signers could cause the {totalWeight} computation to overflow. Adding a {totalWeight} calls after the new
  121. * signers are added ensures no such overflow happens.
  122. */
  123. function _addSigners(bytes[] memory newSigners) internal virtual override {
  124. super._addSigners(newSigners);
  125. // This will revert if the new signers cause an overflow
  126. _validateReachableThreshold();
  127. }
  128. /**
  129. * @dev See {MultiSignerERC7913-_removeSigners}.
  130. *
  131. * Just like {_addSigners}, this function does not emit {ERC7913SignerWeightChanged} events. The
  132. * {ERC7913SignerRemoved} event emitted by {MultiSignerERC7913-_removeSigners} is enough to track weights here.
  133. */
  134. function _removeSigners(bytes[] memory signers) internal virtual override {
  135. // Clean up weights for removed signers
  136. //
  137. // The `extraWeightRemoved` is bounded by `_totalExtraWeight`. The `super._removeSigners` function will revert
  138. // if the signers array contains any duplicates, ensuring each signer's weight is only counted once. Since
  139. // `_totalExtraWeight` is stored as a `uint64`, the final subtraction operation is also safe.
  140. unchecked {
  141. uint64 extraWeightRemoved = 0;
  142. for (uint256 i = 0; i < signers.length; ++i) {
  143. bytes memory signer = signers[i];
  144. extraWeightRemoved += _extraWeights[signer];
  145. delete _extraWeights[signer];
  146. }
  147. _totalExtraWeight -= extraWeightRemoved;
  148. }
  149. super._removeSigners(signers);
  150. }
  151. /**
  152. * @dev Sets the threshold for the multisignature operation. Internal version without access control.
  153. *
  154. * Requirements:
  155. *
  156. * * The {totalWeight} must be `>=` the {threshold}. Otherwise reverts with {MultiSignerERC7913UnreachableThreshold}
  157. *
  158. * NOTE: This function intentionally does not call `super._validateReachableThreshold` because the base implementation
  159. * assumes each signer has a weight of 1, which is a subset of this weighted implementation. Consider that multiple
  160. * implementations of this function may exist in the contract, so important side effects may be missed
  161. * depending on the linearization order.
  162. */
  163. function _validateReachableThreshold() internal view virtual override {
  164. uint64 weight = totalWeight();
  165. uint64 currentThreshold = threshold();
  166. require(weight >= currentThreshold, MultiSignerERC7913UnreachableThreshold(weight, currentThreshold));
  167. }
  168. /**
  169. * @dev Validates that the total weight of signers meets the threshold requirement.
  170. *
  171. * NOTE: This function intentionally does not call `super._validateThreshold` because the base implementation
  172. * assumes each signer has a weight of 1, which is a subset of this weighted implementation. Consider that multiple
  173. * implementations of this function may exist in the contract, so important side effects may be missed
  174. * depending on the linearization order.
  175. */
  176. function _validateThreshold(bytes[] memory signers) internal view virtual override returns (bool) {
  177. unchecked {
  178. uint64 weight = 0;
  179. for (uint256 i = 0; i < signers.length; ++i) {
  180. // Overflow impossible: weight values are bounded by uint64 and economic constraints
  181. weight += signerWeight(signers[i]);
  182. }
  183. return weight >= threshold();
  184. }
  185. }
  186. }