GovernorTimelockAccess.sol 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.0.0) (governance/extensions/GovernorTimelockAccess.sol)
  3. pragma solidity ^0.8.20;
  4. import {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. abstract contract GovernorTimelockAccess is Governor {
  37. // An execution plan is produced at the moment a proposal is created, in order to fix at that point the exact
  38. // execution semantics of the proposal, namely whether a call will go through {AccessManager-execute}.
  39. struct ExecutionPlan {
  40. uint16 length;
  41. uint32 delay;
  42. // We use mappings instead of arrays because it allows us to pack values in storage more tightly without
  43. // storing the length redundantly.
  44. // We pack 8 operations' data in each bucket. Each uint32 value is set to 1 upon proposal creation if it has
  45. // to be scheduled and executed through the manager. Upon queuing, the value is set to nonce + 2, where the
  46. // nonce is received from the manager when scheduling the operation.
  47. mapping(uint256 operationBucket => uint32[8]) managerData;
  48. }
  49. // The meaning of the "toggle" set to true depends on the target contract.
  50. // If target == address(this), the manager is ignored by default, and a true toggle means it won't be ignored.
  51. // For all other target contracts, the manager is used by default, and a true toggle means it will be ignored.
  52. mapping(address target => mapping(bytes4 selector => bool)) private _ignoreToggle;
  53. mapping(uint256 proposalId => ExecutionPlan) private _executionPlan;
  54. uint32 private _baseDelay;
  55. IAccessManager private immutable _manager;
  56. error GovernorUnmetDelay(uint256 proposalId, uint256 neededTimestamp);
  57. error GovernorMismatchedNonce(uint256 proposalId, uint256 expectedNonce, uint256 actualNonce);
  58. error GovernorLockedIgnore();
  59. event BaseDelaySet(uint32 oldBaseDelaySeconds, uint32 newBaseDelaySeconds);
  60. event AccessManagerIgnoredSet(address target, bytes4 selector, bool ignored);
  61. /**
  62. * @dev Initialize the governor with an {AccessManager} and initial base delay.
  63. */
  64. constructor(address manager, uint32 initialBaseDelay) {
  65. _manager = IAccessManager(manager);
  66. _setBaseDelaySeconds(initialBaseDelay);
  67. }
  68. /**
  69. * @dev Returns the {AccessManager} instance associated to this governor.
  70. */
  71. function accessManager() public view virtual returns (IAccessManager) {
  72. return _manager;
  73. }
  74. /**
  75. * @dev Base delay that will be applied to all function calls. Some may be further delayed by their associated
  76. * `AccessManager` authority; in this case the final delay will be the maximum of the base delay and the one
  77. * demanded by the authority.
  78. *
  79. * NOTE: Execution delays are processed by the `AccessManager` contracts, and according to that contract are
  80. * expressed in seconds. Therefore, the base delay is also in seconds, regardless of the governor's clock mode.
  81. */
  82. function baseDelaySeconds() public view virtual returns (uint32) {
  83. return _baseDelay;
  84. }
  85. /**
  86. * @dev Change the value of {baseDelaySeconds}. This operation can only be invoked through a governance proposal.
  87. */
  88. function setBaseDelaySeconds(uint32 newBaseDelay) public virtual onlyGovernance {
  89. _setBaseDelaySeconds(newBaseDelay);
  90. }
  91. /**
  92. * @dev Change the value of {baseDelaySeconds}. Internal function without access control.
  93. */
  94. function _setBaseDelaySeconds(uint32 newBaseDelay) internal virtual {
  95. emit BaseDelaySet(_baseDelay, newBaseDelay);
  96. _baseDelay = newBaseDelay;
  97. }
  98. /**
  99. * @dev Check if restrictions from the associated {AccessManager} are ignored for a target function. Returns true
  100. * when the target function will be invoked directly regardless of `AccessManager` settings for the function.
  101. * See {setAccessManagerIgnored} and Security Considerations above.
  102. */
  103. function isAccessManagerIgnored(address target, bytes4 selector) public view virtual returns (bool) {
  104. bool isGovernor = target == address(this);
  105. return _ignoreToggle[target][selector] != isGovernor; // equivalent to: isGovernor ? !toggle : toggle
  106. }
  107. /**
  108. * @dev Configure whether restrictions from the associated {AccessManager} are ignored for a target function.
  109. * See Security Considerations above.
  110. */
  111. function setAccessManagerIgnored(
  112. address target,
  113. bytes4[] calldata selectors,
  114. bool ignored
  115. ) public virtual onlyGovernance {
  116. for (uint256 i = 0; i < selectors.length; ++i) {
  117. _setAccessManagerIgnored(target, selectors[i], ignored);
  118. }
  119. }
  120. /**
  121. * @dev Internal version of {setAccessManagerIgnored} without access restriction.
  122. */
  123. function _setAccessManagerIgnored(address target, bytes4 selector, bool ignored) internal virtual {
  124. bool isGovernor = target == address(this);
  125. if (isGovernor && selector == this.setAccessManagerIgnored.selector) {
  126. revert GovernorLockedIgnore();
  127. }
  128. _ignoreToggle[target][selector] = ignored != isGovernor; // equivalent to: isGovernor ? !ignored : ignored
  129. emit AccessManagerIgnoredSet(target, selector, ignored);
  130. }
  131. /**
  132. * @dev Public accessor to check the execution plan, including the number of seconds that the proposal will be
  133. * delayed since queuing, an array indicating which of the proposal actions will be executed indirectly through
  134. * the associated {AccessManager}, and another indicating which will be scheduled in {queue}. Note that
  135. * those that must be scheduled are cancellable by `AccessManager` guardians.
  136. */
  137. function proposalExecutionPlan(
  138. uint256 proposalId
  139. ) public view returns (uint32 delay, bool[] memory indirect, bool[] memory withDelay) {
  140. ExecutionPlan storage plan = _executionPlan[proposalId];
  141. uint32 length = plan.length;
  142. delay = plan.delay;
  143. indirect = new bool[](length);
  144. withDelay = new bool[](length);
  145. for (uint256 i = 0; i < length; ++i) {
  146. (indirect[i], withDelay[i], ) = _getManagerData(plan, i);
  147. }
  148. return (delay, indirect, withDelay);
  149. }
  150. /**
  151. * @dev See {IGovernor-proposalNeedsQueuing}.
  152. */
  153. function proposalNeedsQueuing(uint256 proposalId) public view virtual override returns (bool) {
  154. return _executionPlan[proposalId].delay > 0;
  155. }
  156. /**
  157. * @dev See {IGovernor-propose}
  158. */
  159. function propose(
  160. address[] memory targets,
  161. uint256[] memory values,
  162. bytes[] memory calldatas,
  163. string memory description
  164. ) public virtual override returns (uint256) {
  165. uint256 proposalId = super.propose(targets, values, calldatas, description);
  166. uint32 neededDelay = baseDelaySeconds();
  167. ExecutionPlan storage plan = _executionPlan[proposalId];
  168. plan.length = SafeCast.toUint16(targets.length);
  169. for (uint256 i = 0; i < targets.length; ++i) {
  170. if (calldatas[i].length < 4) {
  171. continue;
  172. }
  173. address target = targets[i];
  174. bytes4 selector = bytes4(calldatas[i]);
  175. (bool immediate, uint32 delay) = AuthorityUtils.canCallWithDelay(
  176. address(_manager),
  177. address(this),
  178. target,
  179. selector
  180. );
  181. if ((immediate || delay > 0) && !isAccessManagerIgnored(target, selector)) {
  182. _setManagerData(plan, i, !immediate, 0);
  183. // downcast is safe because both arguments are uint32
  184. neededDelay = uint32(Math.max(delay, neededDelay));
  185. }
  186. }
  187. plan.delay = neededDelay;
  188. return proposalId;
  189. }
  190. /**
  191. * @dev Mechanism to queue a proposal, potentially scheduling some of its operations in the AccessManager.
  192. *
  193. * NOTE: The execution delay is chosen based on the delay information retrieved in {propose}. This value may be
  194. * off if the delay was updated since proposal creation. In this case, the proposal needs to be recreated.
  195. */
  196. function _queueOperations(
  197. uint256 proposalId,
  198. address[] memory targets,
  199. uint256[] memory /* values */,
  200. bytes[] memory calldatas,
  201. bytes32 /* descriptionHash */
  202. ) internal virtual override returns (uint48) {
  203. ExecutionPlan storage plan = _executionPlan[proposalId];
  204. uint48 etaSeconds = Time.timestamp() + plan.delay;
  205. for (uint256 i = 0; i < targets.length; ++i) {
  206. (, bool withDelay, ) = _getManagerData(plan, i);
  207. if (withDelay) {
  208. (, uint32 nonce) = _manager.schedule(targets[i], calldatas[i], etaSeconds);
  209. _setManagerData(plan, i, true, nonce);
  210. }
  211. }
  212. return etaSeconds;
  213. }
  214. /**
  215. * @dev Mechanism to execute a proposal, potentially going through {AccessManager-execute} for delayed operations.
  216. */
  217. function _executeOperations(
  218. uint256 proposalId,
  219. address[] memory targets,
  220. uint256[] memory values,
  221. bytes[] memory calldatas,
  222. bytes32 /* descriptionHash */
  223. ) internal virtual override {
  224. uint48 etaSeconds = SafeCast.toUint48(proposalEta(proposalId));
  225. if (block.timestamp < etaSeconds) {
  226. revert GovernorUnmetDelay(proposalId, etaSeconds);
  227. }
  228. ExecutionPlan storage plan = _executionPlan[proposalId];
  229. for (uint256 i = 0; i < targets.length; ++i) {
  230. (bool controlled, bool withDelay, uint32 nonce) = _getManagerData(plan, i);
  231. if (controlled) {
  232. uint32 executedNonce = _manager.execute{value: values[i]}(targets[i], calldatas[i]);
  233. if (withDelay && executedNonce != nonce) {
  234. revert GovernorMismatchedNonce(proposalId, nonce, executedNonce);
  235. }
  236. } else {
  237. (bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
  238. Address.verifyCallResult(success, returndata);
  239. }
  240. }
  241. }
  242. /**
  243. * @dev See {IGovernor-_cancel}
  244. */
  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. }