AccessManager.sol 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.20;
  3. import {IAccessManager} from "./IAccessManager.sol";
  4. import {IAccessManaged} from "./IAccessManaged.sol";
  5. import {Address} from "../../utils/Address.sol";
  6. import {Context} from "../../utils/Context.sol";
  7. import {Multicall} from "../../utils/Multicall.sol";
  8. import {Math} from "../../utils/math/Math.sol";
  9. import {Time} from "../../utils/types/Time.sol";
  10. /**
  11. * @dev AccessManager is a central contract to store the permissions of a system.
  12. *
  13. * A smart contract under the control of an AccessManager instance is known as a target, and will inherit from the
  14. * {AccessManaged} contract, be connected to this contract as its manager and implement the {AccessManaged-restricted}
  15. * modifier on a set of functions selected to be permissioned. Note that any function without this setup won't be
  16. * effectively restricted.
  17. *
  18. * The restriction rules for such functions are defined in terms of "roles" identified by an `uint64` and scoped
  19. * by target (`address`) and function selectors (`bytes4`). These roles are stored in this contract and can be
  20. * configured by admins (`ADMIN_ROLE` members) after a delay (see {getTargetAdminDelay}).
  21. *
  22. * For each target contract, admins can configure the following without any delay:
  23. *
  24. * * The target's {AccessManaged-authority} via {updateAuthority}.
  25. * * Close or open a target via {setTargetClosed} keeping the permissions intact.
  26. * * The roles that are allowed (or disallowed) to call a given function (identified by its selector) through {setTargetFunctionRole}.
  27. *
  28. * By default every address is member of the `PUBLIC_ROLE` and every target function is restricted to the `ADMIN_ROLE` until configured otherwise.
  29. * Additionally, each role has the following configuration options restricted to this manager's admins:
  30. *
  31. * * A role's admin role via {setRoleAdmin} who can grant or revoke roles.
  32. * * A role's guardian role via {setRoleGuardian} who's allowed to cancel operations.
  33. * * A delay in which a role takes effect after being granted through {setGrantDelay}.
  34. * * A delay of any target's admin action via {setTargetAdminDelay}.
  35. * * A role label for discoverability purposes with {labelRole}.
  36. *
  37. * Any account can be added and removed into any number of these roles by using the {grantRole} and {revokeRole} functions
  38. * restricted to each role's admin (see {getRoleAdmin}).
  39. *
  40. * Since all the permissions of the managed system can be modified by the admins of this instance, it is expected that
  41. * they will be highly secured (e.g., a multisig or a well-configured DAO).
  42. *
  43. * NOTE: This contract implements a form of the {IAuthority} interface, but {canCall} has additional return data so it
  44. * doesn't inherit `IAuthority`. It is however compatible with the `IAuthority` interface since the first 32 bytes of
  45. * the return data are a boolean as expected by that interface.
  46. *
  47. * NOTE: Systems that implement other access control mechanisms (for example using {Ownable}) can be paired with an
  48. * {AccessManager} by transferring permissions (ownership in the case of {Ownable}) directly to the {AccessManager}.
  49. * Users will be able to interact with these contracts through the {execute} function, following the access rules
  50. * registered in the {AccessManager}. Keep in mind that in that context, the msg.sender seen by restricted functions
  51. * will be {AccessManager} itself.
  52. *
  53. * WARNING: When granting permissions over an {Ownable} or {AccessControl} contract to an {AccessManager}, be very
  54. * mindful of the danger associated with functions such as {{Ownable-renounceOwnership}} or
  55. * {{AccessControl-renounceRole}}.
  56. */
  57. contract AccessManager is Context, Multicall, IAccessManager {
  58. using Time for *;
  59. // Structure that stores the details for a target contract.
  60. struct TargetConfig {
  61. mapping(bytes4 selector => uint64 roleId) allowedRoles;
  62. Time.Delay adminDelay;
  63. bool closed;
  64. }
  65. // Structure that stores the details for a role/account pair. This structures fit into a single slot.
  66. struct Access {
  67. // Timepoint at which the user gets the permission.
  68. // If this is either 0 or in the future, then the role permission is not available.
  69. uint48 since;
  70. // Delay for execution. Only applies to restricted() / execute() calls.
  71. Time.Delay delay;
  72. }
  73. // Structure that stores the details of a role.
  74. struct Role {
  75. // Members of the role.
  76. mapping(address user => Access access) members;
  77. // Admin who can grant or revoke permissions.
  78. uint64 admin;
  79. // Guardian who can cancel operations targeting functions that need this role.
  80. uint64 guardian;
  81. // Delay in which the role takes effect after being granted.
  82. Time.Delay grantDelay;
  83. }
  84. // Structure that stores the details for a scheduled operation. This structure fits into a single slot.
  85. struct Schedule {
  86. // Moment at which the operation can be executed.
  87. uint48 timepoint;
  88. // Operation nonce to allow third-party contracts to identify the operation.
  89. uint32 nonce;
  90. }
  91. uint64 public constant ADMIN_ROLE = type(uint64).min; // 0
  92. uint64 public constant PUBLIC_ROLE = type(uint64).max; // 2**64-1
  93. mapping(address target => TargetConfig mode) private _targets;
  94. mapping(uint64 roleId => Role) private _roles;
  95. mapping(bytes32 operationId => Schedule) private _schedules;
  96. // Used to identify operations that are currently being executed via {execute}.
  97. // This should be transient storage when supported by the EVM.
  98. bytes32 private _executionId;
  99. /**
  100. * @dev Check that the caller is authorized to perform the operation, following the restrictions encoded in
  101. * {_getAdminRestrictions}.
  102. */
  103. modifier onlyAuthorized() {
  104. _checkAuthorized();
  105. _;
  106. }
  107. constructor(address initialAdmin) {
  108. if (initialAdmin == address(0)) {
  109. revert AccessManagerInvalidInitialAdmin(address(0));
  110. }
  111. // admin is active immediately and without any execution delay.
  112. _grantRole(ADMIN_ROLE, initialAdmin, 0, 0);
  113. }
  114. // =================================================== GETTERS ====================================================
  115. /**
  116. * @dev Check if an address (`caller`) is authorised to call a given function on a given contract directly (with
  117. * no restriction). Additionally, it returns the delay needed to perform the call indirectly through the {schedule}
  118. * & {execute} workflow.
  119. *
  120. * This function is usually called by the targeted contract to control immediate execution of restricted functions.
  121. * Therefore we only return true if the call can be performed without any delay. If the call is subject to a
  122. * previously set delay (not zero), then the function should return false and the caller should schedule the operation
  123. * for future execution.
  124. *
  125. * If `immediate` is true, the delay can be disregarded and the operation can be immediately executed, otherwise
  126. * the operation can be executed if and only if delay is greater than 0.
  127. *
  128. * NOTE: The IAuthority interface does not include the `uint32` delay. This is an extension of that interface that
  129. * is backward compatible. Some contracts may thus ignore the second return argument. In that case they will fail
  130. * to identify the indirect workflow, and will consider calls that require a delay to be forbidden.
  131. *
  132. * NOTE: This function does not report the permissions of this manager itself. These are defined by the
  133. * {_canCallSelf} function instead.
  134. */
  135. function canCall(
  136. address caller,
  137. address target,
  138. bytes4 selector
  139. ) public view virtual returns (bool immediate, uint32 delay) {
  140. if (isTargetClosed(target)) {
  141. return (false, 0);
  142. } else if (caller == address(this)) {
  143. // Caller is AccessManager, this means the call was sent through {execute} and it already checked
  144. // permissions. We verify that the call "identifier", which is set during {execute}, is correct.
  145. return (_isExecuting(target, selector), 0);
  146. } else {
  147. uint64 roleId = getTargetFunctionRole(target, selector);
  148. (bool isMember, uint32 currentDelay) = hasRole(roleId, caller);
  149. return isMember ? (currentDelay == 0, currentDelay) : (false, 0);
  150. }
  151. }
  152. /**
  153. * @dev Expiration delay for scheduled proposals. Defaults to 1 week.
  154. *
  155. * IMPORTANT: Avoid overriding the expiration with 0. Otherwise every contract proposal will be expired immediately,
  156. * disabling any scheduling usage.
  157. */
  158. function expiration() public view virtual returns (uint32) {
  159. return 1 weeks;
  160. }
  161. /**
  162. * @dev Minimum setback for all delay updates, with the exception of execution delays. It
  163. * can be increased without setback (and in the event of an accidental increase can be reset
  164. * via {revokeRole}). Defaults to 5 days.
  165. */
  166. function minSetback() public view virtual returns (uint32) {
  167. return 5 days;
  168. }
  169. /**
  170. * @dev Get whether the contract is closed disabling any access. Otherwise role permissions are applied.
  171. */
  172. function isTargetClosed(address target) public view virtual returns (bool) {
  173. return _targets[target].closed;
  174. }
  175. /**
  176. * @dev Get the role required to call a function.
  177. */
  178. function getTargetFunctionRole(address target, bytes4 selector) public view virtual returns (uint64) {
  179. return _targets[target].allowedRoles[selector];
  180. }
  181. /**
  182. * @dev Get the admin delay for a target contract. Changes to contract configuration are subject to this delay.
  183. */
  184. function getTargetAdminDelay(address target) public view virtual returns (uint32) {
  185. return _targets[target].adminDelay.get();
  186. }
  187. /**
  188. * @dev Get the id of the role that acts as an admin for the given role.
  189. *
  190. * The admin permission is required to grant the role, revoke the role and update the execution delay to execute
  191. * an operation that is restricted to this role.
  192. */
  193. function getRoleAdmin(uint64 roleId) public view virtual returns (uint64) {
  194. return _roles[roleId].admin;
  195. }
  196. /**
  197. * @dev Get the role that acts as a guardian for a given role.
  198. *
  199. * The guardian permission allows canceling operations that have been scheduled under the role.
  200. */
  201. function getRoleGuardian(uint64 roleId) public view virtual returns (uint64) {
  202. return _roles[roleId].guardian;
  203. }
  204. /**
  205. * @dev Get the role current grant delay.
  206. *
  207. * Its value may change at any point without an event emitted following a call to {setGrantDelay}.
  208. * Changes to this value, including effect timepoint are notified in advance by the {RoleGrantDelayChanged} event.
  209. */
  210. function getRoleGrantDelay(uint64 roleId) public view virtual returns (uint32) {
  211. return _roles[roleId].grantDelay.get();
  212. }
  213. /**
  214. * @dev Get the access details for a given account for a given role. These details include the timepoint at which
  215. * membership becomes active, and the delay applied to all operation by this user that requires this permission
  216. * level.
  217. *
  218. * Returns:
  219. * [0] Timestamp at which the account membership becomes valid. 0 means role is not granted.
  220. * [1] Current execution delay for the account.
  221. * [2] Pending execution delay for the account.
  222. * [3] Timestamp at which the pending execution delay will become active. 0 means no delay update is scheduled.
  223. */
  224. function getAccess(
  225. uint64 roleId,
  226. address account
  227. ) public view virtual returns (uint48 since, uint32 currentDelay, uint32 pendingDelay, uint48 effect) {
  228. Access storage access = _roles[roleId].members[account];
  229. since = access.since;
  230. (currentDelay, pendingDelay, effect) = access.delay.getFull();
  231. return (since, currentDelay, pendingDelay, effect);
  232. }
  233. /**
  234. * @dev Check if a given account currently has the permission level corresponding to a given role. Note that this
  235. * permission might be associated with an execution delay. {getAccess} can provide more details.
  236. */
  237. function hasRole(
  238. uint64 roleId,
  239. address account
  240. ) public view virtual returns (bool isMember, uint32 executionDelay) {
  241. if (roleId == PUBLIC_ROLE) {
  242. return (true, 0);
  243. } else {
  244. (uint48 hasRoleSince, uint32 currentDelay, , ) = getAccess(roleId, account);
  245. return (hasRoleSince != 0 && hasRoleSince <= Time.timestamp(), currentDelay);
  246. }
  247. }
  248. // =============================================== ROLE MANAGEMENT ===============================================
  249. /**
  250. * @dev Give a label to a role, for improved role discoverabily by UIs.
  251. *
  252. * Requirements:
  253. *
  254. * - the caller must be a global admin
  255. *
  256. * Emits a {RoleLabel} event.
  257. */
  258. function labelRole(uint64 roleId, string calldata label) public virtual onlyAuthorized {
  259. if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
  260. revert AccessManagerLockedRole(roleId);
  261. }
  262. emit RoleLabel(roleId, label);
  263. }
  264. /**
  265. * @dev Add `account` to `roleId`, or change its execution delay.
  266. *
  267. * This gives the account the authorization to call any function that is restricted to this role. An optional
  268. * execution delay (in seconds) can be set. If that delay is non 0, the user is required to schedule any operation
  269. * that is restricted to members of this role. The user will only be able to execute the operation after the delay has
  270. * passed, before it has expired. During this period, admin and guardians can cancel the operation (see {cancel}).
  271. *
  272. * If the account has already been granted this role, the execution delay will be updated. This update is not
  273. * immediate and follows the delay rules. For example, if a user currently has a delay of 3 hours, and this is
  274. * called to reduce that delay to 1 hour, the new delay will take some time to take effect, enforcing that any
  275. * operation executed in the 3 hours that follows this update was indeed scheduled before this update.
  276. *
  277. * Requirements:
  278. *
  279. * - the caller must be an admin for the role (see {getRoleAdmin})
  280. * - granted role must not be the `PUBLIC_ROLE`
  281. *
  282. * Emits a {RoleGranted} event.
  283. */
  284. function grantRole(uint64 roleId, address account, uint32 executionDelay) public virtual onlyAuthorized {
  285. _grantRole(roleId, account, getRoleGrantDelay(roleId), executionDelay);
  286. }
  287. /**
  288. * @dev Remove an account from a role, with immediate effect. If the account does not have the role, this call has
  289. * no effect.
  290. *
  291. * Requirements:
  292. *
  293. * - the caller must be an admin for the role (see {getRoleAdmin})
  294. * - revoked role must not be the `PUBLIC_ROLE`
  295. *
  296. * Emits a {RoleRevoked} event if the account had the role.
  297. */
  298. function revokeRole(uint64 roleId, address account) public virtual onlyAuthorized {
  299. _revokeRole(roleId, account);
  300. }
  301. /**
  302. * @dev Renounce role permissions for the calling account with immediate effect. If the sender is not in
  303. * the role this call has no effect.
  304. *
  305. * Requirements:
  306. *
  307. * - the caller must be `callerConfirmation`.
  308. *
  309. * Emits a {RoleRevoked} event if the account had the role.
  310. */
  311. function renounceRole(uint64 roleId, address callerConfirmation) public virtual {
  312. if (callerConfirmation != _msgSender()) {
  313. revert AccessManagerBadConfirmation();
  314. }
  315. _revokeRole(roleId, callerConfirmation);
  316. }
  317. /**
  318. * @dev Change admin role for a given role.
  319. *
  320. * Requirements:
  321. *
  322. * - the caller must be a global admin
  323. *
  324. * Emits a {RoleAdminChanged} event
  325. */
  326. function setRoleAdmin(uint64 roleId, uint64 admin) public virtual onlyAuthorized {
  327. _setRoleAdmin(roleId, admin);
  328. }
  329. /**
  330. * @dev Change guardian role for a given role.
  331. *
  332. * Requirements:
  333. *
  334. * - the caller must be a global admin
  335. *
  336. * Emits a {RoleGuardianChanged} event
  337. */
  338. function setRoleGuardian(uint64 roleId, uint64 guardian) public virtual onlyAuthorized {
  339. _setRoleGuardian(roleId, guardian);
  340. }
  341. /**
  342. * @dev Update the delay for granting a `roleId`.
  343. *
  344. * Requirements:
  345. *
  346. * - the caller must be a global admin
  347. *
  348. * Emits a {RoleGrantDelayChanged} event.
  349. */
  350. function setGrantDelay(uint64 roleId, uint32 newDelay) public virtual onlyAuthorized {
  351. _setGrantDelay(roleId, newDelay);
  352. }
  353. /**
  354. * @dev Internal version of {grantRole} without access control. Returns true if the role was newly granted.
  355. *
  356. * Emits a {RoleGranted} event.
  357. */
  358. function _grantRole(
  359. uint64 roleId,
  360. address account,
  361. uint32 grantDelay,
  362. uint32 executionDelay
  363. ) internal virtual returns (bool) {
  364. if (roleId == PUBLIC_ROLE) {
  365. revert AccessManagerLockedRole(roleId);
  366. }
  367. bool newMember = _roles[roleId].members[account].since == 0;
  368. uint48 since;
  369. if (newMember) {
  370. since = Time.timestamp() + grantDelay;
  371. _roles[roleId].members[account] = Access({since: since, delay: executionDelay.toDelay()});
  372. } else {
  373. // No setback here. Value can be reset by doing revoke + grant, effectively allowing the admin to perform
  374. // any change to the execution delay within the duration of the role admin delay.
  375. (_roles[roleId].members[account].delay, since) = _roles[roleId].members[account].delay.withUpdate(
  376. executionDelay,
  377. 0
  378. );
  379. }
  380. emit RoleGranted(roleId, account, executionDelay, since, newMember);
  381. return newMember;
  382. }
  383. /**
  384. * @dev Internal version of {revokeRole} without access control. This logic is also used by {renounceRole}.
  385. * Returns true if the role was previously granted.
  386. *
  387. * Emits a {RoleRevoked} event if the account had the role.
  388. */
  389. function _revokeRole(uint64 roleId, address account) internal virtual returns (bool) {
  390. if (roleId == PUBLIC_ROLE) {
  391. revert AccessManagerLockedRole(roleId);
  392. }
  393. if (_roles[roleId].members[account].since == 0) {
  394. return false;
  395. }
  396. delete _roles[roleId].members[account];
  397. emit RoleRevoked(roleId, account);
  398. return true;
  399. }
  400. /**
  401. * @dev Internal version of {setRoleAdmin} without access control.
  402. *
  403. * Emits a {RoleAdminChanged} event.
  404. *
  405. * NOTE: Setting the admin role as the `PUBLIC_ROLE` is allowed, but it will effectively allow
  406. * anyone to set grant or revoke such role.
  407. */
  408. function _setRoleAdmin(uint64 roleId, uint64 admin) internal virtual {
  409. if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
  410. revert AccessManagerLockedRole(roleId);
  411. }
  412. _roles[roleId].admin = admin;
  413. emit RoleAdminChanged(roleId, admin);
  414. }
  415. /**
  416. * @dev Internal version of {setRoleGuardian} without access control.
  417. *
  418. * Emits a {RoleGuardianChanged} event.
  419. *
  420. * NOTE: Setting the guardian role as the `PUBLIC_ROLE` is allowed, but it will effectively allow
  421. * anyone to cancel any scheduled operation for such role.
  422. */
  423. function _setRoleGuardian(uint64 roleId, uint64 guardian) internal virtual {
  424. if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
  425. revert AccessManagerLockedRole(roleId);
  426. }
  427. _roles[roleId].guardian = guardian;
  428. emit RoleGuardianChanged(roleId, guardian);
  429. }
  430. /**
  431. * @dev Internal version of {setGrantDelay} without access control.
  432. *
  433. * Emits a {RoleGrantDelayChanged} event.
  434. */
  435. function _setGrantDelay(uint64 roleId, uint32 newDelay) internal virtual {
  436. if (roleId == PUBLIC_ROLE) {
  437. revert AccessManagerLockedRole(roleId);
  438. }
  439. uint48 effect;
  440. (_roles[roleId].grantDelay, effect) = _roles[roleId].grantDelay.withUpdate(newDelay, minSetback());
  441. emit RoleGrantDelayChanged(roleId, newDelay, effect);
  442. }
  443. // ============================================= FUNCTION MANAGEMENT ==============================================
  444. /**
  445. * @dev Set the role required to call functions identified by the `selectors` in the `target` contract.
  446. *
  447. * Requirements:
  448. *
  449. * - the caller must be a global admin
  450. *
  451. * Emits a {TargetFunctionRoleUpdated} event per selector.
  452. */
  453. function setTargetFunctionRole(
  454. address target,
  455. bytes4[] calldata selectors,
  456. uint64 roleId
  457. ) public virtual onlyAuthorized {
  458. for (uint256 i = 0; i < selectors.length; ++i) {
  459. _setTargetFunctionRole(target, selectors[i], roleId);
  460. }
  461. }
  462. /**
  463. * @dev Internal version of {setTargetFunctionRole} without access control.
  464. *
  465. * Emits a {TargetFunctionRoleUpdated} event.
  466. */
  467. function _setTargetFunctionRole(address target, bytes4 selector, uint64 roleId) internal virtual {
  468. _targets[target].allowedRoles[selector] = roleId;
  469. emit TargetFunctionRoleUpdated(target, selector, roleId);
  470. }
  471. /**
  472. * @dev Set the delay for changing the configuration of a given target contract.
  473. *
  474. * Requirements:
  475. *
  476. * - the caller must be a global admin
  477. *
  478. * Emits a {TargetAdminDelayUpdated} event.
  479. */
  480. function setTargetAdminDelay(address target, uint32 newDelay) public virtual onlyAuthorized {
  481. _setTargetAdminDelay(target, newDelay);
  482. }
  483. /**
  484. * @dev Internal version of {setTargetAdminDelay} without access control.
  485. *
  486. * Emits a {TargetAdminDelayUpdated} event.
  487. */
  488. function _setTargetAdminDelay(address target, uint32 newDelay) internal virtual {
  489. uint48 effect;
  490. (_targets[target].adminDelay, effect) = _targets[target].adminDelay.withUpdate(newDelay, minSetback());
  491. emit TargetAdminDelayUpdated(target, newDelay, effect);
  492. }
  493. // =============================================== MODE MANAGEMENT ================================================
  494. /**
  495. * @dev Set the closed flag for a contract.
  496. *
  497. * Requirements:
  498. *
  499. * - the caller must be a global admin
  500. *
  501. * Emits a {TargetClosed} event.
  502. */
  503. function setTargetClosed(address target, bool closed) public virtual onlyAuthorized {
  504. _setTargetClosed(target, closed);
  505. }
  506. /**
  507. * @dev Set the closed flag for a contract. This is an internal setter with no access restrictions.
  508. *
  509. * Emits a {TargetClosed} event.
  510. */
  511. function _setTargetClosed(address target, bool closed) internal virtual {
  512. if (target == address(this)) {
  513. revert AccessManagerLockedAccount(target);
  514. }
  515. _targets[target].closed = closed;
  516. emit TargetClosed(target, closed);
  517. }
  518. // ============================================== DELAYED OPERATIONS ==============================================
  519. /**
  520. * @dev Return the timepoint at which a scheduled operation will be ready for execution. This returns 0 if the
  521. * operation is not yet scheduled, has expired, was executed, or was canceled.
  522. */
  523. function getSchedule(bytes32 id) public view virtual returns (uint48) {
  524. uint48 timepoint = _schedules[id].timepoint;
  525. return _isExpired(timepoint) ? 0 : timepoint;
  526. }
  527. /**
  528. * @dev Return the nonce for the latest scheduled operation with a given id. Returns 0 if the operation has never
  529. * been scheduled.
  530. */
  531. function getNonce(bytes32 id) public view virtual returns (uint32) {
  532. return _schedules[id].nonce;
  533. }
  534. /**
  535. * @dev Schedule a delayed operation for future execution, and return the operation identifier. It is possible to
  536. * choose the timestamp at which the operation becomes executable as long as it satisfies the execution delays
  537. * required for the caller. The special value zero will automatically set the earliest possible time.
  538. *
  539. * Returns the `operationId` that was scheduled. Since this value is a hash of the parameters, it can reoccur when
  540. * the same parameters are used; if this is relevant, the returned `nonce` can be used to uniquely identify this
  541. * scheduled operation from other occurrences of the same `operationId` in invocations of {execute} and {cancel}.
  542. *
  543. * Emits a {OperationScheduled} event.
  544. *
  545. * NOTE: It is not possible to concurrently schedule more than one operation with the same `target` and `data`. If
  546. * this is necessary, a random byte can be appended to `data` to act as a salt that will be ignored by the target
  547. * contract if it is using standard Solidity ABI encoding.
  548. */
  549. function schedule(
  550. address target,
  551. bytes calldata data,
  552. uint48 when
  553. ) public virtual returns (bytes32 operationId, uint32 nonce) {
  554. address caller = _msgSender();
  555. // Fetch restrictions that apply to the caller on the targeted function
  556. (, uint32 setback) = _canCallExtended(caller, target, data);
  557. uint48 minWhen = Time.timestamp() + setback;
  558. // If call with delay is not authorized, or if requested timing is too soon, revert
  559. if (setback == 0 || (when > 0 && when < minWhen)) {
  560. revert AccessManagerUnauthorizedCall(caller, target, _checkSelector(data));
  561. }
  562. // Reuse variable due to stack too deep
  563. when = uint48(Math.max(when, minWhen)); // cast is safe: both inputs are uint48
  564. // If caller is authorised, schedule operation
  565. operationId = hashOperation(caller, target, data);
  566. _checkNotScheduled(operationId);
  567. unchecked {
  568. // It's not feasible to overflow the nonce in less than 1000 years
  569. nonce = _schedules[operationId].nonce + 1;
  570. }
  571. _schedules[operationId].timepoint = when;
  572. _schedules[operationId].nonce = nonce;
  573. emit OperationScheduled(operationId, nonce, when, caller, target, data);
  574. // Using named return values because otherwise we get stack too deep
  575. }
  576. /**
  577. * @dev Reverts if the operation is currently scheduled and has not expired.
  578. * (Note: This function was introduced due to stack too deep errors in schedule.)
  579. */
  580. function _checkNotScheduled(bytes32 operationId) private view {
  581. uint48 prevTimepoint = _schedules[operationId].timepoint;
  582. if (prevTimepoint != 0 && !_isExpired(prevTimepoint)) {
  583. revert AccessManagerAlreadyScheduled(operationId);
  584. }
  585. }
  586. /**
  587. * @dev Execute a function that is delay restricted, provided it was properly scheduled beforehand, or the
  588. * execution delay is 0.
  589. *
  590. * Returns the nonce that identifies the previously scheduled operation that is executed, or 0 if the
  591. * operation wasn't previously scheduled (if the caller doesn't have an execution delay).
  592. *
  593. * Emits an {OperationExecuted} event only if the call was scheduled and delayed.
  594. */
  595. // Reentrancy is not an issue because permissions are checked on msg.sender. Additionally,
  596. // _consumeScheduledOp guarantees a scheduled operation is only executed once.
  597. // slither-disable-next-line reentrancy-no-eth
  598. function execute(address target, bytes calldata data) public payable virtual returns (uint32) {
  599. address caller = _msgSender();
  600. // Fetch restrictions that apply to the caller on the targeted function
  601. (bool immediate, uint32 setback) = _canCallExtended(caller, target, data);
  602. // If call is not authorized, revert
  603. if (!immediate && setback == 0) {
  604. revert AccessManagerUnauthorizedCall(caller, target, _checkSelector(data));
  605. }
  606. bytes32 operationId = hashOperation(caller, target, data);
  607. uint32 nonce;
  608. // If caller is authorised, check operation was scheduled early enough
  609. // Consume an available schedule even if there is no currently enforced delay
  610. if (setback != 0 || getSchedule(operationId) != 0) {
  611. nonce = _consumeScheduledOp(operationId);
  612. }
  613. // Mark the target and selector as authorised
  614. bytes32 executionIdBefore = _executionId;
  615. _executionId = _hashExecutionId(target, _checkSelector(data));
  616. // Perform call
  617. Address.functionCallWithValue(target, data, msg.value);
  618. // Reset execute identifier
  619. _executionId = executionIdBefore;
  620. return nonce;
  621. }
  622. /**
  623. * @dev Consume a scheduled operation targeting the caller. If such an operation exists, mark it as consumed
  624. * (emit an {OperationExecuted} event and clean the state). Otherwise, throw an error.
  625. *
  626. * This is useful for contract that want to enforce that calls targeting them were scheduled on the manager,
  627. * with all the verifications that it implies.
  628. *
  629. * Emit a {OperationExecuted} event.
  630. */
  631. function consumeScheduledOp(address caller, bytes calldata data) public virtual {
  632. address target = _msgSender();
  633. if (IAccessManaged(target).isConsumingScheduledOp() != IAccessManaged.isConsumingScheduledOp.selector) {
  634. revert AccessManagerUnauthorizedConsume(target);
  635. }
  636. _consumeScheduledOp(hashOperation(caller, target, data));
  637. }
  638. /**
  639. * @dev Internal variant of {consumeScheduledOp} that operates on bytes32 operationId.
  640. *
  641. * Returns the nonce of the scheduled operation that is consumed.
  642. */
  643. function _consumeScheduledOp(bytes32 operationId) internal virtual returns (uint32) {
  644. uint48 timepoint = _schedules[operationId].timepoint;
  645. uint32 nonce = _schedules[operationId].nonce;
  646. if (timepoint == 0) {
  647. revert AccessManagerNotScheduled(operationId);
  648. } else if (timepoint > Time.timestamp()) {
  649. revert AccessManagerNotReady(operationId);
  650. } else if (_isExpired(timepoint)) {
  651. revert AccessManagerExpired(operationId);
  652. }
  653. delete _schedules[operationId].timepoint; // reset the timepoint, keep the nonce
  654. emit OperationExecuted(operationId, nonce);
  655. return nonce;
  656. }
  657. /**
  658. * @dev Cancel a scheduled (delayed) operation. Returns the nonce that identifies the previously scheduled
  659. * operation that is cancelled.
  660. *
  661. * Requirements:
  662. *
  663. * - the caller must be the proposer, a guardian of the targeted function, or a global admin
  664. *
  665. * Emits a {OperationCanceled} event.
  666. */
  667. function cancel(address caller, address target, bytes calldata data) public virtual returns (uint32) {
  668. address msgsender = _msgSender();
  669. bytes4 selector = _checkSelector(data);
  670. bytes32 operationId = hashOperation(caller, target, data);
  671. if (_schedules[operationId].timepoint == 0) {
  672. revert AccessManagerNotScheduled(operationId);
  673. } else if (caller != msgsender) {
  674. // calls can only be canceled by the account that scheduled them, a global admin, or by a guardian of the required role.
  675. (bool isAdmin, ) = hasRole(ADMIN_ROLE, msgsender);
  676. (bool isGuardian, ) = hasRole(getRoleGuardian(getTargetFunctionRole(target, selector)), msgsender);
  677. if (!isAdmin && !isGuardian) {
  678. revert AccessManagerUnauthorizedCancel(msgsender, caller, target, selector);
  679. }
  680. }
  681. delete _schedules[operationId].timepoint; // reset the timepoint, keep the nonce
  682. uint32 nonce = _schedules[operationId].nonce;
  683. emit OperationCanceled(operationId, nonce);
  684. return nonce;
  685. }
  686. /**
  687. * @dev Hashing function for delayed operations
  688. */
  689. function hashOperation(address caller, address target, bytes calldata data) public view virtual returns (bytes32) {
  690. return keccak256(abi.encode(caller, target, data));
  691. }
  692. /**
  693. * @dev Hashing function for execute protection
  694. */
  695. function _hashExecutionId(address target, bytes4 selector) private pure returns (bytes32) {
  696. return keccak256(abi.encode(target, selector));
  697. }
  698. // ==================================================== OTHERS ====================================================
  699. /**
  700. * @dev Change the AccessManager instance used by a contract that correctly uses this instance.
  701. *
  702. * Requirements:
  703. *
  704. * - the caller must be a global admin
  705. */
  706. function updateAuthority(address target, address newAuthority) public virtual onlyAuthorized {
  707. IAccessManaged(target).setAuthority(newAuthority);
  708. }
  709. // ================================================= ADMIN LOGIC ==================================================
  710. /**
  711. * @dev Check if the current call is authorized according to admin logic.
  712. */
  713. function _checkAuthorized() private {
  714. address caller = _msgSender();
  715. (bool immediate, uint32 delay) = _canCallSelf(caller, _msgData());
  716. if (!immediate) {
  717. if (delay == 0) {
  718. (, uint64 requiredRole, ) = _getAdminRestrictions(_msgData());
  719. revert AccessManagerUnauthorizedAccount(caller, requiredRole);
  720. } else {
  721. _consumeScheduledOp(hashOperation(caller, address(this), _msgData()));
  722. }
  723. }
  724. }
  725. /**
  726. * @dev Get the admin restrictions of a given function call based on the function and arguments involved.
  727. *
  728. * Returns:
  729. * - bool restricted: does this data match a restricted operation
  730. * - uint64: which role is this operation restricted to
  731. * - uint32: minimum delay to enforce for that operation (max between operation's delay and admin's execution delay)
  732. */
  733. function _getAdminRestrictions(
  734. bytes calldata data
  735. ) private view returns (bool restricted, uint64 roleAdminId, uint32 executionDelay) {
  736. if (data.length < 4) {
  737. return (false, 0, 0);
  738. }
  739. bytes4 selector = _checkSelector(data);
  740. // Restricted to ADMIN with no delay beside any execution delay the caller may have
  741. if (
  742. selector == this.labelRole.selector ||
  743. selector == this.setRoleAdmin.selector ||
  744. selector == this.setRoleGuardian.selector ||
  745. selector == this.setGrantDelay.selector ||
  746. selector == this.setTargetAdminDelay.selector
  747. ) {
  748. return (true, ADMIN_ROLE, 0);
  749. }
  750. // Restricted to ADMIN with the admin delay corresponding to the target
  751. if (
  752. selector == this.updateAuthority.selector ||
  753. selector == this.setTargetClosed.selector ||
  754. selector == this.setTargetFunctionRole.selector
  755. ) {
  756. // First argument is a target.
  757. address target = abi.decode(data[0x04:0x24], (address));
  758. uint32 delay = getTargetAdminDelay(target);
  759. return (true, ADMIN_ROLE, delay);
  760. }
  761. // Restricted to that role's admin with no delay beside any execution delay the caller may have.
  762. if (selector == this.grantRole.selector || selector == this.revokeRole.selector) {
  763. // First argument is a roleId.
  764. uint64 roleId = abi.decode(data[0x04:0x24], (uint64));
  765. return (true, getRoleAdmin(roleId), 0);
  766. }
  767. return (false, 0, 0);
  768. }
  769. // =================================================== HELPERS ====================================================
  770. /**
  771. * @dev An extended version of {canCall} for internal usage that checks {_canCallSelf}
  772. * when the target is this contract.
  773. *
  774. * Returns:
  775. * - bool immediate: whether the operation can be executed immediately (with no delay)
  776. * - uint32 delay: the execution delay
  777. */
  778. function _canCallExtended(
  779. address caller,
  780. address target,
  781. bytes calldata data
  782. ) private view returns (bool immediate, uint32 delay) {
  783. if (target == address(this)) {
  784. return _canCallSelf(caller, data);
  785. } else {
  786. return data.length < 4 ? (false, 0) : canCall(caller, target, _checkSelector(data));
  787. }
  788. }
  789. /**
  790. * @dev A version of {canCall} that checks for admin restrictions in this contract.
  791. */
  792. function _canCallSelf(address caller, bytes calldata data) private view returns (bool immediate, uint32 delay) {
  793. if (data.length < 4) {
  794. return (false, 0);
  795. }
  796. if (caller == address(this)) {
  797. // Caller is AccessManager, this means the call was sent through {execute} and it already checked
  798. // permissions. We verify that the call "identifier", which is set during {execute}, is correct.
  799. return (_isExecuting(address(this), _checkSelector(data)), 0);
  800. }
  801. (bool enabled, uint64 roleId, uint32 operationDelay) = _getAdminRestrictions(data);
  802. if (!enabled) {
  803. return (false, 0);
  804. }
  805. (bool inRole, uint32 executionDelay) = hasRole(roleId, caller);
  806. if (!inRole) {
  807. return (false, 0);
  808. }
  809. // downcast is safe because both options are uint32
  810. delay = uint32(Math.max(operationDelay, executionDelay));
  811. return (delay == 0, delay);
  812. }
  813. /**
  814. * @dev Returns true if a call with `target` and `selector` is being executed via {executed}.
  815. */
  816. function _isExecuting(address target, bytes4 selector) private view returns (bool) {
  817. return _executionId == _hashExecutionId(target, selector);
  818. }
  819. /**
  820. * @dev Returns true if a schedule timepoint is past its expiration deadline.
  821. */
  822. function _isExpired(uint48 timepoint) private view returns (bool) {
  823. return timepoint + expiration() <= Time.timestamp();
  824. }
  825. /**
  826. * @dev Extracts the selector from calldata. Panics if data is not at least 4 bytes
  827. */
  828. function _checkSelector(bytes calldata data) private pure returns (bytes4) {
  829. return bytes4(data[0:4]);
  830. }
  831. }