AccessManager.sol 33 KB

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