AccessManager.sol 29 KB

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