// (c) Cartesi and individual authors (see AUTHORS)
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)
pragma solidity ^0.8.8;
import {IApplication} from "./IApplication.sol";
import {IOutputsMerkleRootValidator} from "../consensus/IOutputsMerkleRootValidator.sol";
import {LibOutputValidityProof} from "../library/LibOutputValidityProof.sol";
import {OutputValidityProof} from "../common/OutputValidityProof.sol";
import {Outputs} from "../common/Outputs.sol";
import {LibAddress} from "../library/LibAddress.sol";
import {IOwnable} from "../access/IOwnable.sol";
import {Ownable} from "@openzeppelin-contracts-5.2.0/access/Ownable.sol";
import {ERC721Holder} from
"@openzeppelin-contracts-5.2.0/token/ERC721/utils/ERC721Holder.sol";
import {ERC1155Holder} from
"@openzeppelin-contracts-5.2.0/token/ERC1155/utils/ERC1155Holder.sol";
import {ReentrancyGuard} from "@openzeppelin-contracts-5.2.0/utils/ReentrancyGuard.sol";
import {IERC721Receiver} from
"@openzeppelin-contracts-5.2.0/token/ERC721/IERC721Receiver.sol";
import {BitMaps} from "@openzeppelin-contracts-5.2.0/utils/structs/BitMaps.sol";
contract Application is
IApplication,
Ownable,
ERC721Holder,
ERC1155Holder,
ReentrancyGuard
{
using BitMaps for BitMaps.BitMap;
using LibAddress for address;
using LibOutputValidityProof for OutputValidityProof;
/// @notice Deployment block number
uint256 immutable _deploymentBlockNumber = block.number;
/// @notice The initial machine state hash.
/// @dev See the `getTemplateHash` function.
bytes32 internal immutable _templateHash;
/// @notice Keeps track of which outputs have been executed.
/// @dev See the `wasOutputExecuted` function.
BitMaps.BitMap internal _executed;
/// @notice The current outputs Merkle root validator contract.
/// @dev See the `getOutputsMerkleRootValidator` and `migrateToOutputsMerkleRootValidator` functions.
IOutputsMerkleRootValidator internal _outputsMerkleRootValidator;
/// @notice The data availability solution.
/// @dev See the `getDataAvailability` function.
bytes internal _dataAvailability;
/// @notice Creates an `Application` contract.
/// @param outputsMerkleRootValidator The initial outputs Merkle root validator contract
/// @param initialOwner The initial application owner
/// @param templateHash The initial machine state hash
/// @dev Reverts if the initial application owner address is zero.
constructor(
IOutputsMerkleRootValidator outputsMerkleRootValidator,
address initialOwner,
bytes32 templateHash,
bytes memory dataAvailability
) Ownable(initialOwner) {
_templateHash = templateHash;
_outputsMerkleRootValidator = outputsMerkleRootValidator;
_dataAvailability = dataAvailability;
}
/// @notice Accept Ether transfers.
/// @dev If you wish to transfer Ether to an application while informing
/// the backend of it, then please do so through the Ether portal contract.
receive() external payable {}
/// @inheritdoc IApplication
function executeOutput(bytes calldata output, OutputValidityProof calldata proof)
external
override
nonReentrant
{
validateOutput(output, proof);
uint64 outputIndex = proof.outputIndex;
if (output.length < 4) {
revert OutputNotExecutable(output);
}
bytes4 selector = bytes4(output[:4]);
bytes calldata arguments = output[4:];
if (selector == Outputs.Voucher.selector) {
if (_executed.get(outputIndex)) {
revert OutputNotReexecutable(output);
}
_executeVoucher(arguments);
} else if (selector == Outputs.DelegateCallVoucher.selector) {
if (_executed.get(outputIndex)) {
revert OutputNotReexecutable(output);
}
_executeDelegateCallVoucher(arguments);
} else {
revert OutputNotExecutable(output);
}
_executed.set(outputIndex);
emit OutputExecuted(outputIndex, output);
}
/// @inheritdoc IApplication
function migrateToOutputsMerkleRootValidator(
IOutputsMerkleRootValidator newOutputsMerkleRootValidator
) external override onlyOwner {
_outputsMerkleRootValidator = newOutputsMerkleRootValidator;
emit OutputsMerkleRootValidatorChanged(newOutputsMerkleRootValidator);
}
/// @inheritdoc IApplication
function wasOutputExecuted(uint256 outputIndex)
external
view
override
returns (bool)
{
return _executed.get(outputIndex);
}
/// @inheritdoc IApplication
function validateOutput(bytes calldata output, OutputValidityProof calldata proof)
public
view
override
{
validateOutputHash(keccak256(output), proof);
}
/// @inheritdoc IApplication
function validateOutputHash(bytes32 outputHash, OutputValidityProof calldata proof)
public
view
override
{
if (!proof.isSiblingsArrayLengthValid()) {
revert InvalidOutputHashesSiblingsArrayLength();
}
bytes32 outputsMerkleRoot = proof.computeOutputsMerkleRoot(outputHash);
if (!_isOutputsMerkleRootValid(outputsMerkleRoot)) {
revert InvalidOutputsMerkleRoot(outputsMerkleRoot);
}
}
/// @inheritdoc IApplication
function getTemplateHash() external view override returns (bytes32) {
return _templateHash;
}
/// @inheritdoc IApplication
function getOutputsMerkleRootValidator()
external
view
override
returns (IOutputsMerkleRootValidator)
{
return _outputsMerkleRootValidator;
}
/// @inheritdoc IApplication
function getDataAvailability() external view override returns (bytes memory) {
return _dataAvailability;
}
/// @inheritdoc IApplication
function getDeploymentBlockNumber() external view override returns (uint256) {
return _deploymentBlockNumber;
}
/// @inheritdoc Ownable
function owner() public view override(IOwnable, Ownable) returns (address) {
return super.owner();
}
/// @inheritdoc Ownable
function renounceOwnership() public override(IOwnable, Ownable) {
super.renounceOwnership();
}
/// @inheritdoc Ownable
function transferOwnership(address newOwner) public override(IOwnable, Ownable) {
super.transferOwnership(newOwner);
}
/// @notice Check if an outputs Merkle root is valid,
/// according to the current outputs Merkle root validator.
/// @param outputsMerkleRoot The output Merkle root
function _isOutputsMerkleRootValid(bytes32 outputsMerkleRoot)
internal
view
returns (bool)
{
return _outputsMerkleRootValidator.isOutputsMerkleRootValid(
address(this), outputsMerkleRoot
);
}
/// @notice Executes a voucher
/// @param arguments ABI-encoded arguments
function _executeVoucher(bytes calldata arguments) internal {
address destination;
uint256 value;
bytes memory payload;
(destination, value, payload) = abi.decode(arguments, (address, uint256, bytes));
bool enoughFunds;
uint256 balance;
(enoughFunds, balance) = destination.safeCall(value, payload);
if (!enoughFunds) {
revert InsufficientFunds(value, balance);
}
}
/// @notice Executes a delegatecall voucher
/// @param arguments ABI-encoded arguments
function _executeDelegateCallVoucher(bytes calldata arguments) internal {
address destination;
bytes memory payload;
(destination, payload) = abi.decode(arguments, (address, bytes));
destination.safeDelegateCall(payload);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/BitMaps.sol)
pragma solidity ^0.8.20;
/**
* @dev Library for managing uint256 to bool mapping in a compact and efficient way, provided the keys are sequential.
* Largely inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor].
*
* BitMaps pack 256 booleans across each bit of a single 256-bit slot of `uint256` type.
* Hence booleans corresponding to 256 _sequential_ indices would only consume a single slot,
* unlike the regular `bool` which would consume an entire slot for a single value.
*
* This results in gas savings in two ways:
*
* - Setting a zero value to non-zero only once every 256 times
* - Accessing the same warm slot for every 256 _sequential_ indices
*/
library BitMaps {
struct BitMap {
mapping(uint256 bucket => uint256) _data;
}
/**
* @dev Returns whether the bit at `index` is set.
*/
function get(BitMap storage bitmap, uint256 index) internal view returns (bool) {
uint256 bucket = index >> 8;
uint256 mask = 1 << (index & 0xff);
return bitmap._data[bucket] & mask != 0;
}
/**
* @dev Sets the bit at `index` to the boolean `value`.
*/
function setTo(BitMap storage bitmap, uint256 index, bool value) internal {
if (value) {
set(bitmap, index);
} else {
unset(bitmap, index);
}
}
/**
* @dev Sets the bit at `index`.
*/
function set(BitMap storage bitmap, uint256 index) internal {
uint256 bucket = index >> 8;
uint256 mask = 1 << (index & 0xff);
bitmap._data[bucket] |= mask;
}
/**
* @dev Unsets the bit at `index`.
*/
function unset(BitMap storage bitmap, uint256 index) internal {
uint256 bucket = index >> 8;
uint256 mask = 1 << (index & 0xff);
bitmap._data[bucket] &= ~mask;
}
}
// (c) Cartesi and individual authors (see AUTHORS)
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)
pragma solidity ^0.8.8;
/// @title Canonical Machine Constants Library
///
/// @notice Defines several constants related to the reference implementation
/// of the RISC-V machine that runs Linux, also known as the "Cartesi Machine".
library CanonicalMachine {
/// @notice Maximum input size (64 kilobytes).
uint256 constant INPUT_MAX_SIZE = 1 << 16;
/// @notice Log2 of maximum number of outputs.
uint256 constant LOG2_MAX_OUTPUTS = 63;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC1155/utils/ERC1155Holder.sol)
pragma solidity ^0.8.20;
import {IERC165, ERC165} from "../../../utils/introspection/ERC165.sol";
import {IERC1155Receiver} from "../IERC1155Receiver.sol";
/**
* @dev Simple implementation of `IERC1155Receiver` that will allow a contract to hold ERC-1155 tokens.
*
* IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
* stuck.
*/
abstract contract ERC1155Holder is ERC165, IERC1155Receiver {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/utils/ERC721Holder.sol)
pragma solidity ^0.8.20;
import {IERC721Receiver} from "../IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or
* {IERC721-setApprovalForAll}.
*/
abstract contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
return this.onERC721Received.selector;
}
}
// (c) Cartesi and individual authors (see AUTHORS)
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)
pragma solidity ^0.8.8;
import {IOwnable} from "../access/IOwnable.sol";
import {IOutputsMerkleRootValidator} from "../consensus/IOutputsMerkleRootValidator.sol";
import {OutputValidityProof} from "../common/OutputValidityProof.sol";
/// @notice The base layer incarnation of an application running on the execution layer.
/// @notice The state of the application advances through inputs sent to an `IInputBox` contract.
/// @notice These inputs can be sent either directly, or indirectly through portals.
/// @notice Reader nodes can retrieve inputs sent to the `IInputBox` contract through events, and feed them into the machine.
/// @notice Validator nodes can also submit claims to the `IOutputsMerkleRootValidator` contract (see the `getOutputsMerkleRootValidator` function).
/// @notice Once accepted, claims can be used to validate outputs generated by the machine.
/// @notice Some outputs are executable, which means they can have on-chain side effects.
/// @notice Every application is subscribed to some outputs Merkle root validator, and may be governed by some owner.
/// The outputs Merkle root validator has the power to accept claims, which, in turn, are used to validate outputs.
/// Meanwhile, the owner can replace the outputs Merkle root validator at any time.
/// Therefore, the users of an application must trust both the outputs Merkle root validator and the application owner.
/// @notice There are several ownership models to choose from:
/// - no owner (address zero)
/// - individual signer (externally-owned account)
/// - multiple signers (multi-sig)
/// - DAO (decentralized autonomous organization)
/// - self-owned application (off-chain governance logic)
interface IApplication is IOwnable {
// Events
/// @notice MUST trigger when a new outputs Merkle root validator is chosen.
/// @param newOutputsMerkleRootValidator The new outputs Merkle root validator
event OutputsMerkleRootValidatorChanged(
IOutputsMerkleRootValidator newOutputsMerkleRootValidator
);
/// @notice MUST trigger when an output is executed.
/// @param outputIndex The index of the output
/// @param output The output
event OutputExecuted(uint64 outputIndex, bytes output);
// Errors
/// @notice Could not execute an output, because the application contract doesn't know how to.
/// @param output The output
error OutputNotExecutable(bytes output);
/// @notice Could not execute an output, because it was already executed.
/// @param output The output
error OutputNotReexecutable(bytes output);
/// @notice Could not execute an output, because the application contract doesn't have enough Ether.
/// @param value The amount of Wei necessary for the execution of the output
/// @param balance The current application contract balance
error InsufficientFunds(uint256 value, uint256 balance);
/// @notice Raised when the output hashes siblings array has an invalid size.
/// @dev Please consult `CanonicalMachine` for the maximum number of outputs.
error InvalidOutputHashesSiblingsArrayLength();
/// @notice Raised when the computed outputs Merkle root is invalid, according to the current outputs Merkle root validator.
error InvalidOutputsMerkleRoot(bytes32 outputsMerkleRoot);
// Permissioned functions
/// @notice Migrate the application to a new outputs Merkle root validator.
/// @param newOutputsMerkleRootValidator The new outputs Merkle root validator
/// @dev Can only be called by the application owner.
function migrateToOutputsMerkleRootValidator(
IOutputsMerkleRootValidator newOutputsMerkleRootValidator
) external;
// Permissionless functions
/// @notice Execute an output.
/// @param output The output
/// @param proof The proof used to validate the output against
/// a claim accepted to the current outputs Merkle root validator contract
/// @dev On a successful execution, emits a `OutputExecuted` event.
/// @dev May raise any of the errors raised by `validateOutput`,
/// as well as `OutputNotExecutable` and `OutputNotReexecutable`.
function executeOutput(bytes calldata output, OutputValidityProof calldata proof)
external;
/// @notice Check whether an output has been executed.
/// @param outputIndex The index of output
/// @return Whether the output has been executed before
function wasOutputExecuted(uint256 outputIndex) external view returns (bool);
/// @notice Validate an output.
/// @param output The output
/// @param proof The proof used to validate the output against
/// a claim accepted to the current outputs Merkle root validator contract
/// @dev May raise any of the errors raised by `validateOutputHash`.
function validateOutput(bytes calldata output, OutputValidityProof calldata proof)
external
view;
/// @notice Validate an output hash.
/// @param outputHash The output hash
/// @param proof The proof used to validate the output against
/// a claim accepted to the current outputs Merkle root validator contract
/// @dev May raise `InvalidOutputHashesSiblingsArrayLength`
/// or `InvalidOutputsMerkleRoot`.
function validateOutputHash(bytes32 outputHash, OutputValidityProof calldata proof)
external
view;
/// @notice Get the application's template hash.
/// @return The application's template hash
function getTemplateHash() external view returns (bytes32);
/// @notice Get the current outputs Merkle root validator.
/// @return The current outputs Merkle root validator
function getOutputsMerkleRootValidator()
external
view
returns (IOutputsMerkleRootValidator);
/// @notice Get the data availability solution used by application.
/// @return Solidity ABI-encoded function call that describes
/// the source of inputs that should be fed to the application.
function getDataAvailability() external view returns (bytes memory);
/// @notice Get number of block in which contract was deployed
function getDeploymentBlockNumber() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Interface that must be implemented by smart contracts in order to receive
* ERC-1155 token transfers.
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC-1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC-1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.20;
/**
* @title ERC-721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC-721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be
* reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// (c) Cartesi and individual authors (see AUTHORS)
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)
pragma solidity ^0.8.8;
import {IERC165} from "@openzeppelin-contracts-5.2.0/utils/introspection/IERC165.sol";
/// @notice Provides valid outputs Merkle roots for validation.
/// @dev ERC-165 can be used to determine whether this contract also
/// supports any other interface (e.g. for submitting claims).
interface IOutputsMerkleRootValidator is IERC165 {
/// @notice Check whether an outputs Merkle root is valid.
/// @param appContract The application contract address
/// @param outputsMerkleRoot The outputs Merkle root
function isOutputsMerkleRootValid(address appContract, bytes32 outputsMerkleRoot)
external
view
returns (bool);
}
// (c) Cartesi and individual authors (see AUTHORS)
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)
pragma solidity ^0.8.8;
/// @notice The interface of OpenZeppelin's `Ownable` contract.
interface IOwnable {
function owner() external view returns (address);
function renounceOwnership() external;
function transferOwnership(address newOwner) external;
}
// (c) Cartesi and individual authors (see AUTHORS)
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)
pragma solidity ^0.8.8;
import {LibError} from "../library/LibError.sol";
library LibAddress {
using LibError for bytes;
/// @notice Perform a low level call and raise error if failed
/// @param destination The address that will be called
/// @param value The amount of Wei to be transferred through the call
/// @param payload The payload, which—in the case of Solidity
/// contracts—encodes a function call
/// @return Whether the caller had enough Ether to make the call,
/// and the balance before the call
function safeCall(address destination, uint256 value, bytes memory payload)
internal
returns (bool, uint256)
{
address caller = address(this);
uint256 balance = caller.balance;
if (value > balance) {
return (false, balance);
}
bool success;
bytes memory returndata;
(success, returndata) = destination.call{value: value}(payload);
if (!success) {
returndata.raise();
}
return (true, balance);
}
/// @notice Perform a delegate call and raise error if failed
/// @param destination The address that will be called
/// @param payload The payload, which—in the case of Solidity
/// libraries—encodes a function call
function safeDelegateCall(address destination, bytes memory payload) internal {
bool success;
bytes memory returndata;
(success, returndata) = destination.delegatecall(payload);
if (!success) {
returndata.raise();
}
}
}
// (c) Cartesi and individual authors (see AUTHORS)
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)
pragma solidity ^0.8.8;
library LibError {
/// @notice Raise error data
/// @param errordata Data returned by failed low-level call
function raise(bytes memory errordata) internal pure {
if (errordata.length == 0) {
revert();
} else {
assembly {
revert(add(32, errordata), mload(errordata))
}
}
}
}
// (c) Cartesi and individual authors (see AUTHORS)
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)
pragma solidity ^0.8.22;
/// @title Merkle library for trees of 32-byte leaves
/// @notice This library is meant for creating and verifying Merkle proofs.
/// @notice Each Merkle tree is assumed to have `2^height` leaves.
/// @notice Nodes are concatenated pairwise and hashed with `keccak256`.
/// @notice Siblings are in bottom-up order, from leaf to root.
library LibMerkle32 {
using LibMerkle32 for bytes32[];
/// @notice Compute the root of a Merkle tree from its leaves.
/// @param leaves The left-most leaves of the Merkle tree
/// @param height The height of the Merkle tree
/// @return The root hash of the Merkle tree
/// @dev Raises an error if more than `2^height` leaves are provided.
function merkleRoot(bytes32[] memory leaves, uint256 height)
internal
pure
returns (bytes32)
{
bytes32 defaultNode;
for (uint256 i; i < height; ++i) {
leaves = leaves.parentLevel(defaultNode);
defaultNode = parent(defaultNode, defaultNode);
}
require(leaves.length <= 1, "LibMerkle32: too many leaves");
return leaves.at(0, defaultNode);
}
/// @notice Compute the siblings of the ancestors of a leaf in a Merkle tree.
/// @param leaves The left-most leaves of the Merkle tree
/// @param index The index of the leaf
/// @param height The height of the Merkle tree
/// @return The siblings of the ancestors of the leaf in bottom-up order
/// @dev Raises an error if the provided index is out of bounds.
/// @dev Raises an error if more than `2^height` leaves are provided.
function siblings(bytes32[] memory leaves, uint256 index, uint256 height)
internal
pure
returns (bytes32[] memory)
{
bytes32[] memory sibs = new bytes32[](height);
bytes32 defaultNode;
for (uint256 i; i < height; ++i) {
sibs[i] = leaves.at(index ^ 1, defaultNode);
leaves = leaves.parentLevel(defaultNode);
defaultNode = parent(defaultNode, defaultNode);
index >>= 1;
}
require(index == 0, "LibMerkle32: index out of bounds");
require(leaves.length <= 1, "LibMerkle32: too many leaves");
return sibs;
}
/// @notice Compute the root of a Merkle tree after replacing one of its leaves.
/// @param sibs The siblings of the ancestors of the leaf in bottom-up order
/// @param index The index of the leaf
/// @param leaf The new leaf
/// @return The root hash of the new Merkle tree
/// @dev Raises an error if the provided index is out of bounds.
function merkleRootAfterReplacement(
bytes32[] calldata sibs,
uint256 index,
bytes32 leaf
) internal pure returns (bytes32) {
uint256 height = sibs.length;
for (uint256 i; i < height; ++i) {
bytes32 sibling = sibs[i];
if (index & 1 == 0) {
leaf = parent(leaf, sibling);
} else {
leaf = parent(sibling, leaf);
}
index >>= 1;
}
require(index == 0, "LibMerkle32: index out of bounds");
return leaf;
}
/// @notice Compute the parent of two nodes.
/// @param leftNode The left node
/// @param rightNode The right node
/// @return parentNode The parent node
/// @dev Uses assembly for extra performance
function parent(bytes32 leftNode, bytes32 rightNode)
internal
pure
returns (bytes32 parentNode)
{
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, leftNode)
mstore(0x20, rightNode)
parentNode := keccak256(0x00, 0x40)
}
}
/// @notice Compute the parent level of an array of nodes.
/// @param nodes The array of left-most nodes
/// @param defaultNode The default node after the array
/// @return The left-most nodes of the parent level
/// @dev The default node of a parent level is
/// the parent node of two default nodes.
function parentLevel(bytes32[] memory nodes, bytes32 defaultNode)
internal
pure
returns (bytes32[] memory)
{
uint256 n = (nodes.length + 1) / 2; // ceil(#nodes / 2)
bytes32[] memory level = new bytes32[](n);
for (uint256 i; i < n; ++i) {
bytes32 leftLeaf = nodes[2 * i];
bytes32 rightLeaf = nodes.at(2 * i + 1, defaultNode);
level[i] = parent(leftLeaf, rightLeaf);
}
return level;
}
/// @notice Get the node at some index
/// @param nodes The array of left-most nodes
/// @param index The index of the node
/// @param defaultNode The default node after the array
function at(bytes32[] memory nodes, uint256 index, bytes32 defaultNode)
internal
pure
returns (bytes32)
{
if (index < nodes.length) {
return nodes[index];
} else {
return defaultNode;
}
}
}
// (c) Cartesi and individual authors (see AUTHORS)
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)
pragma solidity ^0.8.8;
import {CanonicalMachine} from "../common/CanonicalMachine.sol";
import {OutputValidityProof} from "../common/OutputValidityProof.sol";
import {LibMerkle32} from "./LibMerkle32.sol";
library LibOutputValidityProof {
using LibMerkle32 for bytes32[];
function isSiblingsArrayLengthValid(OutputValidityProof calldata v)
internal
pure
returns (bool)
{
return v.outputHashesSiblings.length == CanonicalMachine.LOG2_MAX_OUTPUTS;
}
function computeOutputsMerkleRoot(OutputValidityProof calldata v, bytes32 outputHash)
internal
pure
returns (bytes32)
{
return
v.outputHashesSiblings.merkleRootAfterReplacement(v.outputIndex, outputHash);
}
}
// (c) Cartesi and individual authors (see AUTHORS)
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)
pragma solidity ^0.8.8;
/// @notice Proof of inclusion of an output in the output Merkle tree.
/// @param outputIndex Index of output in the Merkle tree
/// @param outputHashesSiblings Siblings of the output in the Merkle tree
/// @dev From the index and siblings, one can calculate the root of the Merkle tree.
/// @dev The siblings array should have size equal to the log2 of the maximum number of outputs.
/// @dev See the `CanonicalMachine` library for constants.
struct OutputValidityProof {
uint64 outputIndex;
bytes32[] outputHashesSiblings;
}
// (c) Cartesi and individual authors (see AUTHORS)
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)
pragma solidity ^0.8.8;
/// @title Outputs
/// @notice Defines the signatures of outputs that can be generated by the
/// off-chain machine and verified by the on-chain contracts.
interface Outputs {
/// @notice A piece of verifiable information.
/// @param payload An arbitrary payload.
function Notice(bytes calldata payload) external;
/// @notice A single-use permission to execute a specific message call
/// from the context of the application contract.
/// @param destination The address that will be called
/// @param value The amount of Wei to be transferred through the call
/// @param payload The payload, which—in the case of Solidity
/// contracts—encodes a function call
function Voucher(address destination, uint256 value, bytes calldata payload)
external;
/// @notice A single-use permission to execute a specific delegate call
/// from the context of the application contract.
/// @param destination The address that will be called
/// @param payload The payload, which—in the case of Solidity
/// libraries—encodes a function call
function DelegateCallVoucher(address destination, bytes calldata payload) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
{
"compilationTarget": {
"src/dapp/Application.sol": "Application"
},
"evmVersion": "cancun",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": [
":@openzeppelin-contracts-5.2.0/=dependencies/@openzeppelin-contracts-5.2.0/",
":forge-std-1.9.6/=dependencies/forge-std-1.9.6/"
],
"viaIR": true
}
[{"inputs":[{"internalType":"contract IOutputsMerkleRootValidator","name":"outputsMerkleRootValidator","type":"address"},{"internalType":"address","name":"initialOwner","type":"address"},{"internalType":"bytes32","name":"templateHash","type":"bytes32"},{"internalType":"bytes","name":"dataAvailability","type":"bytes"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"balance","type":"uint256"}],"name":"InsufficientFunds","type":"error"},{"inputs":[],"name":"InvalidOutputHashesSiblingsArrayLength","type":"error"},{"inputs":[{"internalType":"bytes32","name":"outputsMerkleRoot","type":"bytes32"}],"name":"InvalidOutputsMerkleRoot","type":"error"},{"inputs":[{"internalType":"bytes","name":"output","type":"bytes"}],"name":"OutputNotExecutable","type":"error"},{"inputs":[{"internalType":"bytes","name":"output","type":"bytes"}],"name":"OutputNotReexecutable","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"outputIndex","type":"uint64"},{"indexed":false,"internalType":"bytes","name":"output","type":"bytes"}],"name":"OutputExecuted","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract IOutputsMerkleRootValidator","name":"newOutputsMerkleRootValidator","type":"address"}],"name":"OutputsMerkleRootValidatorChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"inputs":[{"internalType":"bytes","name":"output","type":"bytes"},{"components":[{"internalType":"uint64","name":"outputIndex","type":"uint64"},{"internalType":"bytes32[]","name":"outputHashesSiblings","type":"bytes32[]"}],"internalType":"struct OutputValidityProof","name":"proof","type":"tuple"}],"name":"executeOutput","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getDataAvailability","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getDeploymentBlockNumber","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getOutputsMerkleRootValidator","outputs":[{"internalType":"contract IOutputsMerkleRootValidator","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTemplateHash","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IOutputsMerkleRootValidator","name":"newOutputsMerkleRootValidator","type":"address"}],"name":"migrateToOutputsMerkleRootValidator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC1155BatchReceived","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC1155Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"output","type":"bytes"},{"components":[{"internalType":"uint64","name":"outputIndex","type":"uint64"},{"internalType":"bytes32[]","name":"outputHashesSiblings","type":"bytes32[]"}],"internalType":"struct OutputValidityProof","name":"proof","type":"tuple"}],"name":"validateOutput","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"outputHash","type":"bytes32"},{"components":[{"internalType":"uint64","name":"outputIndex","type":"uint64"},{"internalType":"bytes32[]","name":"outputHashesSiblings","type":"bytes32[]"}],"internalType":"struct OutputValidityProof","name":"proof","type":"tuple"}],"name":"validateOutputHash","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"outputIndex","type":"uint256"}],"name":"wasOutputExecuted","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]