Governor.sol 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.9.0) (governance/Governor.sol)
  3. pragma solidity ^0.8.19;
  4. import "../token/ERC721/IERC721Receiver.sol";
  5. import "../token/ERC1155/IERC1155Receiver.sol";
  6. import "../utils/cryptography/ECDSA.sol";
  7. import "../utils/cryptography/EIP712.sol";
  8. import "../utils/introspection/ERC165.sol";
  9. import "../utils/math/SafeCast.sol";
  10. import "../utils/structs/DoubleEndedQueue.sol";
  11. import "../utils/Address.sol";
  12. import "../utils/Context.sol";
  13. import "./IGovernor.sol";
  14. /**
  15. * @dev Core of the governance system, designed to be extended though various modules.
  16. *
  17. * This contract is abstract and requires several functions to be implemented in various modules:
  18. *
  19. * - A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote}
  20. * - A voting module must implement {_getVotes}
  21. * - Additionally, {votingPeriod} must also be implemented
  22. *
  23. * _Available since v4.3._
  24. */
  25. abstract contract Governor is Context, ERC165, EIP712, IGovernor, IERC721Receiver, IERC1155Receiver {
  26. using DoubleEndedQueue for DoubleEndedQueue.Bytes32Deque;
  27. bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)");
  28. bytes32 public constant EXTENDED_BALLOT_TYPEHASH =
  29. keccak256("ExtendedBallot(uint256 proposalId,uint8 support,string reason,bytes params)");
  30. // solhint-disable var-name-mixedcase
  31. struct ProposalCore {
  32. // --- start retyped from Timers.BlockNumber at offset 0x00 ---
  33. uint64 voteStart;
  34. address proposer;
  35. bytes4 __gap_unused0;
  36. // --- start retyped from Timers.BlockNumber at offset 0x20 ---
  37. uint64 voteEnd;
  38. bytes24 __gap_unused1;
  39. // --- Remaining fields starting at offset 0x40 ---------------
  40. bool executed;
  41. bool canceled;
  42. }
  43. // solhint-enable var-name-mixedcase
  44. string private _name;
  45. /// @custom:oz-retyped-from mapping(uint256 => Governor.ProposalCore)
  46. mapping(uint256 => ProposalCore) private _proposals;
  47. // This queue keeps track of the governor operating on itself. Calls to functions protected by the
  48. // {onlyGovernance} modifier needs to be whitelisted in this queue. Whitelisting is set in {_beforeExecute},
  49. // consumed by the {onlyGovernance} modifier and eventually reset in {_afterExecute}. This ensures that the
  50. // execution of {onlyGovernance} protected calls can only be achieved through successful proposals.
  51. DoubleEndedQueue.Bytes32Deque private _governanceCall;
  52. /**
  53. * @dev Restricts a function so it can only be executed through governance proposals. For example, governance
  54. * parameter setters in {GovernorSettings} are protected using this modifier.
  55. *
  56. * The governance executing address may be different from the Governor's own address, for example it could be a
  57. * timelock. This can be customized by modules by overriding {_executor}. The executor is only able to invoke these
  58. * functions during the execution of the governor's {execute} function, and not under any other circumstances. Thus,
  59. * for example, additional timelock proposers are not able to change governance parameters without going through the
  60. * governance protocol (since v4.6).
  61. */
  62. modifier onlyGovernance() {
  63. require(_msgSender() == _executor(), "Governor: onlyGovernance");
  64. if (_executor() != address(this)) {
  65. bytes32 msgDataHash = keccak256(_msgData());
  66. // loop until popping the expected operation - throw if deque is empty (operation not authorized)
  67. while (_governanceCall.popFront() != msgDataHash) {}
  68. }
  69. _;
  70. }
  71. /**
  72. * @dev Sets the value for {name} and {version}
  73. */
  74. constructor(string memory name_) EIP712(name_, version()) {
  75. _name = name_;
  76. }
  77. /**
  78. * @dev Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract)
  79. */
  80. receive() external payable virtual {
  81. require(_executor() == address(this), "Governor: must send to executor");
  82. }
  83. /**
  84. * @dev See {IERC165-supportsInterface}.
  85. */
  86. function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
  87. bytes4 governorCancelId = this.cancel.selector ^ this.proposalProposer.selector;
  88. bytes4 governorParamsId = this.castVoteWithReasonAndParams.selector ^
  89. this.castVoteWithReasonAndParamsBySig.selector ^
  90. this.getVotesWithParams.selector;
  91. // The original interface id in v4.3.
  92. bytes4 governor43Id = type(IGovernor).interfaceId ^
  93. type(IERC6372).interfaceId ^
  94. governorCancelId ^
  95. governorParamsId;
  96. // An updated interface id in v4.6, with params added.
  97. bytes4 governor46Id = type(IGovernor).interfaceId ^ type(IERC6372).interfaceId ^ governorCancelId;
  98. // For the updated interface id in v4.9, we use governorCancelId directly.
  99. return
  100. interfaceId == governor43Id ||
  101. interfaceId == governor46Id ||
  102. interfaceId == governorCancelId ||
  103. interfaceId == type(IERC1155Receiver).interfaceId ||
  104. super.supportsInterface(interfaceId);
  105. }
  106. /**
  107. * @dev See {IGovernor-name}.
  108. */
  109. function name() public view virtual override returns (string memory) {
  110. return _name;
  111. }
  112. /**
  113. * @dev See {IGovernor-version}.
  114. */
  115. function version() public view virtual override returns (string memory) {
  116. return "1";
  117. }
  118. /**
  119. * @dev See {IGovernor-hashProposal}.
  120. *
  121. * The proposal id is produced by hashing the ABI encoded `targets` array, the `values` array, the `calldatas` array
  122. * and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id
  123. * can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in
  124. * advance, before the proposal is submitted.
  125. *
  126. * Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the
  127. * same proposal (with same operation and same description) will have the same id if submitted on multiple governors
  128. * across multiple networks. This also means that in order to execute the same operation twice (on the same
  129. * governor) the proposer will have to change the description in order to avoid proposal id conflicts.
  130. */
  131. function hashProposal(
  132. address[] memory targets,
  133. uint256[] memory values,
  134. bytes[] memory calldatas,
  135. bytes32 descriptionHash
  136. ) public pure virtual override returns (uint256) {
  137. return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash)));
  138. }
  139. /**
  140. * @dev See {IGovernor-state}.
  141. */
  142. function state(uint256 proposalId) public view virtual override returns (ProposalState) {
  143. ProposalCore storage proposal = _proposals[proposalId];
  144. if (proposal.executed) {
  145. return ProposalState.Executed;
  146. }
  147. if (proposal.canceled) {
  148. return ProposalState.Canceled;
  149. }
  150. uint256 snapshot = proposalSnapshot(proposalId);
  151. if (snapshot == 0) {
  152. revert("Governor: unknown proposal id");
  153. }
  154. uint256 currentTimepoint = clock();
  155. if (snapshot >= currentTimepoint) {
  156. return ProposalState.Pending;
  157. }
  158. uint256 deadline = proposalDeadline(proposalId);
  159. if (deadline >= currentTimepoint) {
  160. return ProposalState.Active;
  161. }
  162. if (_quorumReached(proposalId) && _voteSucceeded(proposalId)) {
  163. return ProposalState.Succeeded;
  164. } else {
  165. return ProposalState.Defeated;
  166. }
  167. }
  168. /**
  169. * @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_.
  170. */
  171. function proposalThreshold() public view virtual returns (uint256) {
  172. return 0;
  173. }
  174. /**
  175. * @dev See {IGovernor-proposalSnapshot}.
  176. */
  177. function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) {
  178. return _proposals[proposalId].voteStart;
  179. }
  180. /**
  181. * @dev See {IGovernor-proposalDeadline}.
  182. */
  183. function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) {
  184. return _proposals[proposalId].voteEnd;
  185. }
  186. /**
  187. * @dev Returns the account that created a given proposal.
  188. */
  189. function proposalProposer(uint256 proposalId) public view virtual override returns (address) {
  190. return _proposals[proposalId].proposer;
  191. }
  192. /**
  193. * @dev Amount of votes already cast passes the threshold limit.
  194. */
  195. function _quorumReached(uint256 proposalId) internal view virtual returns (bool);
  196. /**
  197. * @dev Is the proposal successful or not.
  198. */
  199. function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool);
  200. /**
  201. * @dev Get the voting weight of `account` at a specific `timepoint`, for a vote as described by `params`.
  202. */
  203. function _getVotes(address account, uint256 timepoint, bytes memory params) internal view virtual returns (uint256);
  204. /**
  205. * @dev Register a vote for `proposalId` by `account` with a given `support`, voting `weight` and voting `params`.
  206. *
  207. * Note: Support is generic and can represent various things depending on the voting system used.
  208. */
  209. function _countVote(
  210. uint256 proposalId,
  211. address account,
  212. uint8 support,
  213. uint256 weight,
  214. bytes memory params
  215. ) internal virtual;
  216. /**
  217. * @dev Default additional encoded parameters used by castVote methods that don't include them
  218. *
  219. * Note: Should be overridden by specific implementations to use an appropriate value, the
  220. * meaning of the additional params, in the context of that implementation
  221. */
  222. function _defaultParams() internal view virtual returns (bytes memory) {
  223. return "";
  224. }
  225. /**
  226. * @dev See {IGovernor-propose}. This function has opt-in frontrunning protection, described in {_isValidDescriptionForProposer}.
  227. */
  228. function propose(
  229. address[] memory targets,
  230. uint256[] memory values,
  231. bytes[] memory calldatas,
  232. string memory description
  233. ) public virtual override returns (uint256) {
  234. address proposer = _msgSender();
  235. require(_isValidDescriptionForProposer(proposer, description), "Governor: proposer restricted");
  236. uint256 currentTimepoint = clock();
  237. require(
  238. getVotes(proposer, currentTimepoint - 1) >= proposalThreshold(),
  239. "Governor: proposer votes below proposal threshold"
  240. );
  241. uint256 proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
  242. require(targets.length == values.length, "Governor: invalid proposal length");
  243. require(targets.length == calldatas.length, "Governor: invalid proposal length");
  244. require(targets.length > 0, "Governor: empty proposal");
  245. require(_proposals[proposalId].voteStart == 0, "Governor: proposal already exists");
  246. uint256 snapshot = currentTimepoint + votingDelay();
  247. uint256 deadline = snapshot + votingPeriod();
  248. _proposals[proposalId] = ProposalCore({
  249. proposer: proposer,
  250. voteStart: SafeCast.toUint64(snapshot),
  251. voteEnd: SafeCast.toUint64(deadline),
  252. executed: false,
  253. canceled: false,
  254. __gap_unused0: 0,
  255. __gap_unused1: 0
  256. });
  257. emit ProposalCreated(
  258. proposalId,
  259. proposer,
  260. targets,
  261. values,
  262. new string[](targets.length),
  263. calldatas,
  264. snapshot,
  265. deadline,
  266. description
  267. );
  268. return proposalId;
  269. }
  270. /**
  271. * @dev See {IGovernor-execute}.
  272. */
  273. function execute(
  274. address[] memory targets,
  275. uint256[] memory values,
  276. bytes[] memory calldatas,
  277. bytes32 descriptionHash
  278. ) public payable virtual override returns (uint256) {
  279. uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
  280. ProposalState currentState = state(proposalId);
  281. require(
  282. currentState == ProposalState.Succeeded || currentState == ProposalState.Queued,
  283. "Governor: proposal not successful"
  284. );
  285. _proposals[proposalId].executed = true;
  286. emit ProposalExecuted(proposalId);
  287. _beforeExecute(proposalId, targets, values, calldatas, descriptionHash);
  288. _execute(proposalId, targets, values, calldatas, descriptionHash);
  289. _afterExecute(proposalId, targets, values, calldatas, descriptionHash);
  290. return proposalId;
  291. }
  292. /**
  293. * @dev See {IGovernor-cancel}.
  294. */
  295. function cancel(
  296. address[] memory targets,
  297. uint256[] memory values,
  298. bytes[] memory calldatas,
  299. bytes32 descriptionHash
  300. ) public virtual override returns (uint256) {
  301. uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
  302. require(state(proposalId) == ProposalState.Pending, "Governor: too late to cancel");
  303. require(_msgSender() == _proposals[proposalId].proposer, "Governor: only proposer can cancel");
  304. return _cancel(targets, values, calldatas, descriptionHash);
  305. }
  306. /**
  307. * @dev Internal execution mechanism. Can be overridden to implement different execution mechanism
  308. */
  309. function _execute(
  310. uint256 /* proposalId */,
  311. address[] memory targets,
  312. uint256[] memory values,
  313. bytes[] memory calldatas,
  314. bytes32 /*descriptionHash*/
  315. ) internal virtual {
  316. string memory errorMessage = "Governor: call reverted without message";
  317. for (uint256 i = 0; i < targets.length; ++i) {
  318. (bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]);
  319. Address.verifyCallResult(success, returndata, errorMessage);
  320. }
  321. }
  322. /**
  323. * @dev Hook before execution is triggered.
  324. */
  325. function _beforeExecute(
  326. uint256 /* proposalId */,
  327. address[] memory targets,
  328. uint256[] memory /* values */,
  329. bytes[] memory calldatas,
  330. bytes32 /*descriptionHash*/
  331. ) internal virtual {
  332. if (_executor() != address(this)) {
  333. for (uint256 i = 0; i < targets.length; ++i) {
  334. if (targets[i] == address(this)) {
  335. _governanceCall.pushBack(keccak256(calldatas[i]));
  336. }
  337. }
  338. }
  339. }
  340. /**
  341. * @dev Hook after execution is triggered.
  342. */
  343. function _afterExecute(
  344. uint256 /* proposalId */,
  345. address[] memory /* targets */,
  346. uint256[] memory /* values */,
  347. bytes[] memory /* calldatas */,
  348. bytes32 /*descriptionHash*/
  349. ) internal virtual {
  350. if (_executor() != address(this)) {
  351. if (!_governanceCall.empty()) {
  352. _governanceCall.clear();
  353. }
  354. }
  355. }
  356. /**
  357. * @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as
  358. * canceled to allow distinguishing it from executed proposals.
  359. *
  360. * Emits a {IGovernor-ProposalCanceled} event.
  361. */
  362. function _cancel(
  363. address[] memory targets,
  364. uint256[] memory values,
  365. bytes[] memory calldatas,
  366. bytes32 descriptionHash
  367. ) internal virtual returns (uint256) {
  368. uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash);
  369. ProposalState currentState = state(proposalId);
  370. require(
  371. currentState != ProposalState.Canceled &&
  372. currentState != ProposalState.Expired &&
  373. currentState != ProposalState.Executed,
  374. "Governor: proposal not active"
  375. );
  376. _proposals[proposalId].canceled = true;
  377. emit ProposalCanceled(proposalId);
  378. return proposalId;
  379. }
  380. /**
  381. * @dev See {IGovernor-getVotes}.
  382. */
  383. function getVotes(address account, uint256 timepoint) public view virtual override returns (uint256) {
  384. return _getVotes(account, timepoint, _defaultParams());
  385. }
  386. /**
  387. * @dev See {IGovernor-getVotesWithParams}.
  388. */
  389. function getVotesWithParams(
  390. address account,
  391. uint256 timepoint,
  392. bytes memory params
  393. ) public view virtual override returns (uint256) {
  394. return _getVotes(account, timepoint, params);
  395. }
  396. /**
  397. * @dev See {IGovernor-castVote}.
  398. */
  399. function castVote(uint256 proposalId, uint8 support) public virtual override returns (uint256) {
  400. address voter = _msgSender();
  401. return _castVote(proposalId, voter, support, "");
  402. }
  403. /**
  404. * @dev See {IGovernor-castVoteWithReason}.
  405. */
  406. function castVoteWithReason(
  407. uint256 proposalId,
  408. uint8 support,
  409. string calldata reason
  410. ) public virtual override returns (uint256) {
  411. address voter = _msgSender();
  412. return _castVote(proposalId, voter, support, reason);
  413. }
  414. /**
  415. * @dev See {IGovernor-castVoteWithReasonAndParams}.
  416. */
  417. function castVoteWithReasonAndParams(
  418. uint256 proposalId,
  419. uint8 support,
  420. string calldata reason,
  421. bytes memory params
  422. ) public virtual override returns (uint256) {
  423. address voter = _msgSender();
  424. return _castVote(proposalId, voter, support, reason, params);
  425. }
  426. /**
  427. * @dev See {IGovernor-castVoteBySig}.
  428. */
  429. function castVoteBySig(
  430. uint256 proposalId,
  431. uint8 support,
  432. uint8 v,
  433. bytes32 r,
  434. bytes32 s
  435. ) public virtual override returns (uint256) {
  436. address voter = ECDSA.recover(
  437. _hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))),
  438. v,
  439. r,
  440. s
  441. );
  442. return _castVote(proposalId, voter, support, "");
  443. }
  444. /**
  445. * @dev See {IGovernor-castVoteWithReasonAndParamsBySig}.
  446. */
  447. function castVoteWithReasonAndParamsBySig(
  448. uint256 proposalId,
  449. uint8 support,
  450. string calldata reason,
  451. bytes memory params,
  452. uint8 v,
  453. bytes32 r,
  454. bytes32 s
  455. ) public virtual override returns (uint256) {
  456. address voter = ECDSA.recover(
  457. _hashTypedDataV4(
  458. keccak256(
  459. abi.encode(
  460. EXTENDED_BALLOT_TYPEHASH,
  461. proposalId,
  462. support,
  463. keccak256(bytes(reason)),
  464. keccak256(params)
  465. )
  466. )
  467. ),
  468. v,
  469. r,
  470. s
  471. );
  472. return _castVote(proposalId, voter, support, reason, params);
  473. }
  474. /**
  475. * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
  476. * voting weight using {IGovernor-getVotes} and call the {_countVote} internal function. Uses the _defaultParams().
  477. *
  478. * Emits a {IGovernor-VoteCast} event.
  479. */
  480. function _castVote(
  481. uint256 proposalId,
  482. address account,
  483. uint8 support,
  484. string memory reason
  485. ) internal virtual returns (uint256) {
  486. return _castVote(proposalId, account, support, reason, _defaultParams());
  487. }
  488. /**
  489. * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
  490. * voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
  491. *
  492. * Emits a {IGovernor-VoteCast} event.
  493. */
  494. function _castVote(
  495. uint256 proposalId,
  496. address account,
  497. uint8 support,
  498. string memory reason,
  499. bytes memory params
  500. ) internal virtual returns (uint256) {
  501. ProposalCore storage proposal = _proposals[proposalId];
  502. require(state(proposalId) == ProposalState.Active, "Governor: vote not currently active");
  503. uint256 weight = _getVotes(account, proposal.voteStart, params);
  504. _countVote(proposalId, account, support, weight, params);
  505. if (params.length == 0) {
  506. emit VoteCast(account, proposalId, support, weight, reason);
  507. } else {
  508. emit VoteCastWithParams(account, proposalId, support, weight, reason, params);
  509. }
  510. return weight;
  511. }
  512. /**
  513. * @dev Relays a transaction or function call to an arbitrary target. In cases where the governance executor
  514. * is some contract other than the governor itself, like when using a timelock, this function can be invoked
  515. * in a governance proposal to recover tokens or Ether that was sent to the governor contract by mistake.
  516. * Note that if the executor is simply the governor itself, use of `relay` is redundant.
  517. */
  518. function relay(address target, uint256 value, bytes calldata data) external payable virtual onlyGovernance {
  519. (bool success, bytes memory returndata) = target.call{value: value}(data);
  520. Address.verifyCallResult(success, returndata, "Governor: relay reverted without message");
  521. }
  522. /**
  523. * @dev Address through which the governor executes action. Will be overloaded by module that execute actions
  524. * through another contract such as a timelock.
  525. */
  526. function _executor() internal view virtual returns (address) {
  527. return address(this);
  528. }
  529. /**
  530. * @dev See {IERC721Receiver-onERC721Received}.
  531. */
  532. function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
  533. return this.onERC721Received.selector;
  534. }
  535. /**
  536. * @dev See {IERC1155Receiver-onERC1155Received}.
  537. */
  538. function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual returns (bytes4) {
  539. return this.onERC1155Received.selector;
  540. }
  541. /**
  542. * @dev See {IERC1155Receiver-onERC1155BatchReceived}.
  543. */
  544. function onERC1155BatchReceived(
  545. address,
  546. address,
  547. uint256[] memory,
  548. uint256[] memory,
  549. bytes memory
  550. ) public virtual returns (bytes4) {
  551. return this.onERC1155BatchReceived.selector;
  552. }
  553. /**
  554. * @dev Check if the proposer is authorized to submit a proposal with the given description.
  555. *
  556. * If the proposal description ends with `#proposer=0x???`, where `0x???` is an address written as a hex string
  557. * (case insensitive), then the submission of this proposal will only be authorized to said address.
  558. *
  559. * This is used for frontrunning protection. By adding this pattern at the end of their proposal, one can ensure
  560. * that no other address can submit the same proposal. An attacker would have to either remove or change that part,
  561. * which would result in a different proposal id.
  562. *
  563. * If the description does not match this pattern, it is unrestricted and anyone can submit it. This includes:
  564. * - If the `0x???` part is not a valid hex string.
  565. * - If the `0x???` part is a valid hex string, but does not contain exactly 40 hex digits.
  566. * - If it ends with the expected suffix followed by newlines or other whitespace.
  567. * - If it ends with some other similar suffix, e.g. `#other=abc`.
  568. * - If it does not end with any such suffix.
  569. */
  570. function _isValidDescriptionForProposer(
  571. address proposer,
  572. string memory description
  573. ) internal view virtual returns (bool) {
  574. uint256 len = bytes(description).length;
  575. // Length is too short to contain a valid proposer suffix
  576. if (len < 52) {
  577. return true;
  578. }
  579. // Extract what would be the `#proposer=0x` marker beginning the suffix
  580. bytes12 marker;
  581. assembly {
  582. // - Start of the string contents in memory = description + 32
  583. // - First character of the marker = len - 52
  584. // - Length of "#proposer=0x0000000000000000000000000000000000000000" = 52
  585. // - We read the memory word starting at the first character of the marker:
  586. // - (description + 32) + (len - 52) = description + (len - 20)
  587. // - Note: Solidity will ignore anything past the first 12 bytes
  588. marker := mload(add(description, sub(len, 20)))
  589. }
  590. // If the marker is not found, there is no proposer suffix to check
  591. if (marker != bytes12("#proposer=0x")) {
  592. return true;
  593. }
  594. // Parse the 40 characters following the marker as uint160
  595. uint160 recovered = 0;
  596. for (uint256 i = len - 40; i < len; ++i) {
  597. (bool isHex, uint8 value) = _tryHexToUint(bytes(description)[i]);
  598. // If any of the characters is not a hex digit, ignore the suffix entirely
  599. if (!isHex) {
  600. return true;
  601. }
  602. recovered = (recovered << 4) | value;
  603. }
  604. return recovered == uint160(proposer);
  605. }
  606. /**
  607. * @dev Try to parse a character from a string as a hex value. Returns `(true, value)` if the char is in
  608. * `[0-9a-fA-F]` and `(false, 0)` otherwise. Value is guaranteed to be in the range `0 <= value < 16`
  609. */
  610. function _tryHexToUint(bytes1 char) private pure returns (bool, uint8) {
  611. uint8 c = uint8(char);
  612. unchecked {
  613. // Case 0-9
  614. if (47 < c && c < 58) {
  615. return (true, c - 48);
  616. }
  617. // Case A-F
  618. else if (64 < c && c < 71) {
  619. return (true, c - 55);
  620. }
  621. // Case a-f
  622. else if (96 < c && c < 103) {
  623. return (true, c - 87);
  624. }
  625. // Else: not a hex char
  626. else {
  627. return (false, 0);
  628. }
  629. }
  630. }
  631. }