AccessManager.sol 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  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. * The smart contracts under the control of an AccessManager instance will have a set of "restricted" functions, and the
  14. * exact details of how access is restricted for each of those functions is configurable by the admins of the instance.
  15. * These restrictions are expressed in terms of "groups".
  16. *
  17. * An AccessManager instance will define a set of groups. Accounts can be added into any number of these groups. Each of
  18. * them defines a role, and may confer access to some of the restricted functions in the system, as configured by admins
  19. * through the use of {setFunctionAllowedGroup}.
  20. *
  21. * Note that a function in a target contract may become permissioned in this way only when: 1) said contract is
  22. * {AccessManaged} and is connected to this contract as its manager, and 2) said function is decorated with the
  23. * `restricted` modifier.
  24. *
  25. * There is a special group defined by default named "public" which all accounts automatically have.
  26. *
  27. * Contracts where functions are mapped to groups are said to be in a "custom" mode, but contracts can also be
  28. * configured in two special modes: 1) the "open" mode, where all functions are allowed to the "public" group, and 2)
  29. * the "closed" mode, where no function is allowed to any group.
  30. *
  31. * Since all the permissions of the managed system can be modified by the admins of this instance, it is expected that
  32. * they will be highly secured (e.g., a multisig or a well-configured DAO).
  33. *
  34. * NOTE: This contract implements a form of the {IAuthority} interface, but {canCall} has additional return data so it
  35. * doesn't inherit `IAuthority`. It is however compatible with the `IAuthority` interface since the first 32 bytes of
  36. * the return data are a boolean as expected by that interface.
  37. *
  38. * NOTE: Systems that implement other access control mechanisms (for example using {Ownable}) can be paired with an
  39. * {AccessManager} by transferring permissions (ownership in the case of {Ownable}) directly to the {AccessManager}.
  40. * Users will be able to interact with these contracts through the {relay} function, following the access rules
  41. * registered in the {AccessManager}. Keep in mind that in that context, the msg.sender seen by restricted functions
  42. * will be {AccessManager} itself.
  43. *
  44. * WARNING: When granting permissions over an {Ownable} or {AccessControl} contract to an {AccessManager}, be very
  45. * mindful of the danger associated with functions such as {{Ownable-renounceOwnership}} or
  46. * {{AccessControl-renounceRole}}.
  47. */
  48. contract AccessManager is Context, Multicall, IAccessManager {
  49. using Time for *;
  50. struct TargetConfig {
  51. mapping(bytes4 selector => uint64 groupId) allowedGroups;
  52. Time.Delay adminDelay;
  53. bool closed;
  54. }
  55. // Structure that stores the details for a group/account pair. This structure fits into a single slot.
  56. struct Access {
  57. // Timepoint at which the user gets the permission. If this is either 0, or in the future, the group permission
  58. // is not available. Should be checked using {Time-isSetAndPast}
  59. uint48 since;
  60. // delay for execution. Only applies to restricted() / relay() calls. This does not restrict access to
  61. // functions that use the `onlyGroup` modifier.
  62. Time.Delay delay;
  63. }
  64. // Structure that stores the details of a group, including:
  65. // - the members of the group
  66. // - the admin group (that can grant or revoke permissions)
  67. // - the guardian group (that can cancel operations targeting functions that need this group
  68. // - the grant delay
  69. struct Group {
  70. mapping(address user => Access access) members;
  71. uint64 admin;
  72. uint64 guardian;
  73. Time.Delay grantDelay;
  74. }
  75. struct Schedule {
  76. uint48 timepoint;
  77. uint32 nonce;
  78. }
  79. uint64 public constant ADMIN_GROUP = type(uint64).min; // 0
  80. uint64 public constant PUBLIC_GROUP = type(uint64).max; // 2**64-1
  81. mapping(address target => TargetConfig mode) private _targets;
  82. mapping(uint64 groupId => Group) private _groups;
  83. mapping(bytes32 operationId => Schedule) private _schedules;
  84. // This should be transient storage when supported by the EVM.
  85. bytes32 private _relayIdentifier;
  86. /**
  87. * @dev Check that the caller is authorized to perform the operation, following the restrictions encoded in
  88. * {_getAdminRestrictions}.
  89. */
  90. modifier onlyAuthorized() {
  91. _checkAuthorized();
  92. _;
  93. }
  94. constructor(address initialAdmin) {
  95. // admin is active immediately and without any execution delay.
  96. _grantGroup(ADMIN_GROUP, initialAdmin, 0, 0);
  97. }
  98. // =================================================== GETTERS ====================================================
  99. /**
  100. * @dev Check if an address (`caller`) is authorised to call a given function on a given contract directly (with
  101. * no restriction). Additionally, it returns the delay needed to perform the call indirectly through the {schedule}
  102. * & {relay} workflow.
  103. *
  104. * This function is usually called by the targeted contract to control immediate execution of restricted functions.
  105. * Therefore we only return true is the call can be performed without any delay. If the call is subject to a delay,
  106. * then the function should return false, and the caller should schedule the operation for future execution.
  107. *
  108. * We may be able to hash the operation, and check if the call was scheduled, but we would not be able to cleanup
  109. * the schedule, leaving the possibility of multiple executions. Maybe this function should not be view?
  110. *
  111. * NOTE: The IAuthority interface does not include the `uint32` delay. This is an extension of that interface that
  112. * is backward compatible. Some contracts may thus ignore the second return argument. In that case they will fail
  113. * to identify the indirect workflow, and will consider calls that require a delay to be forbidden.
  114. */
  115. function canCall(address caller, address target, bytes4 selector) public view virtual returns (bool, uint32) {
  116. if (isTargetClosed(target)) {
  117. return (false, 0);
  118. } else if (caller == address(this)) {
  119. // Caller is AccessManager => call was relayed. In that case the relay already checked permissions. We
  120. // verify that the call "identifier", which is set during the relay call, is correct.
  121. return (_relayIdentifier == _hashRelayIdentifier(target, selector), 0);
  122. } else {
  123. uint64 groupId = getTargetFunctionGroup(target, selector);
  124. (bool inGroup, uint32 currentDelay) = hasGroup(groupId, caller);
  125. return inGroup ? (currentDelay == 0, currentDelay) : (false, 0);
  126. }
  127. }
  128. /**
  129. * @dev Expiration delay for scheduled proposals. Defaults to 1 week.
  130. */
  131. function expiration() public view virtual returns (uint32) {
  132. return 1 weeks;
  133. }
  134. /**
  135. * @dev Minimum setback for all delay updates, with the exception of execution delays, which
  136. * can be increased without setback (and in the event of an accidental increase can be reset
  137. * via {revokeGroup}). Defaults to 5 days.
  138. */
  139. function minSetback() public view virtual returns (uint32) {
  140. return 5 days;
  141. }
  142. /**
  143. * @dev Get the mode under which a contract is operating.
  144. */
  145. function isTargetClosed(address target) public view virtual returns (bool) {
  146. return _targets[target].closed;
  147. }
  148. /**
  149. * @dev Get the permission level (group) required to call a function. This only applies for contract that are
  150. * operating under the `Custom` mode.
  151. */
  152. function getTargetFunctionGroup(address target, bytes4 selector) public view virtual returns (uint64) {
  153. return _targets[target].allowedGroups[selector];
  154. }
  155. function getTargetAdminDelay(address target) public view virtual returns (uint32) {
  156. return _targets[target].adminDelay.get();
  157. }
  158. /**
  159. * @dev Get the id of the group that acts as an admin for given group.
  160. *
  161. * The admin permission is required to grant the group, revoke the group and update the execution delay to execute
  162. * an operation that is restricted to this group.
  163. */
  164. function getGroupAdmin(uint64 groupId) public view virtual returns (uint64) {
  165. return _groups[groupId].admin;
  166. }
  167. /**
  168. * @dev Get the group that acts as a guardian for a given group.
  169. *
  170. * The guardian permission allows canceling operations that have been scheduled under the group.
  171. */
  172. function getGroupGuardian(uint64 groupId) public view virtual returns (uint64) {
  173. return _groups[groupId].guardian;
  174. }
  175. /**
  176. * @dev Get the group current grant delay, that value may change at any point, without an event emitted, following
  177. * a call to {setGrantDelay}. Changes to this value, including effect timepoint are notified by the
  178. * {GroupGrantDelayChanged} event.
  179. */
  180. function getGroupGrantDelay(uint64 groupId) public view virtual returns (uint32) {
  181. return _groups[groupId].grantDelay.get();
  182. }
  183. /**
  184. * @dev Get the access details for a given account in a given group. These details include the timepoint at which
  185. * membership becomes active, and the delay applied to all operation by this user that requires this permission
  186. * level.
  187. *
  188. * Returns:
  189. * [0] Timestamp at which the account membership becomes valid. 0 means role is not granted.
  190. * [1] Current execution delay for the account.
  191. * [2] Pending execution delay for the account.
  192. * [3] Timestamp at which the pending execution delay will become active. 0 means no delay update is scheduled.
  193. */
  194. function getAccess(uint64 groupId, address account) public view virtual returns (uint48, uint32, uint32, uint48) {
  195. Access storage access = _groups[groupId].members[account];
  196. uint48 since = access.since;
  197. (uint32 currentDelay, uint32 pendingDelay, uint48 effect) = access.delay.getFull();
  198. return (since, currentDelay, pendingDelay, effect);
  199. }
  200. /**
  201. * @dev Check if a given account currently had the permission level corresponding to a given group. Note that this
  202. * permission might be associated with a delay. {getAccess} can provide more details.
  203. */
  204. function hasGroup(uint64 groupId, address account) public view virtual returns (bool, uint32) {
  205. if (groupId == PUBLIC_GROUP) {
  206. return (true, 0);
  207. } else {
  208. (uint48 inGroupSince, uint32 currentDelay, , ) = getAccess(groupId, account);
  209. return (inGroupSince.isSetAndPast(Time.timestamp()), currentDelay);
  210. }
  211. }
  212. // =============================================== GROUP MANAGEMENT ===============================================
  213. /**
  214. * @dev Give a label to a group, for improved group discoverabily by UIs.
  215. *
  216. * Emits a {GroupLabel} event.
  217. */
  218. function labelGroup(uint64 groupId, string calldata label) public virtual onlyAuthorized {
  219. if (groupId == ADMIN_GROUP || groupId == PUBLIC_GROUP) {
  220. revert AccessManagerLockedGroup(groupId);
  221. }
  222. emit GroupLabel(groupId, label);
  223. }
  224. /**
  225. * @dev Add `account` to `groupId`, or change its execution delay.
  226. *
  227. * This gives the account the authorization to call any function that is restricted to this group. An optional
  228. * execution delay (in seconds) can be set. If that delay is non 0, the user is required to schedule any operation
  229. * that is restricted to members this group. The user will only be able to execute the operation after the delay has
  230. * passed, before it has expired. During this period, admin and guardians can cancel the operation (see {cancel}).
  231. *
  232. * If the account has already been granted this group, the execution delay will be updated. This update is not
  233. * immediate and follows the delay rules. For example, If a user currently has a delay of 3 hours, and this is
  234. * called to reduce that delay to 1 hour, the new delay will take some time to take effect, enforcing that any
  235. * operation executed in the 3 hours that follows this update was indeed scheduled before this update.
  236. *
  237. * Requirements:
  238. *
  239. * - the caller must be in the group's admins
  240. *
  241. * Emits a {GroupGranted} event
  242. */
  243. function grantGroup(uint64 groupId, address account, uint32 executionDelay) public virtual onlyAuthorized {
  244. _grantGroup(groupId, account, getGroupGrantDelay(groupId), executionDelay);
  245. }
  246. /**
  247. * @dev Remove an account for a group, with immediate effect. If the sender is not in the group, this call has no
  248. * effect.
  249. *
  250. * Requirements:
  251. *
  252. * - the caller must be in the group's admins
  253. *
  254. * Emits a {GroupRevoked} event
  255. */
  256. function revokeGroup(uint64 groupId, address account) public virtual onlyAuthorized {
  257. _revokeGroup(groupId, account);
  258. }
  259. /**
  260. * @dev Renounce group permissions for the calling account, with immediate effect. If the sender is not in
  261. * the group, this call has no effect.
  262. *
  263. * Requirements:
  264. *
  265. * - the caller must be `callerConfirmation`.
  266. *
  267. * Emits a {GroupRevoked} event
  268. */
  269. function renounceGroup(uint64 groupId, address callerConfirmation) public virtual {
  270. if (callerConfirmation != _msgSender()) {
  271. revert AccessManagerBadConfirmation();
  272. }
  273. _revokeGroup(groupId, callerConfirmation);
  274. }
  275. /**
  276. * @dev Change admin group for a given group.
  277. *
  278. * Requirements:
  279. *
  280. * - the caller must be a global admin
  281. *
  282. * Emits a {GroupAdminChanged} event
  283. */
  284. function setGroupAdmin(uint64 groupId, uint64 admin) public virtual onlyAuthorized {
  285. _setGroupAdmin(groupId, admin);
  286. }
  287. /**
  288. * @dev Change guardian group for a given group.
  289. *
  290. * Requirements:
  291. *
  292. * - the caller must be a global admin
  293. *
  294. * Emits a {GroupGuardianChanged} event
  295. */
  296. function setGroupGuardian(uint64 groupId, uint64 guardian) public virtual onlyAuthorized {
  297. _setGroupGuardian(groupId, guardian);
  298. }
  299. /**
  300. * @dev Update the delay for granting a `groupId`.
  301. *
  302. * Requirements:
  303. *
  304. * - the caller must be a global admin
  305. *
  306. * Emits a {GroupGrantDelayChanged} event
  307. */
  308. function setGrantDelay(uint64 groupId, uint32 newDelay) public virtual onlyAuthorized {
  309. _setGrantDelay(groupId, newDelay);
  310. }
  311. /**
  312. * @dev Internal version of {grantGroup} without access control. Returns true if the group was newly granted.
  313. *
  314. * Emits a {GroupGranted} event
  315. */
  316. function _grantGroup(
  317. uint64 groupId,
  318. address account,
  319. uint32 grantDelay,
  320. uint32 executionDelay
  321. ) internal virtual returns (bool) {
  322. if (groupId == PUBLIC_GROUP) {
  323. revert AccessManagerLockedGroup(groupId);
  324. }
  325. bool inGroup = _groups[groupId].members[account].since != 0;
  326. uint48 since;
  327. if (inGroup) {
  328. // No setback here. Value can be reset by doing revoke + grant, effectively allowing the admin to perform
  329. // any change to the execution delay within the duration of the group admin delay.
  330. (_groups[groupId].members[account].delay, since) = _groups[groupId].members[account].delay.withUpdate(
  331. executionDelay,
  332. 0
  333. );
  334. } else {
  335. since = Time.timestamp() + grantDelay;
  336. _groups[groupId].members[account] = Access({since: since, delay: executionDelay.toDelay()});
  337. }
  338. emit GroupGranted(groupId, account, executionDelay, since);
  339. return !inGroup;
  340. }
  341. /**
  342. * @dev Internal version of {revokeGroup} without access control. This logic is also used by {renounceGroup}.
  343. * Returns true if the group was previously granted.
  344. *
  345. * Emits a {GroupRevoked} event
  346. */
  347. function _revokeGroup(uint64 groupId, address account) internal virtual returns (bool) {
  348. if (groupId == PUBLIC_GROUP) {
  349. revert AccessManagerLockedGroup(groupId);
  350. }
  351. if (_groups[groupId].members[account].since == 0) {
  352. return false;
  353. }
  354. delete _groups[groupId].members[account];
  355. emit GroupRevoked(groupId, account);
  356. return true;
  357. }
  358. /**
  359. * @dev Internal version of {setGroupAdmin} without access control.
  360. *
  361. * Emits a {GroupAdminChanged} event
  362. */
  363. function _setGroupAdmin(uint64 groupId, uint64 admin) internal virtual {
  364. if (groupId == ADMIN_GROUP || groupId == PUBLIC_GROUP) {
  365. revert AccessManagerLockedGroup(groupId);
  366. }
  367. _groups[groupId].admin = admin;
  368. emit GroupAdminChanged(groupId, admin);
  369. }
  370. /**
  371. * @dev Internal version of {setGroupGuardian} without access control.
  372. *
  373. * Emits a {GroupGuardianChanged} event
  374. */
  375. function _setGroupGuardian(uint64 groupId, uint64 guardian) internal virtual {
  376. if (groupId == ADMIN_GROUP || groupId == PUBLIC_GROUP) {
  377. revert AccessManagerLockedGroup(groupId);
  378. }
  379. _groups[groupId].guardian = guardian;
  380. emit GroupGuardianChanged(groupId, guardian);
  381. }
  382. /**
  383. * @dev Internal version of {setGrantDelay} without access control.
  384. *
  385. * Emits a {GroupGrantDelayChanged} event
  386. */
  387. function _setGrantDelay(uint64 groupId, uint32 newDelay) internal virtual {
  388. if (groupId == PUBLIC_GROUP) {
  389. revert AccessManagerLockedGroup(groupId);
  390. }
  391. uint48 effect;
  392. (_groups[groupId].grantDelay, effect) = _groups[groupId].grantDelay.withUpdate(newDelay, minSetback());
  393. emit GroupGrantDelayChanged(groupId, newDelay, effect);
  394. }
  395. // ============================================= FUNCTION MANAGEMENT ==============================================
  396. /**
  397. * @dev Set the level of permission (`group`) required to call functions identified by the `selectors` in the
  398. * `target` contract.
  399. *
  400. * Requirements:
  401. *
  402. * - the caller must be a global admin
  403. *
  404. * Emits a {FunctionAllowedGroupUpdated} event per selector
  405. */
  406. function setTargetFunctionGroup(
  407. address target,
  408. bytes4[] calldata selectors,
  409. uint64 groupId
  410. ) public virtual onlyAuthorized {
  411. for (uint256 i = 0; i < selectors.length; ++i) {
  412. _setTargetFunctionGroup(target, selectors[i], groupId);
  413. }
  414. }
  415. /**
  416. * @dev Internal version of {setFunctionAllowedGroup} without access control.
  417. *
  418. * Emits a {FunctionAllowedGroupUpdated} event
  419. */
  420. function _setTargetFunctionGroup(address target, bytes4 selector, uint64 groupId) internal virtual {
  421. _targets[target].allowedGroups[selector] = groupId;
  422. emit TargetFunctionGroupUpdated(target, selector, groupId);
  423. }
  424. /**
  425. * @dev Set the delay for management operations on a given class of contract.
  426. *
  427. * Requirements:
  428. *
  429. * - the caller must be a global admin
  430. *
  431. * Emits a {FunctionAllowedGroupUpdated} event per selector
  432. */
  433. function setTargetAdminDelay(address target, uint32 newDelay) public virtual onlyAuthorized {
  434. _setTargetAdminDelay(target, newDelay);
  435. }
  436. /**
  437. * @dev Internal version of {setClassAdminDelay} without access control.
  438. *
  439. * Emits a {ClassAdminDelayUpdated} event
  440. */
  441. function _setTargetAdminDelay(address target, uint32 newDelay) internal virtual {
  442. uint48 effect;
  443. (_targets[target].adminDelay, effect) = _targets[target].adminDelay.withUpdate(newDelay, minSetback());
  444. emit TargetAdminDelayUpdated(target, newDelay, effect);
  445. }
  446. // =============================================== MODE MANAGEMENT ================================================
  447. /**
  448. * @dev Set the closed flag for a contract.
  449. *
  450. * Requirements:
  451. *
  452. * - the caller must be a global admin
  453. *
  454. * Emits a {TargetClosed} event.
  455. */
  456. function setTargetClosed(address target, bool closed) public virtual onlyAuthorized {
  457. _setTargetClosed(target, closed);
  458. }
  459. /**
  460. * @dev Set the closed flag for a contract. This is an internal setter with no access restrictions.
  461. *
  462. * Emits a {TargetClosed} event.
  463. */
  464. function _setTargetClosed(address target, bool closed) internal virtual {
  465. if (target == address(this)) {
  466. revert AccessManagerLockedAccount(target);
  467. }
  468. _targets[target].closed = closed;
  469. emit TargetClosed(target, closed);
  470. }
  471. // ============================================== DELAYED OPERATIONS ==============================================
  472. /**
  473. * @dev Return the timepoint at which a scheduled operation will be ready for execution. This returns 0 if the
  474. * operation is not yet scheduled, has expired, was executed, or was canceled.
  475. */
  476. function getSchedule(bytes32 id) public view virtual returns (uint48) {
  477. uint48 timepoint = _schedules[id].timepoint;
  478. return _isExpired(timepoint) ? 0 : timepoint;
  479. }
  480. /**
  481. * @dev Return the nonce for the latest scheduled operation with a given id. Returns 0 if the operation has never
  482. * been scheduled.
  483. */
  484. function getNonce(bytes32 id) public view virtual returns (uint32) {
  485. return _schedules[id].nonce;
  486. }
  487. /**
  488. * @dev Schedule a delayed operation for future execution, and return the operation identifier. It is possible to
  489. * choose the timestamp at which the operation becomes executable as long as it satisfies the execution delays
  490. * required for the caller. The special value zero will automatically set the earliest possible time.
  491. *
  492. * Returns the `operationId` that was scheduled. Since this value is a hash of the parameters, it can reoccur when
  493. * the same parameters are used; if this is relevant, the returned `nonce` can be used to uniquely identify this
  494. * scheduled operation from other occurrences of the same `operationId` in invocations of {relay} and {cancel}.
  495. *
  496. * Emits a {OperationScheduled} event.
  497. */
  498. function schedule(
  499. address target,
  500. bytes calldata data,
  501. uint48 when
  502. ) public virtual returns (bytes32 operationId, uint32 nonce) {
  503. address caller = _msgSender();
  504. // Fetch restrictions that apply to the caller on the targeted function
  505. (bool immediate, uint32 setback) = _canCallExtended(caller, target, data);
  506. uint48 minWhen = Time.timestamp() + setback;
  507. if (when == 0) {
  508. when = minWhen;
  509. }
  510. // If caller is not authorised, revert
  511. if (!immediate && (setback == 0 || when < minWhen)) {
  512. revert AccessManagerUnauthorizedCall(caller, target, bytes4(data[0:4]));
  513. }
  514. // If caller is authorised, schedule operation
  515. operationId = _hashOperation(caller, target, data);
  516. // Cannot reschedule unless the operation has expired
  517. uint48 prevTimepoint = _schedules[operationId].timepoint;
  518. if (prevTimepoint != 0 && !_isExpired(prevTimepoint)) {
  519. revert AccessManagerAlreadyScheduled(operationId);
  520. }
  521. unchecked {
  522. // It's not feasible to overflow the nonce in less than 1000 years
  523. nonce = _schedules[operationId].nonce + 1;
  524. }
  525. _schedules[operationId].timepoint = when;
  526. _schedules[operationId].nonce = nonce;
  527. emit OperationScheduled(operationId, nonce, when, caller, target, data);
  528. // Using named return values because otherwise we get stack too deep
  529. }
  530. /**
  531. * @dev Execute a function that is delay restricted, provided it was properly scheduled beforehand, or the
  532. * execution delay is 0.
  533. *
  534. * Returns the nonce that identifies the previously scheduled operation that is relayed, or 0 if the
  535. * operation wasn't previously scheduled (if the caller doesn't have an execution delay).
  536. *
  537. * Emits an {OperationExecuted} event only if the call was scheduled and delayed.
  538. */
  539. // Reentrancy is not an issue because permissions are checked on msg.sender. Additionally,
  540. // _consumeScheduledOp guarantees a scheduled operation is only executed once.
  541. // slither-disable-next-line reentrancy-no-eth
  542. function relay(address target, bytes calldata data) public payable virtual returns (uint32) {
  543. address caller = _msgSender();
  544. // Fetch restrictions that apply to the caller on the targeted function
  545. (bool immediate, uint32 setback) = _canCallExtended(caller, target, data);
  546. // If caller is not authorised, revert
  547. if (!immediate && setback == 0) {
  548. revert AccessManagerUnauthorizedCall(caller, target, bytes4(data));
  549. }
  550. // If caller is authorised, check operation was scheduled early enough
  551. bytes32 operationId = _hashOperation(caller, target, data);
  552. uint32 nonce;
  553. if (setback != 0) {
  554. nonce = _consumeScheduledOp(operationId);
  555. }
  556. // Mark the target and selector as authorised
  557. bytes32 relayIdentifierBefore = _relayIdentifier;
  558. _relayIdentifier = _hashRelayIdentifier(target, bytes4(data));
  559. // Perform call
  560. Address.functionCallWithValue(target, data, msg.value);
  561. // Reset relay identifier
  562. _relayIdentifier = relayIdentifierBefore;
  563. return nonce;
  564. }
  565. /**
  566. * @dev Consume a scheduled operation targeting the caller. If such an operation exists, mark it as consumed
  567. * (emit an {OperationExecuted} event and clean the state). Otherwise, throw an error.
  568. *
  569. * This is useful for contract that want to enforce that calls targeting them were scheduled on the manager,
  570. * with all the verifications that it implies.
  571. *
  572. * Emit a {OperationExecuted} event
  573. */
  574. function consumeScheduledOp(address caller, bytes calldata data) public virtual {
  575. address target = _msgSender();
  576. require(IAccessManaged(target).isConsumingScheduledOp());
  577. _consumeScheduledOp(_hashOperation(caller, target, data));
  578. }
  579. /**
  580. * @dev Internal variant of {consumeScheduledOp} that operates on bytes32 operationId.
  581. *
  582. * Returns the nonce of the scheduled operation that is consumed.
  583. */
  584. function _consumeScheduledOp(bytes32 operationId) internal virtual returns (uint32) {
  585. uint48 timepoint = _schedules[operationId].timepoint;
  586. uint32 nonce = _schedules[operationId].nonce;
  587. if (timepoint == 0) {
  588. revert AccessManagerNotScheduled(operationId);
  589. } else if (timepoint > Time.timestamp()) {
  590. revert AccessManagerNotReady(operationId);
  591. } else if (_isExpired(timepoint)) {
  592. revert AccessManagerExpired(operationId);
  593. }
  594. delete _schedules[operationId];
  595. emit OperationExecuted(operationId, nonce);
  596. return nonce;
  597. }
  598. /**
  599. * @dev Cancel a scheduled (delayed) operation. Returns the nonce that identifies the previously scheduled
  600. * operation that is cancelled.
  601. *
  602. * Requirements:
  603. *
  604. * - the caller must be the proposer, or a guardian of the targeted function
  605. *
  606. * Emits a {OperationCanceled} event.
  607. */
  608. function cancel(address caller, address target, bytes calldata data) public virtual returns (uint32) {
  609. address msgsender = _msgSender();
  610. bytes4 selector = bytes4(data[0:4]);
  611. bytes32 operationId = _hashOperation(caller, target, data);
  612. if (_schedules[operationId].timepoint == 0) {
  613. revert AccessManagerNotScheduled(operationId);
  614. } else if (caller != msgsender) {
  615. // calls can only be canceled by the account that scheduled them, a global admin, or by a guardian of the required group.
  616. (bool isAdmin, ) = hasGroup(ADMIN_GROUP, msgsender);
  617. (bool isGuardian, ) = hasGroup(getGroupGuardian(getTargetFunctionGroup(target, selector)), msgsender);
  618. if (!isAdmin && !isGuardian) {
  619. revert AccessManagerCannotCancel(msgsender, caller, target, selector);
  620. }
  621. }
  622. delete _schedules[operationId].timepoint;
  623. uint32 nonce = _schedules[operationId].nonce;
  624. emit OperationCanceled(operationId, nonce);
  625. return nonce;
  626. }
  627. /**
  628. * @dev Hashing function for delayed operations
  629. */
  630. function _hashOperation(address caller, address target, bytes calldata data) private pure returns (bytes32) {
  631. return keccak256(abi.encode(caller, target, data));
  632. }
  633. /**
  634. * @dev Hashing function for relay protection
  635. */
  636. function _hashRelayIdentifier(address target, bytes4 selector) private pure returns (bytes32) {
  637. return keccak256(abi.encode(target, selector));
  638. }
  639. // ==================================================== OTHERS ====================================================
  640. /**
  641. * @dev Change the AccessManager instance used by a contract that correctly uses this instance.
  642. *
  643. * Requirements:
  644. *
  645. * - the caller must be a global admin
  646. */
  647. function updateAuthority(address target, address newAuthority) public virtual onlyAuthorized {
  648. IAccessManaged(target).setAuthority(newAuthority);
  649. }
  650. // ================================================= ADMIN LOGIC ==================================================
  651. /**
  652. * @dev Check if the current call is authorized according to admin logic.
  653. */
  654. function _checkAuthorized() private {
  655. address caller = _msgSender();
  656. (bool immediate, uint32 delay) = _canCallExtended(caller, address(this), _msgData());
  657. if (!immediate) {
  658. if (delay == 0) {
  659. (, uint64 requiredGroup, ) = _getAdminRestrictions(_msgData());
  660. revert AccessManagerUnauthorizedAccount(caller, requiredGroup);
  661. } else {
  662. _consumeScheduledOp(_hashOperation(caller, address(this), _msgData()));
  663. }
  664. }
  665. }
  666. /**
  667. * @dev Get the admin restrictions of a given function call based on the function and arguments involved.
  668. *
  669. * Returns:
  670. * - bool restricted: does this data match a restricted operation
  671. * - uint64: which group is this operation restricted to
  672. * - uint32: minimum delay to enforce for that operation (on top of the admin's execution delay)
  673. */
  674. function _getAdminRestrictions(bytes calldata data) private view returns (bool, uint64, uint32) {
  675. bytes4 selector = bytes4(data);
  676. if (data.length < 4) {
  677. return (false, 0, 0);
  678. }
  679. // Restricted to ADMIN with no delay beside any execution delay the caller may have
  680. if (
  681. selector == this.labelGroup.selector ||
  682. selector == this.setGroupAdmin.selector ||
  683. selector == this.setGroupGuardian.selector ||
  684. selector == this.setGrantDelay.selector ||
  685. selector == this.setTargetAdminDelay.selector
  686. ) {
  687. return (true, ADMIN_GROUP, 0);
  688. }
  689. // Restricted to ADMIN with the admin delay corresponding to the target
  690. if (
  691. selector == this.updateAuthority.selector ||
  692. selector == this.setTargetClosed.selector ||
  693. selector == this.setTargetFunctionGroup.selector
  694. ) {
  695. // First argument is a target.
  696. address target = abi.decode(data[0x04:0x24], (address));
  697. uint32 delay = getTargetAdminDelay(target);
  698. return (true, ADMIN_GROUP, delay);
  699. }
  700. // Restricted to that group's admin with no delay beside any execution delay the caller may have.
  701. if (selector == this.grantGroup.selector || selector == this.revokeGroup.selector) {
  702. // First argument is a groupId.
  703. uint64 groupId = abi.decode(data[0x04:0x24], (uint64));
  704. uint64 groupAdminId = getGroupAdmin(groupId);
  705. return (true, groupAdminId, 0);
  706. }
  707. return (false, 0, 0);
  708. }
  709. // =================================================== HELPERS ====================================================
  710. /**
  711. * @dev An extended version of {canCall} for internal use that considers restrictions for admin functions.
  712. */
  713. function _canCallExtended(address caller, address target, bytes calldata data) private view returns (bool, uint32) {
  714. if (target == address(this)) {
  715. (bool enabled, uint64 groupId, uint32 operationDelay) = _getAdminRestrictions(data);
  716. if (!enabled) {
  717. return (false, 0);
  718. }
  719. (bool inGroup, uint32 executionDelay) = hasGroup(groupId, caller);
  720. if (!inGroup) {
  721. return (false, 0);
  722. }
  723. // downcast is safe because both options are uint32
  724. uint32 delay = uint32(Math.max(operationDelay, executionDelay));
  725. return (delay == 0, delay);
  726. } else {
  727. bytes4 selector = bytes4(data);
  728. return canCall(caller, target, selector);
  729. }
  730. }
  731. /**
  732. * @dev Returns true if a schedule timepoint is past its expiration deadline.
  733. */
  734. function _isExpired(uint48 timepoint) private view returns (bool) {
  735. return timepoint + expiration() <= Time.timestamp();
  736. }
  737. }