GovernorTimelockAccess.sol 15 KB

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