AccessManager.sol 32 KB

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