Transaction Hash:
Block:
19187549 at Feb-09-2024 02:17:35 AM +UTC
Transaction Fee:
0.004899466702648553 ETH
$12.33
Gas Used:
96,131 Gas / 50.966563363 Gwei
Emitted Events:
127 |
Proxy.0x9866f8ddfe70bb512b2f2b28b49d4017c43f7ba775f1a20c61c13eea8cdac111( 0x9866f8ddfe70bb512b2f2b28b49d4017c43f7ba775f1a20c61c13eea8cdac111, b85a53575c3c24bcf4d1eab7c75a9d8c54bb0d079b28d88840c204c28f668000 )
|
128 |
Proxy.0x9592d37825c744e33fa80c469683bbd04d336241bb600b574758efd182abe26a( 0x9592d37825c744e33fa80c469683bbd04d336241bb600b574758efd182abe26a, 0x000000000000000000000000023a2aac5d0fa69e3243994672822ba43e34e5c9, 0x07c76a71952ce3acd1f953fd2a3fda8564408b821ff367041c89f44526076633, 0x02d757788a8d8d6f21d1cd40bce38a8222d70654214e96ff95d8086e684fbee5, 0000000000000000000000000000000000000000000000000000000000000040, 000000000000000000000000000000000000000000000000000000000018dd43, 0000000000000000000000000000000000000000000000000000000000000003, 05f1da1721932923811386da9f001b367eed17934981076010f8e953d4371d98, 000000000000000000000000000000000000000000000878678326eac9000000, 0000000000000000000000000000000000000000000000000000000000000000 )
|
129 |
Proxy.0xd342ddf7a308dec111745b00315c14b7efb2bdae570a6856e088ed0c65a3576c( 0xd342ddf7a308dec111745b00315c14b7efb2bdae570a6856e088ed0c65a3576c, 0505aa19515cbae2c5416a92ab6743afd1ee460f3b7f9665369cb2e58d0c47cf, 000000000000000000000000000000000000000000000000000000000008308b, 04a505dd5775aba52806faceb02a6ddbbf83c13e95cd69fdc788af4cce6cc9ec )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x2C169DFe...bFE260CA7 | (StarkNet: Operator) |
123.342490718826686753 Eth
Nonce: 536715
|
123.337591252124038201 Eth
Nonce: 536716
| 0.004899466702648552 | |
0x4838B106...B0BAD5f97
Miner
| (Titan Builder) | 121.650887936836480733 Eth | 121.650897549936480733 Eth | 0.0000096131 | |
0xc662c410...BeBD9C8c4 | (Starknet: Core Contract) | 0.073042845283280315 Eth | 0.073042845283280314 Eth | 0.000000000000000001 |
Execution Trace
Proxy.77552641( )
Starknet.updateState( programOutput=[1641100271157161382105318587739304506280416704295758784732157132715252468418, 2271572457686287482033831876318901839713657255541103026217557430552119494607, 536715, 2100821636112022567559813339326169319879593045659580051982446396000499976684, 2590421891839256512113614983194993186457498815986333310670788206383913888162, 0, 8, 12715142131438166996925287687735483027063891401, 3518527153270494256475755541726550738597926965391766941271488561627919771187, 1629507, 1285101517810983806491589552491143496277809242732141897358598292095611420389, 3, 2688879589846140277533829482634145128530408804415014823990402615834513448344, 40000000000000000000000, 0], onchainDataHash=88567326914558954625843645388734019515887518546393987099926819488124422788805, onchainDataSize=865 )
Proxy.6a938567( )
CallProxy.isValid( fact=B6DE6C2B1850A64C9F59AC4CC029387ECAE870189639A366B0D5C61859CD9DE6 ) => ( True )
-
GpsStatementVerifier.isValid( fact=B6DE6C2B1850A64C9F59AC4CC029387ECAE870189639A366B0D5C61859CD9DE6 ) => ( True )
-
- ETH 0.000000000000000001
StarkNet: Operator.CALL( )
updateState[Starknet (ln:1085)]
state[Starknet (ln:1092)]
validate[Starknet (ln:1094)]
configHash[Starknet (ln:1097)]
setUintValue[Starknet (ln:1012)]
encodeFactWithOnchainData[Starknet (ln:1100)]
DataAvailabilityFact[Starknet (ln:1102)]
encode[Starknet (ln:1104)]
programHash[Starknet (ln:1104)]
getUintValue[Starknet (ln:1000)]
isValid[Starknet (ln:1105)]
verifier[Starknet (ln:1105)]
getAddressValue[Starknet (ln:1008)]
LogStateTransitionFact[Starknet (ln:1106)]
update[Starknet (ln:1108)]
state[Starknet (ln:1108)]
processMessages[Starknet (ln:1114)]
LogMessageToL1[StarknetOutput (ln:800)]
ConsumedMessageToL2[StarknetOutput (ln:823)]
call[StarknetOutput (ln:841)]
l2ToL1Messages[Starknet (ln:1118)]
processMessages[Starknet (ln:1121)]
LogMessageToL1[StarknetOutput (ln:800)]
ConsumedMessageToL2[StarknetOutput (ln:823)]
call[StarknetOutput (ln:841)]
l1ToL2Messages[Starknet (ln:1125)]
state[Starknet (ln:1130)]
LogStateUpdate[Starknet (ln:1131)]
File 1 of 5: Proxy
File 2 of 5: Starknet
File 3 of 5: Proxy
File 4 of 5: CallProxy
File 5 of 5: GpsStatementVerifier
{"Common.sol":{"content":"/*\n Copyright 2019-2021 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\n/*\n Common Utility librarries.\n I. Addresses (extending address).\n*/\nlibrary Addresses {\n function isContract(address account) internal view returns (bool) {\n uint256 size;\n assembly {\n size := extcodesize(account)\n }\n return size \u003e 0;\n }\n\n function performEthTransfer(address recipient, uint256 amount) internal {\n (bool success, ) = recipient.call{value: amount}(\"\"); // NOLINT: low-level-calls.\n require(success, \"ETH_TRANSFER_FAILED\");\n }\n\n /*\n Safe wrapper around ERC20/ERC721 calls.\n This is required because many deployed ERC20 contracts don\u0027t return a value.\n See https://github.com/ethereum/solidity/issues/4116.\n */\n function safeTokenContractCall(address tokenAddress, bytes memory callData) internal {\n require(isContract(tokenAddress), \"BAD_TOKEN_ADDRESS\");\n // NOLINTNEXTLINE: low-level-calls.\n (bool success, bytes memory returndata) = tokenAddress.call(callData);\n require(success, string(returndata));\n\n if (returndata.length \u003e 0) {\n require(abi.decode(returndata, (bool)), \"TOKEN_OPERATION_FAILED\");\n }\n }\n\n /*\n Validates that the passed contract address is of a real contract,\n and that its id hash (as infered fromn identify()) matched the expected one.\n */\n function validateContractId(address contractAddress, bytes32 expectedIdHash) internal {\n require(isContract(contractAddress), \"ADDRESS_NOT_CONTRACT\");\n (bool success, bytes memory returndata) = contractAddress.call( // NOLINT: low-level-calls.\n abi.encodeWithSignature(\"identify()\")\n );\n require(success, \"FAILED_TO_IDENTIFY_CONTRACT\");\n string memory realContractId = abi.decode(returndata, (string));\n require(\n keccak256(abi.encodePacked(realContractId)) == expectedIdHash,\n \"UNEXPECTED_CONTRACT_IDENTIFIER\"\n );\n }\n}\n\n/*\n II. StarkExTypes - Common data types.\n*/\nlibrary StarkExTypes {\n // Structure representing a list of verifiers (validity/availability).\n // A statement is valid only if all the verifiers in the list agree on it.\n // Adding a verifier to the list is immediate - this is used for fast resolution of\n // any soundness issues.\n // Removing from the list is time-locked, to ensure that any user of the system\n // not content with the announced removal has ample time to leave the system before it is\n // removed.\n struct ApprovalChainData {\n address[] list;\n // Represents the time after which the verifier with the given address can be removed.\n // Removal of the verifier with address A is allowed only in the case the value\n // of unlockedForRemovalTime[A] != 0 and unlockedForRemovalTime[A] \u003c (current time).\n mapping(address =\u003e uint256) unlockedForRemovalTime;\n }\n}\n"},"Governance.sol":{"content":"/*\n Copyright 2019-2021 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"MGovernance.sol\";\n\n/*\n Implements Generic Governance, applicable for both proxy and main contract, and possibly others.\n Notes:\n The use of the same function names by both the Proxy and a delegated implementation\n is not possible since calling the implementation functions is done via the default function\n of the Proxy. For this reason, for example, the implementation of MainContract (MainGovernance)\n exposes mainIsGovernor, which calls the internal isGovernor method.\n*/\nabstract contract Governance is MGovernance {\n event LogNominatedGovernor(address nominatedGovernor);\n event LogNewGovernorAccepted(address acceptedGovernor);\n event LogRemovedGovernor(address removedGovernor);\n event LogNominationCancelled();\n\n function getGovernanceInfo() internal view virtual returns (GovernanceInfoStruct storage);\n\n /*\n Current code intentionally prevents governance re-initialization.\n This may be a problem in an upgrade situation, in a case that the upgrade-to implementation\n performs an initialization (for real) and within that calls initGovernance().\n\n Possible workarounds:\n 1. Clearing the governance info altogether by changing the MAIN_GOVERNANCE_INFO_TAG.\n This will remove existing main governance information.\n 2. Modify the require part in this function, so that it will exit quietly\n when trying to re-initialize (uncomment the lines below).\n */\n function initGovernance() internal {\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n require(!gub.initialized, \"ALREADY_INITIALIZED\");\n gub.initialized = true; // to ensure addGovernor() won\u0027t fail.\n // Add the initial governer.\n addGovernor(msg.sender);\n }\n\n function isGovernor(address testGovernor) internal view override returns (bool) {\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n return gub.effectiveGovernors[testGovernor];\n }\n\n /*\n Cancels the nomination of a governor candidate.\n */\n function cancelNomination() internal onlyGovernance {\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n gub.candidateGovernor = address(0x0);\n emit LogNominationCancelled();\n }\n\n function nominateNewGovernor(address newGovernor) internal onlyGovernance {\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n require(!isGovernor(newGovernor), \"ALREADY_GOVERNOR\");\n gub.candidateGovernor = newGovernor;\n emit LogNominatedGovernor(newGovernor);\n }\n\n /*\n The addGovernor is called in two cases:\n 1. by acceptGovernance when a new governor accepts its role.\n 2. by initGovernance to add the initial governor.\n The difference is that the init path skips the nominate step\n that would fail because of the onlyGovernance modifier.\n */\n function addGovernor(address newGovernor) private {\n require(!isGovernor(newGovernor), \"ALREADY_GOVERNOR\");\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n gub.effectiveGovernors[newGovernor] = true;\n }\n\n function acceptGovernance() internal {\n // The new governor was proposed as a candidate by the current governor.\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n require(msg.sender == gub.candidateGovernor, \"ONLY_CANDIDATE_GOVERNOR\");\n\n // Update state.\n addGovernor(gub.candidateGovernor);\n gub.candidateGovernor = address(0x0);\n\n // Send a notification about the change of governor.\n emit LogNewGovernorAccepted(msg.sender);\n }\n\n /*\n Remove a governor from office.\n */\n function removeGovernor(address governorForRemoval) internal onlyGovernance {\n require(msg.sender != governorForRemoval, \"GOVERNOR_SELF_REMOVE\");\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n require(isGovernor(governorForRemoval), \"NOT_GOVERNOR\");\n gub.effectiveGovernors[governorForRemoval] = false;\n emit LogRemovedGovernor(governorForRemoval);\n }\n}\n"},"GovernanceStorage.sol":{"content":"/*\n Copyright 2019-2021 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\nimport \"MGovernance.sol\";\n\n/*\n Holds the governance slots for ALL entities, including proxy and the main contract.\n*/\ncontract GovernanceStorage {\n // A map from a Governor tag to its own GovernanceInfoStruct.\n mapping(string =\u003e GovernanceInfoStruct) internal governanceInfo; //NOLINT uninitialized-state.\n}\n"},"MGovernance.sol":{"content":"/*\n Copyright 2019-2021 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nstruct GovernanceInfoStruct {\n mapping(address =\u003e bool) effectiveGovernors;\n address candidateGovernor;\n bool initialized;\n}\n\nabstract contract MGovernance {\n function isGovernor(address testGovernor) internal view virtual returns (bool);\n\n /*\n Allows calling the function only by a Governor.\n */\n modifier onlyGovernance() {\n require(isGovernor(msg.sender), \"ONLY_GOVERNANCE\");\n _;\n }\n}\n"},"Proxy.sol":{"content":"/*\n Copyright 2019-2021 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"ProxyGovernance.sol\";\nimport \"ProxyStorage.sol\";\nimport \"StorageSlots.sol\";\nimport \"Common.sol\";\n\n/**\n The Proxy contract implements delegation of calls to other contracts (`implementations`), with\n proper forwarding of return values and revert reasons. This pattern allows retaining the contract\n storage while replacing implementation code.\n\n The following operations are supported by the proxy contract:\n\n - :sol:func:`addImplementation`: Defines a new implementation, the data with which it should be initialized and whether this will be the last version of implementation.\n - :sol:func:`upgradeTo`: Once an implementation is added, the governor may upgrade to that implementation only after a safety time period has passed (time lock), the current implementation is not the last version and the implementation is not frozen (see :sol:mod:`FullWithdrawals`).\n - :sol:func:`removeImplementation`: Any announced implementation may be removed. Removing an implementation is especially important once it has been used for an upgrade in order to avoid an additional unwanted revert to an older version.\n\n The only entity allowed to perform the above operations is the proxy governor\n (see :sol:mod:`ProxyGovernance`).\n\n Every implementation is required to have an `initialize` function that replaces the constructor\n of a normal contract. Furthermore, the only parameter of this function is an array of bytes\n (`data`) which may be decoded arbitrarily by the `initialize` function. It is up to the\n implementation to ensure that this function cannot be run more than once if so desired.\n\n When an implementation is added (:sol:func:`addImplementation`) the initialization `data` is also\n announced, allowing users of the contract to analyze the full effect of an upgrade to the new\n implementation. During an :sol:func:`upgradeTo`, the `data` is provided again and only if it is\n identical to the announced `data` is the upgrade performed by pointing the proxy to the new\n implementation and calling its `initialize` function with this `data`.\n\n It is the responsibility of the implementation not to overwrite any storage belonging to the\n proxy (`ProxyStorage`). In addition, upon upgrade, the new implementation is assumed to be\n backward compatible with previous implementations with respect to the storage used until that\n point.\n*/\ncontract Proxy is ProxyStorage, ProxyGovernance, StorageSlots {\n // Emitted when the active implementation is replaced.\n event ImplementationUpgraded(address indexed implementation, bytes initializer);\n\n // Emitted when an implementation is submitted as an upgrade candidate and a time lock\n // is activated.\n event ImplementationAdded(address indexed implementation, bytes initializer, bool finalize);\n\n // Emitted when an implementation is removed from the list of upgrade candidates.\n event ImplementationRemoved(address indexed implementation, bytes initializer, bool finalize);\n\n // Emitted when the implementation is finalized.\n event FinalizedImplementation(address indexed implementation);\n\n using Addresses for address;\n\n string public constant PROXY_VERSION = \"3.0.0\";\n\n constructor(uint256 upgradeActivationDelay) public {\n initGovernance();\n setUpgradeActivationDelay(upgradeActivationDelay);\n }\n\n function setUpgradeActivationDelay(uint256 delayInSeconds) private {\n bytes32 slot = UPGRADE_DELAY_SLOT;\n assembly {\n sstore(slot, delayInSeconds)\n }\n }\n\n function getUpgradeActivationDelay() public view returns (uint256 delay) {\n bytes32 slot = UPGRADE_DELAY_SLOT;\n assembly {\n delay := sload(slot)\n }\n return delay;\n }\n\n /*\n Returns the address of the current implementation.\n */\n // NOLINTNEXTLINE external-function.\n function implementation() public view returns (address _implementation) {\n bytes32 slot = IMPLEMENTATION_SLOT;\n assembly {\n _implementation := sload(slot)\n }\n }\n\n /*\n Returns true if the implementation is frozen.\n If the implementation was not assigned yet, returns false.\n */\n function implementationIsFrozen() private returns (bool) {\n address _implementation = implementation();\n\n // We can\u0027t call low level implementation before it\u0027s assigned. (i.e. ZERO).\n if (_implementation == address(0x0)) {\n return false;\n }\n\n // NOLINTNEXTLINE: low-level-calls.\n (bool success, bytes memory returndata) = _implementation.delegatecall(\n abi.encodeWithSignature(\"isFrozen()\")\n );\n require(success, string(returndata));\n return abi.decode(returndata, (bool));\n }\n\n /*\n This method blocks delegation to initialize().\n Only upgradeTo should be able to delegate call to initialize().\n */\n function initialize(\n bytes calldata /*data*/\n ) external pure {\n revert(\"CANNOT_CALL_INITIALIZE\");\n }\n\n modifier notFinalized() {\n require(isNotFinalized(), \"IMPLEMENTATION_FINALIZED\");\n _;\n }\n\n /*\n Forbids calling the function if the implementation is frozen.\n This modifier relies on the lower level (logical contract) implementation of isFrozen().\n */\n modifier notFrozen() {\n require(!implementationIsFrozen(), \"STATE_IS_FROZEN\");\n _;\n }\n\n /*\n This entry point serves only transactions with empty calldata. (i.e. pure value transfer tx).\n We don\u0027t expect to receive such, thus block them.\n */\n receive() external payable {\n revert(\"CONTRACT_NOT_EXPECTED_TO_RECEIVE\");\n }\n\n /*\n Contract\u0027s default function. Delegates execution to the implementation contract.\n It returns back to the external caller whatever the implementation delegated code returns.\n */\n fallback() external payable {\n address _implementation = implementation();\n require(_implementation != address(0x0), \"MISSING_IMPLEMENTATION\");\n\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 for now, as we don\u0027t know the out size yet.\n let result := delegatecall(gas(), _implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /*\n Sets the implementation address of the proxy.\n */\n function setImplementation(address newImplementation) private {\n bytes32 slot = IMPLEMENTATION_SLOT;\n assembly {\n sstore(slot, newImplementation)\n }\n }\n\n /*\n Returns true if the contract is not in the finalized state.\n */\n function isNotFinalized() public view returns (bool notFinal) {\n bytes32 slot = FINALIZED_STATE_SLOT;\n uint256 slotValue;\n assembly {\n slotValue := sload(slot)\n }\n notFinal = (slotValue == 0);\n }\n\n /*\n Marks the current implementation as finalized.\n */\n function setFinalizedFlag() private {\n bytes32 slot = FINALIZED_STATE_SLOT;\n assembly {\n sstore(slot, 0x1)\n }\n }\n\n /*\n Introduce an implementation and its initialization vector,\n and start the time-lock before it can be upgraded to.\n addImplementation is not blocked when frozen or finalized.\n (upgradeTo API is blocked when finalized or frozen).\n */\n function addImplementation(\n address newImplementation,\n bytes calldata data,\n bool finalize\n ) external onlyGovernance {\n require(newImplementation.isContract(), \"ADDRESS_NOT_CONTRACT\");\n\n bytes32 implVectorHash = keccak256(abi.encode(newImplementation, data, finalize));\n\n uint256 activationTime = block.timestamp + getUpgradeActivationDelay();\n\n // First implementation should not have time-lock.\n if (implementation() == address(0x0)) {\n activationTime = block.timestamp;\n }\n\n enabledTime[implVectorHash] = activationTime;\n emit ImplementationAdded(newImplementation, data, finalize);\n }\n\n /*\n Removes a candidate implementation.\n Note that it is possible to remove the current implementation. Doing so doesn\u0027t affect the\n current implementation, but rather revokes it as a future candidate.\n */\n function removeImplementation(\n address removedImplementation,\n bytes calldata data,\n bool finalize\n ) external onlyGovernance {\n bytes32 implVectorHash = keccak256(abi.encode(removedImplementation, data, finalize));\n\n // If we have initializer, we set the hash of it.\n uint256 activationTime = enabledTime[implVectorHash];\n require(activationTime \u003e 0, \"UNKNOWN_UPGRADE_INFORMATION\");\n delete enabledTime[implVectorHash];\n emit ImplementationRemoved(removedImplementation, data, finalize);\n }\n\n /*\n Upgrades the proxy to a new implementation, with its initialization.\n to upgrade successfully, implementation must have been added time-lock agreeably\n before, and the init vector must be identical ot the one submitted before.\n\n Upon assignment of new implementation address,\n its initialize will be called with the initializing vector (even if empty).\n Therefore, the implementation MUST must have such a method.\n\n Note - Initialization data is committed to in advance, therefore it must remain valid\n until the actual contract upgrade takes place.\n\n Care should be taken regarding initialization data and flow when planning the contract upgrade.\n\n When planning contract upgrade, special care is also needed with regard to governance\n (See comments in Governance.sol).\n */\n // NOLINTNEXTLINE: reentrancy-events timestamp.\n function upgradeTo(\n address newImplementation,\n bytes calldata data,\n bool finalize\n ) external payable onlyGovernance notFinalized notFrozen {\n bytes32 implVectorHash = keccak256(abi.encode(newImplementation, data, finalize));\n uint256 activationTime = enabledTime[implVectorHash];\n require(activationTime \u003e 0, \"UNKNOWN_UPGRADE_INFORMATION\");\n require(newImplementation.isContract(), \"ADDRESS_NOT_CONTRACT\");\n // NOLINTNEXTLINE: timestamp.\n require(activationTime \u003c= block.timestamp, \"UPGRADE_NOT_ENABLED_YET\");\n\n setImplementation(newImplementation);\n\n // NOLINTNEXTLINE: low-level-calls controlled-delegatecall.\n (bool success, bytes memory returndata) = newImplementation.delegatecall(\n abi.encodeWithSelector(this.initialize.selector, data)\n );\n require(success, string(returndata));\n\n // Verify that the new implementation is not frozen post initialization.\n // NOLINTNEXTLINE: low-level-calls controlled-delegatecall.\n (success, returndata) = newImplementation.delegatecall(\n abi.encodeWithSignature(\"isFrozen()\")\n );\n require(success, \"CALL_TO_ISFROZEN_REVERTED\");\n require(!abi.decode(returndata, (bool)), \"NEW_IMPLEMENTATION_FROZEN\");\n\n if (finalize) {\n setFinalizedFlag();\n emit FinalizedImplementation(newImplementation);\n }\n\n emit ImplementationUpgraded(newImplementation, data);\n }\n}\n"},"ProxyGovernance.sol":{"content":"/*\n Copyright 2019-2021 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"Governance.sol\";\nimport \"GovernanceStorage.sol\";\n\n/**\n The Proxy contract is governed by one or more Governors of which the initial one is the\n deployer of the contract.\n\n A governor has the sole authority to perform the following operations:\n\n 1. Nominate additional governors (:sol:func:`proxyNominateNewGovernor`)\n 2. Remove other governors (:sol:func:`proxyRemoveGovernor`)\n 3. Add new `implementations` (proxied contracts)\n 4. Remove (new or old) `implementations`\n 5. Update `implementations` after a timelock allows it\n\n Adding governors is performed in a two step procedure:\n\n 1. First, an existing governor nominates a new governor (:sol:func:`proxyNominateNewGovernor`)\n 2. Then, the new governor must accept governance to become a governor (:sol:func:`proxyAcceptGovernance`)\n\n This two step procedure ensures that a governor public key cannot be nominated unless there is an\n entity that has the corresponding private key. This is intended to prevent errors in the addition\n process.\n\n The governor private key should typically be held in a secure cold wallet or managed via a\n multi-sig contract.\n*/\n/*\n Implements Governance for the proxy contract.\n It is a thin wrapper to the Governance contract,\n which is needed so that it can have non-colliding function names,\n and a specific tag (key) to allow unique state storage.\n*/\ncontract ProxyGovernance is GovernanceStorage, Governance {\n // The tag is the string key that is used in the Governance storage mapping.\n string public constant PROXY_GOVERNANCE_TAG = \"StarkEx.Proxy.2019.GovernorsInformation\";\n\n /*\n Returns the GovernanceInfoStruct associated with the governance tag.\n */\n function getGovernanceInfo() internal view override returns (GovernanceInfoStruct storage) {\n return governanceInfo[PROXY_GOVERNANCE_TAG];\n }\n\n function proxyIsGovernor(address testGovernor) external view returns (bool) {\n return isGovernor(testGovernor);\n }\n\n function proxyNominateNewGovernor(address newGovernor) external {\n nominateNewGovernor(newGovernor);\n }\n\n function proxyRemoveGovernor(address governorForRemoval) external {\n removeGovernor(governorForRemoval);\n }\n\n function proxyAcceptGovernance() external {\n acceptGovernance();\n }\n\n function proxyCancelNomination() external {\n cancelNomination();\n }\n}\n"},"ProxyStorage.sol":{"content":"/*\n Copyright 2019-2021 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"GovernanceStorage.sol\";\n\n/*\n Holds the Proxy-specific state variables.\n This contract is inherited by the GovernanceStorage (and indirectly by MainStorage)\n to prevent collision hazard.\n*/\ncontract ProxyStorage is GovernanceStorage {\n // NOLINTNEXTLINE: naming-convention uninitialized-state.\n mapping(address =\u003e bytes32) internal initializationHash_DEPRECATED;\n\n // The time after which we can switch to the implementation.\n // Hash(implementation, data, finalize) =\u003e time.\n mapping(bytes32 =\u003e uint256) internal enabledTime;\n\n // A central storage of the flags whether implementation has been initialized.\n // Note - it can be used flexibly enough to accommodate multiple levels of initialization\n // (i.e. using different key salting schemes for different initialization levels).\n mapping(bytes32 =\u003e bool) internal initialized;\n}\n"},"StorageSlots.sol":{"content":"/*\n Copyright 2019-2021 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\n/**\n StorageSlots holds the arbitrary storage slots used throughout the Proxy pattern.\n Storage address slots are a mechanism to define an arbitrary location, that will not be\n overlapped by the logical contracts.\n*/\ncontract StorageSlots {\n // Storage slot with the address of the current implementation.\n // The address of the slot is keccak256(\"StarkWare2019.implemntation-slot\").\n // We need to keep this variable stored outside of the commonly used space,\n // so that it\u0027s not overrun by the logical implementation (the proxied contract).\n bytes32 internal constant IMPLEMENTATION_SLOT =\n 0x177667240aeeea7e35eabe3a35e18306f336219e1386f7710a6bf8783f761b24;\n\n // Storage slot with the address of the call-proxy current implementation.\n // The address of the slot is keccak256(\"\u0027StarkWare2020.CallProxy.Implemntation.Slot\u0027\").\n // We need to keep this variable stored outside of the commonly used space.\n // so that it\u0027s not overrun by the logical implementation (the proxied contract).\n bytes32 internal constant CALL_PROXY_IMPL_SLOT =\n 0x7184681641399eb4ad2fdb92114857ee6ff239f94ad635a1779978947b8843be;\n\n // This storage slot stores the finalization flag.\n // Once the value stored in this slot is set to non-zero\n // the proxy blocks implementation upgrades.\n // The current implementation is then referred to as Finalized.\n // Web3.solidityKeccak([\u0027string\u0027], [\"StarkWare2019.finalization-flag-slot\"]).\n bytes32 internal constant FINALIZED_STATE_SLOT =\n 0x7d433c6f837e8f93009937c466c82efbb5ba621fae36886d0cac433c5d0aa7d2;\n\n // Storage slot to hold the upgrade delay (time-lock).\n // The intention of this slot is to allow modification using an EIC.\n // Web3.solidityKeccak([\u0027string\u0027], [\u0027StarkWare.Upgradibility.Delay.Slot\u0027]).\n bytes32 public constant UPGRADE_DELAY_SLOT =\n 0xc21dbb3089fcb2c4f4c6a67854ab4db2b0f233ea4b21b21f912d52d18fc5db1f;\n}\n"}}
File 2 of 5: Starknet
/* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; /* Common Utility Libraries. I. Addresses (extending address). */ library Addresses { /* Note: isContract function has some known limitation. See https://github.com/OpenZeppelin/ openzeppelin-contracts/blob/master/contracts/utils/Address.sol. */ function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function performEthTransfer(address recipient, uint256 amount) internal { if (amount == 0) return; (bool success, ) = recipient.call{value: amount}(""); // NOLINT: low-level-calls. require(success, "ETH_TRANSFER_FAILED"); } /* Safe wrapper around ERC20/ERC721 calls. This is required because many deployed ERC20 contracts don't return a value. See https://github.com/ethereum/solidity/issues/4116. */ function safeTokenContractCall(address tokenAddress, bytes memory callData) internal { require(isContract(tokenAddress), "BAD_TOKEN_ADDRESS"); // NOLINTNEXTLINE: low-level-calls. (bool success, bytes memory returndata) = tokenAddress.call(callData); require(success, string(returndata)); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "TOKEN_OPERATION_FAILED"); } } } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; /* This contract provides means to block direct call of an external function. A derived contract (e.g. MainDispatcherBase) should decorate sensitive functions with the notCalledDirectly modifier, thereby preventing it from being called directly, and allowing only calling using delegate_call. */ abstract contract BlockDirectCall { address immutable this_; constructor() internal { this_ = address(this); } modifier notCalledDirectly() { require(this_ != address(this), "DIRECT_CALL_DISALLOWED"); _; } } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; /** Interface for contract initialization. The functions it exposes are the app specific parts of the contract initialization, and are called by the ProxySupport contract that implement the generic part of behind-proxy initialization. */ abstract contract ContractInitializer { /* The number of sub-contracts that the proxied contract consists of. */ function numOfSubContracts() internal pure virtual returns (uint256); /* Indicates if the proxied contract has already been initialized. Used to prevent re-init. */ function isInitialized() internal view virtual returns (bool); /* Validates the init data that is passed into the proxied contract. */ function validateInitData(bytes calldata data) internal view virtual; /* For a proxied contract that consists of sub-contracts, this function processes the sub-contract addresses, e.g. validates them, stores them etc. */ function processSubContractAddresses(bytes calldata subContractAddresses) internal virtual; /* This function applies the logic of initializing the proxied contract state, e.g. setting root values etc. */ function initializeContractState(bytes calldata data) internal virtual; } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; import "MGovernance.sol"; /* Implements Generic Governance, applicable for both proxy and main contract, and possibly others. Notes: The use of the same function names by both the Proxy and a delegated implementation is not possible since calling the implementation functions is done via the default function of the Proxy. For this reason, for example, the implementation of MainContract (MainGovernance) exposes mainIsGovernor, which calls the internal _isGovernor method. */ struct GovernanceInfoStruct { mapping(address => bool) effectiveGovernors; address candidateGovernor; bool initialized; } abstract contract Governance is MGovernance { event LogNominatedGovernor(address nominatedGovernor); event LogNewGovernorAccepted(address acceptedGovernor); event LogRemovedGovernor(address removedGovernor); event LogNominationCancelled(); function getGovernanceInfo() internal view virtual returns (GovernanceInfoStruct storage); /* Current code intentionally prevents governance re-initialization. This may be a problem in an upgrade situation, in a case that the upgrade-to implementation performs an initialization (for real) and within that calls initGovernance(). Possible workarounds: 1. Clearing the governance info altogether by changing the MAIN_GOVERNANCE_INFO_TAG. This will remove existing main governance information. 2. Modify the require part in this function, so that it will exit quietly when trying to re-initialize (uncomment the lines below). */ function initGovernance() internal { GovernanceInfoStruct storage gub = getGovernanceInfo(); require(!gub.initialized, "ALREADY_INITIALIZED"); gub.initialized = true; // to ensure acceptNewGovernor() won't fail. // Add the initial governer. acceptNewGovernor(msg.sender); } function _isGovernor(address user) internal view override returns (bool) { GovernanceInfoStruct storage gub = getGovernanceInfo(); return gub.effectiveGovernors[user]; } /* Cancels the nomination of a governor candidate. */ function _cancelNomination() internal onlyGovernance { GovernanceInfoStruct storage gub = getGovernanceInfo(); if (gub.candidateGovernor != address(0x0)) { gub.candidateGovernor = address(0x0); emit LogNominationCancelled(); } } function _nominateNewGovernor(address newGovernor) internal onlyGovernance { GovernanceInfoStruct storage gub = getGovernanceInfo(); require(newGovernor != address(0x0), "BAD_ADDRESS"); require(!_isGovernor(newGovernor), "ALREADY_GOVERNOR"); require(gub.candidateGovernor == address(0x0), "OTHER_CANDIDATE_PENDING"); gub.candidateGovernor = newGovernor; emit LogNominatedGovernor(newGovernor); } /* The acceptNewGovernor is called in two cases: 1. by _acceptGovernance when a new governor accepts its role. 2. by initGovernance to add the initial governor. The difference is that the init path skips the nominate step that would fail because of the onlyGovernance modifier. */ function acceptNewGovernor(address newGovernor) private { require(!_isGovernor(newGovernor), "ALREADY_GOVERNOR"); GovernanceInfoStruct storage gub = getGovernanceInfo(); gub.effectiveGovernors[newGovernor] = true; // Emit governance information. emit LogNewGovernorAccepted(newGovernor); } function _acceptGovernance() internal { // The new governor was proposed as a candidate by the current governor. GovernanceInfoStruct storage gub = getGovernanceInfo(); require(msg.sender == gub.candidateGovernor, "ONLY_CANDIDATE_GOVERNOR"); // Update state. acceptNewGovernor(msg.sender); gub.candidateGovernor = address(0x0); } /* Remove a governor from office. */ function _removeGovernor(address governorForRemoval) internal onlyGovernance { require(msg.sender != governorForRemoval, "GOVERNOR_SELF_REMOVE"); GovernanceInfoStruct storage gub = getGovernanceInfo(); require(_isGovernor(governorForRemoval), "NOT_GOVERNOR"); gub.effectiveGovernors[governorForRemoval] = false; emit LogRemovedGovernor(governorForRemoval); } } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; import "MGovernance.sol"; import "NamedStorage.sol"; /** A Governor controlled finalizable contract. The inherited contract (the one that is GovernedFinalizable) implements the Governance. */ abstract contract GovernedFinalizable is MGovernance { event Finalized(); string constant STORAGE_TAG = "STARKWARE_CONTRACTS_GOVERENED_FINALIZABLE_1.0_TAG"; function isFinalized() public view returns (bool) { return NamedStorage.getBoolValue(STORAGE_TAG); } modifier notFinalized() { require(!isFinalized(), "FINALIZED"); _; } function finalize() external onlyGovernance notFinalized { NamedStorage.setBoolValue(STORAGE_TAG, true); emit Finalized(); } } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; /* The Fact Registry design pattern is a way to separate cryptographic verification from the business logic of the contract flow. A fact registry holds a hash table of verified "facts" which are represented by a hash of claims that the registry hash check and found valid. This table may be queried by accessing the isValid() function of the registry with a given hash. In addition, each fact registry exposes a registry specific function for submitting new claims together with their proofs. The information submitted varies from one registry to the other depending of the type of fact requiring verification. For further reading on the Fact Registry design pattern see this `StarkWare blog post <https://medium.com/starkware/the-fact-registry-a64aafb598b6>`_. */ interface IFactRegistry { /* Returns true if the given fact was previously registered in the contract. */ function isValid(bytes32 fact) external view returns (bool); } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; import "IStarknetMessagingEvents.sol"; interface IStarknetMessaging is IStarknetMessagingEvents { /** Returns the max fee (in Wei) that StarkNet will accept per single message. */ function getMaxL1MsgFee() external pure returns (uint256); /** Sends a message to an L2 contract. This function is payable, the payed amount is the message fee. Returns the hash of the message and the nonce of the message. */ function sendMessageToL2( uint256 toAddress, uint256 selector, uint256[] calldata payload ) external payable returns (bytes32, uint256); /** Consumes a message that was sent from an L2 contract. Returns the hash of the message. */ function consumeMessageFromL2(uint256 fromAddress, uint256[] calldata payload) external returns (bytes32); /** Starts the cancellation of an L1 to L2 message. A message can be canceled messageCancellationDelay() seconds after this function is called. Note: This function may only be called for a message that is currently pending and the caller must be the sender of the that message. */ function startL1ToL2MessageCancellation( uint256 toAddress, uint256 selector, uint256[] calldata payload, uint256 nonce ) external returns (bytes32); /** Cancels an L1 to L2 message, this function should be called at least messageCancellationDelay() seconds after the call to startL1ToL2MessageCancellation(). A message may only be cancelled by its sender. If the message is missing, the call will revert. Note that the message fee is not refunded. */ function cancelL1ToL2Message( uint256 toAddress, uint256 selector, uint256[] calldata payload, uint256 nonce ) external returns (bytes32); } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; interface IStarknetMessagingEvents { // This event needs to be compatible with the one defined in Output.sol. event LogMessageToL1(uint256 indexed fromAddress, address indexed toAddress, uint256[] payload); // An event that is raised when a message is sent from L1 to L2. event LogMessageToL2( address indexed fromAddress, uint256 indexed toAddress, uint256 indexed selector, uint256[] payload, uint256 nonce, uint256 fee ); // An event that is raised when a message from L2 to L1 is consumed. event ConsumedMessageToL1( uint256 indexed fromAddress, address indexed toAddress, uint256[] payload ); // An event that is raised when a message from L1 to L2 is consumed. event ConsumedMessageToL2( address indexed fromAddress, uint256 indexed toAddress, uint256 indexed selector, uint256[] payload, uint256 nonce ); // An event that is raised when a message from L1 to L2 Cancellation is started. event MessageToL2CancellationStarted( address indexed fromAddress, uint256 indexed toAddress, uint256 indexed selector, uint256[] payload, uint256 nonce ); // An event that is raised when a message from L1 to L2 is canceled. event MessageToL2Canceled( address indexed fromAddress, uint256 indexed toAddress, uint256 indexed selector, uint256[] payload, uint256 nonce ); } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; interface Identity { /* Allows a caller to ensure that the provided address is of the expected type and version. */ function identify() external pure returns (string memory); } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; abstract contract MGovernance { function _isGovernor(address user) internal view virtual returns (bool); /* Allows calling the function only by a Governor. */ modifier onlyGovernance() { require(_isGovernor(msg.sender), "ONLY_GOVERNANCE"); _; } } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; import "MGovernance.sol"; abstract contract MOperator { event LogOperatorAdded(address operator); event LogOperatorRemoved(address operator); function isOperator(address user) public view virtual returns (bool); modifier onlyOperator() { require(isOperator(msg.sender), "ONLY_OPERATOR"); _; } function registerOperator(address newOperator) external virtual; function unregisterOperator(address removedOperator) external virtual; function getOperators() internal view virtual returns (mapping(address => bool) storage); } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; /* Library to provide basic storage, in storage location out of the low linear address space. New types of storage variables should be added here upon need. */ library NamedStorage { function bytes32ToUint256Mapping(string memory tag_) internal pure returns (mapping(bytes32 => uint256) storage randomVariable) { bytes32 location = keccak256(abi.encodePacked(tag_)); assembly { randomVariable_slot := location } } function bytes32ToAddressMapping(string memory tag_) internal pure returns (mapping(bytes32 => address) storage randomVariable) { bytes32 location = keccak256(abi.encodePacked(tag_)); assembly { randomVariable_slot := location } } function uintToAddressMapping(string memory tag_) internal pure returns (mapping(uint256 => address) storage randomVariable) { bytes32 location = keccak256(abi.encodePacked(tag_)); assembly { randomVariable_slot := location } } function addressToBoolMapping(string memory tag_) internal pure returns (mapping(address => bool) storage randomVariable) { bytes32 location = keccak256(abi.encodePacked(tag_)); assembly { randomVariable_slot := location } } function getUintValue(string memory tag_) internal view returns (uint256 retVal) { bytes32 slot = keccak256(abi.encodePacked(tag_)); assembly { retVal := sload(slot) } } function setUintValue(string memory tag_, uint256 value) internal { bytes32 slot = keccak256(abi.encodePacked(tag_)); assembly { sstore(slot, value) } } function setUintValueOnce(string memory tag_, uint256 value) internal { require(getUintValue(tag_) == 0, "ALREADY_SET"); setUintValue(tag_, value); } function getAddressValue(string memory tag_) internal view returns (address retVal) { bytes32 slot = keccak256(abi.encodePacked(tag_)); assembly { retVal := sload(slot) } } function setAddressValue(string memory tag_, address value) internal { bytes32 slot = keccak256(abi.encodePacked(tag_)); assembly { sstore(slot, value) } } function setAddressValueOnce(string memory tag_, address value) internal { require(getAddressValue(tag_) == address(0x0), "ALREADY_SET"); setAddressValue(tag_, value); } function getBoolValue(string memory tag_) internal view returns (bool retVal) { bytes32 slot = keccak256(abi.encodePacked(tag_)); assembly { retVal := sload(slot) } } function setBoolValue(string memory tag_, bool value) internal { bytes32 slot = keccak256(abi.encodePacked(tag_)); assembly { sstore(slot, value) } } } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; library OnchainDataFactTreeEncoder { struct DataAvailabilityFact { uint256 onchainDataHash; uint256 onchainDataSize; } // The number of additional words appended to the public input when using the // OnchainDataFactTreeEncoder format. uint256 internal constant ONCHAIN_DATA_FACT_ADDITIONAL_WORDS = 2; /* Encodes a GPS fact Merkle tree where the root has two children. The left child contains the data we care about and the right child contains on-chain data for the fact. */ function encodeFactWithOnchainData( uint256[] calldata programOutput, DataAvailabilityFact memory factData ) internal pure returns (bytes32) { // The state transition fact is computed as a Merkle tree, as defined in // GpsOutputParser. // // In our case the fact tree looks as follows: // The root has two children. // The left child is a leaf that includes the main part - the information regarding // the state transition required by this contract. // The right child contains the onchain-data which shouldn't be accessed by this // contract, so we are only given its hash and length // (it may be a leaf or an inner node, this has no effect on this contract). // Compute the hash without the two additional fields. uint256 mainPublicInputLen = programOutput.length; bytes32 mainPublicInputHash = keccak256(abi.encodePacked(programOutput)); // Compute the hash of the fact Merkle tree. bytes32 hashResult = keccak256( abi.encodePacked( mainPublicInputHash, mainPublicInputLen, factData.onchainDataHash, mainPublicInputLen + factData.onchainDataSize ) ); // Add one to the hash to indicate it represents an inner node, rather than a leaf. return bytes32(uint256(hashResult) + 1); } } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; import "MOperator.sol"; import "MGovernance.sol"; /** The Operator of the contract is the entity entitled to submit state update requests by calling :sol:func:`updateState`. An Operator may be instantly appointed or removed by the contract Governor (see :sol:mod:`Governance`). Typically, the Operator is the hot wallet of the service submitting proofs for state updates. */ abstract contract Operator is MGovernance, MOperator { function registerOperator(address newOperator) external override onlyGovernance { if (!isOperator(newOperator)) { getOperators()[newOperator] = true; emit LogOperatorAdded(newOperator); } } function unregisterOperator(address removedOperator) external override onlyGovernance { if (isOperator(removedOperator)) { getOperators()[removedOperator] = false; emit LogOperatorRemoved(removedOperator); } } function isOperator(address user) public view override returns (bool) { return getOperators()[user]; } } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; library CommitmentTreeUpdateOutput { /** Returns the previous commitment tree root. */ function getPrevRoot(uint256[] calldata commitmentTreeUpdateData) internal pure returns (uint256) { return commitmentTreeUpdateData[0]; } /** Returns the new commitment tree root. */ function getNewRoot(uint256[] calldata commitmentTreeUpdateData) internal pure returns (uint256) { return commitmentTreeUpdateData[1]; } } library StarknetOutput { uint256 internal constant MERKLE_UPDATE_OFFSET = 0; uint256 internal constant BLOCK_NUMBER_OFFSET = 2; uint256 internal constant BLOCK_HASH_OFFSET = 3; uint256 internal constant CONFIG_HASH_OFFSET = 4; uint256 internal constant HEADER_SIZE = 5; uint256 constant MESSAGE_TO_L1_FROM_ADDRESS_OFFSET = 0; uint256 constant MESSAGE_TO_L1_TO_ADDRESS_OFFSET = 1; uint256 constant MESSAGE_TO_L1_PAYLOAD_SIZE_OFFSET = 2; uint256 constant MESSAGE_TO_L1_PREFIX_SIZE = 3; uint256 constant MESSAGE_TO_L2_FROM_ADDRESS_OFFSET = 0; uint256 constant MESSAGE_TO_L2_TO_ADDRESS_OFFSET = 1; uint256 constant MESSAGE_TO_L2_NONCE_OFFSET = 2; uint256 constant MESSAGE_TO_L2_SELECTOR_OFFSET = 3; uint256 constant MESSAGE_TO_L2_PAYLOAD_SIZE_OFFSET = 4; uint256 constant MESSAGE_TO_L2_PREFIX_SIZE = 5; // An event that is raised when a message is sent from L2 to L1. event LogMessageToL1(uint256 indexed fromAddress, address indexed toAddress, uint256[] payload); // An event that is raised when a message from L1 to L2 is consumed. event ConsumedMessageToL2( address indexed fromAddress, uint256 indexed toAddress, uint256 indexed selector, uint256[] payload, uint256 nonce ); /** Does a sanity check of the output_data length. */ function validate(uint256[] calldata output_data) internal pure { require(output_data.length > HEADER_SIZE, "STARKNET_OUTPUT_TOO_SHORT"); } /** Returns a slice of the 'output_data' with the commitment tree update information. */ function getMerkleUpdate(uint256[] calldata output_data) internal pure returns (uint256[] calldata) { return output_data[MERKLE_UPDATE_OFFSET:MERKLE_UPDATE_OFFSET + 2]; } /** Processes a message segment from the program output. The format of a message segment is the length of the messages in words followed by the concatenation of all the messages. The 'messages' mapping is updated according to the messages and the direction ('isL2ToL1'). */ function processMessages( bool isL2ToL1, uint256[] calldata programOutputSlice, mapping(bytes32 => uint256) storage messages ) internal returns (uint256) { uint256 messageSegmentSize = programOutputSlice[0]; require(messageSegmentSize < 2**30, "INVALID_MESSAGE_SEGMENT_SIZE"); uint256 offset = 1; uint256 messageSegmentEnd = offset + messageSegmentSize; uint256 payloadSizeOffset = ( isL2ToL1 ? MESSAGE_TO_L1_PAYLOAD_SIZE_OFFSET : MESSAGE_TO_L2_PAYLOAD_SIZE_OFFSET ); uint256 totalMsgFees = 0; while (offset < messageSegmentEnd) { uint256 payloadLengthOffset = offset + payloadSizeOffset; require(payloadLengthOffset < programOutputSlice.length, "MESSAGE_TOO_SHORT"); uint256 payloadLength = programOutputSlice[payloadLengthOffset]; require(payloadLength < 2**30, "INVALID_PAYLOAD_LENGTH"); uint256 endOffset = payloadLengthOffset + 1 + payloadLength; require(endOffset <= programOutputSlice.length, "TRUNCATED_MESSAGE_PAYLOAD"); if (isL2ToL1) { bytes32 messageHash = keccak256( abi.encodePacked(programOutputSlice[offset:endOffset]) ); emit LogMessageToL1( // from= programOutputSlice[offset + MESSAGE_TO_L1_FROM_ADDRESS_OFFSET], // to= address(programOutputSlice[offset + MESSAGE_TO_L1_TO_ADDRESS_OFFSET]), // payload= (uint256[])(programOutputSlice[offset + MESSAGE_TO_L1_PREFIX_SIZE:endOffset]) ); messages[messageHash] += 1; } else { { bytes32 messageHash = keccak256( abi.encodePacked(programOutputSlice[offset:endOffset]) ); uint256 msgFeePlusOne = messages[messageHash]; require(msgFeePlusOne > 0, "INVALID_MESSAGE_TO_CONSUME"); totalMsgFees += msgFeePlusOne - 1; messages[messageHash] = 0; } uint256 nonce = programOutputSlice[offset + MESSAGE_TO_L2_NONCE_OFFSET]; uint256[] memory messageSlice = (uint256[])( programOutputSlice[offset + MESSAGE_TO_L2_PREFIX_SIZE:endOffset] ); emit ConsumedMessageToL2( // from= address(programOutputSlice[offset + MESSAGE_TO_L2_FROM_ADDRESS_OFFSET]), // to= programOutputSlice[offset + MESSAGE_TO_L2_TO_ADDRESS_OFFSET], // selector= programOutputSlice[offset + MESSAGE_TO_L2_SELECTOR_OFFSET], // payload= messageSlice, // nonce = nonce ); } offset = endOffset; } require(offset == messageSegmentEnd, "INVALID_MESSAGE_SEGMENT_SIZE"); if (totalMsgFees > 0) { // NOLINTNEXTLINE: low-level-calls. (bool success, ) = msg.sender.call{value: totalMsgFees}(""); require(success, "ETH_TRANSFER_FAILED"); } return offset; } } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; import "Governance.sol"; import "Addresses.sol"; import "BlockDirectCall.sol"; import "ContractInitializer.sol"; /** This contract contains the code commonly needed for a contract to be deployed behind an upgradability proxy. It perform the required semantics of the proxy pattern, but in a generic manner. Instantiation of the Governance and of the ContractInitializer, that are the app specific part of initialization, has to be done by the using contract. */ abstract contract ProxySupport is Governance, BlockDirectCall, ContractInitializer { using Addresses for address; // The two function below (isFrozen & initialize) needed to bind to the Proxy. function isFrozen() external view virtual returns (bool) { return false; } /* The initialize() function serves as an alternative constructor for a proxied deployment. Flow and notes: 1. This function cannot be called directly on the deployed contract, but only via delegate call. 2. If an EIC is provided - init is passed onto EIC and the standard init flow is skipped. This true for both first intialization or a later one. 3. The data passed to this function is as follows: [sub_contracts addresses, eic address, initData]. When calling on an initialized contract (no EIC scenario), initData.length must be 0. */ function initialize(bytes calldata data) external notCalledDirectly { uint256 eicOffset = 32 * numOfSubContracts(); uint256 expectedBaseSize = eicOffset + 32; require(data.length >= expectedBaseSize, "INIT_DATA_TOO_SMALL"); address eicAddress = abi.decode(data[eicOffset:expectedBaseSize], (address)); bytes calldata subContractAddresses = data[:eicOffset]; processSubContractAddresses(subContractAddresses); bytes calldata initData = data[expectedBaseSize:]; // EIC Provided - Pass initData to EIC and the skip standard init flow. if (eicAddress != address(0x0)) { callExternalInitializer(eicAddress, initData); return; } if (isInitialized()) { require(initData.length == 0, "UNEXPECTED_INIT_DATA"); } else { // Contract was not initialized yet. validateInitData(initData); initializeContractState(initData); initGovernance(); } } function callExternalInitializer(address externalInitializerAddr, bytes calldata eicData) private { require(externalInitializerAddr.isContract(), "EIC_NOT_A_CONTRACT"); // NOLINTNEXTLINE: low-level-calls, controlled-delegatecall. (bool success, bytes memory returndata) = externalInitializerAddr.delegatecall( abi.encodeWithSelector(this.initialize.selector, eicData) ); require(success, string(returndata)); require(returndata.length == 0, string(returndata)); } } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "Output.sol"; import "StarknetGovernance.sol"; import "StarknetMessaging.sol"; import "StarknetOperator.sol"; import "StarknetState.sol"; import "GovernedFinalizable.sol"; import "OnchainDataFactTreeEncoder.sol"; import "ContractInitializer.sol"; import "Identity.sol"; import "IFactRegistry.sol"; import "ProxySupport.sol"; import "NamedStorage.sol"; contract Starknet is Identity, StarknetMessaging, StarknetGovernance, GovernedFinalizable, StarknetOperator, ContractInitializer, ProxySupport { using StarknetState for StarknetState.State; // Indicates a change of the Starknet config hash. event ConfigHashChanged( address indexed changedBy, uint256 oldConfigHash, uint256 newConfigHash ); // Logs the new state following a state update. event LogStateUpdate(uint256 globalRoot, int256 blockNumber, uint256 blockHash); // Logs a stateTransitionFact that was used to update the state. event LogStateTransitionFact(bytes32 stateTransitionFact); // Indicates a change of the Starknet OS program hash. event ProgramHashChanged( address indexed changedBy, uint256 oldProgramHash, uint256 newProgramHash ); // Random storage slot tags. string internal constant PROGRAM_HASH_TAG = "STARKNET_1.0_INIT_PROGRAM_HASH_UINT"; string internal constant VERIFIER_ADDRESS_TAG = "STARKNET_1.0_INIT_VERIFIER_ADDRESS"; string internal constant STATE_STRUCT_TAG = "STARKNET_1.0_INIT_STARKNET_STATE_STRUCT"; // The hash of the StarkNet config. string internal constant CONFIG_HASH_TAG = "STARKNET_1.0_STARKNET_CONFIG_HASH"; function setProgramHash(uint256 newProgramHash) external notFinalized onlyGovernance { emit ProgramHashChanged(msg.sender, programHash(), newProgramHash); programHash(newProgramHash); } function setConfigHash(uint256 newConfigHash) external notFinalized onlyGovernance { emit ConfigHashChanged(msg.sender, configHash(), newConfigHash); configHash(newConfigHash); } function setMessageCancellationDelay(uint256 delayInSeconds) external notFinalized onlyGovernance { messageCancellationDelay(delayInSeconds); } // State variable "programHash" read-access function. function programHash() public view returns (uint256) { return NamedStorage.getUintValue(PROGRAM_HASH_TAG); } // State variable "programHash" write-access function. function programHash(uint256 value) internal { NamedStorage.setUintValue(PROGRAM_HASH_TAG, value); } // State variable "verifier" access function. function verifier() internal view returns (address) { return NamedStorage.getAddressValue(VERIFIER_ADDRESS_TAG); } // State variable "configHash" write-access function. function configHash(uint256 value) internal { NamedStorage.setUintValue(CONFIG_HASH_TAG, value); } // State variable "configHash" read-access function. function configHash() public view returns (uint256) { return NamedStorage.getUintValue(CONFIG_HASH_TAG); } function setVerifierAddress(address value) internal { NamedStorage.setAddressValueOnce(VERIFIER_ADDRESS_TAG, value); } // State variable "state" access function. function state() internal pure returns (StarknetState.State storage stateStruct) { bytes32 location = keccak256(abi.encodePacked(STATE_STRUCT_TAG)); assembly { stateStruct_slot := location } } function isInitialized() internal view override returns (bool) { return programHash() != 0; } function numOfSubContracts() internal pure override returns (uint256) { return 0; } function validateInitData(bytes calldata data) internal view override { require(data.length == 6 * 32, "ILLEGAL_INIT_DATA_SIZE"); uint256 programHash_ = abi.decode(data[:32], (uint256)); require(programHash_ != 0, "BAD_INITIALIZATION"); } function processSubContractAddresses(bytes calldata subContractAddresses) internal override {} function initializeContractState(bytes calldata data) internal override { ( uint256 programHash_, address verifier_, uint256 configHash_, StarknetState.State memory initialState ) = abi.decode(data, (uint256, address, uint256, StarknetState.State)); programHash(programHash_); setVerifierAddress(verifier_); state().copy(initialState); configHash(configHash_); messageCancellationDelay(5 days); } /** Returns a string that identifies the contract. */ function identify() external pure override returns (string memory) { return "StarkWare_Starknet_2023_6"; } /** Returns the current state root. */ function stateRoot() external view returns (uint256) { return state().globalRoot; } /** Returns the current block number. */ function stateBlockNumber() external view returns (int256) { return state().blockNumber; } /** Returns the current block hash. */ function stateBlockHash() external view returns (uint256) { return state().blockHash; } /** Updates the state of the StarkNet, based on a proof of the StarkNet OS that the state transition is valid. Arguments: programOutput - The main part of the StarkNet OS program output. data_availability_fact - An encoding of the on-chain data associated with the 'programOutput'. */ function updateState( uint256[] calldata programOutput, uint256 onchainDataHash, uint256 onchainDataSize ) external onlyOperator { // We protect against re-entrancy attacks by reading the block number at the beginning // and validating that we have the expected block number at the end. int256 initialBlockNumber = state().blockNumber; // Validate program output. StarknetOutput.validate(programOutput); // Validate config hash. require( configHash() == programOutput[StarknetOutput.CONFIG_HASH_OFFSET], "INVALID_CONFIG_HASH" ); bytes32 stateTransitionFact = OnchainDataFactTreeEncoder.encodeFactWithOnchainData( programOutput, OnchainDataFactTreeEncoder.DataAvailabilityFact(onchainDataHash, onchainDataSize) ); bytes32 sharpFact = keccak256(abi.encode(programHash(), stateTransitionFact)); require(IFactRegistry(verifier()).isValid(sharpFact), "NO_STATE_TRANSITION_PROOF"); emit LogStateTransitionFact(stateTransitionFact); // Perform state update. state().update(programOutput); // Process the messages after updating the state. // This is safer, as there is a call to transfer the fees during // the processing of the L1 -> L2 messages. // Process L2 -> L1 messages. uint256 outputOffset = StarknetOutput.HEADER_SIZE; outputOffset += StarknetOutput.processMessages( // isL2ToL1= true, programOutput[outputOffset:], l2ToL1Messages() ); // Process L1 -> L2 messages. outputOffset += StarknetOutput.processMessages( // isL2ToL1= false, programOutput[outputOffset:], l1ToL2Messages() ); require(outputOffset == programOutput.length, "STARKNET_OUTPUT_TOO_LONG"); // Note that processing L1 -> L2 messages does an external call, and it shouldn't be // followed by storage changes. StarknetState.State storage state_ = state(); emit LogStateUpdate(state_.globalRoot, state_.blockNumber, state_.blockHash); // Re-entrancy protection (see above). require(state_.blockNumber == initialBlockNumber + 1, "INVALID_FINAL_BLOCK_NUMBER"); } } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; import "Governance.sol"; contract StarknetGovernance is Governance { string constant STARKNET_GOVERNANCE_INFO_TAG = "STARKNET_1.0_GOVERNANCE_INFO"; /* Returns the GovernanceInfoStruct associated with the governance tag. */ function getGovernanceInfo() internal view override returns (GovernanceInfoStruct storage gub) { bytes32 location = keccak256(abi.encodePacked(STARKNET_GOVERNANCE_INFO_TAG)); assembly { gub_slot := location } } function starknetIsGovernor(address user) external view returns (bool) { return _isGovernor(user); } function starknetNominateNewGovernor(address newGovernor) external { _nominateNewGovernor(newGovernor); } function starknetRemoveGovernor(address governorForRemoval) external { _removeGovernor(governorForRemoval); } function starknetAcceptGovernance() external { _acceptGovernance(); } function starknetCancelNomination() external { _cancelNomination(); } } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; import "IStarknetMessaging.sol"; import "NamedStorage.sol"; /** Implements sending messages to L2 by adding them to a pipe and consuming messages from L2 by removing them from a different pipe. A deriving contract can handle the former pipe and add items to the latter pipe while interacting with L2. */ contract StarknetMessaging is IStarknetMessaging { /* Random slot storage elements and accessors. */ string constant L1L2_MESSAGE_MAP_TAG = "STARKNET_1.0_MSGING_L1TOL2_MAPPPING_V2"; string constant L2L1_MESSAGE_MAP_TAG = "STARKNET_1.0_MSGING_L2TOL1_MAPPPING"; string constant L1L2_MESSAGE_NONCE_TAG = "STARKNET_1.0_MSGING_L1TOL2_NONCE"; string constant L1L2_MESSAGE_CANCELLATION_MAP_TAG = ( "STARKNET_1.0_MSGING_L1TOL2_CANCELLATION_MAPPPING" ); string constant L1L2_MESSAGE_CANCELLATION_DELAY_TAG = ( "STARKNET_1.0_MSGING_L1TOL2_CANCELLATION_DELAY" ); uint256 constant MAX_L1_MSG_FEE = 1 ether; function getMaxL1MsgFee() public pure override returns (uint256) { return MAX_L1_MSG_FEE; } /** Returns the msg_fee + 1 for the message with the given 'msgHash', or 0 if no message with such a hash is pending. */ function l1ToL2Messages(bytes32 msgHash) external view returns (uint256) { return l1ToL2Messages()[msgHash]; } function l2ToL1Messages(bytes32 msgHash) external view returns (uint256) { return l2ToL1Messages()[msgHash]; } function l1ToL2Messages() internal pure returns (mapping(bytes32 => uint256) storage) { return NamedStorage.bytes32ToUint256Mapping(L1L2_MESSAGE_MAP_TAG); } function l2ToL1Messages() internal pure returns (mapping(bytes32 => uint256) storage) { return NamedStorage.bytes32ToUint256Mapping(L2L1_MESSAGE_MAP_TAG); } function l1ToL2MessageNonce() public view returns (uint256) { return NamedStorage.getUintValue(L1L2_MESSAGE_NONCE_TAG); } function messageCancellationDelay() public view returns (uint256) { return NamedStorage.getUintValue(L1L2_MESSAGE_CANCELLATION_DELAY_TAG); } function messageCancellationDelay(uint256 delayInSeconds) internal { NamedStorage.setUintValue(L1L2_MESSAGE_CANCELLATION_DELAY_TAG, delayInSeconds); } /** Returns the timestamp at the time cancelL1ToL2Message was called with a message matching 'msgHash'. The function returns 0 if cancelL1ToL2Message was never called. */ function l1ToL2MessageCancellations(bytes32 msgHash) external view returns (uint256) { return l1ToL2MessageCancellations()[msgHash]; } function l1ToL2MessageCancellations() internal pure returns (mapping(bytes32 => uint256) storage) { return NamedStorage.bytes32ToUint256Mapping(L1L2_MESSAGE_CANCELLATION_MAP_TAG); } /** Returns the hash of an L1 -> L2 message from msg.sender. */ function getL1ToL2MsgHash( uint256 toAddress, uint256 selector, uint256[] calldata payload, uint256 nonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked( uint256(msg.sender), toAddress, nonce, selector, payload.length, payload ) ); } /** Sends a message to an L2 contract. */ function sendMessageToL2( uint256 toAddress, uint256 selector, uint256[] calldata payload ) external payable override returns (bytes32, uint256) { require(msg.value > 0, "L1_MSG_FEE_MUST_BE_GREATER_THAN_0"); require(msg.value <= getMaxL1MsgFee(), "MAX_L1_MSG_FEE_EXCEEDED"); uint256 nonce = l1ToL2MessageNonce(); NamedStorage.setUintValue(L1L2_MESSAGE_NONCE_TAG, nonce + 1); emit LogMessageToL2(msg.sender, toAddress, selector, payload, nonce, msg.value); bytes32 msgHash = getL1ToL2MsgHash(toAddress, selector, payload, nonce); // Note that the inclusion of the unique nonce in the message hash implies that // l1ToL2Messages()[msgHash] was not accessed before. l1ToL2Messages()[msgHash] = msg.value + 1; return (msgHash, nonce); } /** Consumes a message that was sent from an L2 contract. Returns the hash of the message. */ function consumeMessageFromL2(uint256 fromAddress, uint256[] calldata payload) external override returns (bytes32) { bytes32 msgHash = keccak256( abi.encodePacked(fromAddress, uint256(msg.sender), payload.length, payload) ); require(l2ToL1Messages()[msgHash] > 0, "INVALID_MESSAGE_TO_CONSUME"); emit ConsumedMessageToL1(fromAddress, msg.sender, payload); l2ToL1Messages()[msgHash] -= 1; return msgHash; } function startL1ToL2MessageCancellation( uint256 toAddress, uint256 selector, uint256[] calldata payload, uint256 nonce ) external override returns (bytes32) { emit MessageToL2CancellationStarted(msg.sender, toAddress, selector, payload, nonce); bytes32 msgHash = getL1ToL2MsgHash(toAddress, selector, payload, nonce); uint256 msgFeePlusOne = l1ToL2Messages()[msgHash]; require(msgFeePlusOne > 0, "NO_MESSAGE_TO_CANCEL"); l1ToL2MessageCancellations()[msgHash] = block.timestamp; return msgHash; } function cancelL1ToL2Message( uint256 toAddress, uint256 selector, uint256[] calldata payload, uint256 nonce ) external override returns (bytes32) { emit MessageToL2Canceled(msg.sender, toAddress, selector, payload, nonce); // Note that the message hash depends on msg.sender, which prevents one contract from // cancelling another contract's message. // Trying to do so will result in NO_MESSAGE_TO_CANCEL. bytes32 msgHash = getL1ToL2MsgHash(toAddress, selector, payload, nonce); uint256 msgFeePlusOne = l1ToL2Messages()[msgHash]; require(msgFeePlusOne != 0, "NO_MESSAGE_TO_CANCEL"); uint256 requestTime = l1ToL2MessageCancellations()[msgHash]; require(requestTime != 0, "MESSAGE_CANCELLATION_NOT_REQUESTED"); uint256 cancelAllowedTime = requestTime + messageCancellationDelay(); require(cancelAllowedTime >= requestTime, "CANCEL_ALLOWED_TIME_OVERFLOW"); require(block.timestamp >= cancelAllowedTime, "MESSAGE_CANCELLATION_NOT_ALLOWED_YET"); l1ToL2Messages()[msgHash] = 0; return (msgHash); } } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; import "Operator.sol"; import "NamedStorage.sol"; abstract contract StarknetOperator is Operator { string constant OPERATORS_MAPPING_TAG = "STARKNET_1.0_ROLES_OPERATORS_MAPPING_TAG"; function getOperators() internal view override returns (mapping(address => bool) storage) { return NamedStorage.addressToBoolMapping(OPERATORS_MAPPING_TAG); } } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; import "Output.sol"; library StarknetState { struct State { uint256 globalRoot; int256 blockNumber; uint256 blockHash; } function copy(State storage state, State memory stateFrom) internal { state.globalRoot = stateFrom.globalRoot; state.blockNumber = stateFrom.blockNumber; state.blockHash = stateFrom.blockHash; } /** Validates that the 'blockNumber' and the previous root are consistent with the current state and updates the state. */ function update(State storage state, uint256[] calldata starknetOutput) internal { // Check the blockNumber first as the error is less ambiguous then INVALID_PREVIOUS_ROOT. state.blockNumber += 1; require( uint256(state.blockNumber) == starknetOutput[StarknetOutput.BLOCK_NUMBER_OFFSET], "INVALID_BLOCK_NUMBER" ); state.blockHash = starknetOutput[StarknetOutput.BLOCK_HASH_OFFSET]; uint256[] calldata commitment_tree_update = StarknetOutput.getMerkleUpdate(starknetOutput); require( state.globalRoot == CommitmentTreeUpdateOutput.getPrevRoot(commitment_tree_update), "INVALID_PREVIOUS_ROOT" ); state.globalRoot = CommitmentTreeUpdateOutput.getNewRoot(commitment_tree_update); } }
File 3 of 5: Proxy
{"Common.sol":{"content":"/*\n Copyright 2019-2021 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\n/*\n Common Utility librarries.\n I. Addresses (extending address).\n*/\nlibrary Addresses {\n function isContract(address account) internal view returns (bool) {\n uint256 size;\n assembly {\n size := extcodesize(account)\n }\n return size \u003e 0;\n }\n\n function performEthTransfer(address recipient, uint256 amount) internal {\n (bool success, ) = recipient.call{value: amount}(\"\"); // NOLINT: low-level-calls.\n require(success, \"ETH_TRANSFER_FAILED\");\n }\n\n /*\n Safe wrapper around ERC20/ERC721 calls.\n This is required because many deployed ERC20 contracts don\u0027t return a value.\n See https://github.com/ethereum/solidity/issues/4116.\n */\n function safeTokenContractCall(address tokenAddress, bytes memory callData) internal {\n require(isContract(tokenAddress), \"BAD_TOKEN_ADDRESS\");\n // NOLINTNEXTLINE: low-level-calls.\n (bool success, bytes memory returndata) = tokenAddress.call(callData);\n require(success, string(returndata));\n\n if (returndata.length \u003e 0) {\n require(abi.decode(returndata, (bool)), \"TOKEN_OPERATION_FAILED\");\n }\n }\n\n /*\n Validates that the passed contract address is of a real contract,\n and that its id hash (as infered fromn identify()) matched the expected one.\n */\n function validateContractId(address contractAddress, bytes32 expectedIdHash) internal {\n require(isContract(contractAddress), \"ADDRESS_NOT_CONTRACT\");\n (bool success, bytes memory returndata) = contractAddress.call( // NOLINT: low-level-calls.\n abi.encodeWithSignature(\"identify()\")\n );\n require(success, \"FAILED_TO_IDENTIFY_CONTRACT\");\n string memory realContractId = abi.decode(returndata, (string));\n require(\n keccak256(abi.encodePacked(realContractId)) == expectedIdHash,\n \"UNEXPECTED_CONTRACT_IDENTIFIER\"\n );\n }\n\n /*\n Similar to safeTokenContractCall, but always ignores the return value.\n\n Assumes some other method is used to detect the failures\n (e.g. balance is checked before and after the call).\n */\n function uncheckedTokenContractCall(address tokenAddress, bytes memory callData) internal {\n // NOLINTNEXTLINE: low-level-calls.\n (bool success, bytes memory returndata) = tokenAddress.call(callData);\n require(success, string(returndata));\n }\n}\n\n/*\n II. StarkExTypes - Common data types.\n*/\nlibrary StarkExTypes {\n // Structure representing a list of verifiers (validity/availability).\n // A statement is valid only if all the verifiers in the list agree on it.\n // Adding a verifier to the list is immediate - this is used for fast resolution of\n // any soundness issues.\n // Removing from the list is time-locked, to ensure that any user of the system\n // not content with the announced removal has ample time to leave the system before it is\n // removed.\n struct ApprovalChainData {\n address[] list;\n // Represents the time after which the verifier with the given address can be removed.\n // Removal of the verifier with address A is allowed only in the case the value\n // of unlockedForRemovalTime[A] != 0 and unlockedForRemovalTime[A] \u003c (current time).\n mapping(address =\u003e uint256) unlockedForRemovalTime;\n }\n}\n"},"Governance.sol":{"content":"/*\n Copyright 2019-2021 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"MGovernance.sol\";\n\n/*\n Implements Generic Governance, applicable for both proxy and main contract, and possibly others.\n Notes:\n The use of the same function names by both the Proxy and a delegated implementation\n is not possible since calling the implementation functions is done via the default function\n of the Proxy. For this reason, for example, the implementation of MainContract (MainGovernance)\n exposes mainIsGovernor, which calls the internal isGovernor method.\n*/\nabstract contract Governance is MGovernance {\n event LogNominatedGovernor(address nominatedGovernor);\n event LogNewGovernorAccepted(address acceptedGovernor);\n event LogRemovedGovernor(address removedGovernor);\n event LogNominationCancelled();\n\n function getGovernanceInfo() internal view virtual returns (GovernanceInfoStruct storage);\n\n /*\n Current code intentionally prevents governance re-initialization.\n This may be a problem in an upgrade situation, in a case that the upgrade-to implementation\n performs an initialization (for real) and within that calls initGovernance().\n\n Possible workarounds:\n 1. Clearing the governance info altogether by changing the MAIN_GOVERNANCE_INFO_TAG.\n This will remove existing main governance information.\n 2. Modify the require part in this function, so that it will exit quietly\n when trying to re-initialize (uncomment the lines below).\n */\n function initGovernance() internal {\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n require(!gub.initialized, \"ALREADY_INITIALIZED\");\n gub.initialized = true; // to ensure addGovernor() won\u0027t fail.\n // Add the initial governer.\n addGovernor(msg.sender);\n }\n\n function isGovernor(address testGovernor) internal view override returns (bool) {\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n return gub.effectiveGovernors[testGovernor];\n }\n\n /*\n Cancels the nomination of a governor candidate.\n */\n function cancelNomination() internal onlyGovernance {\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n gub.candidateGovernor = address(0x0);\n emit LogNominationCancelled();\n }\n\n function nominateNewGovernor(address newGovernor) internal onlyGovernance {\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n require(!isGovernor(newGovernor), \"ALREADY_GOVERNOR\");\n gub.candidateGovernor = newGovernor;\n emit LogNominatedGovernor(newGovernor);\n }\n\n /*\n The addGovernor is called in two cases:\n 1. by acceptGovernance when a new governor accepts its role.\n 2. by initGovernance to add the initial governor.\n The difference is that the init path skips the nominate step\n that would fail because of the onlyGovernance modifier.\n */\n function addGovernor(address newGovernor) private {\n require(!isGovernor(newGovernor), \"ALREADY_GOVERNOR\");\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n gub.effectiveGovernors[newGovernor] = true;\n }\n\n function acceptGovernance() internal {\n // The new governor was proposed as a candidate by the current governor.\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n require(msg.sender == gub.candidateGovernor, \"ONLY_CANDIDATE_GOVERNOR\");\n\n // Update state.\n addGovernor(gub.candidateGovernor);\n gub.candidateGovernor = address(0x0);\n\n // Send a notification about the change of governor.\n emit LogNewGovernorAccepted(msg.sender);\n }\n\n /*\n Remove a governor from office.\n */\n function removeGovernor(address governorForRemoval) internal onlyGovernance {\n require(msg.sender != governorForRemoval, \"GOVERNOR_SELF_REMOVE\");\n GovernanceInfoStruct storage gub = getGovernanceInfo();\n require(isGovernor(governorForRemoval), \"NOT_GOVERNOR\");\n gub.effectiveGovernors[governorForRemoval] = false;\n emit LogRemovedGovernor(governorForRemoval);\n }\n}\n"},"GovernanceStorage.sol":{"content":"/*\n Copyright 2019-2021 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\nimport \"MGovernance.sol\";\n\n/*\n Holds the governance slots for ALL entities, including proxy and the main contract.\n*/\ncontract GovernanceStorage {\n // A map from a Governor tag to its own GovernanceInfoStruct.\n mapping(string =\u003e GovernanceInfoStruct) internal governanceInfo; //NOLINT uninitialized-state.\n}\n"},"MGovernance.sol":{"content":"/*\n Copyright 2019-2021 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nstruct GovernanceInfoStruct {\n mapping(address =\u003e bool) effectiveGovernors;\n address candidateGovernor;\n bool initialized;\n}\n\nabstract contract MGovernance {\n function isGovernor(address testGovernor) internal view virtual returns (bool);\n\n /*\n Allows calling the function only by a Governor.\n */\n modifier onlyGovernance() {\n require(isGovernor(msg.sender), \"ONLY_GOVERNANCE\");\n _;\n }\n}\n"},"Proxy.sol":{"content":"/*\n Copyright 2019-2021 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"ProxyGovernance.sol\";\nimport \"ProxyStorage.sol\";\nimport \"StorageSlots.sol\";\nimport \"Common.sol\";\n\n/**\n The Proxy contract implements delegation of calls to other contracts (`implementations`), with\n proper forwarding of return values and revert reasons. This pattern allows retaining the contract\n storage while replacing implementation code.\n\n The following operations are supported by the proxy contract:\n\n - :sol:func:`addImplementation`: Defines a new implementation, the data with which it should be initialized and whether this will be the last version of implementation.\n - :sol:func:`upgradeTo`: Once an implementation is added, the governor may upgrade to that implementation only after a safety time period has passed (time lock), the current implementation is not the last version and the implementation is not frozen (see :sol:mod:`FullWithdrawals`).\n - :sol:func:`removeImplementation`: Any announced implementation may be removed. Removing an implementation is especially important once it has been used for an upgrade in order to avoid an additional unwanted revert to an older version.\n\n The only entity allowed to perform the above operations is the proxy governor\n (see :sol:mod:`ProxyGovernance`).\n\n Every implementation is required to have an `initialize` function that replaces the constructor\n of a normal contract. Furthermore, the only parameter of this function is an array of bytes\n (`data`) which may be decoded arbitrarily by the `initialize` function. It is up to the\n implementation to ensure that this function cannot be run more than once if so desired.\n\n When an implementation is added (:sol:func:`addImplementation`) the initialization `data` is also\n announced, allowing users of the contract to analyze the full effect of an upgrade to the new\n implementation. During an :sol:func:`upgradeTo`, the `data` is provided again and only if it is\n identical to the announced `data` is the upgrade performed by pointing the proxy to the new\n implementation and calling its `initialize` function with this `data`.\n\n It is the responsibility of the implementation not to overwrite any storage belonging to the\n proxy (`ProxyStorage`). In addition, upon upgrade, the new implementation is assumed to be\n backward compatible with previous implementations with respect to the storage used until that\n point.\n*/\ncontract Proxy is ProxyStorage, ProxyGovernance, StorageSlots {\n // Emitted when the active implementation is replaced.\n event ImplementationUpgraded(address indexed implementation, bytes initializer);\n\n // Emitted when an implementation is submitted as an upgrade candidate and a time lock\n // is activated.\n event ImplementationAdded(address indexed implementation, bytes initializer, bool finalize);\n\n // Emitted when an implementation is removed from the list of upgrade candidates.\n event ImplementationRemoved(address indexed implementation, bytes initializer, bool finalize);\n\n // Emitted when the implementation is finalized.\n event FinalizedImplementation(address indexed implementation);\n\n using Addresses for address;\n\n string public constant PROXY_VERSION = \"3.0.0\";\n\n constructor(uint256 upgradeActivationDelay) public {\n initGovernance();\n setUpgradeActivationDelay(upgradeActivationDelay);\n }\n\n function setUpgradeActivationDelay(uint256 delayInSeconds) private {\n bytes32 slot = UPGRADE_DELAY_SLOT;\n assembly {\n sstore(slot, delayInSeconds)\n }\n }\n\n function getUpgradeActivationDelay() public view returns (uint256 delay) {\n bytes32 slot = UPGRADE_DELAY_SLOT;\n assembly {\n delay := sload(slot)\n }\n return delay;\n }\n\n /*\n Returns the address of the current implementation.\n */\n // NOLINTNEXTLINE external-function.\n function implementation() public view returns (address _implementation) {\n bytes32 slot = IMPLEMENTATION_SLOT;\n assembly {\n _implementation := sload(slot)\n }\n }\n\n /*\n Returns true if the implementation is frozen.\n If the implementation was not assigned yet, returns false.\n */\n function implementationIsFrozen() private returns (bool) {\n address _implementation = implementation();\n\n // We can\u0027t call low level implementation before it\u0027s assigned. (i.e. ZERO).\n if (_implementation == address(0x0)) {\n return false;\n }\n\n // NOLINTNEXTLINE: low-level-calls.\n (bool success, bytes memory returndata) = _implementation.delegatecall(\n abi.encodeWithSignature(\"isFrozen()\")\n );\n require(success, string(returndata));\n return abi.decode(returndata, (bool));\n }\n\n /*\n This method blocks delegation to initialize().\n Only upgradeTo should be able to delegate call to initialize().\n */\n function initialize(\n bytes calldata /*data*/\n ) external pure {\n revert(\"CANNOT_CALL_INITIALIZE\");\n }\n\n modifier notFinalized() {\n require(isNotFinalized(), \"IMPLEMENTATION_FINALIZED\");\n _;\n }\n\n /*\n Forbids calling the function if the implementation is frozen.\n This modifier relies on the lower level (logical contract) implementation of isFrozen().\n */\n modifier notFrozen() {\n require(!implementationIsFrozen(), \"STATE_IS_FROZEN\");\n _;\n }\n\n /*\n This entry point serves only transactions with empty calldata. (i.e. pure value transfer tx).\n We don\u0027t expect to receive such, thus block them.\n */\n receive() external payable {\n revert(\"CONTRACT_NOT_EXPECTED_TO_RECEIVE\");\n }\n\n /*\n Contract\u0027s default function. Delegates execution to the implementation contract.\n It returns back to the external caller whatever the implementation delegated code returns.\n */\n fallback() external payable {\n address _implementation = implementation();\n require(_implementation != address(0x0), \"MISSING_IMPLEMENTATION\");\n\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 for now, as we don\u0027t know the out size yet.\n let result := delegatecall(gas(), _implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /*\n Sets the implementation address of the proxy.\n */\n function setImplementation(address newImplementation) private {\n bytes32 slot = IMPLEMENTATION_SLOT;\n assembly {\n sstore(slot, newImplementation)\n }\n }\n\n /*\n Returns true if the contract is not in the finalized state.\n */\n function isNotFinalized() public view returns (bool notFinal) {\n bytes32 slot = FINALIZED_STATE_SLOT;\n uint256 slotValue;\n assembly {\n slotValue := sload(slot)\n }\n notFinal = (slotValue == 0);\n }\n\n /*\n Marks the current implementation as finalized.\n */\n function setFinalizedFlag() private {\n bytes32 slot = FINALIZED_STATE_SLOT;\n assembly {\n sstore(slot, 0x1)\n }\n }\n\n /*\n Introduce an implementation and its initialization vector,\n and start the time-lock before it can be upgraded to.\n addImplementation is not blocked when frozen or finalized.\n (upgradeTo API is blocked when finalized or frozen).\n */\n function addImplementation(\n address newImplementation,\n bytes calldata data,\n bool finalize\n ) external onlyGovernance {\n require(newImplementation.isContract(), \"ADDRESS_NOT_CONTRACT\");\n\n bytes32 implVectorHash = keccak256(abi.encode(newImplementation, data, finalize));\n\n uint256 activationTime = block.timestamp + getUpgradeActivationDelay();\n\n // First implementation should not have time-lock.\n if (implementation() == address(0x0)) {\n activationTime = block.timestamp;\n }\n\n enabledTime[implVectorHash] = activationTime;\n emit ImplementationAdded(newImplementation, data, finalize);\n }\n\n /*\n Removes a candidate implementation.\n Note that it is possible to remove the current implementation. Doing so doesn\u0027t affect the\n current implementation, but rather revokes it as a future candidate.\n */\n function removeImplementation(\n address removedImplementation,\n bytes calldata data,\n bool finalize\n ) external onlyGovernance {\n bytes32 implVectorHash = keccak256(abi.encode(removedImplementation, data, finalize));\n\n // If we have initializer, we set the hash of it.\n uint256 activationTime = enabledTime[implVectorHash];\n require(activationTime \u003e 0, \"UNKNOWN_UPGRADE_INFORMATION\");\n delete enabledTime[implVectorHash];\n emit ImplementationRemoved(removedImplementation, data, finalize);\n }\n\n /*\n Upgrades the proxy to a new implementation, with its initialization.\n to upgrade successfully, implementation must have been added time-lock agreeably\n before, and the init vector must be identical ot the one submitted before.\n\n Upon assignment of new implementation address,\n its initialize will be called with the initializing vector (even if empty).\n Therefore, the implementation MUST must have such a method.\n\n Note - Initialization data is committed to in advance, therefore it must remain valid\n until the actual contract upgrade takes place.\n\n Care should be taken regarding initialization data and flow when planning the contract upgrade.\n\n When planning contract upgrade, special care is also needed with regard to governance\n (See comments in Governance.sol).\n */\n // NOLINTNEXTLINE: reentrancy-events timestamp.\n function upgradeTo(\n address newImplementation,\n bytes calldata data,\n bool finalize\n ) external payable onlyGovernance notFinalized notFrozen {\n bytes32 implVectorHash = keccak256(abi.encode(newImplementation, data, finalize));\n uint256 activationTime = enabledTime[implVectorHash];\n require(activationTime \u003e 0, \"UNKNOWN_UPGRADE_INFORMATION\");\n require(newImplementation.isContract(), \"ADDRESS_NOT_CONTRACT\");\n // NOLINTNEXTLINE: timestamp.\n require(activationTime \u003c= block.timestamp, \"UPGRADE_NOT_ENABLED_YET\");\n\n setImplementation(newImplementation);\n\n // NOLINTNEXTLINE: low-level-calls controlled-delegatecall.\n (bool success, bytes memory returndata) = newImplementation.delegatecall(\n abi.encodeWithSelector(this.initialize.selector, data)\n );\n require(success, string(returndata));\n\n // Verify that the new implementation is not frozen post initialization.\n // NOLINTNEXTLINE: low-level-calls controlled-delegatecall.\n (success, returndata) = newImplementation.delegatecall(\n abi.encodeWithSignature(\"isFrozen()\")\n );\n require(success, \"CALL_TO_ISFROZEN_REVERTED\");\n require(!abi.decode(returndata, (bool)), \"NEW_IMPLEMENTATION_FROZEN\");\n\n if (finalize) {\n setFinalizedFlag();\n emit FinalizedImplementation(newImplementation);\n }\n\n emit ImplementationUpgraded(newImplementation, data);\n }\n}\n"},"ProxyGovernance.sol":{"content":"/*\n Copyright 2019-2021 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"Governance.sol\";\nimport \"GovernanceStorage.sol\";\n\n/**\n The Proxy contract is governed by one or more Governors of which the initial one is the\n deployer of the contract.\n\n A governor has the sole authority to perform the following operations:\n\n 1. Nominate additional governors (:sol:func:`proxyNominateNewGovernor`)\n 2. Remove other governors (:sol:func:`proxyRemoveGovernor`)\n 3. Add new `implementations` (proxied contracts)\n 4. Remove (new or old) `implementations`\n 5. Update `implementations` after a timelock allows it\n\n Adding governors is performed in a two step procedure:\n\n 1. First, an existing governor nominates a new governor (:sol:func:`proxyNominateNewGovernor`)\n 2. Then, the new governor must accept governance to become a governor (:sol:func:`proxyAcceptGovernance`)\n\n This two step procedure ensures that a governor public key cannot be nominated unless there is an\n entity that has the corresponding private key. This is intended to prevent errors in the addition\n process.\n\n The governor private key should typically be held in a secure cold wallet or managed via a\n multi-sig contract.\n*/\n/*\n Implements Governance for the proxy contract.\n It is a thin wrapper to the Governance contract,\n which is needed so that it can have non-colliding function names,\n and a specific tag (key) to allow unique state storage.\n*/\ncontract ProxyGovernance is GovernanceStorage, Governance {\n // The tag is the string key that is used in the Governance storage mapping.\n string public constant PROXY_GOVERNANCE_TAG = \"StarkEx.Proxy.2019.GovernorsInformation\";\n\n /*\n Returns the GovernanceInfoStruct associated with the governance tag.\n */\n function getGovernanceInfo() internal view override returns (GovernanceInfoStruct storage) {\n return governanceInfo[PROXY_GOVERNANCE_TAG];\n }\n\n function proxyIsGovernor(address testGovernor) external view returns (bool) {\n return isGovernor(testGovernor);\n }\n\n function proxyNominateNewGovernor(address newGovernor) external {\n nominateNewGovernor(newGovernor);\n }\n\n function proxyRemoveGovernor(address governorForRemoval) external {\n removeGovernor(governorForRemoval);\n }\n\n function proxyAcceptGovernance() external {\n acceptGovernance();\n }\n\n function proxyCancelNomination() external {\n cancelNomination();\n }\n}\n"},"ProxyStorage.sol":{"content":"/*\n Copyright 2019-2021 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"GovernanceStorage.sol\";\n\n/*\n Holds the Proxy-specific state variables.\n This contract is inherited by the GovernanceStorage (and indirectly by MainStorage)\n to prevent collision hazard.\n*/\ncontract ProxyStorage is GovernanceStorage {\n // NOLINTNEXTLINE: naming-convention uninitialized-state.\n mapping(address =\u003e bytes32) internal initializationHash_DEPRECATED;\n\n // The time after which we can switch to the implementation.\n // Hash(implementation, data, finalize) =\u003e time.\n mapping(bytes32 =\u003e uint256) internal enabledTime;\n\n // A central storage of the flags whether implementation has been initialized.\n // Note - it can be used flexibly enough to accommodate multiple levels of initialization\n // (i.e. using different key salting schemes for different initialization levels).\n mapping(bytes32 =\u003e bool) internal initialized;\n}\n"},"StorageSlots.sol":{"content":"/*\n Copyright 2019-2021 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\n/**\n StorageSlots holds the arbitrary storage slots used throughout the Proxy pattern.\n Storage address slots are a mechanism to define an arbitrary location, that will not be\n overlapped by the logical contracts.\n*/\ncontract StorageSlots {\n // Storage slot with the address of the current implementation.\n // The address of the slot is keccak256(\"StarkWare2019.implemntation-slot\").\n // We need to keep this variable stored outside of the commonly used space,\n // so that it\u0027s not overrun by the logical implementation (the proxied contract).\n bytes32 internal constant IMPLEMENTATION_SLOT =\n 0x177667240aeeea7e35eabe3a35e18306f336219e1386f7710a6bf8783f761b24;\n\n // Storage slot with the address of the call-proxy current implementation.\n // The address of the slot is keccak256(\"\u0027StarkWare2020.CallProxy.Implemntation.Slot\u0027\").\n // We need to keep this variable stored outside of the commonly used space.\n // so that it\u0027s not overrun by the logical implementation (the proxied contract).\n bytes32 internal constant CALL_PROXY_IMPL_SLOT =\n 0x7184681641399eb4ad2fdb92114857ee6ff239f94ad635a1779978947b8843be;\n\n // This storage slot stores the finalization flag.\n // Once the value stored in this slot is set to non-zero\n // the proxy blocks implementation upgrades.\n // The current implementation is then referred to as Finalized.\n // Web3.solidityKeccak([\u0027string\u0027], [\"StarkWare2019.finalization-flag-slot\"]).\n bytes32 internal constant FINALIZED_STATE_SLOT =\n 0x7d433c6f837e8f93009937c466c82efbb5ba621fae36886d0cac433c5d0aa7d2;\n\n // Storage slot to hold the upgrade delay (time-lock).\n // The intention of this slot is to allow modification using an EIC.\n // Web3.solidityKeccak([\u0027string\u0027], [\u0027StarkWare.Upgradibility.Delay.Slot\u0027]).\n bytes32 public constant UPGRADE_DELAY_SLOT =\n 0xc21dbb3089fcb2c4f4c6a67854ab4db2b0f233ea4b21b21f912d52d18fc5db1f;\n}\n"}}
File 4 of 5: CallProxy
{"BlockDirectCall.sol":{"content":"/*\n Copyright 2019-2022 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\n/*\n This contract provides means to block direct call of an external function.\n A derived contract (e.g. MainDispatcherBase) should decorate sensitive functions with the\n notCalledDirectly modifier, thereby preventing it from being called directly, and allowing only calling\n using delegate_call.\n\n This Guard contract uses pseudo-random slot, So each deployed contract would have its own guard.\n*/\nabstract contract BlockDirectCall {\n bytes32 immutable UNIQUE_SAFEGUARD_SLOT; // NOLINT naming-convention.\n\n constructor() internal {\n // The slot is pseudo-random to allow hierarchy of contracts with guarded functions.\n bytes32 slot = keccak256(abi.encode(this, block.timestamp, gasleft()));\n UNIQUE_SAFEGUARD_SLOT = slot;\n assembly {\n sstore(slot, 42)\n }\n }\n\n modifier notCalledDirectly() {\n {\n // Prevent too many local variables in stack.\n uint256 safeGuardValue;\n bytes32 slot = UNIQUE_SAFEGUARD_SLOT;\n assembly {\n safeGuardValue := sload(slot)\n }\n require(safeGuardValue == 0, \"DIRECT_CALL_DISALLOWED\");\n }\n _;\n }\n}\n"},"CallProxy.sol":{"content":"/*\n Copyright 2019-2022 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\nimport \"IFactRegistry.sol\";\nimport \"StorageSlots.sol\";\nimport \"BlockDirectCall.sol\";\nimport \"Common.sol\";\n\n/**\n CallProxy is a \u0027call\u0027 based proxy.\n It is a facade to a real implementation,\n only that unlike the Proxy pattern, it uses call and not delegatecall,\n so that the state is recorded on the called contract.\n\n This contract is expected to be placed behind the regular proxy,\n thus:\n 1. Implementation address is stored in a hashed slot (other than proxy\u0027s one...).\n 2. No state variable is allowed in low address ranges.\n 3. Setting of implementation is done in initialize.\n 4. isFrozen and initialize are implemented, to be compliant with Proxy.\n\n This implementation is intentionally minimal,\n and has no management or governance.\n The assumption is that if a different implementation is needed, it will be performed\n in an upgradeTo a new deployed CallProxy, pointing to a new implementation.\n*/\n// NOLINTNEXTLINE locked-ether.\ncontract CallProxy is BlockDirectCall, StorageSlots {\n using Addresses for address;\n\n string public constant CALL_PROXY_VERSION = \"3.1.0\";\n\n // Proxy client - initialize \u0026 isFrozen.\n // NOLINTNEXTLINE: external-function.\n function isFrozen() public pure returns (bool) {\n return false;\n }\n\n /*\n This function is called by the Proxy upon activating an implementation.\n The data passed in to this function contains the implementation address,\n and if applicable, an address of an EIC (ExternalInitializerContract) and its data.\n\n The expected data format is as following:\n\n Case I (no EIC):\n data.length == 64.\n [0 :32] implementation address\n [32:64] Zero address.\n\n Case II (EIC):\n data length \u003e= 64\n [0 :32] implementation address\n [32:64] EIC address\n [64: ] EIC init data.\n */\n function initialize(bytes calldata data) external notCalledDirectly {\n require(data.length \u003e= 64, \"INCORRECT_DATA_SIZE\");\n (address impl, address eic) = abi.decode(data, (address, address));\n require(impl.isContract(), \"ADDRESS_NOT_CONTRACT\");\n setCallProxyImplementation(impl);\n if (eic != address(0x0)) {\n callExternalInitializer(eic, data[64:]);\n } else {\n require(data.length == 64, \"INVALID_INIT_DATA\");\n }\n }\n\n function callExternalInitializer(address externalInitializerAddr, bytes calldata eicData)\n private\n {\n require(externalInitializerAddr.isContract(), \"EIC_NOT_A_CONTRACT\");\n\n // NOLINTNEXTLINE: low-level-calls, controlled-delegatecall.\n (bool success, bytes memory returndata) = externalInitializerAddr.delegatecall(\n abi.encodeWithSelector(this.initialize.selector, eicData)\n );\n require(success, string(returndata));\n require(returndata.length == 0, string(returndata));\n }\n\n /*\n Returns the call proxy implementation address.\n */\n function callProxyImplementation() public view returns (address _implementation) {\n bytes32 slot = CALL_PROXY_IMPL_SLOT;\n assembly {\n _implementation := sload(slot)\n }\n }\n\n /*\n Sets the call proxy implementation address.\n */\n function setCallProxyImplementation(address newImplementation) private {\n bytes32 slot = CALL_PROXY_IMPL_SLOT;\n assembly {\n sstore(slot, newImplementation)\n }\n }\n\n /*\n An explicit isValid entry point, used to make isValid a part of the ABI and visible\n on Etherscan (and alike).\n */\n function isValid(bytes32 fact) external view returns (bool) {\n return IFactRegistry(callProxyImplementation()).isValid(fact);\n }\n\n /*\n This entry point serves only transactions with empty calldata. (i.e. pure value transfer tx).\n We don\u0027t expect to receive such, thus block them.\n */\n receive() external payable {\n revert(\"CONTRACT_NOT_EXPECTED_TO_RECEIVE\");\n }\n\n /*\n Contract\u0027s default function. Pass execution to the implementation contract (using call).\n It returns back to the external caller whatever the implementation called code returns.\n */\n fallback() external payable {\n // NOLINT locked-ether.\n address _implementation = callProxyImplementation();\n require(_implementation != address(0x0), \"MISSING_IMPLEMENTATION\");\n uint256 value = msg.value;\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 for now, as we don\u0027t know the out size yet.\n let result := call(gas(), _implementation, value, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n}\n"},"Common.sol":{"content":"/*\n Copyright 2019-2022 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\n/*\n Common Utility librarries.\n I. Addresses (extending address).\n*/\nlibrary Addresses {\n function isContract(address account) internal view returns (bool) {\n uint256 size;\n assembly {\n size := extcodesize(account)\n }\n return size \u003e 0;\n }\n\n function performEthTransfer(address recipient, uint256 amount) internal {\n (bool success, ) = recipient.call{value: amount}(\"\"); // NOLINT: low-level-calls.\n require(success, \"ETH_TRANSFER_FAILED\");\n }\n\n /*\n Safe wrapper around ERC20/ERC721 calls.\n This is required because many deployed ERC20 contracts don\u0027t return a value.\n See https://github.com/ethereum/solidity/issues/4116.\n */\n function safeTokenContractCall(address tokenAddress, bytes memory callData) internal {\n require(isContract(tokenAddress), \"BAD_TOKEN_ADDRESS\");\n // NOLINTNEXTLINE: low-level-calls.\n (bool success, bytes memory returndata) = tokenAddress.call(callData);\n require(success, string(returndata));\n\n if (returndata.length \u003e 0) {\n require(abi.decode(returndata, (bool)), \"TOKEN_OPERATION_FAILED\");\n }\n }\n\n /*\n Validates that the passed contract address is of a real contract,\n and that its id hash (as infered fromn identify()) matched the expected one.\n */\n function validateContractId(address contractAddress, bytes32 expectedIdHash) internal {\n require(isContract(contractAddress), \"ADDRESS_NOT_CONTRACT\");\n (bool success, bytes memory returndata) = contractAddress.call( // NOLINT: low-level-calls.\n abi.encodeWithSignature(\"identify()\")\n );\n require(success, \"FAILED_TO_IDENTIFY_CONTRACT\");\n string memory realContractId = abi.decode(returndata, (string));\n require(\n keccak256(abi.encodePacked(realContractId)) == expectedIdHash,\n \"UNEXPECTED_CONTRACT_IDENTIFIER\"\n );\n }\n\n /*\n Similar to safeTokenContractCall, but always ignores the return value.\n\n Assumes some other method is used to detect the failures\n (e.g. balance is checked before and after the call).\n */\n function uncheckedTokenContractCall(address tokenAddress, bytes memory callData) internal {\n // NOLINTNEXTLINE: low-level-calls.\n (bool success, bytes memory returndata) = tokenAddress.call(callData);\n require(success, string(returndata));\n }\n}\n\n/*\n II. StarkExTypes - Common data types.\n*/\nlibrary StarkExTypes {\n // Structure representing a list of verifiers (validity/availability).\n // A statement is valid only if all the verifiers in the list agree on it.\n // Adding a verifier to the list is immediate - this is used for fast resolution of\n // any soundness issues.\n // Removing from the list is time-locked, to ensure that any user of the system\n // not content with the announced removal has ample time to leave the system before it is\n // removed.\n struct ApprovalChainData {\n address[] list;\n // Represents the time after which the verifier with the given address can be removed.\n // Removal of the verifier with address A is allowed only in the case the value\n // of unlockedForRemovalTime[A] != 0 and unlockedForRemovalTime[A] \u003c (current time).\n mapping(address =\u003e uint256) unlockedForRemovalTime;\n }\n}\n"},"IFactRegistry.sol":{"content":"/*\n Copyright 2019-2022 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\n/*\n The Fact Registry design pattern is a way to separate cryptographic verification from the\n business logic of the contract flow.\n\n A fact registry holds a hash table of verified \"facts\" which are represented by a hash of claims\n that the registry hash check and found valid. This table may be queried by accessing the\n isValid() function of the registry with a given hash.\n\n In addition, each fact registry exposes a registry specific function for submitting new claims\n together with their proofs. The information submitted varies from one registry to the other\n depending of the type of fact requiring verification.\n\n For further reading on the Fact Registry design pattern see this\n `StarkWare blog post \u003chttps://medium.com/starkware/the-fact-registry-a64aafb598b6\u003e`_.\n*/\ninterface IFactRegistry {\n /*\n Returns true if the given fact was previously registered in the contract.\n */\n function isValid(bytes32 fact) external view returns (bool);\n}\n"},"StorageSlots.sol":{"content":"/*\n Copyright 2019-2022 StarkWare Industries Ltd.\n\n Licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://www.starkware.co/open-source-license/\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions\n and limitations under the License.\n*/\n// SPDX-License-Identifier: Apache-2.0.\npragma solidity ^0.6.12;\n\n/**\n StorageSlots holds the arbitrary storage slots used throughout the Proxy pattern.\n Storage address slots are a mechanism to define an arbitrary location, that will not be\n overlapped by the logical contracts.\n*/\ncontract StorageSlots {\n // Storage slot with the address of the current implementation.\n // The address of the slot is keccak256(\"StarkWare2019.implemntation-slot\").\n // We need to keep this variable stored outside of the commonly used space,\n // so that it\u0027s not overrun by the logical implementation (the proxied contract).\n bytes32 internal constant IMPLEMENTATION_SLOT =\n 0x177667240aeeea7e35eabe3a35e18306f336219e1386f7710a6bf8783f761b24;\n\n // Storage slot with the address of the call-proxy current implementation.\n // The address of the slot is keccak256(\"\u0027StarkWare2020.CallProxy.Implemntation.Slot\u0027\").\n // We need to keep this variable stored outside of the commonly used space.\n // so that it\u0027s not overrun by the logical implementation (the proxied contract).\n bytes32 internal constant CALL_PROXY_IMPL_SLOT =\n 0x7184681641399eb4ad2fdb92114857ee6ff239f94ad635a1779978947b8843be;\n\n // This storage slot stores the finalization flag.\n // Once the value stored in this slot is set to non-zero\n // the proxy blocks implementation upgrades.\n // The current implementation is then referred to as Finalized.\n // Web3.solidityKeccak([\u0027string\u0027], [\"StarkWare2019.finalization-flag-slot\"]).\n bytes32 internal constant FINALIZED_STATE_SLOT =\n 0x7d433c6f837e8f93009937c466c82efbb5ba621fae36886d0cac433c5d0aa7d2;\n\n // Storage slot to hold the upgrade delay (time-lock).\n // The intention of this slot is to allow modification using an EIC.\n // Web3.solidityKeccak([\u0027string\u0027], [\u0027StarkWare.Upgradibility.Delay.Slot\u0027]).\n bytes32 public constant UPGRADE_DELAY_SLOT =\n 0xc21dbb3089fcb2c4f4c6a67854ab4db2b0f233ea4b21b21f912d52d18fc5db1f;\n}\n"}}
File 5 of 5: GpsStatementVerifier
/* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // ---------- The following code was auto-generated. PLEASE DO NOT EDIT. ---------- // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; contract CairoBootloaderProgramSize { uint256 internal constant PROGRAM_SIZE = 562; } contract CairoBootloaderProgram is CairoBootloaderProgramSize { function getCompiledProgram() external pure returns (uint256[PROGRAM_SIZE] memory) { return [ 290341444919459839, 8, 1226245742482522112, 386, 74168662805676031, 0, 2345108766317314046, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020480, 5198420613823102976, 3618502788666131213697322783095070105623107215331596699973092056135872020479, 2345108766317314046, 146226256843603965, 4, 5191102238658887680, 2345108766317314046, 290341444919459839, 3, 4632937381316558848, 4612671182992932865, 4612671182992998402, 146226256843603968, 4, 74168662805676031, 4, 4612671182993063937, 4612671182993129474, 5198983563776196608, 1, 5198983563776262144, 1, 5200109459388203008, 5200109459388268544, 5198983563776458752, 3618502788666131213697322783095070105623107215331596699973092056135872020480, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020458, 2345108766317314046, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020449, 5191102234363920384, 5191102238658887680, 5191102242953854976, 5198420613822906368, 90, 5189976364521848832, 8, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020446, 4623648689905041407, 291467327646433279, 2345108766317314046, 5199827962936983548, 5208553695804948479, 4612389708016287743, 5198983563776262144, 1, 2345108766317314046, 146226256843603965, 4, 5191102230068953088, 2345108766317314046, 5191102230068953088, 5188850460319711232, 5188850460319776768, 5188850460319842304, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020467, 5198983563776262144, 1, 5198983563776327680, 1, 5198983563776393216, 1, 5198983563776458752, 3618502788666131213697322783095070105623107215331596699973092056135872020480, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020463, 2345108766317314046, 5188850460319907840, 5202361254907052032, 5191102242953854976, 5188287510366552064, 5188287506071519232, 5188287510366486527, 4611826762357964797, 5198420613822906368, 3618502788666131213697322783095070105623107215331596699973092056135872020480, 5198420613822906368, 3, 5188287518956224512, 4623085744246521853, 145944781866893308, 3618502788666131213697322783095070105623107215331596699973092056135872020472, 2345108766317314046, 290341444919459839, 24, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020390, 4617174774030761984, 4612671182992998402, 5189976364521848832, 0, 4612389712311713791, 5188850464614678528, 5191102264428691456, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020454, 4612389712311779327, 4622804286450008067, 4, 4612671195878359044, 5200109476568596480, 5188850468910104576, 4625619027626983429, 4622804286450073606, 2, 4617174765440827399, 4612671191582933000, 4612671195877900297, 4612671200172867594, 4612671204467834891, 4612671208762802188, 4612671213057769485, 5191102242953854976, 5198983563776655360, 6, 5191102273018626048, 5191102277313593344, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020390, 1191342862550269952, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020356, 4623648724265893887, 5191102242953854976, 5198983563776655360, 15, 5191102273018626048, 5191102320263266304, 5189976364521848832, 8, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020351, 4623648719970271231, 5191102238658887680, 5198983563776655360, 6, 5198983563776655360, 15, 5191102247248822272, 5189976364521848832, 8, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020386, 4623930190653259791, 4612671182993522711, 5198983563776655360, 15, 5193354051357474816, 2345108766317314046, 290341444919459839, 26, 4622804286449287169, 1, 4614922944152305666, 4614922982807011331, 4614922952742240260, 4614922957037207557, 4614922961332174854, 4614922965627142151, 4614922969922109448, 4613797087195136009, 122550255383924, 4613797087195136010, 8098989891770344814, 4613797087195136011, 138277649577220228665140075, 4613797087195136012, 435459224417, 4613797087195136013, 27700496658166629, 4613797087195136014, 435458895728, 4613797087195136015, 118083203326315, 4613797087195136016, 8101821134059892590, 4613797087195136017, 1, 4613797087195136018, 3, 4613797087195136019, 1, 4613797087195136020, 2, 4613797087195136021, 5, 4613797087195136022, 7, 4613797087195136023, 16, 4613797087195136024, 6, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020283, 5198420613823102976, 1, 5191102225773985792, 5198420613822971904, 9, 5198420613822906368, 17, 5188850460319449088, 1226245742482522112, 35, 4614641507830300671, 4617174774030762009, 5188850468911677440, 5201798300658860031, 5189976364521848832, 64, 1226245742482522112, 11, 5188850460321742848, 5188850464616710144, 5188850468911677440, 5188850473206644736, 5188850477501612032, 5188850481796579328, 5188850486091546624, 5188850490386513920, 2345108766317314046, 146226256843603965, 5, 4613797087195135996, 0, 2345108766317314046, 290341444919459839, 1, 5201798304953761792, 5202079779930537980, 4634344751905079295, 5193354047062507520, 5198983563776458752, 3618502788666131213697322783095070105623107215331596699973092056135872020480, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020468, 2345108766317314046, 146226256843603965, 5, 5191102230068953088, 5191102234363920384, 2345108766317314046, 5191102230068953088, 5191102234363920384, 5191102238658887680, 5191102242953854976, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020318, 5191102238658887680, 5191102242953854976, 5198983563776458752, 3618502788666131213697322783095070105623107215331596699973092056135872020480, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020466, 2345108766317314046, 4612671182993129469, 5198983563776393216, 1, 2345108766317314046, 5191102238658887680, 5199827967231950845, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020475, 2345108766317314046, 5191102238658887680, 5191102242953854976, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020470, 5191102242953854976, 5191102247248822272, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020470, 2345108766317314046, 290341444919459839, 1, 5191102230068953088, 5191102260133724160, 5198983563776393216, 3618502788666131213697322783095070105623107215331596699973092056135872020480, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020466, 5209116658642944000, 5202361254906855424, 4612108233039904765, 5193354047062507520, 5193354051357474816, 2345108766317314046, 4612671182993063932, 4612671187288031229, 5198983563776327680, 3, 5188850468909711360, 2345108766317314046, 290341444919459839, 2, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020180, 4613797087195136000, 0, 4613797087195136001, 0, 5193354051357474816, 2345108766317314046, 290341444919459839, 2, 5191102234363920384, 5191102242953854976, 5191102247248822272, 5188850460319776768, 1226245742482522112, 16, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020164, 4617174769735794688, 5188850464614744064, 4623367219223429121, 5193354038472572928, 5193354042767540224, 2345108766317314046, 5191102242953854976, 5188850460319907840, 5188850464614875136, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020446, 2345108766317314046, 146226256843603964, 5, 5191102234363920384, 5191102247248822272, 2345108766317314046, 290341444919459839, 1, 5198983563776393216, 3618502788666131213697322783095070105623107215331596699973092056135872020480, 4626181977580208128, 5191102238658887680, 5191102234363920384, 5191102247248822272, 5202079771340603392, 4611826758063063038, 5188287510366420992, 4611826762357964799, 5198420613822906368, 1, 5198420613822906368, 3, 5188287518956224512, 145944781866893307, 3618502788666131213697322783095070105623107215331596699973092056135872020472, 2345108766317314046, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020424, 5191102238658887680, 5193354051357474816, 5191102242953854976, 5191102247248822272, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020428, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020442, 2345108766317314046, 146226256843603965, 3, 2345108766317314046, 5191102238658887680, 5191102242953854976, 5188287510366617600, 4611826758063063039, 5198420613823037441, 1, 5198420613823037441, 1, 722405534170316798, 3618502788666131213697322783095070105623107215331596699973092056135872020475, 4623648689905041407, 2345108766317314046, 290341444919459839, 10, 5191102260133724160, 5191102221479018496, 5191102225773985792, 5191102230068953088, 5191102234363920384, 5191102238658887680, 5191102242953854976, 5191102247248822272, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020244, 4617174756850892801, 4617174761145860098, 4617174765440827395, 4617174769735794692, 4617174774030761989, 4617174778325729286, 4617174748260958215, 5191102217184051200, 5193354025587671040, 5191102294493462528, 1226245742482522112, 64, 4617174774030761993, 5198420613823102976, 1, 5193354051357474816, 5191102264428691456, 5189976364521848832, 0, 5198983563776655360, 1, 5191102294493462528, 5188850460320104448, 1226245742482522112, 13, 4617174778325729287, 4612389708017270782, 5193354038472572928, 5193354038472572928, 5193354038472572928, 5191102268723658752, 5191102273018626048, 5191102277313593344, 5191102281608560640, 5191102285903527936, 2345108766317314046, 146226256843603965, 8, 5191102221479018496, 5191102225773985792, 5191102230068953088, 5191102234363920384, 5191102238658887680, 2345108766317314046, 290341444919459839, 0, 290341444919459839, 1, 145944781866893311, 12, 5191102221479018496, 5191102225773985792, 5191102230068953088, 5191102234363920384, 5191102238658887680, 5191102242953854976, 1226245742482522112, 34, 74168662805676031, 10, 5191102221479018496, 5191102225773985792, 5191102230068953088, 5191102234363920384, 5191102238658887680, 5191102242953854976, 1226245742482522112, 68, 5191102242953854976, 5198983563776458752, 3618502788666131213697322783095070105623107215331596699973092056135872020480, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020446, 2345108766317314046, 5188850460319907840, 4612389708016353279, 5191102242953854976, 5188850468909842432, 5188850464614875136, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020364, 4612389712311320575, 5198983563776327680, 2, 5193354047062507520, 2345108766317314046, 5198983563776458752, 2, 5191102247248822272, 2345108766317314046, 290341444919459839, 4, 5191102230068953088, 5191102260133724160, 5191102264428691456, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020348, 5191102242953854976, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020469, 5189976364521848832, 4, 4611826758063128575, 5191102234363920384, 5188850468909842432, 5189976364521848832, 1, 5188850464614875136, 5188287514661257216, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020257, 5188850460319907840, 4611826758060965887, 4611826762355933145, 4622241336494227458, 2, 4614922982807011331, 5191102225773985792, 5193353883853750272, 5193354038472572928, 5191102238658887680, 5198983563776655360, 1, 5191102247248822272, 5188850460320104448, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020392, 4623648711380271103, 5193354038472572928, 5193354038472572928, 5193354038472572928, 5193354038472572928, 5191102268723658752, 2345108766317314046, 290341444919459839, 2, 5191102242953854976, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020430, 4617174774030761984, 5188287510366617600, 4612389708016156671, 5188287514661519360, 4612389712311123967, 5188287510366486528, 4622241336496455681, 3618502788666131213697322783095070105623107215331596699973092056135872020479, 5198983563776131072, 2, 5191102260133724160, 5191102264428691456, 1226245742482522112, 3618502788666131213697322783095070105623107215331596699973092056135872020303, 5198983563776131072, 2, 5199546513730011136, 5191102230068953088, 5191102234363920384, 5198983563776327680, 1, 5200109463683497984, 2345108766317314046 ]; } } // ---------- End of auto-generated code. ---------- /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; abstract contract CairoVerifierContract { function verifyProofExternal( uint256[] calldata proofParams, uint256[] calldata proof, uint256[] calldata publicInput ) external virtual; /* Returns information that is related to the layout. publicMemoryOffset is the offset of the public memory pages' information in the public input. selectedBuiltins is a bit-map of builtins that are present in the layout. */ function getLayoutInfo() external pure virtual returns (uint256 publicMemoryOffset, uint256 selectedBuiltins); uint256 internal constant OUTPUT_BUILTIN_BIT = 0; uint256 internal constant PEDERSEN_BUILTIN_BIT = 1; uint256 internal constant RANGE_CHECK_BUILTIN_BIT = 2; uint256 internal constant ECDSA_BUILTIN_BIT = 3; uint256 internal constant BITWISE_BUILTIN_BIT = 4; uint256 internal constant EC_OP_BUILTIN_BIT = 5; uint256 internal constant KECCAK_BUILTIN_BIT = 6; uint256 internal constant POSEIDON_BUILTIN_BIT = 7; } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; import "PageInfo.sol"; contract CpuPublicInputOffsetsBase is PageInfo { // The following constants are offsets of data expected in the public input. uint256 internal constant OFFSET_LOG_N_STEPS = 0; uint256 internal constant OFFSET_RC_MIN = 1; uint256 internal constant OFFSET_RC_MAX = 2; uint256 internal constant OFFSET_LAYOUT_CODE = 3; uint256 internal constant OFFSET_PROGRAM_BEGIN_ADDR = 4; uint256 internal constant OFFSET_PROGRAM_STOP_PTR = 5; uint256 internal constant OFFSET_EXECUTION_BEGIN_ADDR = 6; uint256 internal constant OFFSET_EXECUTION_STOP_PTR = 7; uint256 internal constant OFFSET_OUTPUT_BEGIN_ADDR = 8; uint256 internal constant OFFSET_OUTPUT_STOP_PTR = 9; uint256 internal constant OFFSET_PEDERSEN_BEGIN_ADDR = 10; uint256 internal constant OFFSET_PEDERSEN_STOP_PTR = 11; uint256 internal constant OFFSET_RANGE_CHECK_BEGIN_ADDR = 12; uint256 internal constant OFFSET_RANGE_CHECK_STOP_PTR = 13; // The program segment starts from 1, so that memory address 0 is kept for the null pointer. uint256 internal constant INITIAL_PC = 1; // The first Cairo instructions are: // ap += n_args; call main; jmp rel 0. // As the first two instructions occupy 2 cells each, the "jmp rel 0" instruction is at // offset 4 relative to INITIAL_PC. uint256 internal constant FINAL_PC = INITIAL_PC + 4; } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; import "IQueryableFactRegistry.sol"; contract FactRegistry is IQueryableFactRegistry { // Mapping: fact hash -> true. mapping(bytes32 => bool) private verifiedFact; // Indicates whether the Fact Registry has at least one fact registered. bool anyFactRegistered = false; /* Checks if a fact has been verified. */ function isValid(bytes32 fact) external view override returns (bool) { return _factCheck(fact); } /* This is an internal method to check if the fact is already registered. In current implementation of FactRegistry it's identical to isValid(). But the check is against the local fact registry, So for a derived referral fact registry, it's not the same. */ function _factCheck(bytes32 fact) internal view returns (bool) { return verifiedFact[fact]; } function registerFact(bytes32 factHash) internal { // This function stores the fact hash in the mapping. verifiedFact[factHash] = true; // Mark first time off. if (!anyFactRegistered) { anyFactRegistered = true; } } /* Indicates whether at least one fact was registered. */ function hasRegisteredFact() external view override returns (bool) { return anyFactRegistered; } } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; import "FactRegistry.sol"; import "CpuPublicInputOffsetsBase.sol"; /* A utility contract to parse the GPS output. See registerGpsFacts for more details. */ contract GpsOutputParser is CpuPublicInputOffsetsBase, FactRegistry { uint256 internal constant METADATA_TASKS_OFFSET = 1; uint256 internal constant METADATA_OFFSET_TASK_OUTPUT_SIZE = 0; uint256 internal constant METADATA_OFFSET_TASK_PROGRAM_HASH = 1; uint256 internal constant METADATA_OFFSET_TASK_N_TREE_PAIRS = 2; uint256 internal constant METADATA_TASK_HEADER_SIZE = 3; uint256 internal constant METADATA_OFFSET_TREE_PAIR_N_PAGES = 0; uint256 internal constant METADATA_OFFSET_TREE_PAIR_N_NODES = 1; uint256 internal constant NODE_STACK_OFFSET_HASH = 0; uint256 internal constant NODE_STACK_OFFSET_END = 1; // The size of each node in the node stack. uint256 internal constant NODE_STACK_ITEM_SIZE = 2; uint256 internal constant FIRST_CONTINUOUS_PAGE_INDEX = 1; /* Logs the program output fact together with the relevant continuous memory pages' hashes. The event is emitted for each registered fact. */ event LogMemoryPagesHashes(bytes32 programOutputFact, bytes32[] pagesHashes); /* Parses the GPS program output (using taskMetadata, which should be verified by the caller), and registers the facts of the tasks which were executed. The first entry in taskMetadata is the number of tasks. For each task, the structure is as follows: 1. Size (including the size and hash fields). 2. Program hash. 3. The number of pairs in the Merkle tree structure (see below). 4. The Merkle tree structure (see below). The fact of each task is stored as a (non-binary) Merkle tree. Leaf nodes are labeled with the hash of their data. Each non-leaf node is labeled as 1 + the hash of (node0, end0, node1, end1, ...) where node* is a label of a child children and end* is the total number of data words up to and including that node and its children (including the previous sibling nodes). We add 1 to the result of the hash to prevent an attacker from using a preimage of a leaf node as a preimage of a non-leaf hash and vice versa. The structure of the tree is passed as a list of pairs (n_pages, n_nodes), and the tree is constructed using a stack of nodes (initialized to an empty stack) by repeating for each pair: 1. Add n_pages to the stack of nodes. 2. Pop the top n_nodes, construct a parent node for them, and push it back to the stack. After applying the steps above, the stack much contain exactly one node, which will constitute the root of the Merkle tree. For example, [(2, 2)] will create a Merkle tree with a root and two direct children, while [(3, 2), (0, 2)] will create a Merkle tree with a root whose left child is a leaf and right child has two leaf children. Assumptions: taskMetadata and cairoAuxInput are verified externally. */ function registerGpsFacts( uint256[] calldata taskMetadata, uint256[] memory publicMemoryPages, uint256 outputStartAddress ) internal { uint256 totalNumPages = publicMemoryPages[0]; // Allocate some of the loop variables here to avoid the stack-too-deep error. uint256 task; uint256 nTreePairs; uint256 nTasks = taskMetadata[0]; // Contains fact hash with the relevant memory pages' hashes. // Size is bounded from above with the total number of pages. Three extra places are // dedicated for the fact hash and the array address and length. uint256[] memory pageHashesLogData = new uint256[](totalNumPages + 3); // Relative address to the beginning of the memory pages' hashes in the array. pageHashesLogData[1] = 0x40; uint256 taskMetadataOffset = METADATA_TASKS_OFFSET; // Skip the 5 first output cells which contain the bootloader config, the number of tasks // and the size and program hash of the first task. curAddr points to the output of the // first task. uint256 curAddr = outputStartAddress + 5; // Skip the main page. uint256 curPage = FIRST_CONTINUOUS_PAGE_INDEX; // Bound the size of the stack by the total number of pages. // TODO(lior, 15/04/2022): Get a better bound on the size of the stack. uint256[] memory nodeStack = new uint256[](NODE_STACK_ITEM_SIZE * totalNumPages); // Copy to memory to workaround the "stack too deep" error. uint256[] memory taskMetadataCopy = taskMetadata; uint256[PAGE_INFO_SIZE] memory pageInfoPtr; assembly { // Skip the array length and the first page. pageInfoPtr := add(add(publicMemoryPages, 0x20), PAGE_INFO_SIZE_IN_BYTES) } // Register the fact for each task. for (task = 0; task < nTasks; task++) { uint256 curOffset = 0; uint256 firstPageOfTask = curPage; nTreePairs = taskMetadataCopy[taskMetadataOffset + METADATA_OFFSET_TASK_N_TREE_PAIRS]; // Build the Merkle tree using a stack (see the function documentation) to compute // the fact. uint256 nodeStackLen = 0; for (uint256 treePair = 0; treePair < nTreePairs; treePair++) { // Add nPages to the stack of nodes. uint256 nPages = taskMetadataCopy[ taskMetadataOffset + METADATA_TASK_HEADER_SIZE + 2 * treePair + METADATA_OFFSET_TREE_PAIR_N_PAGES ]; // Ensure 'nPages' is bounded from above as a sanity check // (the bound is somewhat arbitrary). require(nPages < 2**20, "Invalid value of n_pages in tree structure."); for (uint256 i = 0; i < nPages; i++) { (uint256 pageSize, uint256 pageHash) = pushPageToStack( pageInfoPtr, curAddr, curOffset, nodeStack, nodeStackLen ); pageHashesLogData[curPage - firstPageOfTask + 3] = pageHash; curPage += 1; nodeStackLen += 1; curAddr += pageSize; curOffset += pageSize; assembly { pageInfoPtr := add(pageInfoPtr, PAGE_INFO_SIZE_IN_BYTES) } } // Pop the top n_nodes, construct a parent node for them, and push it back to the // stack. uint256 nNodes = taskMetadataCopy[ taskMetadataOffset + METADATA_TASK_HEADER_SIZE + 2 * treePair + METADATA_OFFSET_TREE_PAIR_N_NODES ]; if (nNodes != 0) { nodeStackLen = constructNode(nodeStack, nodeStackLen, nNodes); } } require(nodeStackLen == 1, "Node stack must contain exactly one item."); uint256 programHash = taskMetadataCopy[ taskMetadataOffset + METADATA_OFFSET_TASK_PROGRAM_HASH ]; // Verify that the sizes of the pages correspond to the task output, to make // sure that the computed hash is indeed the hash of the entire output of the task. { uint256 outputSize = taskMetadataCopy[ taskMetadataOffset + METADATA_OFFSET_TASK_OUTPUT_SIZE ]; require( nodeStack[NODE_STACK_OFFSET_END] + 2 == outputSize, "The sum of the page sizes does not match output size." ); } uint256 programOutputFact = nodeStack[NODE_STACK_OFFSET_HASH]; bytes32 fact = keccak256(abi.encode(programHash, programOutputFact)); // Update taskMetadataOffset. taskMetadataOffset += METADATA_TASK_HEADER_SIZE + 2 * nTreePairs; { // Log the output Merkle root with the hashes of the relevant memory pages. // Instead of emit, we use log1 https://docs.soliditylang.org/en/v0.4.24/assembly.html, // https://docs.soliditylang.org/en/v0.6.2/abi-spec.html#use-of-dynamic-types. bytes32 logHash = keccak256("LogMemoryPagesHashes(bytes32,bytes32[])"); assembly { let buf := add(pageHashesLogData, 0x20) // Number of memory pages that are relevant for this fact. let length := sub(curPage, firstPageOfTask) mstore(buf, programOutputFact) mstore(add(buf, 0x40), length) log1(buf, mul(add(length, 3), 0x20), logHash) } } registerFact(fact); // Move curAddr to the output of the next task (skipping the size and hash fields). curAddr += 2; } require(totalNumPages == curPage, "Not all memory pages were processed."); } /* Push one page (curPage) to the top of the node stack. curAddr is the memory address, curOffset is the offset from the beginning of the task output. Verifies that the page has the right start address and returns the page size and the page hash. */ function pushPageToStack( uint256[PAGE_INFO_SIZE] memory pageInfoPtr, uint256 curAddr, uint256 curOffset, uint256[] memory nodeStack, uint256 nodeStackLen ) private pure returns (uint256 pageSize, uint256 pageHash) { // Read the first address, page size and hash. uint256 pageAddr = pageInfoPtr[PAGE_INFO_ADDRESS_OFFSET]; pageSize = pageInfoPtr[PAGE_INFO_SIZE_OFFSET]; pageHash = pageInfoPtr[PAGE_INFO_HASH_OFFSET]; // Ensure 'pageSize' is bounded as a sanity check (the bound is somewhat arbitrary). require(pageSize < 2**30, "Invalid page size."); require(pageAddr == curAddr, "Invalid page address."); nodeStack[NODE_STACK_ITEM_SIZE * nodeStackLen + NODE_STACK_OFFSET_END] = curOffset + pageSize; nodeStack[NODE_STACK_ITEM_SIZE * nodeStackLen + NODE_STACK_OFFSET_HASH] = pageHash; } /* Pops the top nNodes nodes from the stack and pushes one parent node instead. Returns the new value of nodeStackLen. */ function constructNode( uint256[] memory nodeStack, uint256 nodeStackLen, uint256 nNodes ) private pure returns (uint256) { require(nNodes <= nodeStackLen, "Invalid value of n_nodes in tree structure."); // The end of the node is the end of the last child. uint256 newNodeEnd = nodeStack[ NODE_STACK_ITEM_SIZE * (nodeStackLen - 1) + NODE_STACK_OFFSET_END ]; uint256 newStackLen = nodeStackLen - nNodes; // Compute node hash. uint256 nodeStart = 0x20 + newStackLen * NODE_STACK_ITEM_SIZE * 0x20; uint256 newNodeHash; assembly { newNodeHash := keccak256( add(nodeStack, nodeStart), mul( nNodes, // NODE_STACK_ITEM_SIZE * 0x20 = 0x40 ) ) } nodeStack[NODE_STACK_ITEM_SIZE * newStackLen + NODE_STACK_OFFSET_END] = newNodeEnd; // Add one to the new node hash to distinguish it from the hash of a leaf (a page). nodeStack[NODE_STACK_ITEM_SIZE * newStackLen + NODE_STACK_OFFSET_HASH] = newNodeHash + 1; return newStackLen + 1; } } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; import "CairoBootloaderProgram.sol"; import "CairoVerifierContract.sol"; import "MemoryPageFactRegistry.sol"; import "Identity.sol"; import "PrimeFieldElement0.sol"; import "GpsOutputParser.sol"; contract GpsStatementVerifier is GpsOutputParser, Identity, CairoBootloaderProgramSize, PrimeFieldElement0 { CairoBootloaderProgram bootloaderProgramContractAddress; MemoryPageFactRegistry memoryPageFactRegistry; CairoVerifierContract[] cairoVerifierContractAddresses; uint256 internal constant N_BUILTINS = 8; uint256 internal constant N_MAIN_ARGS = N_BUILTINS; uint256 internal constant N_MAIN_RETURN_VALUES = N_BUILTINS; // Cairo verifier program hash. uint256 immutable hashedSupportedCairoVerifiers_; // Simple bootloader program hash. uint256 immutable simpleBootloaderProgramHash_; /* Constructs an instance of GpsStatementVerifier. bootloaderProgramContract is the address of the bootloader program contract and cairoVerifierContracts is a list of cairoVerifiers indexed by their id. */ constructor( address bootloaderProgramContract, address memoryPageFactRegistry_, address[] memory cairoVerifierContracts, uint256 hashedSupportedCairoVerifiers, uint256 simpleBootloaderProgramHash ) public { bootloaderProgramContractAddress = CairoBootloaderProgram(bootloaderProgramContract); memoryPageFactRegistry = MemoryPageFactRegistry(memoryPageFactRegistry_); cairoVerifierContractAddresses = new CairoVerifierContract[](cairoVerifierContracts.length); for (uint256 i = 0; i < cairoVerifierContracts.length; ++i) { cairoVerifierContractAddresses[i] = CairoVerifierContract(cairoVerifierContracts[i]); } hashedSupportedCairoVerifiers_ = hashedSupportedCairoVerifiers; simpleBootloaderProgramHash_ = simpleBootloaderProgramHash; } function identify() external pure override returns (string memory) { return "StarkWare_GpsStatementVerifier_2022_7"; } /* Returns the bootloader config. */ function getBootloaderConfig() external view returns (uint256, uint256) { return (simpleBootloaderProgramHash_, hashedSupportedCairoVerifiers_); } /* Verifies a proof and registers the corresponding facts. For the structure of cairoAuxInput, see cpu/CpuPublicInputOffsets.sol. taskMetadata is structured as follows: 1. Number of tasks. 2. For each task: 1. Task output size (including program hash and size). 2. Program hash. */ function verifyProofAndRegister( uint256[] calldata proofParams, uint256[] calldata proof, uint256[] calldata taskMetadata, uint256[] calldata cairoAuxInput, uint256 cairoVerifierId ) external { require( cairoVerifierId < cairoVerifierContractAddresses.length, "cairoVerifierId is out of range." ); CairoVerifierContract cairoVerifier = cairoVerifierContractAddresses[cairoVerifierId]; // The values z and alpha are used only for the fact registration of the main page. // They are not part of the public input of CpuVerifier as they are computed there. // Take the relevant slice from 'cairoAuxInput'. uint256[] calldata cairoPublicInput = ( cairoAuxInput[:cairoAuxInput.length - // z and alpha. 2] ); uint256[] memory publicMemoryPages; { (uint256 publicMemoryOffset, uint256 selectedBuiltins) = cairoVerifier.getLayoutInfo(); require(cairoAuxInput.length > publicMemoryOffset, "Invalid cairoAuxInput length."); publicMemoryPages = (uint256[])(cairoPublicInput[publicMemoryOffset:]); uint256 nPages = publicMemoryPages[0]; require(nPages < 10000, "Invalid nPages."); // Validate publicMemoryPages.length. // Each page has a page info and a cumulative product. // There is no 'page address' in the page info for page 0, but this 'free' slot is // used to store the number of pages. require( publicMemoryPages.length == nPages * (PAGE_INFO_SIZE + 1), "Invalid publicMemoryPages length." ); // Process public memory. ( uint256 publicMemoryLength, uint256 memoryHash, uint256 prod ) = registerPublicMemoryMainPage(taskMetadata, cairoAuxInput, selectedBuiltins); // Make sure the first page is valid. // If the size or the hash are invalid, it may indicate that there is a mismatch // between the prover and the verifier on the bootloader program or bootloader config. require( publicMemoryPages[PAGE_INFO_SIZE_OFFSET] == publicMemoryLength, "Invalid size for memory page 0." ); require( publicMemoryPages[PAGE_INFO_HASH_OFFSET] == memoryHash, "Invalid hash for memory page 0." ); require( publicMemoryPages[nPages * PAGE_INFO_SIZE] == prod, "Invalid cumulative product for memory page 0." ); } // NOLINTNEXTLINE: reentrancy-benign. cairoVerifier.verifyProofExternal(proofParams, proof, (uint256[])(cairoPublicInput)); registerGpsFacts(taskMetadata, publicMemoryPages, cairoAuxInput[OFFSET_OUTPUT_BEGIN_ADDR]); } /* Registers the fact for memory page 0, which includes: 1. The bootloader program, 2. Arguments and return values of main() 3. Some of the data required for computing the task facts. which is represented in taskMetadata. Returns information on the registered fact. Arguments: selectedBuiltins: A bit-map of builtins that are present in the layout. See CairoVerifierContract.sol for more information. taskMetadata: Per task metadata. cairoAuxInput: Auxiliary input for the cairo verifier. Assumptions: cairoAuxInput is connected to the public input, which is verified by cairoVerifierContractAddresses. Guarantees: taskMetadata is consistent with the public memory, with some sanity checks. */ function registerPublicMemoryMainPage( uint256[] calldata taskMetadata, uint256[] calldata cairoAuxInput, uint256 selectedBuiltins ) private returns ( uint256 publicMemoryLength, uint256 memoryHash, uint256 prod ) { uint256 nTasks = taskMetadata[0]; // Ensure 'nTasks' is bounded as a sanity check (the bound is somewhat arbitrary). require(nTasks < 2**30, "Invalid number of tasks."); // Public memory length. publicMemoryLength = (PROGRAM_SIZE + // return fp and pc = 2 + N_MAIN_ARGS + N_MAIN_RETURN_VALUES + // Bootloader config size = 2 + // Number of tasks cell = 1 + 2 * nTasks); uint256[] memory publicMemory = new uint256[](MEMORY_PAIR_SIZE * publicMemoryLength); uint256 offset = 0; // Write public memory, which is a list of pairs (address, value). { // Program segment. uint256[PROGRAM_SIZE] memory bootloaderProgram = bootloaderProgramContractAddress .getCompiledProgram(); for (uint256 i = 0; i < bootloaderProgram.length; i++) { // Force that memory[i + INITIAL_PC] = bootloaderProgram[i]. publicMemory[offset] = i + INITIAL_PC; publicMemory[offset + 1] = bootloaderProgram[i]; offset += 2; } } { // Execution segment - Make sure [initial_fp - 2] = initial_fp and . // This is required for the "safe call" feature (that is, all "call" instructions will // return, even if the called function is malicious). // It guarantees that it's not possible to create a cycle in the call stack. uint256 initialFp = cairoAuxInput[OFFSET_EXECUTION_BEGIN_ADDR]; require(initialFp >= 2, "Invalid execution begin address."); publicMemory[offset + 0] = initialFp - 2; publicMemory[offset + 1] = initialFp; // Make sure [initial_fp - 1] = 0. publicMemory[offset + 2] = initialFp - 1; publicMemory[offset + 3] = 0; offset += 4; // Execution segment: Enforce main's arguments and return values. // Note that the page hash depends on the order of the (address, value) pair in the // publicMemory and consequently the arguments must be written before the return values. uint256 returnValuesAddress = cairoAuxInput[OFFSET_EXECUTION_STOP_PTR] - N_BUILTINS; uint256 builtinSegmentInfoOffset = OFFSET_OUTPUT_BEGIN_ADDR; for (uint256 i = 0; i < N_BUILTINS; i++) { // Write argument address. publicMemory[offset] = initialFp + i; uint256 returnValueOffset = offset + 2 * N_BUILTINS; // Write return value address. publicMemory[returnValueOffset] = returnValuesAddress + i; // Write values. if ((selectedBuiltins & 1) != 0) { // Set the argument to the builtin start pointer. publicMemory[offset + 1] = cairoAuxInput[builtinSegmentInfoOffset]; // Set the return value to the builtin stop pointer. publicMemory[returnValueOffset + 1] = cairoAuxInput[ builtinSegmentInfoOffset + 1 ]; builtinSegmentInfoOffset += 2; } else { // Builtin is not present in layout, set the argument value and return value to 0. publicMemory[offset + 1] = 0; publicMemory[returnValueOffset + 1] = 0; } offset += 2; selectedBuiltins >>= 1; } require(selectedBuiltins == 0, "SELECTED_BUILTINS_VECTOR_IS_TOO_LONG"); // Skip the return values which were already written. offset += 2 * N_BUILTINS; } // Program output. { { uint256 outputAddress = cairoAuxInput[OFFSET_OUTPUT_BEGIN_ADDR]; // Force that memory[outputAddress] and memory[outputAddress + 1] contain the // bootloader config (which is 2 words size). publicMemory[offset + 0] = outputAddress; publicMemory[offset + 1] = simpleBootloaderProgramHash_; publicMemory[offset + 2] = outputAddress + 1; publicMemory[offset + 3] = hashedSupportedCairoVerifiers_; // Force that memory[outputAddress + 2] = nTasks. publicMemory[offset + 4] = outputAddress + 2; publicMemory[offset + 5] = nTasks; offset += 6; outputAddress += 3; uint256[] calldata taskMetadataSlice = taskMetadata[METADATA_TASKS_OFFSET:]; for (uint256 task = 0; task < nTasks; task++) { uint256 outputSize = taskMetadataSlice[METADATA_OFFSET_TASK_OUTPUT_SIZE]; // Ensure 'outputSize' is at least 2 and bounded from above as a sanity check // (the bound is somewhat arbitrary). require(2 <= outputSize && outputSize < 2**30, "Invalid task output size."); uint256 programHash = taskMetadataSlice[METADATA_OFFSET_TASK_PROGRAM_HASH]; uint256 nTreePairs = taskMetadataSlice[METADATA_OFFSET_TASK_N_TREE_PAIRS]; // Ensure 'nTreePairs' is at least 1 and bounded from above as a sanity check // (the bound is somewhat arbitrary). require( 1 <= nTreePairs && nTreePairs < 2**20, "Invalid number of pairs in the Merkle tree structure." ); // Force that memory[outputAddress] = outputSize. publicMemory[offset + 0] = outputAddress; publicMemory[offset + 1] = outputSize; // Force that memory[outputAddress + 1] = programHash. publicMemory[offset + 2] = outputAddress + 1; publicMemory[offset + 3] = programHash; offset += 4; outputAddress += outputSize; taskMetadataSlice = taskMetadataSlice[METADATA_TASK_HEADER_SIZE + 2 * nTreePairs:]; } require(taskMetadataSlice.length == 0, "Invalid length of taskMetadata."); require( cairoAuxInput[OFFSET_OUTPUT_STOP_PTR] == outputAddress, "Inconsistent program output length." ); } } require(publicMemory.length == offset, "Not all Cairo public inputs were written."); uint256 z = cairoAuxInput[cairoAuxInput.length - 2]; uint256 alpha = cairoAuxInput[cairoAuxInput.length - 1]; bytes32 factHash; (factHash, memoryHash, prod) = memoryPageFactRegistry.registerRegularMemoryPage( publicMemory, z, alpha, K_MODULUS ); } } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; /* The Fact Registry design pattern is a way to separate cryptographic verification from the business logic of the contract flow. A fact registry holds a hash table of verified "facts" which are represented by a hash of claims that the registry hash check and found valid. This table may be queried by accessing the isValid() function of the registry with a given hash. In addition, each fact registry exposes a registry specific function for submitting new claims together with their proofs. The information submitted varies from one registry to the other depending of the type of fact requiring verification. For further reading on the Fact Registry design pattern see this `StarkWare blog post <https://medium.com/starkware/the-fact-registry-a64aafb598b6>`_. */ interface IFactRegistry { /* Returns true if the given fact was previously registered in the contract. */ function isValid(bytes32 fact) external view returns (bool); } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; import "IFactRegistry.sol"; /* Extends the IFactRegistry interface with a query method that indicates whether the fact registry has successfully registered any fact or is still empty of such facts. */ interface IQueryableFactRegistry is IFactRegistry { /* Returns true if at least one fact has been registered. */ function hasRegisteredFact() external view returns (bool); } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; interface Identity { /* Allows a caller to ensure that the provided address is of the expected type and version. */ function identify() external pure returns (string memory); } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; import "FactRegistry.sol"; contract MemoryPageFactRegistryConstants { // A page based on a list of pairs (address, value). // In this case, memoryHash = hash(address, value, address, value, address, value, ...). uint256 internal constant REGULAR_PAGE = 0; // A page based on adjacent memory cells, starting from a given address. // In this case, memoryHash = hash(value, value, value, ...). uint256 internal constant CONTINUOUS_PAGE = 1; } /* A fact registry for the claim: I know n pairs (addr, value) for which the hash of the pairs is memoryHash, and the cumulative product: \\prod_i( z - (addr_i + alpha * value_i) ) is prod. The exact format of the hash depends on the type of the page (see MemoryPageFactRegistryConstants). The fact consists of (pageType, prime, n, z, alpha, prod, memoryHash, address). Note that address is only available for CONTINUOUS_PAGE, and otherwise it is 0. */ contract MemoryPageFactRegistry is FactRegistry, MemoryPageFactRegistryConstants { event LogMemoryPageFactRegular(bytes32 factHash, uint256 memoryHash, uint256 prod); event LogMemoryPageFactContinuous(bytes32 factHash, uint256 memoryHash, uint256 prod); /* Registers a fact based of the given memory (address, value) pairs (REGULAR_PAGE). */ function registerRegularMemoryPage( uint256[] calldata memoryPairs, uint256 z, uint256 alpha, uint256 prime ) external returns ( bytes32 factHash, uint256 memoryHash, uint256 prod ) { // Ensure 'memoryPairs.length' is bounded as a sanity check (the bound is somewhat arbitrary). require(memoryPairs.length < 2**20, "Too many memory values."); require(memoryPairs.length % 2 == 0, "Size of memoryPairs must be even."); require(z < prime, "Invalid value of z."); require(alpha < prime, "Invalid value of alpha."); (factHash, memoryHash, prod) = computeFactHash(memoryPairs, z, alpha, prime); emit LogMemoryPageFactRegular(factHash, memoryHash, prod); registerFact(factHash); } function computeFactHash( uint256[] memory memoryPairs, uint256 z, uint256 alpha, uint256 prime ) private pure returns ( bytes32 factHash, uint256 memoryHash, uint256 prod ) { uint256 memorySize = memoryPairs.length / 2; // NOLINT: divide-before-multiply. prod = 1; assembly { let memoryPtr := add(memoryPairs, 0x20) // Each value of memoryPairs is a pair: (address, value). let lastPtr := add(memoryPtr, mul(memorySize, 0x40)) for { let ptr := memoryPtr } lt(ptr, lastPtr) { ptr := add(ptr, 0x40) } { // Compute address + alpha * value. let address_value_lin_comb := addmod( // address= mload(ptr), mulmod( // value= mload(add(ptr, 0x20)), alpha, prime ), prime ) prod := mulmod(prod, add(z, sub(prime, address_value_lin_comb)), prime) } memoryHash := keccak256( memoryPtr, mul( // 0x20 * 2. 0x40, memorySize ) ) } factHash = keccak256( abi.encodePacked( REGULAR_PAGE, prime, memorySize, z, alpha, prod, memoryHash, uint256(0) ) ); } /* Registers a fact based on the given values, assuming continuous addresses. values should be [value at startAddr, value at (startAddr + 1), ...]. */ function registerContinuousMemoryPage( // NOLINT: external-function. uint256 startAddr, uint256[] memory values, uint256 z, uint256 alpha, uint256 prime ) public returns ( bytes32 factHash, uint256 memoryHash, uint256 prod ) { require(values.length < 2**20, "Too many memory values."); require(prime < 2**254, "prime is too big for the optimizations in this function."); require(z < prime, "Invalid value of z."); require(alpha < prime, "Invalid value of alpha."); // Ensure 'startAddr' less then prime and bounded as a sanity check (the bound is somewhat arbitrary). require((startAddr < prime) && (startAddr < 2**64), "Invalid value of startAddr."); uint256 nValues = values.length; assembly { // Initialize prod to 1. prod := 1 // Initialize valuesPtr to point to the first value in the array. let valuesPtr := add(values, 0x20) let minus_z := mod(sub(prime, z), prime) // Start by processing full batches of 8 cells, addr represents the last address in each // batch. let addr := add(startAddr, 7) let lastAddr := add(startAddr, nValues) for { } lt(addr, lastAddr) { addr := add(addr, 8) } { // Compute the product of (lin_comb - z) instead of (z - lin_comb), since we're // doing an even number of iterations, the result is the same. prod := mulmod( prod, mulmod( add(add(sub(addr, 7), mulmod(mload(valuesPtr), alpha, prime)), minus_z), add( add(sub(addr, 6), mulmod(mload(add(valuesPtr, 0x20)), alpha, prime)), minus_z ), prime ), prime ) prod := mulmod( prod, mulmod( add( add(sub(addr, 5), mulmod(mload(add(valuesPtr, 0x40)), alpha, prime)), minus_z ), add( add(sub(addr, 4), mulmod(mload(add(valuesPtr, 0x60)), alpha, prime)), minus_z ), prime ), prime ) prod := mulmod( prod, mulmod( add( add(sub(addr, 3), mulmod(mload(add(valuesPtr, 0x80)), alpha, prime)), minus_z ), add( add(sub(addr, 2), mulmod(mload(add(valuesPtr, 0xa0)), alpha, prime)), minus_z ), prime ), prime ) prod := mulmod( prod, mulmod( add( add(sub(addr, 1), mulmod(mload(add(valuesPtr, 0xc0)), alpha, prime)), minus_z ), add(add(addr, mulmod(mload(add(valuesPtr, 0xe0)), alpha, prime)), minus_z), prime ), prime ) valuesPtr := add(valuesPtr, 0x100) } // Handle leftover. // Translate addr to the beginning of the last incomplete batch. addr := sub(addr, 7) for { } lt(addr, lastAddr) { addr := add(addr, 1) } { let address_value_lin_comb := addmod( addr, mulmod(mload(valuesPtr), alpha, prime), prime ) prod := mulmod(prod, add(z, sub(prime, address_value_lin_comb)), prime) valuesPtr := add(valuesPtr, 0x20) } memoryHash := keccak256(add(values, 0x20), mul(0x20, nValues)) } factHash = keccak256( abi.encodePacked(CONTINUOUS_PAGE, prime, nValues, z, alpha, prod, memoryHash, startAddr) ); emit LogMemoryPageFactContinuous(factHash, memoryHash, prod); registerFact(factHash); } } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; contract PageInfo { uint256 public constant PAGE_INFO_SIZE = 3; // PAGE_INFO_SIZE_IN_BYTES cannot reference PAGE_INFO_SIZE as only direct constants are // supported in assembly. uint256 public constant PAGE_INFO_SIZE_IN_BYTES = 3 * 32; uint256 public constant PAGE_INFO_ADDRESS_OFFSET = 0; uint256 public constant PAGE_INFO_SIZE_OFFSET = 1; uint256 public constant PAGE_INFO_HASH_OFFSET = 2; // A regular page entry is a (address, value) pair stored as 2 uint256 words. uint256 internal constant MEMORY_PAIR_SIZE = 2; } /* Copyright 2019-2022 StarkWare Industries Ltd. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.starkware.co/open-source-license/ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; contract PrimeFieldElement0 { uint256 internal constant K_MODULUS = 0x800000000000011000000000000000000000000000000000000000000000001; uint256 internal constant K_MONTGOMERY_R = 0x7fffffffffffdf0ffffffffffffffffffffffffffffffffffffffffffffffe1; uint256 internal constant K_MONTGOMERY_R_INV = 0x40000000000001100000000000012100000000000000000000000000000000; uint256 internal constant GENERATOR_VAL = 3; uint256 internal constant ONE_VAL = 1; function fromMontgomery(uint256 val) internal pure returns (uint256 res) { // uint256 res = fmul(val, kMontgomeryRInv); assembly { res := mulmod(val, K_MONTGOMERY_R_INV, K_MODULUS) } return res; } function fromMontgomeryBytes(bytes32 bs) internal pure returns (uint256) { // Assuming bs is a 256bit bytes object, in Montgomery form, it is read into a field // element. uint256 res = uint256(bs); return fromMontgomery(res); } function toMontgomeryInt(uint256 val) internal pure returns (uint256 res) { //uint256 res = fmul(val, kMontgomeryR); assembly { res := mulmod(val, K_MONTGOMERY_R, K_MODULUS) } return res; } function fmul(uint256 a, uint256 b) internal pure returns (uint256 res) { //uint256 res = mulmod(a, b, kModulus); assembly { res := mulmod(a, b, K_MODULUS) } return res; } function fadd(uint256 a, uint256 b) internal pure returns (uint256 res) { // uint256 res = addmod(a, b, kModulus); assembly { res := addmod(a, b, K_MODULUS) } return res; } function fsub(uint256 a, uint256 b) internal pure returns (uint256 res) { // uint256 res = addmod(a, kModulus - b, kModulus); assembly { res := addmod(a, sub(K_MODULUS, b), K_MODULUS) } return res; } function fpow(uint256 val, uint256 exp) internal view returns (uint256) { return expmod(val, exp, K_MODULUS); } function expmod( uint256 base, uint256 exponent, uint256 modulus ) private view returns (uint256 res) { assembly { let p := mload(0x40) mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(staticcall(gas(), 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } } function inverse(uint256 val) internal view returns (uint256) { return expmod(val, K_MODULUS - 2, K_MODULUS); } }