AccessManager.sol 33 KB

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