AccessManager.sol 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.1.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. import {Hashes} from "../../utils/cryptography/Hashes.sol";
  12. /**
  13. * @dev AccessManager is a central contract to store the permissions of a system.
  14. *
  15. * A smart contract under the control of an AccessManager instance is known as a target, and will inherit from the
  16. * {AccessManaged} contract, be connected to this contract as its manager and implement the {AccessManaged-restricted}
  17. * modifier on a set of functions selected to be permissioned. Note that any function without this setup won't be
  18. * effectively restricted.
  19. *
  20. * The restriction rules for such functions are defined in terms of "roles" identified by an `uint64` and scoped
  21. * by target (`address`) and function selectors (`bytes4`). These roles are stored in this contract and can be
  22. * configured by admins (`ADMIN_ROLE` members) after a delay (see {getTargetAdminDelay}).
  23. *
  24. * For each target contract, admins can configure the following without any delay:
  25. *
  26. * * The target's {AccessManaged-authority} via {updateAuthority}.
  27. * * Close or open a target via {setTargetClosed} keeping the permissions intact.
  28. * * The roles that are allowed (or disallowed) to call a given function (identified by its selector) through {setTargetFunctionRole}.
  29. *
  30. * By default every address is member of the `PUBLIC_ROLE` and every target function is restricted to the `ADMIN_ROLE` until configured otherwise.
  31. * Additionally, each role has the following configuration options restricted to this manager's admins:
  32. *
  33. * * A role's admin role via {setRoleAdmin} who can grant or revoke roles.
  34. * * A role's guardian role via {setRoleGuardian} who's allowed to cancel operations.
  35. * * A delay in which a role takes effect after being granted through {setGrantDelay}.
  36. * * A delay of any target's admin action via {setTargetAdminDelay}.
  37. * * A role label for discoverability purposes with {labelRole}.
  38. *
  39. * Any account can be added and removed into any number of these roles by using the {grantRole} and {revokeRole} functions
  40. * restricted to each role's admin (see {getRoleAdmin}).
  41. *
  42. * Since all the permissions of the managed system can be modified by the admins of this instance, it is expected that
  43. * they will be highly secured (e.g., a multisig or a well-configured DAO).
  44. *
  45. * NOTE: This contract implements a form of the {IAuthority} interface, but {canCall} has additional return data so it
  46. * doesn't inherit `IAuthority`. It is however compatible with the `IAuthority` interface since the first 32 bytes of
  47. * the return data are a boolean as expected by that interface.
  48. *
  49. * NOTE: Systems that implement other access control mechanisms (for example using {Ownable}) can be paired with an
  50. * {AccessManager} by transferring permissions (ownership in the case of {Ownable}) directly to the {AccessManager}.
  51. * Users will be able to interact with these contracts through the {execute} function, following the access rules
  52. * registered in the {AccessManager}. Keep in mind that in that context, the msg.sender seen by restricted functions
  53. * will be {AccessManager} itself.
  54. *
  55. * WARNING: When granting permissions over an {Ownable} or {AccessControl} contract to an {AccessManager}, be very
  56. * mindful of the danger associated with functions such as {Ownable-renounceOwnership} or
  57. * {AccessControl-renounceRole}.
  58. */
  59. contract AccessManager is Context, Multicall, IAccessManager {
  60. using Time for *;
  61. // Structure that stores the details for a target contract.
  62. struct TargetConfig {
  63. mapping(bytes4 selector => uint64 roleId) allowedRoles;
  64. Time.Delay adminDelay;
  65. bool closed;
  66. }
  67. // Structure that stores the details for a role/account pair. This structures fit into a single slot.
  68. struct Access {
  69. // Timepoint at which the user gets the permission.
  70. // If this is either 0 or in the future, then the role permission is not available.
  71. uint48 since;
  72. // Delay for execution. Only applies to restricted() / execute() calls.
  73. Time.Delay delay;
  74. }
  75. // Structure that stores the details of a role.
  76. struct Role {
  77. // Members of the role.
  78. mapping(address user => Access access) members;
  79. // Admin who can grant or revoke permissions.
  80. uint64 admin;
  81. // Guardian who can cancel operations targeting functions that need this role.
  82. uint64 guardian;
  83. // Delay in which the role takes effect after being granted.
  84. Time.Delay grantDelay;
  85. }
  86. // Structure that stores the details for a scheduled operation. This structure fits into a single slot.
  87. struct Schedule {
  88. // Moment at which the operation can be executed.
  89. uint48 timepoint;
  90. // Operation nonce to allow third-party contracts to identify the operation.
  91. uint32 nonce;
  92. }
  93. /**
  94. * @dev The identifier of the admin role. Required to perform most configuration operations including
  95. * other roles' management and target restrictions.
  96. */
  97. uint64 public constant ADMIN_ROLE = type(uint64).min; // 0
  98. /**
  99. * @dev The identifier of the public role. Automatically granted to all addresses with no delay.
  100. */
  101. uint64 public constant PUBLIC_ROLE = type(uint64).max; // 2**64-1
  102. mapping(address target => TargetConfig mode) private _targets;
  103. mapping(uint64 roleId => Role) private _roles;
  104. mapping(bytes32 operationId => Schedule) private _schedules;
  105. // Used to identify operations that are currently being executed via {execute}.
  106. // This should be transient storage when supported by the EVM.
  107. bytes32 private _executionId;
  108. /**
  109. * @dev Check that the caller is authorized to perform the operation.
  110. * See {AccessManager} description for a detailed breakdown of the authorization logic.
  111. */
  112. modifier onlyAuthorized() {
  113. _checkAuthorized();
  114. _;
  115. }
  116. constructor(address initialAdmin) {
  117. if (initialAdmin == address(0)) {
  118. revert AccessManagerInvalidInitialAdmin(address(0));
  119. }
  120. // admin is active immediately and without any execution delay.
  121. _grantRole(ADMIN_ROLE, initialAdmin, 0, 0);
  122. }
  123. // =================================================== GETTERS ====================================================
  124. /// @inheritdoc IAccessManager
  125. function canCall(
  126. address caller,
  127. address target,
  128. bytes4 selector
  129. ) public view virtual returns (bool immediate, uint32 delay) {
  130. if (isTargetClosed(target)) {
  131. return (false, 0);
  132. } else if (caller == address(this)) {
  133. // Caller is AccessManager, this means the call was sent through {execute} and it already checked
  134. // permissions. We verify that the call "identifier", which is set during {execute}, is correct.
  135. return (_isExecuting(target, selector), 0);
  136. } else {
  137. uint64 roleId = getTargetFunctionRole(target, selector);
  138. (bool isMember, uint32 currentDelay) = hasRole(roleId, caller);
  139. return isMember ? (currentDelay == 0, currentDelay) : (false, 0);
  140. }
  141. }
  142. /// @inheritdoc IAccessManager
  143. function expiration() public view virtual returns (uint32) {
  144. return 1 weeks;
  145. }
  146. /// @inheritdoc IAccessManager
  147. function minSetback() public view virtual returns (uint32) {
  148. return 5 days;
  149. }
  150. /// @inheritdoc IAccessManager
  151. function isTargetClosed(address target) public view virtual returns (bool) {
  152. return _targets[target].closed;
  153. }
  154. /// @inheritdoc IAccessManager
  155. function getTargetFunctionRole(address target, bytes4 selector) public view virtual returns (uint64) {
  156. return _targets[target].allowedRoles[selector];
  157. }
  158. /// @inheritdoc IAccessManager
  159. function getTargetAdminDelay(address target) public view virtual returns (uint32) {
  160. return _targets[target].adminDelay.get();
  161. }
  162. /// @inheritdoc IAccessManager
  163. function getRoleAdmin(uint64 roleId) public view virtual returns (uint64) {
  164. return _roles[roleId].admin;
  165. }
  166. /// @inheritdoc IAccessManager
  167. function getRoleGuardian(uint64 roleId) public view virtual returns (uint64) {
  168. return _roles[roleId].guardian;
  169. }
  170. /// @inheritdoc IAccessManager
  171. function getRoleGrantDelay(uint64 roleId) public view virtual returns (uint32) {
  172. return _roles[roleId].grantDelay.get();
  173. }
  174. /// @inheritdoc IAccessManager
  175. function getAccess(
  176. uint64 roleId,
  177. address account
  178. ) public view virtual returns (uint48 since, uint32 currentDelay, uint32 pendingDelay, uint48 effect) {
  179. Access storage access = _roles[roleId].members[account];
  180. since = access.since;
  181. (currentDelay, pendingDelay, effect) = access.delay.getFull();
  182. return (since, currentDelay, pendingDelay, effect);
  183. }
  184. /// @inheritdoc IAccessManager
  185. function hasRole(
  186. uint64 roleId,
  187. address account
  188. ) public view virtual returns (bool isMember, uint32 executionDelay) {
  189. if (roleId == PUBLIC_ROLE) {
  190. return (true, 0);
  191. } else {
  192. (uint48 hasRoleSince, uint32 currentDelay, , ) = getAccess(roleId, account);
  193. return (hasRoleSince != 0 && hasRoleSince <= Time.timestamp(), currentDelay);
  194. }
  195. }
  196. // =============================================== ROLE MANAGEMENT ===============================================
  197. /// @inheritdoc IAccessManager
  198. function labelRole(uint64 roleId, string calldata label) public virtual onlyAuthorized {
  199. if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
  200. revert AccessManagerLockedRole(roleId);
  201. }
  202. emit RoleLabel(roleId, label);
  203. }
  204. /// @inheritdoc IAccessManager
  205. function grantRole(uint64 roleId, address account, uint32 executionDelay) public virtual onlyAuthorized {
  206. _grantRole(roleId, account, getRoleGrantDelay(roleId), executionDelay);
  207. }
  208. /// @inheritdoc IAccessManager
  209. function revokeRole(uint64 roleId, address account) public virtual onlyAuthorized {
  210. _revokeRole(roleId, account);
  211. }
  212. /// @inheritdoc IAccessManager
  213. function renounceRole(uint64 roleId, address callerConfirmation) public virtual {
  214. if (callerConfirmation != _msgSender()) {
  215. revert AccessManagerBadConfirmation();
  216. }
  217. _revokeRole(roleId, callerConfirmation);
  218. }
  219. /// @inheritdoc IAccessManager
  220. function setRoleAdmin(uint64 roleId, uint64 admin) public virtual onlyAuthorized {
  221. _setRoleAdmin(roleId, admin);
  222. }
  223. /// @inheritdoc IAccessManager
  224. function setRoleGuardian(uint64 roleId, uint64 guardian) public virtual onlyAuthorized {
  225. _setRoleGuardian(roleId, guardian);
  226. }
  227. /// @inheritdoc IAccessManager
  228. function setGrantDelay(uint64 roleId, uint32 newDelay) public virtual onlyAuthorized {
  229. _setGrantDelay(roleId, newDelay);
  230. }
  231. /**
  232. * @dev Internal version of {grantRole} without access control. Returns true if the role was newly granted.
  233. *
  234. * Emits a {RoleGranted} event.
  235. */
  236. function _grantRole(
  237. uint64 roleId,
  238. address account,
  239. uint32 grantDelay,
  240. uint32 executionDelay
  241. ) internal virtual returns (bool) {
  242. if (roleId == PUBLIC_ROLE) {
  243. revert AccessManagerLockedRole(roleId);
  244. }
  245. bool newMember = _roles[roleId].members[account].since == 0;
  246. uint48 since;
  247. if (newMember) {
  248. since = Time.timestamp() + grantDelay;
  249. _roles[roleId].members[account] = Access({since: since, delay: executionDelay.toDelay()});
  250. } else {
  251. // No setback here. Value can be reset by doing revoke + grant, effectively allowing the admin to perform
  252. // any change to the execution delay within the duration of the role admin delay.
  253. (_roles[roleId].members[account].delay, since) = _roles[roleId].members[account].delay.withUpdate(
  254. executionDelay,
  255. 0
  256. );
  257. }
  258. emit RoleGranted(roleId, account, executionDelay, since, newMember);
  259. return newMember;
  260. }
  261. /**
  262. * @dev Internal version of {revokeRole} without access control. This logic is also used by {renounceRole}.
  263. * Returns true if the role was previously granted.
  264. *
  265. * Emits a {RoleRevoked} event if the account had the role.
  266. */
  267. function _revokeRole(uint64 roleId, address account) internal virtual returns (bool) {
  268. if (roleId == PUBLIC_ROLE) {
  269. revert AccessManagerLockedRole(roleId);
  270. }
  271. if (_roles[roleId].members[account].since == 0) {
  272. return false;
  273. }
  274. delete _roles[roleId].members[account];
  275. emit RoleRevoked(roleId, account);
  276. return true;
  277. }
  278. /**
  279. * @dev Internal version of {setRoleAdmin} without access control.
  280. *
  281. * Emits a {RoleAdminChanged} event.
  282. *
  283. * NOTE: Setting the admin role as the `PUBLIC_ROLE` is allowed, but it will effectively allow
  284. * anyone to set grant or revoke such role.
  285. */
  286. function _setRoleAdmin(uint64 roleId, uint64 admin) internal virtual {
  287. if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
  288. revert AccessManagerLockedRole(roleId);
  289. }
  290. _roles[roleId].admin = admin;
  291. emit RoleAdminChanged(roleId, admin);
  292. }
  293. /**
  294. * @dev Internal version of {setRoleGuardian} without access control.
  295. *
  296. * Emits a {RoleGuardianChanged} event.
  297. *
  298. * NOTE: Setting the guardian role as the `PUBLIC_ROLE` is allowed, but it will effectively allow
  299. * anyone to cancel any scheduled operation for such role.
  300. */
  301. function _setRoleGuardian(uint64 roleId, uint64 guardian) internal virtual {
  302. if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
  303. revert AccessManagerLockedRole(roleId);
  304. }
  305. _roles[roleId].guardian = guardian;
  306. emit RoleGuardianChanged(roleId, guardian);
  307. }
  308. /**
  309. * @dev Internal version of {setGrantDelay} without access control.
  310. *
  311. * Emits a {RoleGrantDelayChanged} event.
  312. */
  313. function _setGrantDelay(uint64 roleId, uint32 newDelay) internal virtual {
  314. if (roleId == PUBLIC_ROLE) {
  315. revert AccessManagerLockedRole(roleId);
  316. }
  317. uint48 effect;
  318. (_roles[roleId].grantDelay, effect) = _roles[roleId].grantDelay.withUpdate(newDelay, minSetback());
  319. emit RoleGrantDelayChanged(roleId, newDelay, effect);
  320. }
  321. // ============================================= FUNCTION MANAGEMENT ==============================================
  322. /// @inheritdoc IAccessManager
  323. function setTargetFunctionRole(
  324. address target,
  325. bytes4[] calldata selectors,
  326. uint64 roleId
  327. ) public virtual onlyAuthorized {
  328. for (uint256 i = 0; i < selectors.length; ++i) {
  329. _setTargetFunctionRole(target, selectors[i], roleId);
  330. }
  331. }
  332. /**
  333. * @dev Internal version of {setTargetFunctionRole} without access control.
  334. *
  335. * Emits a {TargetFunctionRoleUpdated} event.
  336. */
  337. function _setTargetFunctionRole(address target, bytes4 selector, uint64 roleId) internal virtual {
  338. _targets[target].allowedRoles[selector] = roleId;
  339. emit TargetFunctionRoleUpdated(target, selector, roleId);
  340. }
  341. /// @inheritdoc IAccessManager
  342. function setTargetAdminDelay(address target, uint32 newDelay) public virtual onlyAuthorized {
  343. _setTargetAdminDelay(target, newDelay);
  344. }
  345. /**
  346. * @dev Internal version of {setTargetAdminDelay} without access control.
  347. *
  348. * Emits a {TargetAdminDelayUpdated} event.
  349. */
  350. function _setTargetAdminDelay(address target, uint32 newDelay) internal virtual {
  351. uint48 effect;
  352. (_targets[target].adminDelay, effect) = _targets[target].adminDelay.withUpdate(newDelay, minSetback());
  353. emit TargetAdminDelayUpdated(target, newDelay, effect);
  354. }
  355. // =============================================== MODE MANAGEMENT ================================================
  356. /// @inheritdoc IAccessManager
  357. function setTargetClosed(address target, bool closed) public virtual onlyAuthorized {
  358. _setTargetClosed(target, closed);
  359. }
  360. /**
  361. * @dev Set the closed flag for a contract. This is an internal setter with no access restrictions.
  362. *
  363. * Emits a {TargetClosed} event.
  364. */
  365. function _setTargetClosed(address target, bool closed) internal virtual {
  366. _targets[target].closed = closed;
  367. emit TargetClosed(target, closed);
  368. }
  369. // ============================================== DELAYED OPERATIONS ==============================================
  370. /// @inheritdoc IAccessManager
  371. function getSchedule(bytes32 id) public view virtual returns (uint48) {
  372. uint48 timepoint = _schedules[id].timepoint;
  373. return _isExpired(timepoint) ? 0 : timepoint;
  374. }
  375. /// @inheritdoc IAccessManager
  376. function getNonce(bytes32 id) public view virtual returns (uint32) {
  377. return _schedules[id].nonce;
  378. }
  379. /// @inheritdoc IAccessManager
  380. function schedule(
  381. address target,
  382. bytes calldata data,
  383. uint48 when
  384. ) public virtual returns (bytes32 operationId, uint32 nonce) {
  385. address caller = _msgSender();
  386. // Fetch restrictions that apply to the caller on the targeted function
  387. (, uint32 setback) = _canCallExtended(caller, target, data);
  388. uint48 minWhen = Time.timestamp() + setback;
  389. // If call with delay is not authorized, or if requested timing is too soon, revert
  390. if (setback == 0 || (when > 0 && when < minWhen)) {
  391. revert AccessManagerUnauthorizedCall(caller, target, _checkSelector(data));
  392. }
  393. // Reuse variable due to stack too deep
  394. when = uint48(Math.max(when, minWhen)); // cast is safe: both inputs are uint48
  395. // If caller is authorised, schedule operation
  396. operationId = hashOperation(caller, target, data);
  397. _checkNotScheduled(operationId);
  398. unchecked {
  399. // It's not feasible to overflow the nonce in less than 1000 years
  400. nonce = _schedules[operationId].nonce + 1;
  401. }
  402. _schedules[operationId].timepoint = when;
  403. _schedules[operationId].nonce = nonce;
  404. emit OperationScheduled(operationId, nonce, when, caller, target, data);
  405. // Using named return values because otherwise we get stack too deep
  406. }
  407. /**
  408. * @dev Reverts if the operation is currently scheduled and has not expired.
  409. *
  410. * NOTE: This function was introduced due to stack too deep errors in schedule.
  411. */
  412. function _checkNotScheduled(bytes32 operationId) private view {
  413. uint48 prevTimepoint = _schedules[operationId].timepoint;
  414. if (prevTimepoint != 0 && !_isExpired(prevTimepoint)) {
  415. revert AccessManagerAlreadyScheduled(operationId);
  416. }
  417. }
  418. /// @inheritdoc IAccessManager
  419. // Reentrancy is not an issue because permissions are checked on msg.sender. Additionally,
  420. // _consumeScheduledOp guarantees a scheduled operation is only executed once.
  421. // slither-disable-next-line reentrancy-no-eth
  422. function execute(address target, bytes calldata data) public payable virtual returns (uint32) {
  423. address caller = _msgSender();
  424. // Fetch restrictions that apply to the caller on the targeted function
  425. (bool immediate, uint32 setback) = _canCallExtended(caller, target, data);
  426. // If call is not authorized, revert
  427. if (!immediate && setback == 0) {
  428. revert AccessManagerUnauthorizedCall(caller, target, _checkSelector(data));
  429. }
  430. bytes32 operationId = hashOperation(caller, target, data);
  431. uint32 nonce;
  432. // If caller is authorised, check operation was scheduled early enough
  433. // Consume an available schedule even if there is no currently enforced delay
  434. if (setback != 0 || getSchedule(operationId) != 0) {
  435. nonce = _consumeScheduledOp(operationId);
  436. }
  437. // Mark the target and selector as authorised
  438. bytes32 executionIdBefore = _executionId;
  439. _executionId = _hashExecutionId(target, _checkSelector(data));
  440. // Perform call
  441. Address.functionCallWithValue(target, data, msg.value);
  442. // Reset execute identifier
  443. _executionId = executionIdBefore;
  444. return nonce;
  445. }
  446. /// @inheritdoc IAccessManager
  447. function cancel(address caller, address target, bytes calldata data) public virtual returns (uint32) {
  448. address msgsender = _msgSender();
  449. bytes4 selector = _checkSelector(data);
  450. bytes32 operationId = hashOperation(caller, target, data);
  451. if (_schedules[operationId].timepoint == 0) {
  452. revert AccessManagerNotScheduled(operationId);
  453. } else if (caller != msgsender) {
  454. // calls can only be canceled by the account that scheduled them, a global admin, or by a guardian of the required role.
  455. (bool isAdmin, ) = hasRole(ADMIN_ROLE, msgsender);
  456. (bool isGuardian, ) = hasRole(getRoleGuardian(getTargetFunctionRole(target, selector)), msgsender);
  457. if (!isAdmin && !isGuardian) {
  458. revert AccessManagerUnauthorizedCancel(msgsender, caller, target, selector);
  459. }
  460. }
  461. delete _schedules[operationId].timepoint; // reset the timepoint, keep the nonce
  462. uint32 nonce = _schedules[operationId].nonce;
  463. emit OperationCanceled(operationId, nonce);
  464. return nonce;
  465. }
  466. /// @inheritdoc IAccessManager
  467. function consumeScheduledOp(address caller, bytes calldata data) public virtual {
  468. address target = _msgSender();
  469. if (IAccessManaged(target).isConsumingScheduledOp() != IAccessManaged.isConsumingScheduledOp.selector) {
  470. revert AccessManagerUnauthorizedConsume(target);
  471. }
  472. _consumeScheduledOp(hashOperation(caller, target, data));
  473. }
  474. /**
  475. * @dev Internal variant of {consumeScheduledOp} that operates on bytes32 operationId.
  476. *
  477. * Returns the nonce of the scheduled operation that is consumed.
  478. */
  479. function _consumeScheduledOp(bytes32 operationId) internal virtual returns (uint32) {
  480. uint48 timepoint = _schedules[operationId].timepoint;
  481. uint32 nonce = _schedules[operationId].nonce;
  482. if (timepoint == 0) {
  483. revert AccessManagerNotScheduled(operationId);
  484. } else if (timepoint > Time.timestamp()) {
  485. revert AccessManagerNotReady(operationId);
  486. } else if (_isExpired(timepoint)) {
  487. revert AccessManagerExpired(operationId);
  488. }
  489. delete _schedules[operationId].timepoint; // reset the timepoint, keep the nonce
  490. emit OperationExecuted(operationId, nonce);
  491. return nonce;
  492. }
  493. /// @inheritdoc IAccessManager
  494. function hashOperation(address caller, address target, bytes calldata data) public view virtual returns (bytes32) {
  495. return keccak256(abi.encode(caller, target, data));
  496. }
  497. // ==================================================== OTHERS ====================================================
  498. /// @inheritdoc IAccessManager
  499. function updateAuthority(address target, address newAuthority) public virtual onlyAuthorized {
  500. IAccessManaged(target).setAuthority(newAuthority);
  501. }
  502. // ================================================= ADMIN LOGIC ==================================================
  503. /**
  504. * @dev Check if the current call is authorized according to admin and roles logic.
  505. *
  506. * WARNING: Carefully review the considerations of {AccessManaged-restricted} since they apply to this modifier.
  507. */
  508. function _checkAuthorized() private {
  509. address caller = _msgSender();
  510. (bool immediate, uint32 delay) = _canCallSelf(caller, _msgData());
  511. if (!immediate) {
  512. if (delay == 0) {
  513. (, uint64 requiredRole, ) = _getAdminRestrictions(_msgData());
  514. revert AccessManagerUnauthorizedAccount(caller, requiredRole);
  515. } else {
  516. _consumeScheduledOp(hashOperation(caller, address(this), _msgData()));
  517. }
  518. }
  519. }
  520. /**
  521. * @dev Get the admin restrictions of a given function call based on the function and arguments involved.
  522. *
  523. * Returns:
  524. * - bool restricted: does this data match a restricted operation
  525. * - uint64: which role is this operation restricted to
  526. * - uint32: minimum delay to enforce for that operation (max between operation's delay and admin's execution delay)
  527. */
  528. function _getAdminRestrictions(
  529. bytes calldata data
  530. ) private view returns (bool adminRestricted, uint64 roleAdminId, uint32 executionDelay) {
  531. if (data.length < 4) {
  532. return (false, 0, 0);
  533. }
  534. bytes4 selector = _checkSelector(data);
  535. // Restricted to ADMIN with no delay beside any execution delay the caller may have
  536. if (
  537. selector == this.labelRole.selector ||
  538. selector == this.setRoleAdmin.selector ||
  539. selector == this.setRoleGuardian.selector ||
  540. selector == this.setGrantDelay.selector ||
  541. selector == this.setTargetAdminDelay.selector
  542. ) {
  543. return (true, ADMIN_ROLE, 0);
  544. }
  545. // Restricted to ADMIN with the admin delay corresponding to the target
  546. if (
  547. selector == this.updateAuthority.selector ||
  548. selector == this.setTargetClosed.selector ||
  549. selector == this.setTargetFunctionRole.selector
  550. ) {
  551. // First argument is a target.
  552. address target = abi.decode(data[0x04:0x24], (address));
  553. uint32 delay = getTargetAdminDelay(target);
  554. return (true, ADMIN_ROLE, delay);
  555. }
  556. // Restricted to that role's admin with no delay beside any execution delay the caller may have.
  557. if (selector == this.grantRole.selector || selector == this.revokeRole.selector) {
  558. // First argument is a roleId.
  559. uint64 roleId = abi.decode(data[0x04:0x24], (uint64));
  560. return (true, getRoleAdmin(roleId), 0);
  561. }
  562. return (false, getTargetFunctionRole(address(this), selector), 0);
  563. }
  564. // =================================================== HELPERS ====================================================
  565. /**
  566. * @dev An extended version of {canCall} for internal usage that checks {_canCallSelf}
  567. * when the target is this contract.
  568. *
  569. * Returns:
  570. * - bool immediate: whether the operation can be executed immediately (with no delay)
  571. * - uint32 delay: the execution delay
  572. */
  573. function _canCallExtended(
  574. address caller,
  575. address target,
  576. bytes calldata data
  577. ) private view returns (bool immediate, uint32 delay) {
  578. if (target == address(this)) {
  579. return _canCallSelf(caller, data);
  580. } else {
  581. return data.length < 4 ? (false, 0) : canCall(caller, target, _checkSelector(data));
  582. }
  583. }
  584. /**
  585. * @dev A version of {canCall} that checks for restrictions in this contract.
  586. */
  587. function _canCallSelf(address caller, bytes calldata data) private view returns (bool immediate, uint32 delay) {
  588. if (data.length < 4) {
  589. return (false, 0);
  590. }
  591. if (caller == address(this)) {
  592. // Caller is AccessManager, this means the call was sent through {execute} and it already checked
  593. // permissions. We verify that the call "identifier", which is set during {execute}, is correct.
  594. return (_isExecuting(address(this), _checkSelector(data)), 0);
  595. }
  596. (bool adminRestricted, uint64 roleId, uint32 operationDelay) = _getAdminRestrictions(data);
  597. // isTargetClosed apply to non-admin-restricted function
  598. if (!adminRestricted && isTargetClosed(address(this))) {
  599. return (false, 0);
  600. }
  601. (bool inRole, uint32 executionDelay) = hasRole(roleId, caller);
  602. if (!inRole) {
  603. return (false, 0);
  604. }
  605. // downcast is safe because both options are uint32
  606. delay = uint32(Math.max(operationDelay, executionDelay));
  607. return (delay == 0, delay);
  608. }
  609. /**
  610. * @dev Returns true if a call with `target` and `selector` is being executed via {executed}.
  611. */
  612. function _isExecuting(address target, bytes4 selector) private view returns (bool) {
  613. return _executionId == _hashExecutionId(target, selector);
  614. }
  615. /**
  616. * @dev Returns true if a schedule timepoint is past its expiration deadline.
  617. */
  618. function _isExpired(uint48 timepoint) private view returns (bool) {
  619. return timepoint + expiration() <= Time.timestamp();
  620. }
  621. /**
  622. * @dev Extracts the selector from calldata. Panics if data is not at least 4 bytes
  623. */
  624. function _checkSelector(bytes calldata data) private pure returns (bytes4) {
  625. return bytes4(data[0:4]);
  626. }
  627. /**
  628. * @dev Hashing function for execute protection
  629. */
  630. function _hashExecutionId(address target, bytes4 selector) private pure returns (bytes32) {
  631. return Hashes.efficientKeccak256(bytes32(uint256(uint160(target))), selector);
  632. }
  633. }