AccessManager.sol 29 KB

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