AccessManager.sol 35 KB

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