AccessManager.sol 36 KB

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