creation_sourcecode: {{
    "language": "Solidity",
    "settings": {
      "evmVersion": "paris",
      "libraries": {},
      "metadata": {
        "bytecodeHash": "ipfs",
        "useLiteralContent": true
      },
      "optimizer": {
        "enabled": false,
        "runs": 200
      },
      "remappings": [],
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      }
    },
    "sources": {
      "@cartesi/rollups/contracts/common/CanonicalMachine.sol": {
        "content": "// (c) Cartesi and individual authors (see AUTHORS)\n// SPDX-License-Identifier: Apache-2.0 (see LICENSE)\n\npragma solidity ^0.8.8;\n\n/// @title Canonical Machine Constants Library\n///\n/// @notice Defines several constants related to the reference implementation\n/// of the RISC-V machine that runs Linux, also known as the \"Cartesi Machine\".\nlibrary CanonicalMachine {\n    /// @notice Base-2 logarithm of number of bytes.\n    type Log2Size is uint64;\n\n    /// @notice Machine word size (8 bytes).\n    Log2Size constant WORD_LOG2_SIZE = Log2Size.wrap(3);\n\n    /// @notice Machine address space size (2^64 bytes).\n    Log2Size constant MACHINE_LOG2_SIZE = Log2Size.wrap(64);\n\n    /// @notice Keccak-256 output size (32 bytes).\n    Log2Size constant KECCAK_LOG2_SIZE = Log2Size.wrap(5);\n\n    /// @notice Maximum input size (~2 megabytes).\n    /// @dev The offset and size fields use up the extra 64 bytes.\n    uint256 constant INPUT_MAX_SIZE = (1 << 21) - 64;\n\n    /// @notice Maximum voucher metadata memory range (2 megabytes).\n    Log2Size constant VOUCHER_METADATA_LOG2_SIZE = Log2Size.wrap(21);\n\n    /// @notice Maximum notice metadata memory range (2 megabytes).\n    Log2Size constant NOTICE_METADATA_LOG2_SIZE = Log2Size.wrap(21);\n\n    /// @notice Maximum epoch voucher memory range (128 megabytes).\n    Log2Size constant EPOCH_VOUCHER_LOG2_SIZE = Log2Size.wrap(37);\n\n    /// @notice Maximum epoch notice memory range (128 megabytes).\n    Log2Size constant EPOCH_NOTICE_LOG2_SIZE = Log2Size.wrap(37);\n\n    /// @notice Unwrap `s` into its underlying uint64 value.\n    /// @param s Base-2 logarithm of some number of bytes\n    function uint64OfSize(Log2Size s) internal pure returns (uint64) {\n        return Log2Size.unwrap(s);\n    }\n\n    /// @notice Return the position of an intra memory range on a memory range\n    ///         with contents with the same size.\n    /// @param index Index of intra memory range\n    /// @param log2Size Base-2 logarithm of intra memory range size\n    function getIntraMemoryRangePosition(\n        uint64 index,\n        Log2Size log2Size\n    ) internal pure returns (uint64) {\n        return index << Log2Size.unwrap(log2Size);\n    }\n}\n"
      },
      "@cartesi/rollups/contracts/common/OutputEncoding.sol": {
        "content": "// (c) Cartesi and individual authors (see AUTHORS)\n// SPDX-License-Identifier: Apache-2.0 (see LICENSE)\n\npragma solidity ^0.8.8;\n\n/// @title Output Encoding Library\n///\n/// @notice Defines the encoding of outputs generated by the off-chain machine.\nlibrary OutputEncoding {\n    /// @notice Encode a notice.\n    /// @param notice The notice\n    /// @return The encoded output\n    function encodeNotice(\n        bytes calldata notice\n    ) internal pure returns (bytes memory) {\n        return abi.encode(notice);\n    }\n\n    /// @notice Encode a voucher.\n    /// @param destination The address that will receive the payload through a message call\n    /// @param payload The payload, which—in the case of Solidity contracts—encodes a function call\n    /// @return The encoded output\n    function encodeVoucher(\n        address destination,\n        bytes calldata payload\n    ) internal pure returns (bytes memory) {\n        return abi.encode(destination, payload);\n    }\n}\n"
      },
      "@cartesi/rollups/contracts/consensus/AbstractConsensus.sol": {
        "content": "// (c) Cartesi and individual authors (see AUTHORS)\n// SPDX-License-Identifier: Apache-2.0 (see LICENSE)\n\npragma solidity ^0.8.8;\n\nimport {IConsensus} from \"./IConsensus.sol\";\n\n/// @title Abstract Consensus\n/// @notice An abstract contract that partially implements `IConsensus`.\nabstract contract AbstractConsensus is IConsensus {\n    /// @notice Emits an `ApplicationJoined` event with the message sender.\n    function join() external override {\n        emit ApplicationJoined(msg.sender);\n    }\n}\n"
      },
      "@cartesi/rollups/contracts/consensus/IConsensus.sol": {
        "content": "// (c) Cartesi and individual authors (see AUTHORS)\n// SPDX-License-Identifier: Apache-2.0 (see LICENSE)\n\npragma solidity ^0.8.8;\n\n/// @title Consensus interface\n///\n/// @notice This contract defines a generic interface for consensuses.\n/// We use the word \"consensus\" to designate a contract that provides claims\n/// in the base layer regarding the state of off-chain machines running in\n/// the execution layer. How this contract is able to reach consensus, who is\n/// able to submit claims, and how are claims stored in the base layer are\n/// some of the implementation details left unspecified by this interface.\n///\n/// From the point of view of a DApp, these claims are necessary to validate\n/// on-chain action allowed by the off-chain machine in the form of vouchers\n/// and notices. Each claim is composed of three parts: an epoch hash, a first\n/// index, and a last index. We'll explain each of these parts below.\n///\n/// First, let us define the word \"epoch\". For finality reasons, we need to\n/// divide the stream of inputs being fed into the off-chain machine into\n/// batches of inputs, which we call \"epoches\". At the end of every epoch,\n/// we summarize the state of the off-chain machine in a single hash, called\n/// \"epoch hash\". Please note that this interface does not define how this\n/// stream of inputs is being chopped up into epoches.\n///\n/// The other two parts are simply the indices of the first and last inputs\n/// accepted during the epoch. Logically, the first index MUST BE less than\n/// or equal to the last index. As a result, every epoch MUST accept at least\n/// one input. This assumption stems from the fact that the state of a machine\n/// can only change after an input is fed into it.\n///\n/// Examples of possible implementations of this interface include:\n///\n/// * An authority consensus, controlled by a single address who has full\n///   control over epoch boundaries, claim submission, asset management, etc.\n///\n/// * A quorum consensus, controlled by a limited set of validators, that\n///   vote on the state of the machine at the end of every epoch. Also, epoch\n///   boundaries are determined by the timestamp in the base layer, and assets\n///   are split equally amongst the validators.\n///\n/// * An NxN consensus, which allows anyone to submit and dispute claims\n///   in the base layer. Epoch boundaries are determined in the same fashion\n///   as in the quorum example.\n///\ninterface IConsensus {\n    /// @notice An application has joined the consensus' validation set.\n    /// @param application The application\n    /// @dev MUST be triggered on a successful call to `join`.\n    event ApplicationJoined(address application);\n\n    /// @notice Get a specific claim regarding a specific DApp.\n    ///         The encoding of `_proofContext` might vary\n    ///         depending on the implementation.\n    /// @param _dapp The DApp address\n    /// @param _proofContext Data for retrieving the desired claim\n    /// @return epochHash_ The claimed epoch hash\n    /// @return firstInputIndex_ The index of the first input of the epoch in the input box\n    /// @return lastInputIndex_ The index of the last input of the epoch in the input box\n    function getClaim(\n        address _dapp,\n        bytes calldata _proofContext\n    )\n        external\n        view\n        returns (\n            bytes32 epochHash_,\n            uint256 firstInputIndex_,\n            uint256 lastInputIndex_\n        );\n\n    /// @notice Signal the consensus that the message sender wants to join its validation set.\n    /// @dev MUST fire an `ApplicationJoined` event with the message sender as argument.\n    function join() external;\n}\n"
      },
      "@cartesi/rollups/contracts/consensus/authority/Authority.sol": {
        "content": "// (c) Cartesi and individual authors (see AUTHORS)\n// SPDX-License-Identifier: Apache-2.0 (see LICENSE)\n\npragma solidity ^0.8.8;\n\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\nimport {IConsensus} from \"../IConsensus.sol\";\nimport {AbstractConsensus} from \"../AbstractConsensus.sol\";\nimport {IHistory} from \"../../history/IHistory.sol\";\n\n/// @title Authority consensus\n/// @notice A consensus model controlled by a single address, the owner.\n///         Claims are stored in an auxiliary contract called `History`.\n/// @dev This contract inherits `AbstractConsensus` and OpenZeppelin's `Ownable` contract.\n///      For more information on `Ownable`, please consult OpenZeppelin's official documentation.\ncontract Authority is AbstractConsensus, Ownable {\n    /// @notice The current history contract.\n    /// @dev See the `getHistory` and `setHistory` functions.\n    IHistory internal history;\n\n    /// @notice A new history contract is used to store claims.\n    /// @param history The new history contract\n    /// @dev MUST be triggered on a successful call to `setHistory`.\n    event NewHistory(IHistory history);\n\n    /// @notice Raised when a transfer of tokens from an authority to a recipient fails.\n    error AuthorityWithdrawalFailed();\n\n    /// @notice Constructs an `Authority` contract.\n    /// @param _owner The initial contract owner\n    constructor(address _owner) {\n        // constructor in Ownable already called `transferOwnership(msg.sender)`, so\n        // we only need to call `transferOwnership(_owner)` if _owner != msg.sender\n        if (msg.sender != _owner) {\n            transferOwnership(_owner);\n        }\n    }\n\n    /// @notice Submits a claim to the current history contract.\n    ///         The encoding of `_claimData` might vary depending on the\n    ///         implementation of the current history contract.\n    /// @param _claimData Data for submitting a claim\n    /// @dev Can only be called by the `Authority` owner,\n    ///      and the `Authority` contract must have ownership over\n    ///      its current history contract.\n    function submitClaim(bytes calldata _claimData) external onlyOwner {\n        history.submitClaim(_claimData);\n    }\n\n    /// @notice Transfer ownership over the current history contract to `_consensus`.\n    /// @param _consensus The new owner of the current history contract\n    /// @dev Can only be called by the `Authority` owner,\n    ///      and the `Authority` contract must have ownership over\n    ///      its current history contract.\n    function migrateHistoryToConsensus(address _consensus) external onlyOwner {\n        history.migrateToConsensus(_consensus);\n    }\n\n    /// @notice Make `Authority` point to another history contract.\n    /// @param _history The new history contract\n    /// @dev Emits a `NewHistory` event.\n    ///      Can only be called by the `Authority` owner.\n    function setHistory(IHistory _history) external onlyOwner {\n        history = _history;\n        emit NewHistory(_history);\n    }\n\n    /// @notice Get the current history contract.\n    /// @return The current history contract\n    function getHistory() external view returns (IHistory) {\n        return history;\n    }\n\n    /// @notice Get a claim from the current history.\n    ///         The encoding of `_proofContext` might vary depending on the\n    ///         implementation of the current history contract.\n    /// @inheritdoc IConsensus\n    function getClaim(\n        address _dapp,\n        bytes calldata _proofContext\n    ) external view override returns (bytes32, uint256, uint256) {\n        return history.getClaim(_dapp, _proofContext);\n    }\n\n    /// @notice Transfer some amount of ERC-20 tokens to a recipient.\n    /// @param _token The token contract\n    /// @param _recipient The recipient address\n    /// @param _amount The amount of tokens to be withdrawn\n    /// @dev Can only be called by the `Authority` owner.\n    function withdrawERC20Tokens(\n        IERC20 _token,\n        address _recipient,\n        uint256 _amount\n    ) external onlyOwner {\n        bool success = _token.transfer(_recipient, _amount);\n\n        if (!success) {\n            revert AuthorityWithdrawalFailed();\n        }\n    }\n}\n"
      },
      "@cartesi/rollups/contracts/consensus/authority/IAuthorityFactory.sol": {
        "content": "// (c) Cartesi and individual authors (see AUTHORS)\n// SPDX-License-Identifier: Apache-2.0 (see LICENSE)\n\npragma solidity ^0.8.8;\n\nimport {Authority} from \"./Authority.sol\";\n\n/// @title Authority Factory interface\ninterface IAuthorityFactory {\n    // Events\n\n    /// @notice A new authority was deployed.\n    /// @param authorityOwner The initial authority owner\n    /// @param authority The authority\n    /// @dev MUST be triggered on a successful call to `newAuthority`.\n    event AuthorityCreated(address authorityOwner, Authority authority);\n\n    // Permissionless functions\n\n    /// @notice Deploy a new authority.\n    /// @param _authorityOwner The initial authority owner\n    /// @return The authority\n    /// @dev On success, MUST emit an `AuthorityCreated` event.\n    function newAuthority(address _authorityOwner) external returns (Authority);\n\n    /// @notice Deploy a new authority deterministically.\n    /// @param _authorityOwner The initial authority owner\n    /// @param _salt The salt used to deterministically generate the authority address\n    /// @return The authority\n    /// @dev On success, MUST emit an `AuthorityCreated` event.\n    function newAuthority(\n        address _authorityOwner,\n        bytes32 _salt\n    ) external returns (Authority);\n\n    /// @notice Calculate the address of an authority to be deployed deterministically.\n    /// @param _authorityOwner The initial authority owner\n    /// @param _salt The salt used to deterministically generate the authority address\n    /// @return The deterministic authority address\n    /// @dev Beware that only the `newAuthority` function with the `_salt` parameter\n    ///      is able to deterministically deploy an authority.\n    function calculateAuthorityAddress(\n        address _authorityOwner,\n        bytes32 _salt\n    ) external view returns (address);\n}\n"
      },
      "@cartesi/rollups/contracts/consensus/authority/IAuthorityHistoryPairFactory.sol": {
        "content": "// (c) Cartesi and individual authors (see AUTHORS)\n// SPDX-License-Identifier: Apache-2.0 (see LICENSE)\n\npragma solidity ^0.8.8;\n\nimport {Authority} from \"./Authority.sol\";\nimport {IAuthorityFactory} from \"./IAuthorityFactory.sol\";\nimport {History} from \"../../history/History.sol\";\nimport {IHistoryFactory} from \"../../history/IHistoryFactory.sol\";\n\n/// @title Authority-History Pair Factory interface\ninterface IAuthorityHistoryPairFactory {\n    // Events\n\n    /// @notice The factory was created.\n    /// @param authorityFactory The underlying `Authority` factory\n    /// @param historyFactory The underlying `History` factory\n    /// @dev MUST be emitted on construction.\n    event AuthorityHistoryPairFactoryCreated(\n        IAuthorityFactory authorityFactory,\n        IHistoryFactory historyFactory\n    );\n\n    // Permissionless functions\n\n    /// @notice Get the factory used to deploy `Authority` contracts\n    /// @return The `Authority` factory\n    function getAuthorityFactory() external view returns (IAuthorityFactory);\n\n    /// @notice Get the factory used to deploy `History` contracts\n    /// @return The `History` factory\n    function getHistoryFactory() external view returns (IHistoryFactory);\n\n    /// @notice Deploy a new authority-history pair.\n    /// @param _authorityOwner The initial authority owner\n    /// @return The authority\n    /// @return The history\n    function newAuthorityHistoryPair(\n        address _authorityOwner\n    ) external returns (Authority, History);\n\n    /// @notice Deploy a new authority-history pair deterministically.\n    /// @param _authorityOwner The initial authority owner\n    /// @param _salt The salt used to deterministically generate the authority-history pair address\n    /// @return The authority\n    /// @return The history\n    function newAuthorityHistoryPair(\n        address _authorityOwner,\n        bytes32 _salt\n    ) external returns (Authority, History);\n\n    /// @notice Calculate the address of an authority-history pair to be deployed deterministically.\n    /// @param _authorityOwner The initial authority owner\n    /// @param _salt The salt used to deterministically generate the authority-history address pair\n    /// @return The deterministic authority address\n    /// @return The deterministic history address\n    /// @dev Beware that only the `newAuthorityHistoryPair` function with the `_salt` parameter\n    ///      is able to deterministically deploy an authority-history pair.\n    function calculateAuthorityHistoryAddressPair(\n        address _authorityOwner,\n        bytes32 _salt\n    ) external view returns (address, address);\n}\n"
      },
      "@cartesi/rollups/contracts/dapp/CartesiDApp.sol": {
        "content": "// (c) Cartesi and individual authors (see AUTHORS)\n// SPDX-License-Identifier: Apache-2.0 (see LICENSE)\n\npragma solidity ^0.8.8;\n\nimport {ICartesiDApp, Proof} from \"./ICartesiDApp.sol\";\nimport {IConsensus} from \"../consensus/IConsensus.sol\";\nimport {LibOutputValidation, OutputValidityProof} from \"../library/LibOutputValidation.sol\";\nimport {Bitmask} from \"@cartesi/util/contracts/Bitmask.sol\";\n\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport {ERC721Holder} from \"@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol\";\nimport {ERC1155Holder} from \"@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol\";\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/security/ReentrancyGuard.sol\";\n\n/// @title Cartesi DApp\n///\n/// @notice This contract acts as the base layer incarnation of a DApp running on the execution layer.\n/// The DApp is hereby able to interact with other smart contracts through the execution of vouchers\n/// and the validation of notices. These outputs are generated by the DApp backend on the execution\n/// layer and can be proven in the base layer thanks to claims submitted by a consensus contract.\n///\n/// A voucher is a one-time message call to another contract. It can encode asset transfers, approvals,\n/// or any other message call that doesn't require Ether to be sent along. A voucher will only be consumed\n/// if the underlying message call succeeds (that is, it doesn't revert). Furthermore, the return data of\n/// the message call is discarded entirely. As a protective measure against reentrancy attacks, nested\n/// voucher executions are prohibited.\n///\n/// A notice, on the other hand, constitutes an arbitrary piece of data that can be proven any number of times.\n/// On their own, they do not trigger any type of contract-to-contract interaction.\n/// Rather, they merely serve to attest off-chain results, e.g. which player won a particular chess match.\n///\n/// Every DApp is subscribed to a consensus contract, and governed by a single address, the owner.\n/// The consensus has the power of submitting claims, which, in turn, are used to validate vouchers and notices.\n/// Meanwhile, the owner has complete power over the DApp, as it can replace the consensus at any time.\n/// Therefore, the users of a DApp must trust both the consensus and the DApp owner.\n///\n/// The DApp developer can choose whichever ownership and consensus models it wants.\n///\n/// Examples of DApp ownership models include:\n///\n/// * no owner (address zero)\n/// * individual signer (externally-owned account)\n/// * multiple signers (multi-sig)\n/// * DAO (decentralized autonomous organization)\n/// * self-owned DApp (off-chain governance logic)\n///\n/// See `IConsensus` for examples of consensus models.\n///\n/// This contract inherits the following OpenZeppelin contracts.\n/// For more information, please consult OpenZeppelin's official documentation.\n///\n/// * `Ownable`\n/// * `ERC721Holder`\n/// * `ERC1155Holder`\n/// * `ReentrancyGuard`\n///\ncontract CartesiDApp is\n    ICartesiDApp,\n    Ownable,\n    ERC721Holder,\n    ERC1155Holder,\n    ReentrancyGuard\n{\n    using Bitmask for mapping(uint256 => uint256);\n    using LibOutputValidation for OutputValidityProof;\n\n    /// @notice Raised when executing an already executed voucher.\n    error VoucherReexecutionNotAllowed();\n\n    /// @notice Raised when the transfer fails.\n    error EtherTransferFailed();\n\n    /// @notice Raised when a mehtod is not called by DApp itself.\n    error OnlyDApp();\n\n    /// @notice The initial machine state hash.\n    /// @dev See the `getTemplateHash` function.\n    bytes32 internal immutable templateHash;\n\n    /// @notice The executed voucher bitmask, which keeps track of which vouchers\n    ///         were executed already in order to avoid re-execution.\n    /// @dev See the `wasVoucherExecuted` function.\n    mapping(uint256 => uint256) internal voucherBitmask;\n\n    /// @notice The current consensus contract.\n    /// @dev See the `getConsensus` and `migrateToConsensus` functions.\n    IConsensus internal consensus;\n\n    /// @notice Creates a `CartesiDApp` contract.\n    /// @param _consensus The initial consensus contract\n    /// @param _owner The initial DApp owner\n    /// @param _templateHash The initial machine state hash\n    /// @dev Calls the `join` function on `_consensus`.\n    constructor(IConsensus _consensus, address _owner, bytes32 _templateHash) {\n        transferOwnership(_owner);\n        templateHash = _templateHash;\n        consensus = _consensus;\n\n        _consensus.join();\n    }\n\n    function executeVoucher(\n        address _destination,\n        bytes calldata _payload,\n        Proof calldata _proof\n    ) external override nonReentrant returns (bool) {\n        bytes32 epochHash;\n        uint256 firstInputIndex;\n        uint256 lastInputIndex;\n        uint256 inputIndex;\n\n        // query the current consensus for the desired claim\n        (epochHash, firstInputIndex, lastInputIndex) = getClaim(_proof.context);\n\n        // validate input index range and calculate the input index\n        // based on the input index range provided by the consensus\n        inputIndex = _proof.validity.validateInputIndexRange(\n            firstInputIndex,\n            lastInputIndex\n        );\n\n        // reverts if proof isn't valid\n        _proof.validity.validateVoucher(_destination, _payload, epochHash);\n\n        uint256 voucherPosition = LibOutputValidation.getBitMaskPosition(\n            _proof.validity.outputIndexWithinInput,\n            inputIndex\n        );\n\n        // check if voucher has been executed\n        if (_wasVoucherExecuted(voucherPosition)) {\n            revert VoucherReexecutionNotAllowed();\n        }\n\n        // execute voucher\n        (bool succ, ) = _destination.call(_payload);\n\n        // if properly executed, mark it as executed and emit event\n        if (succ) {\n            voucherBitmask.setBit(voucherPosition, true);\n            emit VoucherExecuted(voucherPosition);\n        }\n\n        return succ;\n    }\n\n    function wasVoucherExecuted(\n        uint256 _inputIndex,\n        uint256 _outputIndexWithinInput\n    ) external view override returns (bool) {\n        uint256 voucherPosition = LibOutputValidation.getBitMaskPosition(\n            _outputIndexWithinInput,\n            _inputIndex\n        );\n        return _wasVoucherExecuted(voucherPosition);\n    }\n\n    function _wasVoucherExecuted(\n        uint256 _voucherPosition\n    ) internal view returns (bool) {\n        return voucherBitmask.getBit(_voucherPosition);\n    }\n\n    function validateNotice(\n        bytes calldata _notice,\n        Proof calldata _proof\n    ) external view override returns (bool) {\n        bytes32 epochHash;\n        uint256 firstInputIndex;\n        uint256 lastInputIndex;\n\n        // query the current consensus for the desired claim\n        (epochHash, firstInputIndex, lastInputIndex) = getClaim(_proof.context);\n\n        // validate the epoch input index based on the input index range\n        // provided by the consensus\n        _proof.validity.validateInputIndexRange(\n            firstInputIndex,\n            lastInputIndex\n        );\n\n        // reverts if proof isn't valid\n        _proof.validity.validateNotice(_notice, epochHash);\n\n        return true;\n    }\n\n    /// @notice Retrieve a claim about the DApp from the current consensus.\n    ///         The encoding of `_proofContext` might vary depending on the implementation.\n    /// @param _proofContext Data for retrieving the desired claim\n    /// @return The claimed epoch hash\n    /// @return The index of the first input of the epoch in the input box\n    /// @return The index of the last input of the epoch in the input box\n    function getClaim(\n        bytes calldata _proofContext\n    ) internal view returns (bytes32, uint256, uint256) {\n        return consensus.getClaim(address(this), _proofContext);\n    }\n\n    function migrateToConsensus(\n        IConsensus _newConsensus\n    ) external override onlyOwner {\n        consensus = _newConsensus;\n\n        _newConsensus.join();\n\n        emit NewConsensus(_newConsensus);\n    }\n\n    function getTemplateHash() external view override returns (bytes32) {\n        return templateHash;\n    }\n\n    function getConsensus() external view override returns (IConsensus) {\n        return consensus;\n    }\n\n    /// @notice Accept Ether transfers.\n    /// @dev If you wish to transfer Ether to a DApp while informing\n    ///      the DApp backend of it, then please do so through the Ether portal contract.\n    receive() external payable {}\n\n    /// @notice Transfer some amount of Ether to some recipient.\n    /// @param _receiver The address which will receive the amount of Ether\n    /// @param _value The amount of Ether to be transferred in Wei\n    /// @dev This function can only be called by the DApp itself through vouchers.\n    ///      If this method is not called by DApp itself, `OnlyDApp` error is raised.\n    ///      If the transfer fails, `EtherTransferFailed` error is raised.\n    function withdrawEther(address _receiver, uint256 _value) external {\n        if (msg.sender != address(this)) {\n            revert OnlyDApp();\n        }\n\n        (bool sent, ) = _receiver.call{value: _value}(\"\");\n\n        if (!sent) {\n            revert EtherTransferFailed();\n        }\n    }\n}\n"
      },
      "@cartesi/rollups/contracts/dapp/CartesiDAppFactory.sol": {
        "content": "// (c) Cartesi and individual authors (see AUTHORS)\n// SPDX-License-Identifier: Apache-2.0 (see LICENSE)\n\npragma solidity ^0.8.8;\n\nimport {Create2} from \"@openzeppelin/contracts/utils/Create2.sol\";\n\nimport {ICartesiDAppFactory} from \"./ICartesiDAppFactory.sol\";\nimport {IConsensus} from \"../consensus/IConsensus.sol\";\nimport {CartesiDApp} from \"./CartesiDApp.sol\";\n\n/// @title Cartesi DApp Factory\n/// @notice Allows anyone to reliably deploy a new `CartesiDApp` contract.\ncontract CartesiDAppFactory is ICartesiDAppFactory {\n    function newApplication(\n        IConsensus _consensus,\n        address _dappOwner,\n        bytes32 _templateHash\n    ) external override returns (CartesiDApp) {\n        CartesiDApp application = new CartesiDApp(\n            _consensus,\n            _dappOwner,\n            _templateHash\n        );\n\n        emit ApplicationCreated(\n            _consensus,\n            _dappOwner,\n            _templateHash,\n            application\n        );\n\n        return application;\n    }\n\n    function newApplication(\n        IConsensus _consensus,\n        address _dappOwner,\n        bytes32 _templateHash,\n        bytes32 _salt\n    ) external override returns (CartesiDApp) {\n        CartesiDApp application = new CartesiDApp{salt: _salt}(\n            _consensus,\n            _dappOwner,\n            _templateHash\n        );\n\n        emit ApplicationCreated(\n            _consensus,\n            _dappOwner,\n            _templateHash,\n            application\n        );\n\n        return application;\n    }\n\n    function calculateApplicationAddress(\n        IConsensus _consensus,\n        address _dappOwner,\n        bytes32 _templateHash,\n        bytes32 _salt\n    ) external view override returns (address) {\n        return\n            Create2.computeAddress(\n                _salt,\n                keccak256(\n                    abi.encodePacked(\n                        type(CartesiDApp).creationCode,\n                        abi.encode(_consensus, _dappOwner, _templateHash)\n                    )\n                )\n            );\n    }\n}\n"
      },
      "@cartesi/rollups/contracts/dapp/ICartesiDApp.sol": {
        "content": "// (c) Cartesi and individual authors (see AUTHORS)\n// SPDX-License-Identifier: Apache-2.0 (see LICENSE)\n\npragma solidity ^0.8.8;\n\nimport {IConsensus} from \"../consensus/IConsensus.sol\";\nimport {OutputValidityProof} from \"../library/LibOutputValidation.sol\";\n\n/// @notice Data for validating outputs.\n/// @param validity A validity proof for the output\n/// @param context Data for querying the right claim from the current consensus contract\n/// @dev The encoding of `context` might vary depending on the implementation of the consensus contract.\nstruct Proof {\n    OutputValidityProof validity;\n    bytes context;\n}\n\n/// @title Cartesi DApp interface\ninterface ICartesiDApp {\n    // Events\n\n    /// @notice The DApp has migrated to another consensus contract.\n    /// @param newConsensus The new consensus contract\n    /// @dev MUST be triggered on a successful call to `migrateToConsensus`.\n    event NewConsensus(IConsensus newConsensus);\n\n    /// @notice A voucher was executed from the DApp.\n    /// @param voucherId A number that uniquely identifies the voucher\n    ///                  amongst all vouchers emitted by this DApp\n    event VoucherExecuted(uint256 voucherId);\n\n    // Permissioned functions\n\n    /// @notice Migrate the DApp to a new consensus.\n    /// @param _newConsensus The new consensus\n    /// @dev Can only be called by the DApp owner.\n    function migrateToConsensus(IConsensus _newConsensus) external;\n\n    // Permissionless functions\n\n    /// @notice Try to execute a voucher.\n    ///\n    /// Reverts if voucher was already successfully executed.\n    ///\n    /// @param _destination The address that will receive the payload through a message call\n    /// @param _payload The payload, which—in the case of Solidity contracts—encodes a function call\n    /// @param _proof The proof used to validate the voucher against\n    ///               a claim submitted by the current consensus contract\n    /// @return Whether the execution was successful or not\n    /// @dev On a successful execution, emits a `VoucherExecuted` event.\n    ///      Execution of already executed voucher will raise a `VoucherReexecutionNotAllowed` error.\n    function executeVoucher(\n        address _destination,\n        bytes calldata _payload,\n        Proof calldata _proof\n    ) external returns (bool);\n\n    /// @notice Check whether a voucher has been executed.\n    /// @param _inputIndex The index of the input in the input box\n    /// @param _outputIndexWithinInput The index of output emitted by the input\n    /// @return Whether the voucher has been executed before\n    function wasVoucherExecuted(\n        uint256 _inputIndex,\n        uint256 _outputIndexWithinInput\n    ) external view returns (bool);\n\n    /// @notice Validate a notice.\n    /// @param _notice The notice\n    /// @param _proof Data for validating outputs\n    /// @return Whether the notice is valid or not\n    function validateNotice(\n        bytes calldata _notice,\n        Proof calldata _proof\n    ) external view returns (bool);\n\n    /// @notice Get the DApp's template hash.\n    /// @return The DApp's template hash\n    function getTemplateHash() external view returns (bytes32);\n\n    /// @notice Get the current consensus.\n    /// @return The current consensus\n    function getConsensus() external view returns (IConsensus);\n}\n"
      },
      "@cartesi/rollups/contracts/dapp/ICartesiDAppFactory.sol": {
        "content": "// (c) Cartesi and individual authors (see AUTHORS)\n// SPDX-License-Identifier: Apache-2.0 (see LICENSE)\n\npragma solidity ^0.8.8;\n\nimport {CartesiDApp} from \"./CartesiDApp.sol\";\nimport {IConsensus} from \"../consensus/IConsensus.sol\";\n\n/// @title Cartesi DApp Factory interface\ninterface ICartesiDAppFactory {\n    // Events\n\n    /// @notice A new application was deployed.\n    /// @param consensus The initial consensus contract\n    /// @param dappOwner The initial DApp owner\n    /// @param templateHash The initial machine state hash\n    /// @param application The application\n    /// @dev MUST be triggered on a successful call to `newApplication`.\n    event ApplicationCreated(\n        IConsensus indexed consensus,\n        address dappOwner,\n        bytes32 templateHash,\n        CartesiDApp application\n    );\n\n    // Permissionless functions\n\n    /// @notice Deploy a new application.\n    /// @param _consensus The initial consensus contract\n    /// @param _dappOwner The initial DApp owner\n    /// @param _templateHash The initial machine state hash\n    /// @return The application\n    /// @dev On success, MUST emit an `ApplicationCreated` event.\n    function newApplication(\n        IConsensus _consensus,\n        address _dappOwner,\n        bytes32 _templateHash\n    ) external returns (CartesiDApp);\n\n    /// @notice Deploy a new application deterministically.\n    /// @param _consensus The initial consensus contract\n    /// @param _dappOwner The initial DApp owner\n    /// @param _templateHash The initial machine state hash\n    /// @param _salt The salt used to deterministically generate the DApp address\n    /// @return The application\n    /// @dev On success, MUST emit an `ApplicationCreated` event.\n    function newApplication(\n        IConsensus _consensus,\n        address _dappOwner,\n        bytes32 _templateHash,\n        bytes32 _salt\n    ) external returns (CartesiDApp);\n\n    /// @notice Calculate the address of an application to be deployed deterministically.\n    /// @param _consensus The initial consensus contract\n    /// @param _dappOwner The initial DApp owner\n    /// @param _templateHash The initial machine state hash\n    /// @param _salt The salt used to deterministically generate the DApp address\n    /// @return The deterministic application address\n    /// @dev Beware that only the `newApplication` function with the `_salt` parameter\n    ///      is able to deterministically deploy an application.\n    function calculateApplicationAddress(\n        IConsensus _consensus,\n        address _dappOwner,\n        bytes32 _templateHash,\n        bytes32 _salt\n    ) external view returns (address);\n}\n"
      },
      "@cartesi/rollups/contracts/history/History.sol": {
        "content": "// (c) Cartesi and individual authors (see AUTHORS)\n// SPDX-License-Identifier: Apache-2.0 (see LICENSE)\n\npragma solidity ^0.8.8;\n\nimport {Ownable} from \"@openzeppelin/contracts/access/Ownable.sol\";\n\nimport {IHistory} from \"./IHistory.sol\";\n\n/// @title Simple History\n///\n/// @notice This contract stores claims for each DApp individually.\n/// This means that, for each DApp, the contract stores an array of\n/// `Claim` entries, where each `Claim` is composed of:\n///\n/// * An epoch hash (`bytes32`)\n/// * A closed interval of input indices (`uint128`, `uint128`)\n///\n/// The contract guarantees that the first interval starts at index 0,\n/// and that the following intervals don't have gaps or overlaps.\n///\n/// Furthermore, claims can only be submitted by the contract owner\n/// through `submitClaim`, but can be retrieved by anyone with `getClaim`.\n///\n/// @dev This contract inherits OpenZeppelin's `Ownable` contract.\n///      For more information on `Ownable`, please consult OpenZeppelin's official documentation.\ncontract History is IHistory, Ownable {\n    struct Claim {\n        bytes32 epochHash;\n        uint128 firstIndex;\n        uint128 lastIndex;\n    }\n\n    /// @notice Mapping from DApp address to number of claims.\n    mapping(address => uint256) internal numClaims;\n\n    /// @notice Mapping from DApp address and claim index to claim.\n    /// @dev See the `getClaim` and `submitClaim` functions.\n    mapping(address => mapping(uint256 => Claim)) internal claims;\n\n    /// @notice A new claim regarding a specific DApp was submitted.\n    /// @param dapp The address of the DApp\n    /// @param claim The newly-submitted claim\n    /// @dev MUST be triggered on a successful call to `submitClaim`.\n    event NewClaimToHistory(address indexed dapp, Claim claim);\n\n    /// @notice Raised when one tries to submit a claim whose first input index\n    ///         is not less than or equal to its last input index.\n    error InvalidInputIndices();\n\n    /// @notice Raised when one tries to submit a claim that skips some input.\n    ///         For example, when the 1st claim starts at index 5 (instead of 0)\n    ///         or when the 1st claim ends at index 20 but the 2nd claim starts at\n    ///         index 22 (instead of 21).\n    error UnclaimedInputs();\n\n    /// @notice Raised when one tries to retrieve a claim with an invalid index.\n    error InvalidClaimIndex();\n\n    /// @notice Creates a `History` contract.\n    /// @param _owner The initial owner\n    constructor(address _owner) {\n        // constructor in Ownable already called `transferOwnership(msg.sender)`, so\n        // we only need to call `transferOwnership(_owner)` if _owner != msg.sender\n        if (_owner != msg.sender) {\n            transferOwnership(_owner);\n        }\n    }\n\n    /// @notice Submit a claim regarding a DApp.\n    /// There are several requirements for this function to be called successfully.\n    ///\n    /// * `_claimData` MUST be well-encoded. In Solidity, it can be constructed\n    ///   as `abi.encode(dapp, claim)`, where `dapp` is the DApp address (type `address`)\n    ///   and `claim` is the claim structure (type `Claim`).\n    ///\n    /// * `firstIndex` MUST be less than or equal to `lastIndex`.\n    ///   As a result, every claim MUST encompass AT LEAST one input.\n    ///\n    /// * If this is the DApp's first claim, then `firstIndex` MUST be `0`.\n    ///   Otherwise, `firstIndex` MUST be the `lastClaim.lastIndex + 1`.\n    ///   In other words, claims MUST NOT skip inputs.\n    ///\n    /// @inheritdoc IHistory\n    /// @dev Emits a `NewClaimToHistory` event. Should have access control.\n    ///      Incorrect claim input indices could raise two errors:\n    ///      `InvalidInputIndices` if first index is posterior than last index or\n    ///      `UnclaimedInputs` if first index is not the subsequent of previous claimed index or\n    ///                        if the first index of the first claim is not zero.\n    function submitClaim(\n        bytes calldata _claimData\n    ) external override onlyOwner {\n        (address dapp, Claim memory claim) = abi.decode(\n            _claimData,\n            (address, Claim)\n        );\n\n        if (claim.firstIndex > claim.lastIndex) {\n            revert InvalidInputIndices();\n        }\n\n        uint256 numDAppClaims = numClaims[dapp];\n\n        if (\n            claim.firstIndex !=\n            (\n                (numDAppClaims == 0)\n                    ? 0\n                    : (claims[dapp][numDAppClaims - 1].lastIndex + 1)\n            )\n        ) {\n            revert UnclaimedInputs();\n        }\n\n        claims[dapp][numDAppClaims] = claim;\n        numClaims[dapp] = numDAppClaims + 1;\n\n        emit NewClaimToHistory(dapp, claim);\n    }\n\n    /// @notice Get a specific claim regarding a specific DApp.\n    /// There are several requirements for this function to be called successfully.\n    ///\n    /// * `_proofContext` MUST be well-encoded. In Solidity, it can be constructed\n    ///   as `abi.encode(claimIndex)`, where `claimIndex` is the claim index (type `uint256`).\n    ///\n    /// * `claimIndex` MUST be inside the interval `[0, n)` where `n` is the number of claims\n    ///   that have been submitted to `_dapp` already.\n    ///\n    /// @inheritdoc IHistory\n    /// @dev If `claimIndex` is not inside the interval `[0, n)`, then\n    ///      an `InvalidClaimIndex` error is raised.\n    function getClaim(\n        address _dapp,\n        bytes calldata _proofContext\n    ) external view override returns (bytes32, uint256, uint256) {\n        uint256 claimIndex = abi.decode(_proofContext, (uint256));\n\n        uint256 numDAppClaims = numClaims[_dapp];\n\n        if (claimIndex >= numDAppClaims) {\n            revert InvalidClaimIndex();\n        }\n\n        Claim memory claim = claims[_dapp][claimIndex];\n\n        return (claim.epochHash, claim.firstIndex, claim.lastIndex);\n    }\n\n    /// @inheritdoc IHistory\n    /// @dev Emits an `OwnershipTransferred` event. Should have access control.\n    function migrateToConsensus(\n        address _consensus\n    ) external override onlyOwner {\n        transferOwnership(_consensus);\n    }\n}\n"
      },
      "@cartesi/rollups/contracts/history/IHistory.sol": {
        "content": "// (c) Cartesi and individual authors (see AUTHORS)\n// SPDX-License-Identifier: Apache-2.0 (see LICENSE)\n\npragma solidity ^0.8.8;\n\n/// @title History interface\ninterface IHistory {\n    // Permissioned functions\n\n    /// @notice Submit a claim.\n    ///         The encoding of `_claimData` might vary\n    ///         depending on the history implementation.\n    /// @param _claimData Data for submitting a claim\n    /// @dev Should have access control.\n    function submitClaim(bytes calldata _claimData) external;\n\n    /// @notice Transfer ownership to another consensus.\n    /// @param _consensus The new consensus\n    /// @dev Should have access control.\n    function migrateToConsensus(address _consensus) external;\n\n    // Permissionless functions\n\n    /// @notice Get a specific claim regarding a specific DApp.\n    ///         The encoding of `_proofContext` might vary\n    ///         depending on the history implementation.\n    /// @param _dapp The DApp address\n    /// @param _proofContext Data for retrieving the desired claim\n    /// @return epochHash_ The claimed epoch hash\n    /// @return firstInputIndex_ The index of the first input of the epoch in the input box\n    /// @return lastInputIndex_ The index of the last input of the epoch in the input box\n    function getClaim(\n        address _dapp,\n        bytes calldata _proofContext\n    )\n        external\n        view\n        returns (\n            bytes32 epochHash_,\n            uint256 firstInputIndex_,\n            uint256 lastInputIndex_\n        );\n}\n"
      },
      "@cartesi/rollups/contracts/history/IHistoryFactory.sol": {
        "content": "// (c) Cartesi and individual authors (see AUTHORS)\n// SPDX-License-Identifier: Apache-2.0 (see LICENSE)\n\npragma solidity ^0.8.8;\n\nimport {History} from \"./History.sol\";\n\n/// @title History Factory interface\ninterface IHistoryFactory {\n    // Events\n\n    /// @notice A new history was deployed.\n    /// @param historyOwner The initial history owner\n    /// @param history The history\n    /// @dev MUST be triggered on a successful call to `newHistory`.\n    event HistoryCreated(address historyOwner, History history);\n\n    // Permissionless functions\n\n    /// @notice Deploy a new history.\n    /// @param _historyOwner The initial history owner\n    /// @return The history\n    /// @dev On success, MUST emit a `HistoryCreated` event.\n    function newHistory(address _historyOwner) external returns (History);\n\n    /// @notice Deploy a new history deterministically.\n    /// @param _historyOwner The initial history owner\n    /// @param _salt The salt used to deterministically generate the history address\n    /// @return The history\n    /// @dev On success, MUST emit a `HistoryCreated` event.\n    function newHistory(\n        address _historyOwner,\n        bytes32 _salt\n    ) external returns (History);\n\n    /// @notice Calculate the address of a history to be deployed deterministically.\n    /// @param _historyOwner The initial history owner\n    /// @param _salt The salt used to deterministically generate the history address\n    /// @return The deterministic history address\n    /// @dev Beware that only the `newHistory` function with the `_salt` parameter\n    ///      is able to deterministically deploy a history.\n    function calculateHistoryAddress(\n        address _historyOwner,\n        bytes32 _salt\n    ) external view returns (address);\n}\n"
      },
      "@cartesi/rollups/contracts/library/LibOutputValidation.sol": {
        "content": "// (c) Cartesi and individual authors (see AUTHORS)\n// SPDX-License-Identifier: Apache-2.0 (see LICENSE)\n\npragma solidity ^0.8.8;\n\nimport {CanonicalMachine} from \"../common/CanonicalMachine.sol\";\nimport {MerkleV2} from \"@cartesi/util/contracts/MerkleV2.sol\";\nimport {OutputEncoding} from \"../common/OutputEncoding.sol\";\n\n/// @param inputIndexWithinEpoch Which input, inside the epoch, the output belongs to\n/// @param outputIndexWithinInput Index of output emitted by the input\n/// @param outputHashesRootHash Merkle root of hashes of outputs emitted by the input\n/// @param vouchersEpochRootHash Merkle root of all epoch's voucher metadata hashes\n/// @param noticesEpochRootHash Merkle root of all epoch's notice metadata hashes\n/// @param machineStateHash Hash of the machine state claimed this epoch\n/// @param outputHashInOutputHashesSiblings Proof that this output metadata is in metadata memory range\n/// @param outputHashesInEpochSiblings Proof that this output metadata is in epoch's output memory range\nstruct OutputValidityProof {\n    uint64 inputIndexWithinEpoch;\n    uint64 outputIndexWithinInput;\n    bytes32 outputHashesRootHash;\n    bytes32 vouchersEpochRootHash;\n    bytes32 noticesEpochRootHash;\n    bytes32 machineStateHash;\n    bytes32[] outputHashInOutputHashesSiblings;\n    bytes32[] outputHashesInEpochSiblings;\n}\n\n/// @title Output Validation Library\nlibrary LibOutputValidation {\n    using CanonicalMachine for CanonicalMachine.Log2Size;\n\n    /// @notice Raised when some `OutputValidityProof` variables does not match\n    ///         the presented finalized epoch.\n    error IncorrectEpochHash();\n\n    /// @notice Raised when `OutputValidityProof` metadata memory range is NOT\n    ///         contained in epoch's output memory range.\n    error IncorrectOutputsEpochRootHash();\n\n    /// @notice Raised when Merkle root of output hash is NOT contained\n    ///         in the output metadata array memory range.\n    error IncorrectOutputHashesRootHash();\n\n    /// @notice Raised when epoch input index is NOT compatible with the\n    ///         provided input index range.\n    error InputIndexOutOfClaimBounds();\n\n    /// @notice Make sure the output proof is valid, otherwise revert.\n    /// @param v The output validity proof\n    /// @param encodedOutput The encoded output\n    /// @param epochHash The hash of the epoch in which the output was generated\n    /// @param outputsEpochRootHash Either `v.vouchersEpochRootHash` (for vouchers)\n    ///                             or `v.noticesEpochRootHash` (for notices)\n    /// @param outputEpochLog2Size Either `EPOCH_VOUCHER_LOG2_SIZE` (for vouchers)\n    ///                            or `EPOCH_NOTICE_LOG2_SIZE` (for notices)\n    /// @param outputHashesLog2Size Either `VOUCHER_METADATA_LOG2_SIZE` (for vouchers)\n    ///                             or `NOTICE_METADATA_LOG2_SIZE` (for notices)\n    function validateEncodedOutput(\n        OutputValidityProof calldata v,\n        bytes memory encodedOutput,\n        bytes32 epochHash,\n        bytes32 outputsEpochRootHash,\n        uint256 outputEpochLog2Size,\n        uint256 outputHashesLog2Size\n    ) internal pure {\n        // prove that outputs hash is represented in a finalized epoch\n        if (\n            keccak256(\n                abi.encodePacked(\n                    v.vouchersEpochRootHash,\n                    v.noticesEpochRootHash,\n                    v.machineStateHash\n                )\n            ) != epochHash\n        ) {\n            revert IncorrectEpochHash();\n        }\n\n        // prove that output metadata memory range is contained in epoch's output memory range\n        if (\n            MerkleV2.getRootAfterReplacementInDrive(\n                CanonicalMachine.getIntraMemoryRangePosition(\n                    v.inputIndexWithinEpoch,\n                    CanonicalMachine.KECCAK_LOG2_SIZE\n                ),\n                CanonicalMachine.KECCAK_LOG2_SIZE.uint64OfSize(),\n                outputEpochLog2Size,\n                v.outputHashesRootHash,\n                v.outputHashesInEpochSiblings\n            ) != outputsEpochRootHash\n        ) {\n            revert IncorrectOutputsEpochRootHash();\n        }\n\n        // The hash of the output is converted to bytes (abi.encode) and\n        // treated as data. The metadata output memory range stores that data while\n        // being indifferent to its contents. To prove that the received\n        // output is contained in the metadata output memory range we need to\n        // prove that x, where:\n        // x = keccak(\n        //          keccak(\n        //              keccak(hashOfOutput[0:7]),\n        //              keccak(hashOfOutput[8:15])\n        //          ),\n        //          keccak(\n        //              keccak(hashOfOutput[16:23]),\n        //              keccak(hashOfOutput[24:31])\n        //          )\n        //     )\n        // is contained in it. We can't simply use hashOfOutput because the\n        // log2size of the leaf is three (8 bytes) not  five (32 bytes)\n        bytes32 merkleRootOfHashOfOutput = MerkleV2.getMerkleRootFromBytes(\n            abi.encodePacked(keccak256(encodedOutput)),\n            CanonicalMachine.KECCAK_LOG2_SIZE.uint64OfSize()\n        );\n\n        // prove that Merkle root of bytes(hashOfOutput) is contained\n        // in the output metadata array memory range\n        if (\n            MerkleV2.getRootAfterReplacementInDrive(\n                CanonicalMachine.getIntraMemoryRangePosition(\n                    v.outputIndexWithinInput,\n                    CanonicalMachine.KECCAK_LOG2_SIZE\n                ),\n                CanonicalMachine.KECCAK_LOG2_SIZE.uint64OfSize(),\n                outputHashesLog2Size,\n                merkleRootOfHashOfOutput,\n                v.outputHashInOutputHashesSiblings\n            ) != v.outputHashesRootHash\n        ) {\n            revert IncorrectOutputHashesRootHash();\n        }\n    }\n\n    /// @notice Make sure the output proof is valid, otherwise revert.\n    /// @param v The output validity proof\n    /// @param destination The address that will receive the payload through a message call\n    /// @param payload The payload, which—in the case of Solidity contracts—encodes a function call\n    /// @param epochHash The hash of the epoch in which the output was generated\n    function validateVoucher(\n        OutputValidityProof calldata v,\n        address destination,\n        bytes calldata payload,\n        bytes32 epochHash\n    ) internal pure {\n        bytes memory encodedVoucher = OutputEncoding.encodeVoucher(\n            destination,\n            payload\n        );\n        validateEncodedOutput(\n            v,\n            encodedVoucher,\n            epochHash,\n            v.vouchersEpochRootHash,\n            CanonicalMachine.EPOCH_VOUCHER_LOG2_SIZE.uint64OfSize(),\n            CanonicalMachine.VOUCHER_METADATA_LOG2_SIZE.uint64OfSize()\n        );\n    }\n\n    /// @notice Make sure the output proof is valid, otherwise revert.\n    /// @param v The output validity proof\n    /// @param notice The notice\n    /// @param epochHash The hash of the epoch in which the output was generated\n    function validateNotice(\n        OutputValidityProof calldata v,\n        bytes calldata notice,\n        bytes32 epochHash\n    ) internal pure {\n        bytes memory encodedNotice = OutputEncoding.encodeNotice(notice);\n        validateEncodedOutput(\n            v,\n            encodedNotice,\n            epochHash,\n            v.noticesEpochRootHash,\n            CanonicalMachine.EPOCH_NOTICE_LOG2_SIZE.uint64OfSize(),\n            CanonicalMachine.NOTICE_METADATA_LOG2_SIZE.uint64OfSize()\n        );\n    }\n\n    /// @notice Get the position of a voucher on the bit mask.\n    /// @param voucher The index of voucher from those generated by such input\n    /// @param input The index of the input in the DApp's input box\n    /// @return Position of the voucher on the bit mask\n    function getBitMaskPosition(\n        uint256 voucher,\n        uint256 input\n    ) internal pure returns (uint256) {\n        // voucher * 2 ** 128 + input\n        // this shouldn't overflow because it is impossible to have > 2**128 vouchers\n        // and because we are assuming there will be < 2 ** 128 inputs on the input box\n        return (((voucher << 128) | input));\n    }\n\n    /// @notice Validate input index range and get the input index.\n    /// @param v The output validity proof\n    /// @param firstInputIndex The index of the first input of the epoch in the input box\n    /// @param lastInputIndex The index of the last input of the epoch in the input box\n    /// @return The index of the input in the DApp's input box\n    /// @dev Reverts if epoch input index is not compatible with the provided input index range.\n    function validateInputIndexRange(\n        OutputValidityProof calldata v,\n        uint256 firstInputIndex,\n        uint256 lastInputIndex\n    ) internal pure returns (uint256) {\n        uint256 inputIndex = firstInputIndex + v.inputIndexWithinEpoch;\n\n        if (inputIndex > lastInputIndex) {\n            revert InputIndexOutOfClaimBounds();\n        }\n\n        return inputIndex;\n    }\n}\n"
      },
      "@cartesi/util/contracts/Bitmask.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\n// Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use\n// this file except in compliance with the License. You may obtain a copy of the\n// License at http://www.apache.org/licenses/LICENSE-2.0\n\n// Unless required by applicable law or agreed to in writing, software distributed\n// under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n// CONDITIONS OF ANY KIND, either express or implied. See the License for the\n// specific language governing permissions and limitations under the License.\n\npragma solidity ^0.8.0;\n\n/// @title Bit Mask Library\n/// @author Stephen Chen\n/// @notice Implements bit mask with dynamic array\nlibrary Bitmask {\n    /// @notice Set a bit in the bit mask\n    function setBit(mapping(uint256 => uint256) storage bitmask, uint256 _bit, bool _value) public {\n        // calculate the number of bits has been store in bitmask now\n        uint256 positionOfMask = uint256(_bit / 256);\n        uint256 positionOfBit = _bit % 256;\n\n        if (_value) {\n            bitmask[positionOfMask] = bitmask[positionOfMask] | (1 << positionOfBit);\n        } else {\n            bitmask[positionOfMask] = bitmask[positionOfMask] & ~(1 << positionOfBit);\n        }\n    }\n\n    /// @notice Get a bit in the bit mask\n    function getBit(mapping(uint256 => uint256) storage bitmask, uint256 _bit) public view returns (bool) {\n        // calculate the number of bits has been store in bitmask now\n        uint256 positionOfMask = uint256(_bit / 256);\n        uint256 positionOfBit = _bit % 256;\n\n        return ((bitmask[positionOfMask] & (1 << positionOfBit)) != 0);\n    }\n}\n"
      },
      "@cartesi/util/contracts/CartesiMathV2.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\n// Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use\n// this file except in compliance with the License. You may obtain a copy of the\n// License at http://www.apache.org/licenses/LICENSE-2.0\n\n// Unless required by applicable law or agreed to in writing, software distributed\n// under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n// CONDITIONS OF ANY KIND, either express or implied. See the License for the\n// specific language governing permissions and limitations under the License.\n\n/// @title CartesiMath\n/// @author Felipe Argento\npragma solidity ^0.8.0;\n\nlibrary CartesiMathV2 {\n    // mapping values are packed as bytes3 each\n    // see test/TestCartesiMath.ts for decimal values\n    bytes constant log2tableTimes1M =\n        hex\"0000000F4240182F421E8480236E082771822AD63A2DC6C0305E8532B04834C96736B3C23876D73A187A3B9D4A3D09003E5EA63FA0C540D17741F28843057D440BA745062945F60246DC1047B917488DC7495ABA4A207C4ADF8A4B98544C4B404CF8AA4DA0E64E44434EE3054F7D6D5013B750A61A5134C851BFF05247BD52CC58534DE753CC8D54486954C19C55384255AC75561E50568DE956FB575766B057D00758376F589CFA5900BA5962BC59C3135A21CA5A7EF15ADA945B34BF5B8D805BE4DF5C3AEA5C8FA95CE3265D356C5D86835DD6735E25455E73005EBFAD5F0B525F55F75F9FA25FE85A60302460770860BD0A61023061467F6189FD61CCAE620E98624FBF62902762CFD5630ECD634D12638AA963C7966403DC643F7F647A8264B4E864EEB56527EC6560906598A365D029660724663D9766738566A8F066DDDA6712476746386779AF67ACAF67DF3A6811526842FA68743268A4FC68D55C6905536934E169640A6992CF69C13169EF326A1CD46A4A186A76FF6AA38C6ACFC0\";\n\n    /// @notice Approximates log2 * 1M\n    /// @param _num number to take log2 * 1M of\n    /// @return approximate log2 times 1M\n    function log2ApproxTimes1M(uint256 _num) public pure returns (uint256) {\n        require(_num > 0, \"Number cannot be zero\");\n        uint256 leading = 0;\n\n        if (_num == 1) return 0;\n\n        while (_num > 128) {\n            _num = _num >> 1;\n            leading += 1;\n        }\n        return (leading * uint256(1000000)) + (getLog2TableTimes1M(_num));\n    }\n\n    /// @notice navigates log2tableTimes1M\n    /// @param _num number to take log2 of\n    /// @return result after table look-up\n    function getLog2TableTimes1M(uint256 _num) public pure returns (uint256) {\n        bytes3 result = 0;\n        for (uint8 i = 0; i < 3; i++) {\n            bytes3 tempResult = log2tableTimes1M[(_num - 1) * 3 + i];\n            result = result | (tempResult >> (i * 8));\n        }\n\n        return uint256(uint24(result));\n    }\n\n    /// @notice get floor of log2 of number\n    /// @param _num number to take floor(log2) of\n    /// @return floor(log2) of _num\n    function getLog2Floor(uint256 _num) public pure returns (uint8) {\n        require(_num != 0, \"log of zero is undefined\");\n\n        return uint8(255 - clz(_num));\n    }\n\n    /// @notice checks if a number is Power of 2\n    /// @param _num number to check\n    /// @return true if number is power of 2, false if not\n    function isPowerOf2(uint256 _num) public pure returns (bool) {\n        if (_num == 0) return false;\n\n        return _num & (_num - 1) == 0;\n    }\n\n    /// @notice count trailing zeros\n    /// @param _num number you want the ctz of\n    /// @dev this a binary search implementation\n    function ctz(uint256 _num) public pure returns (uint256) {\n        if (_num == 0) return 256;\n\n        uint256 n = 0;\n        if (_num & 0x00000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) {\n            n = n + 128;\n            _num = _num >> 128;\n        }\n        if (_num & 0x000000000000000000000000000000000000000000000000FFFFFFFFFFFFFFFF == 0) {\n            n = n + 64;\n            _num = _num >> 64;\n        }\n        if (_num & 0x00000000000000000000000000000000000000000000000000000000FFFFFFFF == 0) {\n            n = n + 32;\n            _num = _num >> 32;\n        }\n        if (_num & 0x000000000000000000000000000000000000000000000000000000000000FFFF == 0) {\n            n = n + 16;\n            _num = _num >> 16;\n        }\n        if (_num & 0x00000000000000000000000000000000000000000000000000000000000000FF == 0) {\n            n = n + 8;\n            _num = _num >> 8;\n        }\n        if (_num & 0x000000000000000000000000000000000000000000000000000000000000000F == 0) {\n            n = n + 4;\n            _num = _num >> 4;\n        }\n        if (_num & 0x0000000000000000000000000000000000000000000000000000000000000003 == 0) {\n            n = n + 2;\n            _num = _num >> 2;\n        }\n        if (_num & 0x0000000000000000000000000000000000000000000000000000000000000001 == 0) {\n            n = n + 1;\n        }\n\n        return n;\n    }\n\n    /// @notice count leading zeros\n    /// @param _num number you want the clz of\n    /// @dev this a binary search implementation\n    function clz(uint256 _num) public pure returns (uint256) {\n        if (_num == 0) return 256;\n\n        uint256 n = 0;\n        if (_num & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000 == 0) {\n            n = n + 128;\n            _num = _num << 128;\n        }\n        if (_num & 0xFFFFFFFFFFFFFFFF000000000000000000000000000000000000000000000000 == 0) {\n            n = n + 64;\n            _num = _num << 64;\n        }\n        if (_num & 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000 == 0) {\n            n = n + 32;\n            _num = _num << 32;\n        }\n        if (_num & 0xFFFF000000000000000000000000000000000000000000000000000000000000 == 0) {\n            n = n + 16;\n            _num = _num << 16;\n        }\n        if (_num & 0xFF00000000000000000000000000000000000000000000000000000000000000 == 0) {\n            n = n + 8;\n            _num = _num << 8;\n        }\n        if (_num & 0xF000000000000000000000000000000000000000000000000000000000000000 == 0) {\n            n = n + 4;\n            _num = _num << 4;\n        }\n        if (_num & 0xC000000000000000000000000000000000000000000000000000000000000000 == 0) {\n            n = n + 2;\n            _num = _num << 2;\n        }\n        if (_num & 0x8000000000000000000000000000000000000000000000000000000000000000 == 0) {\n            n = n + 1;\n        }\n\n        return n;\n    }\n}\n"
      },
      "@cartesi/util/contracts/MerkleV2.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\n// Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use\n// this file except in compliance with the License. You may obtain a copy of the\n// License at http://www.apache.org/licenses/LICENSE-2.0\n\n// Unless required by applicable law or agreed to in writing, software distributed\n// under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n// CONDITIONS OF ANY KIND, either express or implied. See the License for the\n// specific language governing permissions and limitations under the License.\n\n/// @title Library for Merkle proofs\npragma solidity ^0.8.0;\n\nimport \"./CartesiMathV2.sol\";\n\nlibrary MerkleV2 {\n    using CartesiMathV2 for uint256;\n\n    uint128 constant L_WORD_SIZE = 3; // word = 8 bytes, log = 3\n    // number of hashes in EMPTY_TREE_HASHES\n    uint128 constant EMPTY_TREE_SIZE = 1952; // 61*32=1952. 32 bytes per 61 indexes (64 words)\n\n    // merkle root hashes of trees of zero concatenated\n    // 32 bytes for each root, first one is keccak(0), second one is\n    // keccak(keccack(0), keccak(0)) and so on\n\n    bytes constant EMPTY_TREE_HASHES =\n        hex\"011b4d03dd8c01f1049143cf9c4c817e4b167f1d1b83e5c6f0f10d89ba1e7bce4d9470a821fbe90117ec357e30bad9305732fb19ddf54a07dd3e29f440619254ae39ce8537aca75e2eff3e38c98011dfe934e700a0967732fc07b430dd656a233fc9a15f5b4869c872f81087bb6104b7d63e6f9ab47f2c43f3535eae7172aa7f17d2dd614cddaa4d879276b11e0672c9560033d3e8453a1d045339d34ba601b9c37b8b13ca95166fb7af16988a70fcc90f38bf9126fd833da710a47fb37a55e68e7a427fa943d9966b389f4f257173676090c6e95f43e2cb6d65f8758111e30930b0b9deb73e155c59740bacf14a6ff04b64bb8e201a506409c3fe381ca4ea90cd5deac729d0fdaccc441d09d7325f41586ba13c801b7eccae0f95d8f3933efed8b96e5b7f6f459e9cb6a2f41bf276c7b85c10cd4662c04cbbb365434726c0a0c9695393027fb106a8153109ac516288a88b28a93817899460d6310b71cf1e6163e8806fa0d4b197a259e8c3ac28864268159d0ac85f8581ca28fa7d2c0c03eb91e3eee5ca7a3da2b3053c9770db73599fb149f620e3facef95e947c0ee860b72122e31e4bbd2b7c783d79cc30f60c6238651da7f0726f767d22747264fdb046f7549f26cc70ed5e18baeb6c81bb0625cb95bb4019aeecd40774ee87ae29ec517a71f6ee264c5d761379b3d7d617ca83677374b49d10aec50505ac087408ca892b573c267a712a52e1d06421fe276a03efb1889f337201110fdc32a81f8e152499af665835aabfdc6740c7e2c3791a31c3cdc9f5ab962f681b12fc092816a62f27d86025599a41233848702f0cfc0437b445682df51147a632a0a083d2d38b5e13e466a8935afff58bb533b3ef5d27fba63ee6b0fd9e67ff20af9d50deee3f8bf065ec220c1fd4ba57e341261d55997f85d66d32152526736872693d2b437a233e2337b715f6ac9a6a272622fdc2d67fcfe1da3459f8dab4ed7e40a657a54c36766c5e8ac9a88b35b05c34747e6507f6b044ab66180dc76ac1a696de03189593fedc0d0dbbd855c8ead673544899b0960e4a5a7ca43b4ef90afe607de7698caefdc242788f654b57a4fb32a71b335ef6ff9a4cc118b282b53bdd6d6192b7a82c3c5126b9c7e33c8e5a5ac9738b8bd31247fb7402054f97b573e8abb9faad219f4fd085aceaa7f542d787ee4196d365f3cc566e7bbcfbfd451230c48d804c017d21e2d8fa914e2559bb72bf0ab78c8ab92f00ef0d0d576eccdd486b64138a4172674857e543d1d5b639058dd908186597e366ad5f3d9c7ceaff44d04d1550b8d33abc751df07437834ba5acb32328a396994aebb3c40f759c2d6d7a3cb5377e55d5d218ef5a296dda8ddc355f3f50c3d0b660a51dfa4d98a6a5a33564556cf83c1373a814641d6a1dcef97b883fee61bb84fe60a3409340217e629cc7e4dcc93b85d8820921ff5826148b60e6939acd7838e1d7f20562bff8ee4b5ec4a05ad997a57b9796fdcb2eda87883c2640b072b140b946bfdf6575cacc066fdae04f6951e63624cbd316a677cad529bbe4e97b9144e4bc06c4afd1de55dd3e1175f90423847a230d34dfb71ed56f2965a7f6c72e6aa33c24c303fd67745d632656c5ef90bec80f4f5d1daa251988826cef375c81c36bf457e09687056f924677cb0bccf98dff81e014ce25f2d132497923e267363963cdf4302c5049d63131dc03fd95f65d8b6aa5934f817252c028c90f56d413b9d5d10d89790707dae2fabb249f649929927c21dd71e3f656826de5451c5da375aadecbd59d5ebf3a31fae65ac1b316a1611f1b276b26530f58d7247df459ce1f86db1d734f6f811932f042cee45d0e455306d01081bc3384f82c5fb2aacaa19d89cdfa46cc916eac61121475ba2e6191b4feecbe1789717021a158ace5d06744b40f551076b67cd63af60007f8c99876e1424883a45ec49d497ddaf808a5521ca74a999ab0b3c7aa9c80f85e93977ec61ce68b20307a1a81f71ca645b568fcd319ccbb5f651e87b707d37c39e15f945ea69e2f7c7d2ccc85b7e654c07e96f0636ae4044fe0e38590b431795ad0f8647bdd613713ada493cc17efd313206380e6a685b8198475bbd021c6e9d94daab2214947127506073e44d5408ba166c512a0b86805d07f5a44d3c41706be2bc15e712e55805248b92e8677d90f6d284d1d6ffaff2c430657042a0e82624fa3717b06cc0a6fd12230ea586dae83019fb9e06034ed2803c98d554b93c9a52348cafff75c40174a91f9ae6b8647854a156029f0b88b83316663ce574a4978277bb6bb27a31085634b6ec78864b6d8201c7e93903d75815067e378289a3d072ae172dafa6a452470f8d645bebfad9779594fc0784bb764a22e3a8181d93db7bf97893c414217a618ccb14caa9e92e8c61673afc9583662e812adba1f87a9c68202d60e909efab43c42c0cb00695fc7f1ffe67c75ca894c3c51e1e5e731360199e600f6ced9a87b2a6a87e70bf251bb5075ab222138288164b2eda727515ea7de12e2496d4fe42ea8d1a120c03cf9c50622c2afe4acb0dad98fd62d07ab4e828a94495f6d1ab973982c7ccbe6c1fae02788e4422ae22282fa49cbdb04ba54a7a238c6fc41187451383460762c06d1c8a72b9cd718866ad4b689e10c9a8c38fe5ef045bd785b01e980fc82c7e3532ce81876b778dd9f1ceeba4478e86411fb6fdd790683916ca832592485093644e8760cd7b4c01dba1ccc82b661bf13f0e3f34acd6b88\";\n\n    /// @notice Gets merkle root hash of drive with a replacement\n    /// @param _position position of _drive\n    /// @param _logSizeOfReplacement log2 of size the replacement\n    /// @param _logSizeOfFullDrive log2 of size the full drive, which can be the entire machine\n    /// @param _replacement hash of the replacement\n    /// @param siblings of replacement that merkle root can be calculated\n    function getRootAfterReplacementInDrive(\n        uint256 _position,\n        uint256 _logSizeOfReplacement,\n        uint256 _logSizeOfFullDrive,\n        bytes32 _replacement,\n        bytes32[] calldata siblings\n    ) public pure returns (bytes32) {\n        require(\n            _logSizeOfFullDrive >= _logSizeOfReplacement && _logSizeOfReplacement >= 3 && _logSizeOfFullDrive <= 64,\n            \"3 <= logSizeOfReplacement <= logSizeOfFullDrive <= 64\"\n        );\n\n        uint256 size = 1 << _logSizeOfReplacement;\n\n        require(((size - 1) & _position) == 0, \"Position is not aligned\");\n        require(siblings.length == _logSizeOfFullDrive - _logSizeOfReplacement, \"Proof length does not match\");\n\n        for (uint256 i; i < siblings.length; i++) {\n            if ((_position & (size << i)) == 0) {\n                _replacement = keccak256(abi.encodePacked(_replacement, siblings[i]));\n            } else {\n                _replacement = keccak256(abi.encodePacked(siblings[i], _replacement));\n            }\n        }\n\n        return _replacement;\n    }\n\n    /// @notice Gets precomputed hash of zero in empty tree hashes\n    /// @param _index of hash wanted\n    /// @dev first index is keccak(0), second index is keccak(keccak(0), keccak(0))\n    function getEmptyTreeHashAtIndex(uint256 _index) public pure returns (bytes32) {\n        uint256 start = _index * 32;\n        require(EMPTY_TREE_SIZE >= start + 32, \"index out of bounds\");\n        bytes32 hashedZeros;\n        bytes memory zeroTree = EMPTY_TREE_HASHES;\n\n        // first word is length, then skip index words\n        assembly {\n            hashedZeros := mload(add(add(zeroTree, 0x20), start))\n        }\n        return hashedZeros;\n    }\n\n    /// @notice get merkle root of generic array of bytes\n    /// @param _data array of bytes to be merklelized\n    /// @param _log2Size log2 of total size of the drive\n    /// @dev _data is padded with zeroes until is multiple of 8\n    /// @dev root is completed with zero tree until log2size is complete\n    /// @dev hashes are taken word by word (8 bytes by 8 bytes)\n    function getMerkleRootFromBytes(bytes calldata _data, uint256 _log2Size) public pure returns (bytes32) {\n        require(_log2Size >= 3 && _log2Size <= 64, \"range of log2Size: [3,64]\");\n\n        // if _data is empty return pristine drive of size log2size\n        if (_data.length == 0) return getEmptyTreeHashAtIndex(_log2Size - 3);\n\n        // total size of the drive in words\n        uint256 size = 1 << (_log2Size - 3);\n        require(size << L_WORD_SIZE >= _data.length, \"data is bigger than drive\");\n        // the stack depth is log2(_data.length / 8) + 2\n        uint256 stack_depth = 2 + ((_data.length) >> L_WORD_SIZE).getLog2Floor();\n        bytes32[] memory stack = new bytes32[](stack_depth);\n\n        uint256 numOfHashes; // total number of hashes on stack (counting levels)\n        uint256 stackLength; // total length of stack\n        uint256 numOfJoins; // number of hashes of the same level on stack\n        uint256 topStackLevel; // hash level of the top of the stack\n\n        while (numOfHashes < size) {\n            if ((numOfHashes << L_WORD_SIZE) < _data.length) {\n                // we still have words to hash\n                stack[stackLength] = getHashOfWordAtIndex(_data, numOfHashes);\n                numOfHashes++;\n\n                numOfJoins = numOfHashes;\n            } else {\n                // since padding happens in hashOfWordAtIndex function\n                // we only need to complete the stack with pre-computed\n                // hash(0), hash(hash(0),hash(0)) and so on\n                topStackLevel = numOfHashes.ctz();\n\n                stack[stackLength] = getEmptyTreeHashAtIndex(topStackLevel);\n\n                //Empty Tree Hash summarizes many hashes\n                numOfHashes = numOfHashes + (1 << topStackLevel);\n                numOfJoins = numOfHashes >> topStackLevel;\n            }\n\n            stackLength++;\n\n            // while there are joins, hash top of stack together\n            while (numOfJoins & 1 == 0) {\n                bytes32 h2 = stack[stackLength - 1];\n                bytes32 h1 = stack[stackLength - 2];\n\n                stack[stackLength - 2] = keccak256(abi.encodePacked(h1, h2));\n                stackLength = stackLength - 1; // remove hashes from stack\n\n                numOfJoins = numOfJoins >> 1;\n            }\n        }\n        require(stackLength == 1, \"stack error\");\n\n        return stack[0];\n    }\n\n    /// @notice Get the hash of a word in an array of bytes\n    /// @param _data array of bytes\n    /// @param _wordIndex index of word inside the bytes to get the hash of\n    /// @dev if word is incomplete (< 8 bytes) it gets padded with zeroes\n    function getHashOfWordAtIndex(bytes calldata _data, uint256 _wordIndex) public pure returns (bytes32) {\n        uint256 start = _wordIndex << L_WORD_SIZE;\n        uint256 end = start + (1 << L_WORD_SIZE);\n\n        // TODO: in .lua this just returns zero, but this might be more consistent\n        require(start <= _data.length, \"word out of bounds\");\n\n        if (end <= _data.length) {\n            return keccak256(abi.encodePacked(_data[start:end]));\n        }\n\n        // word is incomplete\n        // fill paddedSlice with incomplete words - the rest is going to be bytes(0)\n        bytes memory paddedSlice = new bytes(8);\n        uint256 remaining = _data.length - start;\n\n        for (uint256 i; i < remaining; i++) {\n            paddedSlice[i] = _data[start + i];\n        }\n\n        return keccak256(paddedSlice);\n    }\n\n    /// @notice Calculate the root of Merkle tree from an array of power of 2 elements\n    /// @param hashes The array containing power of 2 elements\n    /// @return byte32 the root hash being calculated\n    function calculateRootFromPowerOfTwo(bytes32[] memory hashes) public pure returns (bytes32) {\n        // revert when the input is not of power of 2\n        require((hashes.length).isPowerOf2(), \"array len not power of 2\");\n\n        if (hashes.length == 1) {\n            return hashes[0];\n        } else {\n            bytes32[] memory newHashes = new bytes32[](hashes.length >> 1);\n\n            for (uint256 i; i < hashes.length; i += 2) {\n                newHashes[i >> 1] = keccak256(abi.encodePacked(hashes[i], hashes[i + 1]));\n            }\n\n            return calculateRootFromPowerOfTwo(newHashes);\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/access/Ownable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    constructor() {\n        _transferOwnership(_msgSender());\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"
      },
      "@openzeppelin/contracts/security/ReentrancyGuard.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    constructor() {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, _status will be _NOT_ENTERED\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        return _status == _ENTERED;\n    }\n}\n"
      },
      "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev _Available since v3.1._\n */\ninterface IERC1155Receiver is IERC165 {\n    /**\n     * @dev Handles the receipt of a single ERC1155 token type. This function is\n     * called at the end of a `safeTransferFrom` after the balance has been updated.\n     *\n     * NOTE: To accept the transfer, this must return\n     * `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))`\n     * (i.e. 0xf23a6e61, or its own function selector).\n     *\n     * @param operator The address which initiated the transfer (i.e. msg.sender)\n     * @param from The address which previously owned the token\n     * @param id The ID of the token being transferred\n     * @param value The amount of tokens being transferred\n     * @param data Additional data with no specified format\n     * @return `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))` if transfer is allowed\n     */\n    function onERC1155Received(\n        address operator,\n        address from,\n        uint256 id,\n        uint256 value,\n        bytes calldata data\n    ) external returns (bytes4);\n\n    /**\n     * @dev Handles the receipt of a multiple ERC1155 token types. This function\n     * is called at the end of a `safeBatchTransferFrom` after the balances have\n     * been updated.\n     *\n     * NOTE: To accept the transfer(s), this must return\n     * `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))`\n     * (i.e. 0xbc197c81, or its own function selector).\n     *\n     * @param operator The address which initiated the batch transfer (i.e. msg.sender)\n     * @param from The address which previously owned the token\n     * @param ids An array containing ids of each token being transferred (order and length must match values array)\n     * @param values An array containing amounts of each token being transferred (order and length must match ids array)\n     * @param data Additional data with no specified format\n     * @return `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))` if transfer is allowed\n     */\n    function onERC1155BatchReceived(\n        address operator,\n        address from,\n        uint256[] calldata ids,\n        uint256[] calldata values,\n        bytes calldata data\n    ) external returns (bytes4);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/utils/ERC1155Holder.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./ERC1155Receiver.sol\";\n\n/**\n * Simple implementation of `ERC1155Receiver` that will allow a contract to hold ERC1155 tokens.\n *\n * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be\n * stuck.\n *\n * @dev _Available since v3.1._\n */\ncontract ERC1155Holder is ERC1155Receiver {\n    function onERC1155Received(\n        address,\n        address,\n        uint256,\n        uint256,\n        bytes memory\n    ) public virtual override returns (bytes4) {\n        return this.onERC1155Received.selector;\n    }\n\n    function onERC1155BatchReceived(\n        address,\n        address,\n        uint256[] memory,\n        uint256[] memory,\n        bytes memory\n    ) public virtual override returns (bytes4) {\n        return this.onERC1155BatchReceived.selector;\n    }\n}\n"
      },
      "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Receiver.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC1155Receiver.sol\";\nimport \"../../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev _Available since v3.1._\n */\nabstract contract ERC1155Receiver is ERC165, IERC1155Receiver {\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n        return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);\n    }\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 amount) external returns (bool);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n    /**\n     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n     * by `operator` from `from`, this function is called.\n     *\n     * It must return its Solidity selector to confirm the token transfer.\n     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n     *\n     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n     */\n    function onERC721Received(\n        address operator,\n        address from,\n        uint256 tokenId,\n        bytes calldata data\n    ) external returns (bytes4);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/utils/ERC721Holder.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721Receiver.sol\";\n\n/**\n * @dev Implementation of the {IERC721Receiver} interface.\n *\n * Accepts all token transfers.\n * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.\n */\ncontract ERC721Holder is IERC721Receiver {\n    /**\n     * @dev See {IERC721Receiver-onERC721Received}.\n     *\n     * Always returns `IERC721Receiver.onERC721Received.selector`.\n     */\n    function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {\n        return this.onERC721Received.selector;\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Create2.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Create2.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.\n * `CREATE2` can be used to compute in advance the address where a smart\n * contract will be deployed, which allows for interesting new mechanisms known\n * as 'counterfactual interactions'.\n *\n * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more\n * information.\n */\nlibrary Create2 {\n    /**\n     * @dev Deploys a contract using `CREATE2`. The address where the contract\n     * will be deployed can be known in advance via {computeAddress}.\n     *\n     * The bytecode for a contract can be obtained from Solidity with\n     * `type(contractName).creationCode`.\n     *\n     * Requirements:\n     *\n     * - `bytecode` must not be empty.\n     * - `salt` must have not been used for `bytecode` already.\n     * - the factory must have a balance of at least `amount`.\n     * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.\n     */\n    function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {\n        require(address(this).balance >= amount, \"Create2: insufficient balance\");\n        require(bytecode.length != 0, \"Create2: bytecode length is zero\");\n        /// @solidity memory-safe-assembly\n        assembly {\n            addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)\n        }\n        require(addr != address(0), \"Create2: Failed on deploy\");\n    }\n\n    /**\n     * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the\n     * `bytecodeHash` or `salt` will result in a new destination address.\n     */\n    function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {\n        return computeAddress(salt, bytecodeHash, address(this));\n    }\n\n    /**\n     * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at\n     * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.\n     */\n    function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let ptr := mload(0x40) // Get free memory pointer\n\n            // |                   | ↓ ptr ...  ↓ ptr + 0x0B (start) ...  ↓ ptr + 0x20 ...  ↓ ptr + 0x40 ...   |\n            // |-------------------|---------------------------------------------------------------------------|\n            // | bytecodeHash      |                                                        CCCCCCCCCCCCC...CC |\n            // | salt              |                                      BBBBBBBBBBBBB...BB                   |\n            // | deployer          | 000000...0000AAAAAAAAAAAAAAAAAAA...AA                                     |\n            // | 0xFF              |            FF                                                             |\n            // |-------------------|---------------------------------------------------------------------------|\n            // | memory            | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |\n            // | keccak(start, 85) |            ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |\n\n            mstore(add(ptr, 0x40), bytecodeHash)\n            mstore(add(ptr, 0x20), salt)\n            mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes\n            let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff\n            mstore8(start, 0xff)\n            addr := keccak256(start, 85)\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/introspection/ERC165.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/introspection/IERC165.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
      },
      "contracts/self-hosted/ISelfHostedApplicationFactory.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\n/// @title ApplicationFactory interface\npragma solidity ^0.8.13;\n\nimport {CartesiDApp} from \"@cartesi/rollups/contracts/dapp/CartesiDApp.sol\";\n\n/// @notice SelfHostedApplicationFactory interface\ninterface ISelfHostedApplicationFactory {\n    /// @notice Deploy a new authority, history and application deterministically.\n    /// @param _authorityOwner The initial authority owner\n    /// @param _dappOwner The initial DApp owner\n    /// @param _templateHash The initial machine state hash\n    /// @param _salt The salt used to deterministically generate the authority, history and application addresses\n    /// @return The application\n    function newApplication(\n        address _authorityOwner,\n        address _dappOwner,\n        bytes32 _templateHash,\n        bytes32 _salt\n    ) external returns (CartesiDApp);\n\n    /// @notice Calculate the address of an application to be deployed deterministically.\n    /// @param _authorityOwner The initial authority owner\n    /// @param _dappOwner The initial DApp owner\n    /// @param _templateHash The initial machine state hash\n    /// @param _salt The salt used to deterministically generate the DApp address\n    /// @return The deterministic authority address, history address and application address\n    function calculateApplicationAddress(\n        address _authorityOwner,\n        address _dappOwner,\n        bytes32 _templateHash,\n        bytes32 _salt\n    ) external view returns (address, address, address);\n}\n"
      },
      "contracts/self-hosted/SelfHostedApplicationFactory.sol": {
        "content": "// SPDX-License-Identifier: Apache-2.0\n/// @title SelfHostedApplicationFactory\npragma solidity ^0.8.13;\n\nimport {Authority} from \"@cartesi/rollups/contracts/consensus/authority/Authority.sol\";\nimport {IAuthorityHistoryPairFactory} from \"@cartesi/rollups/contracts/consensus/authority/IAuthorityHistoryPairFactory.sol\";\nimport {IConsensus} from \"@cartesi/rollups/contracts/consensus/IConsensus.sol\";\nimport {CartesiDApp} from \"@cartesi/rollups/contracts/dapp/CartesiDApp.sol\";\nimport {CartesiDAppFactory} from \"@cartesi/rollups/contracts/dapp/CartesiDAppFactory.sol\";\n\nimport {ISelfHostedApplicationFactory} from \"./ISelfHostedApplicationFactory.sol\";\n\n/// @notice This contract implements an ISelfHostedApplicationFactory.\ncontract SelfHostedApplicationFactory is ISelfHostedApplicationFactory {\n    IAuthorityHistoryPairFactory immutable authorityHistoryPairFactory;\n    CartesiDAppFactory immutable applicationFactory;\n\n    /// @notice Construct a new SelfHostedApplicationFactory\n    /// @param _authorityHistoryPairFactory The authority and history factory\n    /// @param _applicationFactory The application factory\n    constructor(\n        IAuthorityHistoryPairFactory _authorityHistoryPairFactory,\n        CartesiDAppFactory _applicationFactory\n    ) {\n        authorityHistoryPairFactory = _authorityHistoryPairFactory;\n        applicationFactory = _applicationFactory;\n    }\n\n    function newApplication(\n        address _authorityOwner,\n        address _dappOwner,\n        bytes32 _templateHash,\n        bytes32 _salt\n    ) external returns (CartesiDApp) {\n        (Authority authority, ) = authorityHistoryPairFactory\n            .newAuthorityHistoryPair(_authorityOwner, _salt);\n        return\n            applicationFactory.newApplication(\n                authority,\n                _dappOwner,\n                _templateHash,\n                _salt\n            );\n    }\n\n    function calculateApplicationAddress(\n        address _authorityOwner,\n        address _dappOwner,\n        bytes32 _templateHash,\n        bytes32 _salt\n    ) external view returns (address, address, address) {\n        (address authority, address history) = authorityHistoryPairFactory\n            .calculateAuthorityHistoryAddressPair(_authorityOwner, _salt);\n        address application = applicationFactory.calculateApplicationAddress(\n            IConsensus(authority),\n            _dappOwner,\n            _templateHash,\n            _salt\n        );\n        return (authority, history, application);\n    }\n}\n"
      }
    }
  }}