AccessManager.sol 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.0.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. * 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. uint64 public constant ADMIN_ROLE = type(uint64).min; // 0
  93. uint64 public constant PUBLIC_ROLE = type(uint64).max; // 2**64-1
  94. mapping(address target => TargetConfig mode) private _targets;
  95. mapping(uint64 roleId => Role) private _roles;
  96. mapping(bytes32 operationId => Schedule) private _schedules;
  97. // Used to identify operations that are currently being executed via {execute}.
  98. // This should be transient storage when supported by the EVM.
  99. bytes32 private _executionId;
  100. /**
  101. * @dev Check that the caller is authorized to perform the operation, following the restrictions encoded in
  102. * {_getAdminRestrictions}.
  103. */
  104. modifier onlyAuthorized() {
  105. _checkAuthorized();
  106. _;
  107. }
  108. constructor(address initialAdmin) {
  109. if (initialAdmin == address(0)) {
  110. revert AccessManagerInvalidInitialAdmin(address(0));
  111. }
  112. // admin is active immediately and without any execution delay.
  113. _grantRole(ADMIN_ROLE, initialAdmin, 0, 0);
  114. }
  115. // =================================================== GETTERS ====================================================
  116. /// @inheritdoc IAccessManager
  117. function canCall(
  118. address caller,
  119. address target,
  120. bytes4 selector
  121. ) public view virtual returns (bool immediate, uint32 delay) {
  122. if (isTargetClosed(target)) {
  123. return (false, 0);
  124. } else if (caller == address(this)) {
  125. // Caller is AccessManager, this means the call was sent through {execute} and it already checked
  126. // permissions. We verify that the call "identifier", which is set during {execute}, is correct.
  127. return (_isExecuting(target, selector), 0);
  128. } else {
  129. uint64 roleId = getTargetFunctionRole(target, selector);
  130. (bool isMember, uint32 currentDelay) = hasRole(roleId, caller);
  131. return isMember ? (currentDelay == 0, currentDelay) : (false, 0);
  132. }
  133. }
  134. /// @inheritdoc IAccessManager
  135. function expiration() public view virtual returns (uint32) {
  136. return 1 weeks;
  137. }
  138. /// @inheritdoc IAccessManager
  139. function minSetback() public view virtual returns (uint32) {
  140. return 5 days;
  141. }
  142. /// @inheritdoc IAccessManager
  143. function isTargetClosed(address target) public view virtual returns (bool) {
  144. return _targets[target].closed;
  145. }
  146. /// @inheritdoc IAccessManager
  147. function getTargetFunctionRole(address target, bytes4 selector) public view virtual returns (uint64) {
  148. return _targets[target].allowedRoles[selector];
  149. }
  150. /// @inheritdoc IAccessManager
  151. function getTargetAdminDelay(address target) public view virtual returns (uint32) {
  152. return _targets[target].adminDelay.get();
  153. }
  154. /// @inheritdoc IAccessManager
  155. function getRoleAdmin(uint64 roleId) public view virtual returns (uint64) {
  156. return _roles[roleId].admin;
  157. }
  158. /// @inheritdoc IAccessManager
  159. function getRoleGuardian(uint64 roleId) public view virtual returns (uint64) {
  160. return _roles[roleId].guardian;
  161. }
  162. /// @inheritdoc IAccessManager
  163. function getRoleGrantDelay(uint64 roleId) public view virtual returns (uint32) {
  164. return _roles[roleId].grantDelay.get();
  165. }
  166. /// @inheritdoc IAccessManager
  167. function getAccess(
  168. uint64 roleId,
  169. address account
  170. ) public view virtual returns (uint48 since, uint32 currentDelay, uint32 pendingDelay, uint48 effect) {
  171. Access storage access = _roles[roleId].members[account];
  172. since = access.since;
  173. (currentDelay, pendingDelay, effect) = access.delay.getFull();
  174. return (since, currentDelay, pendingDelay, effect);
  175. }
  176. /// @inheritdoc IAccessManager
  177. function hasRole(
  178. uint64 roleId,
  179. address account
  180. ) public view virtual returns (bool isMember, uint32 executionDelay) {
  181. if (roleId == PUBLIC_ROLE) {
  182. return (true, 0);
  183. } else {
  184. (uint48 hasRoleSince, uint32 currentDelay, , ) = getAccess(roleId, account);
  185. return (hasRoleSince != 0 && hasRoleSince <= Time.timestamp(), currentDelay);
  186. }
  187. }
  188. // =============================================== ROLE MANAGEMENT ===============================================
  189. /// @inheritdoc IAccessManager
  190. function labelRole(uint64 roleId, string calldata label) public virtual onlyAuthorized {
  191. if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
  192. revert AccessManagerLockedRole(roleId);
  193. }
  194. emit RoleLabel(roleId, label);
  195. }
  196. /// @inheritdoc IAccessManager
  197. function grantRole(uint64 roleId, address account, uint32 executionDelay) public virtual onlyAuthorized {
  198. _grantRole(roleId, account, getRoleGrantDelay(roleId), executionDelay);
  199. }
  200. /// @inheritdoc IAccessManager
  201. function revokeRole(uint64 roleId, address account) public virtual onlyAuthorized {
  202. _revokeRole(roleId, account);
  203. }
  204. /// @inheritdoc IAccessManager
  205. function renounceRole(uint64 roleId, address callerConfirmation) public virtual {
  206. if (callerConfirmation != _msgSender()) {
  207. revert AccessManagerBadConfirmation();
  208. }
  209. _revokeRole(roleId, callerConfirmation);
  210. }
  211. /// @inheritdoc IAccessManager
  212. function setRoleAdmin(uint64 roleId, uint64 admin) public virtual onlyAuthorized {
  213. _setRoleAdmin(roleId, admin);
  214. }
  215. /// @inheritdoc IAccessManager
  216. function setRoleGuardian(uint64 roleId, uint64 guardian) public virtual onlyAuthorized {
  217. _setRoleGuardian(roleId, guardian);
  218. }
  219. /// @inheritdoc IAccessManager
  220. function setGrantDelay(uint64 roleId, uint32 newDelay) public virtual onlyAuthorized {
  221. _setGrantDelay(roleId, newDelay);
  222. }
  223. /**
  224. * @dev Internal version of {grantRole} without access control. Returns true if the role was newly granted.
  225. *
  226. * Emits a {RoleGranted} event.
  227. */
  228. function _grantRole(
  229. uint64 roleId,
  230. address account,
  231. uint32 grantDelay,
  232. uint32 executionDelay
  233. ) internal virtual returns (bool) {
  234. if (roleId == PUBLIC_ROLE) {
  235. revert AccessManagerLockedRole(roleId);
  236. }
  237. bool newMember = _roles[roleId].members[account].since == 0;
  238. uint48 since;
  239. if (newMember) {
  240. since = Time.timestamp() + grantDelay;
  241. _roles[roleId].members[account] = Access({since: since, delay: executionDelay.toDelay()});
  242. } else {
  243. // No setback here. Value can be reset by doing revoke + grant, effectively allowing the admin to perform
  244. // any change to the execution delay within the duration of the role admin delay.
  245. (_roles[roleId].members[account].delay, since) = _roles[roleId].members[account].delay.withUpdate(
  246. executionDelay,
  247. 0
  248. );
  249. }
  250. emit RoleGranted(roleId, account, executionDelay, since, newMember);
  251. return newMember;
  252. }
  253. /**
  254. * @dev Internal version of {revokeRole} without access control. This logic is also used by {renounceRole}.
  255. * Returns true if the role was previously granted.
  256. *
  257. * Emits a {RoleRevoked} event if the account had the role.
  258. */
  259. function _revokeRole(uint64 roleId, address account) internal virtual returns (bool) {
  260. if (roleId == PUBLIC_ROLE) {
  261. revert AccessManagerLockedRole(roleId);
  262. }
  263. if (_roles[roleId].members[account].since == 0) {
  264. return false;
  265. }
  266. delete _roles[roleId].members[account];
  267. emit RoleRevoked(roleId, account);
  268. return true;
  269. }
  270. /**
  271. * @dev Internal version of {setRoleAdmin} without access control.
  272. *
  273. * Emits a {RoleAdminChanged} event.
  274. *
  275. * NOTE: Setting the admin role as the `PUBLIC_ROLE` is allowed, but it will effectively allow
  276. * anyone to set grant or revoke such role.
  277. */
  278. function _setRoleAdmin(uint64 roleId, uint64 admin) internal virtual {
  279. if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
  280. revert AccessManagerLockedRole(roleId);
  281. }
  282. _roles[roleId].admin = admin;
  283. emit RoleAdminChanged(roleId, admin);
  284. }
  285. /**
  286. * @dev Internal version of {setRoleGuardian} without access control.
  287. *
  288. * Emits a {RoleGuardianChanged} event.
  289. *
  290. * NOTE: Setting the guardian role as the `PUBLIC_ROLE` is allowed, but it will effectively allow
  291. * anyone to cancel any scheduled operation for such role.
  292. */
  293. function _setRoleGuardian(uint64 roleId, uint64 guardian) internal virtual {
  294. if (roleId == ADMIN_ROLE || roleId == PUBLIC_ROLE) {
  295. revert AccessManagerLockedRole(roleId);
  296. }
  297. _roles[roleId].guardian = guardian;
  298. emit RoleGuardianChanged(roleId, guardian);
  299. }
  300. /**
  301. * @dev Internal version of {setGrantDelay} without access control.
  302. *
  303. * Emits a {RoleGrantDelayChanged} event.
  304. */
  305. function _setGrantDelay(uint64 roleId, uint32 newDelay) internal virtual {
  306. if (roleId == PUBLIC_ROLE) {
  307. revert AccessManagerLockedRole(roleId);
  308. }
  309. uint48 effect;
  310. (_roles[roleId].grantDelay, effect) = _roles[roleId].grantDelay.withUpdate(newDelay, minSetback());
  311. emit RoleGrantDelayChanged(roleId, newDelay, effect);
  312. }
  313. // ============================================= FUNCTION MANAGEMENT ==============================================
  314. /// @inheritdoc IAccessManager
  315. function setTargetFunctionRole(
  316. address target,
  317. bytes4[] calldata selectors,
  318. uint64 roleId
  319. ) public virtual onlyAuthorized {
  320. for (uint256 i = 0; i < selectors.length; ++i) {
  321. _setTargetFunctionRole(target, selectors[i], roleId);
  322. }
  323. }
  324. /**
  325. * @dev Internal version of {setTargetFunctionRole} without access control.
  326. *
  327. * Emits a {TargetFunctionRoleUpdated} event.
  328. */
  329. function _setTargetFunctionRole(address target, bytes4 selector, uint64 roleId) internal virtual {
  330. _targets[target].allowedRoles[selector] = roleId;
  331. emit TargetFunctionRoleUpdated(target, selector, roleId);
  332. }
  333. /// @inheritdoc IAccessManager
  334. function setTargetAdminDelay(address target, uint32 newDelay) public virtual onlyAuthorized {
  335. _setTargetAdminDelay(target, newDelay);
  336. }
  337. /**
  338. * @dev Internal version of {setTargetAdminDelay} without access control.
  339. *
  340. * Emits a {TargetAdminDelayUpdated} event.
  341. */
  342. function _setTargetAdminDelay(address target, uint32 newDelay) internal virtual {
  343. uint48 effect;
  344. (_targets[target].adminDelay, effect) = _targets[target].adminDelay.withUpdate(newDelay, minSetback());
  345. emit TargetAdminDelayUpdated(target, newDelay, effect);
  346. }
  347. // =============================================== MODE MANAGEMENT ================================================
  348. /// @inheritdoc IAccessManager
  349. function setTargetClosed(address target, bool closed) public virtual onlyAuthorized {
  350. _setTargetClosed(target, closed);
  351. }
  352. /**
  353. * @dev Set the closed flag for a contract. This is an internal setter with no access restrictions.
  354. *
  355. * Emits a {TargetClosed} event.
  356. */
  357. function _setTargetClosed(address target, bool closed) internal virtual {
  358. if (target == address(this)) {
  359. revert AccessManagerLockedAccount(target);
  360. }
  361. _targets[target].closed = closed;
  362. emit TargetClosed(target, closed);
  363. }
  364. // ============================================== DELAYED OPERATIONS ==============================================
  365. /// @inheritdoc IAccessManager
  366. function getSchedule(bytes32 id) public view virtual returns (uint48) {
  367. uint48 timepoint = _schedules[id].timepoint;
  368. return _isExpired(timepoint) ? 0 : timepoint;
  369. }
  370. /// @inheritdoc IAccessManager
  371. function getNonce(bytes32 id) public view virtual returns (uint32) {
  372. return _schedules[id].nonce;
  373. }
  374. /// @inheritdoc IAccessManager
  375. function schedule(
  376. address target,
  377. bytes calldata data,
  378. uint48 when
  379. ) public virtual returns (bytes32 operationId, uint32 nonce) {
  380. address caller = _msgSender();
  381. // Fetch restrictions that apply to the caller on the targeted function
  382. (, uint32 setback) = _canCallExtended(caller, target, data);
  383. uint48 minWhen = Time.timestamp() + setback;
  384. // if call with delay is not authorized, or if requested timing is too soon
  385. if (setback == 0 || (when > 0 && when < minWhen)) {
  386. revert AccessManagerUnauthorizedCall(caller, target, _checkSelector(data));
  387. }
  388. // Reuse variable due to stack too deep
  389. when = uint48(Math.max(when, minWhen)); // cast is safe: both inputs are uint48
  390. // If caller is authorised, schedule operation
  391. operationId = hashOperation(caller, target, data);
  392. _checkNotScheduled(operationId);
  393. unchecked {
  394. // It's not feasible to overflow the nonce in less than 1000 years
  395. nonce = _schedules[operationId].nonce + 1;
  396. }
  397. _schedules[operationId].timepoint = when;
  398. _schedules[operationId].nonce = nonce;
  399. emit OperationScheduled(operationId, nonce, when, caller, target, data);
  400. // Using named return values because otherwise we get stack too deep
  401. }
  402. /**
  403. * @dev Reverts if the operation is currently scheduled and has not expired.
  404. * (Note: This function was introduced due to stack too deep errors in schedule.)
  405. */
  406. function _checkNotScheduled(bytes32 operationId) private view {
  407. uint48 prevTimepoint = _schedules[operationId].timepoint;
  408. if (prevTimepoint != 0 && !_isExpired(prevTimepoint)) {
  409. revert AccessManagerAlreadyScheduled(operationId);
  410. }
  411. }
  412. /// @inheritdoc IAccessManager
  413. // Reentrancy is not an issue because permissions are checked on msg.sender. Additionally,
  414. // _consumeScheduledOp guarantees a scheduled operation is only executed once.
  415. // slither-disable-next-line reentrancy-no-eth
  416. function execute(address target, bytes calldata data) public payable virtual returns (uint32) {
  417. address caller = _msgSender();
  418. // Fetch restrictions that apply to the caller on the targeted function
  419. (bool immediate, uint32 setback) = _canCallExtended(caller, target, data);
  420. // If caller is not authorised, revert
  421. if (!immediate && setback == 0) {
  422. revert AccessManagerUnauthorizedCall(caller, target, _checkSelector(data));
  423. }
  424. bytes32 operationId = hashOperation(caller, target, data);
  425. uint32 nonce;
  426. // If caller is authorised, check operation was scheduled early enough
  427. // Consume an available schedule even if there is no currently enforced delay
  428. if (setback != 0 || getSchedule(operationId) != 0) {
  429. nonce = _consumeScheduledOp(operationId);
  430. }
  431. // Mark the target and selector as authorised
  432. bytes32 executionIdBefore = _executionId;
  433. _executionId = _hashExecutionId(target, _checkSelector(data));
  434. // Perform call
  435. Address.functionCallWithValue(target, data, msg.value);
  436. // Reset execute identifier
  437. _executionId = executionIdBefore;
  438. return nonce;
  439. }
  440. /// @inheritdoc IAccessManager
  441. function cancel(address caller, address target, bytes calldata data) public virtual returns (uint32) {
  442. address msgsender = _msgSender();
  443. bytes4 selector = _checkSelector(data);
  444. bytes32 operationId = hashOperation(caller, target, data);
  445. if (_schedules[operationId].timepoint == 0) {
  446. revert AccessManagerNotScheduled(operationId);
  447. } else if (caller != msgsender) {
  448. // calls can only be canceled by the account that scheduled them, a global admin, or by a guardian of the required role.
  449. (bool isAdmin, ) = hasRole(ADMIN_ROLE, msgsender);
  450. (bool isGuardian, ) = hasRole(getRoleGuardian(getTargetFunctionRole(target, selector)), msgsender);
  451. if (!isAdmin && !isGuardian) {
  452. revert AccessManagerUnauthorizedCancel(msgsender, caller, target, selector);
  453. }
  454. }
  455. delete _schedules[operationId].timepoint; // reset the timepoint, keep the nonce
  456. uint32 nonce = _schedules[operationId].nonce;
  457. emit OperationCanceled(operationId, nonce);
  458. return nonce;
  459. }
  460. /// @inheritdoc IAccessManager
  461. function consumeScheduledOp(address caller, bytes calldata data) public virtual {
  462. address target = _msgSender();
  463. if (IAccessManaged(target).isConsumingScheduledOp() != IAccessManaged.isConsumingScheduledOp.selector) {
  464. revert AccessManagerUnauthorizedConsume(target);
  465. }
  466. _consumeScheduledOp(hashOperation(caller, target, data));
  467. }
  468. /**
  469. * @dev Internal variant of {consumeScheduledOp} that operates on bytes32 operationId.
  470. *
  471. * Returns the nonce of the scheduled operation that is consumed.
  472. */
  473. function _consumeScheduledOp(bytes32 operationId) internal virtual returns (uint32) {
  474. uint48 timepoint = _schedules[operationId].timepoint;
  475. uint32 nonce = _schedules[operationId].nonce;
  476. if (timepoint == 0) {
  477. revert AccessManagerNotScheduled(operationId);
  478. } else if (timepoint > Time.timestamp()) {
  479. revert AccessManagerNotReady(operationId);
  480. } else if (_isExpired(timepoint)) {
  481. revert AccessManagerExpired(operationId);
  482. }
  483. delete _schedules[operationId].timepoint; // reset the timepoint, keep the nonce
  484. emit OperationExecuted(operationId, nonce);
  485. return nonce;
  486. }
  487. /// @inheritdoc IAccessManager
  488. function hashOperation(address caller, address target, bytes calldata data) public view virtual returns (bytes32) {
  489. return keccak256(abi.encode(caller, target, data));
  490. }
  491. // ==================================================== OTHERS ====================================================
  492. /// @inheritdoc IAccessManager
  493. function updateAuthority(address target, address newAuthority) public virtual onlyAuthorized {
  494. IAccessManaged(target).setAuthority(newAuthority);
  495. }
  496. // ================================================= ADMIN LOGIC ==================================================
  497. /**
  498. * @dev Check if the current call is authorized according to admin logic.
  499. */
  500. function _checkAuthorized() private {
  501. address caller = _msgSender();
  502. (bool immediate, uint32 delay) = _canCallSelf(caller, _msgData());
  503. if (!immediate) {
  504. if (delay == 0) {
  505. (, uint64 requiredRole, ) = _getAdminRestrictions(_msgData());
  506. revert AccessManagerUnauthorizedAccount(caller, requiredRole);
  507. } else {
  508. _consumeScheduledOp(hashOperation(caller, address(this), _msgData()));
  509. }
  510. }
  511. }
  512. /**
  513. * @dev Get the admin restrictions of a given function call based on the function and arguments involved.
  514. *
  515. * Returns:
  516. * - bool restricted: does this data match a restricted operation
  517. * - uint64: which role is this operation restricted to
  518. * - uint32: minimum delay to enforce for that operation (max between operation's delay and admin's execution delay)
  519. */
  520. function _getAdminRestrictions(
  521. bytes calldata data
  522. ) private view returns (bool restricted, uint64 roleAdminId, uint32 executionDelay) {
  523. if (data.length < 4) {
  524. return (false, 0, 0);
  525. }
  526. bytes4 selector = _checkSelector(data);
  527. // Restricted to ADMIN with no delay beside any execution delay the caller may have
  528. if (
  529. selector == this.labelRole.selector ||
  530. selector == this.setRoleAdmin.selector ||
  531. selector == this.setRoleGuardian.selector ||
  532. selector == this.setGrantDelay.selector ||
  533. selector == this.setTargetAdminDelay.selector
  534. ) {
  535. return (true, ADMIN_ROLE, 0);
  536. }
  537. // Restricted to ADMIN with the admin delay corresponding to the target
  538. if (
  539. selector == this.updateAuthority.selector ||
  540. selector == this.setTargetClosed.selector ||
  541. selector == this.setTargetFunctionRole.selector
  542. ) {
  543. // First argument is a target.
  544. address target = abi.decode(data[0x04:0x24], (address));
  545. uint32 delay = getTargetAdminDelay(target);
  546. return (true, ADMIN_ROLE, delay);
  547. }
  548. // Restricted to that role's admin with no delay beside any execution delay the caller may have.
  549. if (selector == this.grantRole.selector || selector == this.revokeRole.selector) {
  550. // First argument is a roleId.
  551. uint64 roleId = abi.decode(data[0x04:0x24], (uint64));
  552. return (true, getRoleAdmin(roleId), 0);
  553. }
  554. return (false, 0, 0);
  555. }
  556. // =================================================== HELPERS ====================================================
  557. /**
  558. * @dev An extended version of {canCall} for internal usage that checks {_canCallSelf}
  559. * when the target is this contract.
  560. *
  561. * Returns:
  562. * - bool immediate: whether the operation can be executed immediately (with no delay)
  563. * - uint32 delay: the execution delay
  564. */
  565. function _canCallExtended(
  566. address caller,
  567. address target,
  568. bytes calldata data
  569. ) private view returns (bool immediate, uint32 delay) {
  570. if (target == address(this)) {
  571. return _canCallSelf(caller, data);
  572. } else {
  573. return data.length < 4 ? (false, 0) : canCall(caller, target, _checkSelector(data));
  574. }
  575. }
  576. /**
  577. * @dev A version of {canCall} that checks for admin restrictions in this contract.
  578. */
  579. function _canCallSelf(address caller, bytes calldata data) private view returns (bool immediate, uint32 delay) {
  580. if (data.length < 4) {
  581. return (false, 0);
  582. }
  583. if (caller == address(this)) {
  584. // Caller is AccessManager, this means the call was sent through {execute} and it already checked
  585. // permissions. We verify that the call "identifier", which is set during {execute}, is correct.
  586. return (_isExecuting(address(this), _checkSelector(data)), 0);
  587. }
  588. (bool enabled, uint64 roleId, uint32 operationDelay) = _getAdminRestrictions(data);
  589. if (!enabled) {
  590. return (false, 0);
  591. }
  592. (bool inRole, uint32 executionDelay) = hasRole(roleId, caller);
  593. if (!inRole) {
  594. return (false, 0);
  595. }
  596. // downcast is safe because both options are uint32
  597. delay = uint32(Math.max(operationDelay, executionDelay));
  598. return (delay == 0, delay);
  599. }
  600. /**
  601. * @dev Returns true if a call with `target` and `selector` is being executed via {executed}.
  602. */
  603. function _isExecuting(address target, bytes4 selector) private view returns (bool) {
  604. return _executionId == _hashExecutionId(target, selector);
  605. }
  606. /**
  607. * @dev Returns true if a schedule timepoint is past its expiration deadline.
  608. */
  609. function _isExpired(uint48 timepoint) private view returns (bool) {
  610. return timepoint + expiration() <= Time.timestamp();
  611. }
  612. /**
  613. * @dev Extracts the selector from calldata. Panics if data is not at least 4 bytes
  614. */
  615. function _checkSelector(bytes calldata data) private pure returns (bytes4) {
  616. return bytes4(data[0:4]);
  617. }
  618. /**
  619. * @dev Hashing function for execute protection
  620. */
  621. function _hashExecutionId(address target, bytes4 selector) private pure returns (bytes32) {
  622. return keccak256(abi.encode(target, selector));
  623. }
  624. }