GovernorTimelockAccess.sol 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.4.0-rc.0) (governance/extensions/GovernorTimelockAccess.sol)
  3. pragma solidity ^0.8.24;
  4. import {IGovernor, Governor} from "../Governor.sol";
  5. import {AuthorityUtils} from "../../access/manager/AuthorityUtils.sol";
  6. import {IAccessManager} from "../../access/manager/IAccessManager.sol";
  7. import {Address} from "../../utils/Address.sol";
  8. import {Math} from "../../utils/math/Math.sol";
  9. import {SafeCast} from "../../utils/math/SafeCast.sol";
  10. import {Time} from "../../utils/types/Time.sol";
  11. /**
  12. * @dev This module connects a {Governor} instance to an {AccessManager} instance, allowing the governor to make calls
  13. * that are delay-restricted by the manager using the normal {queue} workflow. An optional base delay is applied to
  14. * operations that are not delayed externally by the manager. Execution of a proposal will be delayed as much as
  15. * necessary to meet the required delays of all of its operations.
  16. *
  17. * This extension allows the governor to hold and use its own assets and permissions, unlike {GovernorTimelockControl}
  18. * and {GovernorTimelockCompound}, where the timelock is a separate contract that must be the one to hold assets and
  19. * permissions. Operations that are delay-restricted by the manager, however, will be executed through the
  20. * {AccessManager-execute} function.
  21. *
  22. * ==== Security Considerations
  23. *
  24. * Some operations may be cancelable in the `AccessManager` by the admin or a set of guardians, depending on the
  25. * restricted function being invoked. Since proposals are atomic, the cancellation by a guardian of a single operation
  26. * in a proposal will cause all of the proposal to become unable to execute. Consider proposing cancellable operations
  27. * separately.
  28. *
  29. * By default, function calls will be routed through the associated `AccessManager` whenever it claims the target
  30. * function to be restricted by it. However, admins may configure the manager to make that claim for functions that a
  31. * governor would want to call directly (e.g., token transfers) in an attempt to deny it access to those functions. To
  32. * mitigate this attack vector, the governor is able to ignore the restrictions claimed by the `AccessManager` using
  33. * {setAccessManagerIgnored}. While permanent denial of service is mitigated, temporary DoS may still be technically
  34. * possible. All of the governor's own functions (e.g., {setBaseDelaySeconds}) ignore the `AccessManager` by default.
  35. *
  36. * NOTE: `AccessManager` does not support scheduling more than one operation with the same target and calldata at
  37. * the same time. See {AccessManager-schedule} for a workaround.
  38. */
  39. abstract contract GovernorTimelockAccess is Governor {
  40. // An execution plan is produced at the moment a proposal is created, in order to fix at that point the exact
  41. // execution semantics of the proposal, namely whether a call will go through {AccessManager-execute}.
  42. struct ExecutionPlan {
  43. uint16 length;
  44. uint32 delay;
  45. // We use mappings instead of arrays because it allows us to pack values in storage more tightly without
  46. // storing the length redundantly.
  47. // We pack 8 operations' data in each bucket. Each uint32 value is set to 1 upon proposal creation if it has
  48. // to be scheduled and executed through the manager. Upon queuing, the value is set to nonce + 2, where the
  49. // nonce is received from the manager when scheduling the operation.
  50. mapping(uint256 operationBucket => uint32[8]) managerData;
  51. }
  52. // The meaning of the "toggle" set to true depends on the target contract.
  53. // If target == address(this), the manager is ignored by default, and a true toggle means it won't be ignored.
  54. // For all other target contracts, the manager is used by default, and a true toggle means it will be ignored.
  55. mapping(address target => mapping(bytes4 selector => bool)) private _ignoreToggle;
  56. mapping(uint256 proposalId => ExecutionPlan) private _executionPlan;
  57. uint32 private _baseDelay;
  58. IAccessManager private immutable _manager;
  59. error GovernorUnmetDelay(uint256 proposalId, uint256 neededTimestamp);
  60. error GovernorMismatchedNonce(uint256 proposalId, uint256 expectedNonce, uint256 actualNonce);
  61. error GovernorLockedIgnore();
  62. event BaseDelaySet(uint32 oldBaseDelaySeconds, uint32 newBaseDelaySeconds);
  63. event AccessManagerIgnoredSet(address target, bytes4 selector, bool ignored);
  64. /**
  65. * @dev Initialize the governor with an {AccessManager} and initial base delay.
  66. */
  67. constructor(address manager, uint32 initialBaseDelay) {
  68. _manager = IAccessManager(manager);
  69. _setBaseDelaySeconds(initialBaseDelay);
  70. }
  71. /**
  72. * @dev Returns the {AccessManager} instance associated to this governor.
  73. */
  74. function accessManager() public view virtual returns (IAccessManager) {
  75. return _manager;
  76. }
  77. /**
  78. * @dev Base delay that will be applied to all function calls. Some may be further delayed by their associated
  79. * `AccessManager` authority; in this case the final delay will be the maximum of the base delay and the one
  80. * demanded by the authority.
  81. *
  82. * NOTE: Execution delays are processed by the `AccessManager` contracts, and according to that contract are
  83. * expressed in seconds. Therefore, the base delay is also in seconds, regardless of the governor's clock mode.
  84. */
  85. function baseDelaySeconds() public view virtual returns (uint32) {
  86. return _baseDelay;
  87. }
  88. /**
  89. * @dev Change the value of {baseDelaySeconds}. This operation can only be invoked through a governance proposal.
  90. */
  91. function setBaseDelaySeconds(uint32 newBaseDelay) public virtual onlyGovernance {
  92. _setBaseDelaySeconds(newBaseDelay);
  93. }
  94. /**
  95. * @dev Change the value of {baseDelaySeconds}. Internal function without access control.
  96. */
  97. function _setBaseDelaySeconds(uint32 newBaseDelay) internal virtual {
  98. emit BaseDelaySet(_baseDelay, newBaseDelay);
  99. _baseDelay = newBaseDelay;
  100. }
  101. /**
  102. * @dev Check if restrictions from the associated {AccessManager} are ignored for a target function. Returns true
  103. * when the target function will be invoked directly regardless of `AccessManager` settings for the function.
  104. * See {setAccessManagerIgnored} and Security Considerations above.
  105. */
  106. function isAccessManagerIgnored(address target, bytes4 selector) public view virtual returns (bool) {
  107. bool isGovernor = target == address(this);
  108. return _ignoreToggle[target][selector] != isGovernor; // equivalent to: isGovernor ? !toggle : toggle
  109. }
  110. /**
  111. * @dev Configure whether restrictions from the associated {AccessManager} are ignored for a target function.
  112. * See Security Considerations above.
  113. */
  114. function setAccessManagerIgnored(
  115. address target,
  116. bytes4[] calldata selectors,
  117. bool ignored
  118. ) public virtual onlyGovernance {
  119. for (uint256 i = 0; i < selectors.length; ++i) {
  120. _setAccessManagerIgnored(target, selectors[i], ignored);
  121. }
  122. }
  123. /**
  124. * @dev Internal version of {setAccessManagerIgnored} without access restriction.
  125. */
  126. function _setAccessManagerIgnored(address target, bytes4 selector, bool ignored) internal virtual {
  127. bool isGovernor = target == address(this);
  128. if (isGovernor && selector == this.setAccessManagerIgnored.selector) {
  129. revert GovernorLockedIgnore();
  130. }
  131. _ignoreToggle[target][selector] = ignored != isGovernor; // equivalent to: isGovernor ? !ignored : ignored
  132. emit AccessManagerIgnoredSet(target, selector, ignored);
  133. }
  134. /**
  135. * @dev Public accessor to check the execution plan, including the number of seconds that the proposal will be
  136. * delayed since queuing, an array indicating which of the proposal actions will be executed indirectly through
  137. * the associated {AccessManager}, and another indicating which will be scheduled in {queue}. Note that
  138. * those that must be scheduled are cancellable by `AccessManager` guardians.
  139. */
  140. function proposalExecutionPlan(
  141. uint256 proposalId
  142. ) public view returns (uint32 delay, bool[] memory indirect, bool[] memory withDelay) {
  143. ExecutionPlan storage plan = _executionPlan[proposalId];
  144. uint32 length = plan.length;
  145. delay = plan.delay;
  146. indirect = new bool[](length);
  147. withDelay = new bool[](length);
  148. for (uint256 i = 0; i < length; ++i) {
  149. (indirect[i], withDelay[i], ) = _getManagerData(plan, i);
  150. }
  151. return (delay, indirect, withDelay);
  152. }
  153. /// @inheritdoc IGovernor
  154. function proposalNeedsQueuing(uint256 proposalId) public view virtual override returns (bool) {
  155. return _executionPlan[proposalId].delay > 0;
  156. }
  157. /// @inheritdoc IGovernor
  158. function propose(
  159. address[] memory targets,
  160. uint256[] memory values,
  161. bytes[] memory calldatas,
  162. string memory description
  163. ) public virtual override returns (uint256) {
  164. uint256 proposalId = super.propose(targets, values, calldatas, description);
  165. uint32 neededDelay = baseDelaySeconds();
  166. ExecutionPlan storage plan = _executionPlan[proposalId];
  167. plan.length = SafeCast.toUint16(targets.length);
  168. for (uint256 i = 0; i < targets.length; ++i) {
  169. if (calldatas[i].length < 4) {
  170. continue;
  171. }
  172. address target = targets[i];
  173. bytes4 selector = bytes4(calldatas[i]);
  174. (bool immediate, uint32 delay) = AuthorityUtils.canCallWithDelay(
  175. address(_manager),
  176. address(this),
  177. target,
  178. selector
  179. );
  180. if ((immediate || delay > 0) && !isAccessManagerIgnored(target, selector)) {
  181. _setManagerData(plan, i, !immediate, 0);
  182. // downcast is safe because both arguments are uint32
  183. neededDelay = uint32(Math.max(delay, neededDelay));
  184. }
  185. }
  186. plan.delay = neededDelay;
  187. return proposalId;
  188. }
  189. /**
  190. * @dev Mechanism to queue a proposal, potentially scheduling some of its operations in the AccessManager.
  191. *
  192. * NOTE: The execution delay is chosen based on the delay information retrieved in {propose}. This value may be
  193. * off if the delay was updated since proposal creation. In this case, the proposal needs to be recreated.
  194. */
  195. function _queueOperations(
  196. uint256 proposalId,
  197. address[] memory targets,
  198. uint256[] memory /* values */,
  199. bytes[] memory calldatas,
  200. bytes32 /* descriptionHash */
  201. ) internal virtual override returns (uint48) {
  202. ExecutionPlan storage plan = _executionPlan[proposalId];
  203. uint48 etaSeconds = Time.timestamp() + plan.delay;
  204. for (uint256 i = 0; i < targets.length; ++i) {
  205. (, bool withDelay, ) = _getManagerData(plan, i);
  206. if (withDelay) {
  207. // This function can reenter when calling `_manager.schedule` before performing state updates in `_setManagerData`.
  208. // However, the `manager` is a trusted contract in the current context's security model (e.g. an `AccessManager`).
  209. // slither-disable-next-line reentrancy-no-eth
  210. (, uint32 nonce) = _manager.schedule(targets[i], calldatas[i], etaSeconds);
  211. _setManagerData(plan, i, true, nonce);
  212. }
  213. }
  214. return etaSeconds;
  215. }
  216. /**
  217. * @dev Mechanism to execute a proposal, potentially going through {AccessManager-execute} for delayed operations.
  218. */
  219. function _executeOperations(
  220. uint256 proposalId,
  221. address[] memory targets,
  222. uint256[] memory values,
  223. bytes[] memory calldatas,
  224. bytes32 /* descriptionHash */
  225. ) internal virtual override {
  226. uint48 etaSeconds = SafeCast.toUint48(proposalEta(proposalId));
  227. if (block.timestamp < etaSeconds) {
  228. revert GovernorUnmetDelay(proposalId, etaSeconds);
  229. }
  230. ExecutionPlan storage plan = _executionPlan[proposalId];
  231. for (uint256 i = 0; i < targets.length; ++i) {
  232. (bool controlled, bool withDelay, uint32 nonce) = _getManagerData(plan, i);
  233. if (controlled) {
  234. uint32 executedNonce = _manager.execute{value: values[i]}(targets[i], calldatas[i]);
  235. if (withDelay && executedNonce != nonce) {
  236. revert GovernorMismatchedNonce(proposalId, nonce, executedNonce);
  237. }
  238. } else {
  239. (bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
  240. Address.verifyCallResult(success, returndata);
  241. }
  242. }
  243. }
  244. /// @inheritdoc Governor
  245. function _cancel(
  246. address[] memory targets,
  247. uint256[] memory values,
  248. bytes[] memory calldatas,
  249. bytes32 descriptionHash
  250. ) internal virtual override returns (uint256) {
  251. uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash);
  252. uint48 etaSeconds = SafeCast.toUint48(proposalEta(proposalId));
  253. ExecutionPlan storage plan = _executionPlan[proposalId];
  254. // If the proposal has been scheduled it will have an ETA and we may have to externally cancel
  255. if (etaSeconds != 0) {
  256. for (uint256 i = 0; i < targets.length; ++i) {
  257. (, bool withDelay, uint32 nonce) = _getManagerData(plan, i);
  258. // Only attempt to cancel if the execution plan included a delay
  259. if (withDelay) {
  260. bytes32 operationId = _manager.hashOperation(address(this), targets[i], calldatas[i]);
  261. // Check first if the current operation nonce is the one that we observed previously. It could
  262. // already have been cancelled and rescheduled. We don't want to cancel unless it is exactly the
  263. // instance that we previously scheduled.
  264. if (nonce == _manager.getNonce(operationId)) {
  265. // It is important that all calls have an opportunity to be cancelled. We chose to ignore
  266. // potential failures of some of the cancel operations to give the other operations a chance to
  267. // be properly cancelled. In particular cancel might fail if the operation was already cancelled
  268. // by guardians previously. We don't match on the revert reason to avoid encoding assumptions
  269. // about specific errors.
  270. try _manager.cancel(address(this), targets[i], calldatas[i]) {} catch {}
  271. }
  272. }
  273. }
  274. }
  275. return proposalId;
  276. }
  277. /**
  278. * @dev Returns whether the operation at an index is delayed by the manager, and its scheduling nonce once queued.
  279. */
  280. function _getManagerData(
  281. ExecutionPlan storage plan,
  282. uint256 index
  283. ) private view returns (bool controlled, bool withDelay, uint32 nonce) {
  284. (uint256 bucket, uint256 subindex) = _getManagerDataIndices(index);
  285. uint32 value = plan.managerData[bucket][subindex];
  286. unchecked {
  287. return (value > 0, value > 1, value > 1 ? value - 2 : 0);
  288. }
  289. }
  290. /**
  291. * @dev Marks an operation at an index as permissioned by the manager, potentially delayed, and
  292. * when delayed sets its scheduling nonce.
  293. */
  294. function _setManagerData(ExecutionPlan storage plan, uint256 index, bool withDelay, uint32 nonce) private {
  295. (uint256 bucket, uint256 subindex) = _getManagerDataIndices(index);
  296. plan.managerData[bucket][subindex] = withDelay ? nonce + 2 : 1;
  297. }
  298. /**
  299. * @dev Returns bucket and subindex for reading manager data from the packed array mapping.
  300. */
  301. function _getManagerDataIndices(uint256 index) private pure returns (uint256 bucket, uint256 subindex) {
  302. bucket = index >> 3; // index / 8
  303. subindex = index & 7; // index % 8
  304. }
  305. }