AccessManager.sol 38 KB

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