GovernorTimelockAccess.sol 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.1.0-rc.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. * 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. /**
  154. * @dev See {IGovernor-proposalNeedsQueuing}.
  155. */
  156. function proposalNeedsQueuing(uint256 proposalId) public view virtual override returns (bool) {
  157. return _executionPlan[proposalId].delay > 0;
  158. }
  159. /**
  160. * @dev See {IGovernor-propose}
  161. */
  162. function propose(
  163. address[] memory targets,
  164. uint256[] memory values,
  165. bytes[] memory calldatas,
  166. string memory description
  167. ) public virtual override returns (uint256) {
  168. uint256 proposalId = super.propose(targets, values, calldatas, description);
  169. uint32 neededDelay = baseDelaySeconds();
  170. ExecutionPlan storage plan = _executionPlan[proposalId];
  171. plan.length = SafeCast.toUint16(targets.length);
  172. for (uint256 i = 0; i < targets.length; ++i) {
  173. if (calldatas[i].length < 4) {
  174. continue;
  175. }
  176. address target = targets[i];
  177. bytes4 selector = bytes4(calldatas[i]);
  178. (bool immediate, uint32 delay) = AuthorityUtils.canCallWithDelay(
  179. address(_manager),
  180. address(this),
  181. target,
  182. selector
  183. );
  184. if ((immediate || delay > 0) && !isAccessManagerIgnored(target, selector)) {
  185. _setManagerData(plan, i, !immediate, 0);
  186. // downcast is safe because both arguments are uint32
  187. neededDelay = uint32(Math.max(delay, neededDelay));
  188. }
  189. }
  190. plan.delay = neededDelay;
  191. return proposalId;
  192. }
  193. /**
  194. * @dev Mechanism to queue a proposal, potentially scheduling some of its operations in the AccessManager.
  195. *
  196. * NOTE: The execution delay is chosen based on the delay information retrieved in {propose}. This value may be
  197. * off if the delay was updated since proposal creation. In this case, the proposal needs to be recreated.
  198. */
  199. function _queueOperations(
  200. uint256 proposalId,
  201. address[] memory targets,
  202. uint256[] memory /* values */,
  203. bytes[] memory calldatas,
  204. bytes32 /* descriptionHash */
  205. ) internal virtual override returns (uint48) {
  206. ExecutionPlan storage plan = _executionPlan[proposalId];
  207. uint48 etaSeconds = Time.timestamp() + plan.delay;
  208. for (uint256 i = 0; i < targets.length; ++i) {
  209. (, bool withDelay, ) = _getManagerData(plan, i);
  210. if (withDelay) {
  211. (, uint32 nonce) = _manager.schedule(targets[i], calldatas[i], etaSeconds);
  212. _setManagerData(plan, i, true, nonce);
  213. }
  214. }
  215. return etaSeconds;
  216. }
  217. /**
  218. * @dev Mechanism to execute a proposal, potentially going through {AccessManager-execute} for delayed operations.
  219. */
  220. function _executeOperations(
  221. uint256 proposalId,
  222. address[] memory targets,
  223. uint256[] memory values,
  224. bytes[] memory calldatas,
  225. bytes32 /* descriptionHash */
  226. ) internal virtual override {
  227. uint48 etaSeconds = SafeCast.toUint48(proposalEta(proposalId));
  228. if (block.timestamp < etaSeconds) {
  229. revert GovernorUnmetDelay(proposalId, etaSeconds);
  230. }
  231. ExecutionPlan storage plan = _executionPlan[proposalId];
  232. for (uint256 i = 0; i < targets.length; ++i) {
  233. (bool controlled, bool withDelay, uint32 nonce) = _getManagerData(plan, i);
  234. if (controlled) {
  235. uint32 executedNonce = _manager.execute{value: values[i]}(targets[i], calldatas[i]);
  236. if (withDelay && executedNonce != nonce) {
  237. revert GovernorMismatchedNonce(proposalId, nonce, executedNonce);
  238. }
  239. } else {
  240. (bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
  241. Address.verifyCallResult(success, returndata);
  242. }
  243. }
  244. }
  245. /**
  246. * @dev See {IGovernor-_cancel}
  247. */
  248. function _cancel(
  249. address[] memory targets,
  250. uint256[] memory values,
  251. bytes[] memory calldatas,
  252. bytes32 descriptionHash
  253. ) internal virtual override returns (uint256) {
  254. uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash);
  255. uint48 etaSeconds = SafeCast.toUint48(proposalEta(proposalId));
  256. ExecutionPlan storage plan = _executionPlan[proposalId];
  257. // If the proposal has been scheduled it will have an ETA and we may have to externally cancel
  258. if (etaSeconds != 0) {
  259. for (uint256 i = 0; i < targets.length; ++i) {
  260. (, bool withDelay, uint32 nonce) = _getManagerData(plan, i);
  261. // Only attempt to cancel if the execution plan included a delay
  262. if (withDelay) {
  263. bytes32 operationId = _manager.hashOperation(address(this), targets[i], calldatas[i]);
  264. // Check first if the current operation nonce is the one that we observed previously. It could
  265. // already have been cancelled and rescheduled. We don't want to cancel unless it is exactly the
  266. // instance that we previously scheduled.
  267. if (nonce == _manager.getNonce(operationId)) {
  268. // It is important that all calls have an opportunity to be cancelled. We chose to ignore
  269. // potential failures of some of the cancel operations to give the other operations a chance to
  270. // be properly cancelled. In particular cancel might fail if the operation was already cancelled
  271. // by guardians previously. We don't match on the revert reason to avoid encoding assumptions
  272. // about specific errors.
  273. try _manager.cancel(address(this), targets[i], calldatas[i]) {} catch {}
  274. }
  275. }
  276. }
  277. }
  278. return proposalId;
  279. }
  280. /**
  281. * @dev Returns whether the operation at an index is delayed by the manager, and its scheduling nonce once queued.
  282. */
  283. function _getManagerData(
  284. ExecutionPlan storage plan,
  285. uint256 index
  286. ) private view returns (bool controlled, bool withDelay, uint32 nonce) {
  287. (uint256 bucket, uint256 subindex) = _getManagerDataIndices(index);
  288. uint32 value = plan.managerData[bucket][subindex];
  289. unchecked {
  290. return (value > 0, value > 1, value > 1 ? value - 2 : 0);
  291. }
  292. }
  293. /**
  294. * @dev Marks an operation at an index as permissioned by the manager, potentially delayed, and
  295. * when delayed sets its scheduling nonce.
  296. */
  297. function _setManagerData(ExecutionPlan storage plan, uint256 index, bool withDelay, uint32 nonce) private {
  298. (uint256 bucket, uint256 subindex) = _getManagerDataIndices(index);
  299. plan.managerData[bucket][subindex] = withDelay ? nonce + 2 : 1;
  300. }
  301. /**
  302. * @dev Returns bucket and subindex for reading manager data from the packed array mapping.
  303. */
  304. function _getManagerDataIndices(uint256 index) private pure returns (uint256 bucket, uint256 subindex) {
  305. bucket = index >> 3; // index / 8
  306. subindex = index & 7; // index % 8
  307. }
  308. }