AccessManager.sol 36 KB

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