MultiSignerERC7913Weighted.sol 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.4.0-rc.0) (utils/cryptography/signers/MultiSignerERC7913Weighted.sol)
  3. pragma solidity ^0.8.27;
  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. /// @dev Gets the weight of a signer. Returns 0 if the signer is not authorized.
  63. function signerWeight(bytes memory signer) public view virtual returns (uint64) {
  64. unchecked {
  65. // Safe cast, _setSignerWeights guarantees 1+_extraWeights is a uint64
  66. return uint64(isSigner(signer).toUint() * (1 + _extraWeights[signer]));
  67. }
  68. }
  69. /// @dev Gets the total weight of all signers.
  70. function totalWeight() public view virtual returns (uint64) {
  71. return (getSignerCount() + _totalExtraWeight).toUint64();
  72. }
  73. /**
  74. * @dev Sets weights for multiple signers at once. Internal version without access control.
  75. *
  76. * Requirements:
  77. *
  78. * * `signers` and `weights` arrays must have the same length. Reverts with {MultiSignerERC7913WeightedMismatchedLength} on mismatch.
  79. * * Each signer must exist in the set of authorized signers. Otherwise reverts with {MultiSignerERC7913NonexistentSigner}
  80. * * Each weight must be greater than 0. Otherwise reverts with {MultiSignerERC7913WeightedInvalidWeight}
  81. * * See {_validateReachableThreshold} for the threshold validation.
  82. *
  83. * Emits {ERC7913SignerWeightChanged} for each signer.
  84. */
  85. function _setSignerWeights(bytes[] memory signers, uint64[] memory weights) internal virtual {
  86. require(signers.length == weights.length, MultiSignerERC7913WeightedMismatchedLength());
  87. uint256 extraWeightAdded = 0;
  88. uint256 extraWeightRemoved = 0;
  89. for (uint256 i = 0; i < signers.length; ++i) {
  90. bytes memory signer = signers[i];
  91. uint64 weight = weights[i];
  92. require(isSigner(signer), MultiSignerERC7913NonexistentSigner(signer));
  93. require(weight > 0, MultiSignerERC7913WeightedInvalidWeight(signer, weight));
  94. unchecked {
  95. // Overflow impossible: weight values are bounded by uint64 and economic constraints
  96. extraWeightRemoved += _extraWeights[signer];
  97. extraWeightAdded += _extraWeights[signer] = weight - 1;
  98. }
  99. emit ERC7913SignerWeightChanged(signer, weight);
  100. }
  101. unchecked {
  102. // Safe from underflow: `extraWeightRemoved` is bounded by `_totalExtraWeight` by construction
  103. // and weight values are bounded by uint64 and economic constraints
  104. _totalExtraWeight = (uint256(_totalExtraWeight) + extraWeightAdded - extraWeightRemoved).toUint64();
  105. }
  106. _validateReachableThreshold();
  107. }
  108. /**
  109. * @dev See {MultiSignerERC7913-_removeSigners}.
  110. *
  111. * Just like {_addSigners}, this function does not emit {ERC7913SignerWeightChanged} events. The
  112. * {ERC7913SignerRemoved} event emitted by {MultiSignerERC7913-_removeSigners} is enough to track weights here.
  113. */
  114. function _removeSigners(bytes[] memory signers) internal virtual override {
  115. // Clean up weights for removed signers
  116. //
  117. // The `extraWeightRemoved` is bounded by `_totalExtraWeight`. The `super._removeSigners` function will revert
  118. // if the signers array contains any duplicates, ensuring each signer's weight is only counted once. Since
  119. // `_totalExtraWeight` is stored as a `uint64`, the final subtraction operation is also safe.
  120. unchecked {
  121. uint64 extraWeightRemoved = 0;
  122. for (uint256 i = 0; i < signers.length; ++i) {
  123. bytes memory signer = signers[i];
  124. extraWeightRemoved += _extraWeights[signer];
  125. delete _extraWeights[signer];
  126. }
  127. _totalExtraWeight -= extraWeightRemoved;
  128. }
  129. super._removeSigners(signers);
  130. }
  131. /**
  132. * @dev Sets the threshold for the multisignature operation. Internal version without access control.
  133. *
  134. * Requirements:
  135. *
  136. * * The {totalWeight} must be `>=` the {threshold}. Otherwise reverts with {MultiSignerERC7913UnreachableThreshold}
  137. *
  138. * NOTE: This function intentionally does not call `super._validateReachableThreshold` because the base implementation
  139. * assumes each signer has a weight of 1, which is a subset of this weighted implementation. Consider that multiple
  140. * implementations of this function may exist in the contract, so important side effects may be missed
  141. * depending on the linearization order.
  142. */
  143. function _validateReachableThreshold() internal view virtual override {
  144. uint64 weight = totalWeight();
  145. uint64 currentThreshold = threshold();
  146. require(weight >= currentThreshold, MultiSignerERC7913UnreachableThreshold(weight, currentThreshold));
  147. }
  148. /**
  149. * @dev Validates that the total weight of signers meets the threshold requirement.
  150. *
  151. * NOTE: This function intentionally does not call `super._validateThreshold` because the base implementation
  152. * assumes each signer has a weight of 1, which is a subset of this weighted implementation. Consider that multiple
  153. * implementations of this function may exist in the contract, so important side effects may be missed
  154. * depending on the linearization order.
  155. */
  156. function _validateThreshold(bytes[] memory signers) internal view virtual override returns (bool) {
  157. unchecked {
  158. uint64 weight = 0;
  159. for (uint256 i = 0; i < signers.length; ++i) {
  160. // Overflow impossible: weight values are bounded by uint64 and economic constraints
  161. weight += signerWeight(signers[i]);
  162. }
  163. return weight >= threshold();
  164. }
  165. }
  166. }