> For the complete documentation index, see [llms.txt](https://docs.cartesi.io/llms.txt)

---
title: Command-line interface
---

In the simplest usage scenario, the `cartesi-machine` command-line utility can be used to define a Cartesi Machine and run it until it halts.
The command-line utility, however, is very versatile.
It was designed to simplify the most common prototyping tasks.

## Initialization

The following command instructs `cartesi-machine` to build a Cartesi Machine.
The machine uses `rom.bin` as the ROM image, has 64MiB of RAM, uses `linux.bin` as the RAM image, and uses `rootfs.ext2` as the root file-system.
(The `rom.bin`, `linux.bin`, and `rootfs.ext2` files are generated by the [Emulator SDK](https://github.com/cartesi/machine-emulator-sdk), and sample files are available in the playground.)
Once initialization is complete, the machine executes the command `ls /bin` and exits.

```bash
cartesi-machine \
    --rom-image="/opt/cartesi/share/images/rom.bin" \
    --ram-length=64Mi \
    --ram-image="/opt/cartesi/share/images/linux.bin" \
    --flash-drive="label:root,filename:/opt/cartesi/share/images/rootfs.ext2" \
    -- "ls /bin"
```
The `--rom-image`, `--ram-image`, `--ram-length`, and `--flash-drive` command-line options have the values in the example as default, so these options can be omitted.
To remove these default settings, use the command-line options `--no-ram-image` and `--no-root-flash-drive`, respectively.
(The machine needs a ROM image, and, if needed, you can simply specify a different one.)

The simplified command-line is
```bash
cartesi-machine -- "ls /bin"
```
The output is
```
%machine.host.cmdline.ls
```

It shows the Cartesi Machine splash screen, followed by the listing of directory `/bin/`.
The listing was produced by the command that follows the `--` separator in the command line.
The Linux kernel passes this unmodified to `/sbin/init`, and the Cartesi-provided `/sbin/init` script executes the command before gracefully halting the machine.

:::note
In many of the documentation examples, the utilities invoked from the command-line executed by a Cartesi Machine are in the default search path for executables. (This is setup by the Cartesi-provided `/sbin/init` script itself.)
When in doubt, or when using your own executables installed in custom locations, make sure to invoke them by using their full paths (e.g., `/bin/ls` or `/bin/sh` instead of simply `ls` and `sh`.)
:::

## Interactive sessions

By default, the `cartesi-machine` utility executes the Cartesi Machine in non-interactive mode.
Verifiable computations must always be run in non-interactive sessions.
User interaction with a Cartesi Machine via the console is, after all, not reproducible.
Nevertheless, during development, it is often convenient to directly interact with the emulator, as if using a computer console.

The command-line option `-i` (short for `--htif-console-getchar`) instructs the emulator to monitor the console for input, and to make this input available to the Linux kernel.
Typically, this option will be used in conjunction with the `--` separator and the command `sh`, causing the Cartesi-provided `/sbin/init` script to drop into an interactive shell.
Interaction with the shell enables the exploration of the embedded Linux distribution from the inside.
Exiting the shell returns control back to `/sbin/init`, which then gracefully halts the machine.

For example, if an interactive session is started with the following command
```bash
cartesi-machine -i -- sh
```
it drops into the shell.
Running the command `ls /bin` causes the listing of directory `/bin` to appear.
The command `exit` causes the shell to exit.
The output is
```
%machine.host.cmdline.interactive-ls
```
:::note
When running in interactive mode, not even the final cycle count is reproducible.
To avoid busy wait for new interactive input, the emulator sleeps from one Cartesi Machine timer interrupt to the next, skipping Cartesi Machine cycles forward so programs running inside to stay _roughly_ in sync with wall-clock time outside.
This dynamic balancing act is sure to vary between executions and across different computers.
:::

## Flash drives

The command-line option `--flash-drive=label:<label>,filename:<filename>` can be used to add between 1 and 8 flash drives to the Cartesi Machine.
Here, the string `<label>` is the *label* for the flash drive, and `<filename>` points to an *image file* with the initial contents of the flash drive.
When the image file contains a valid file-system, the Cartesi-provided `/sbin/init` script will automatically mount this file-system at `/mnt/<label>`.

To enable transparency, Cartesi Machine flash drives are mapped into the machine's 64-bit address space.
The start and length are set, respectively, by the `start:<number>` and `length:<number>` parameters to `--flash-drive`.

By default, the start of the first flash drive (which typically holds the root file-system) is set to the beginning of the second half of the address space (i.e., at offset 2<sup>63</sup>).
Additional flash drives are automatically spaced uniformly within that second half of the address space.
They are therefore separated by 2<sup>60</sup> bytes, which &ldquo;should be enough separation for everyone&rdquo;.
(The machine will fail to instantiate if there is any overlap between the ranges occupied by multiple drives.)
If the `start` of *any* drive is specified, then the starts for *all* drives must be specified.

When the `length` parameter is omitted, the `cartesi-machine` utility automatically sets the size of a flash drive to match the size of its image file.
Because RISC-V uses 4KiB pages, image files must have a size multiple of 4KiB.
(The `truncate` utility can be used to pad a file with zeros so its size is a multiple of 4KiB.)

For convenience, numbers can be specified in decimal or hexadecimal (e.g., `4096` or `0x1000`) and may include a suffix multiplier (i.e., `Ki` to multiply by 2<sup>10</sup>, `Mi` to multiply by 2<sup>20</sup>, and `Gi` to multiply by 2<sup>30</sup>).
They can also use the C programming language *shift left* notation to multiply by arbitrary powers of 2 (e.g. `1 << 24` meaning 2<sup>24</sup>).

When the `length` of a drive is specified, the `filename` parameter can be omitted.
In that case, the drive starts in a *pristine* state: i.e., filled with zeros.
If, however, both `length` and `filename` are specified, then the `length` must exactly match the size of image file referred to by the `filename` parameter.

The positioning of flash drives in the machine's address space has implications on certain operations, discussed in detail under [the blockchain perspective](../blockchain/hash.md), that involve the manipulation of hashes of the Cartesi Machine state.

The preferred file-system type is `ext2`.
This is because `ext2` image files can be easily created with the `genext2fs` command-line utility (available in Ubuntu as its own package), and manipulated with `e2ls`, `e2cp`, `e2rm`, etc (command-line utilities available in Ubuntu from the `e2tools` package).
These utilities come pre-installed in the playground image.
Support for `ext4` is also enabled by default in the kernel.
(Support for additional file-systems can be enabled by modifying the configuration the [Emulator SDK](https://github.com/cartesi/machine-emulator-sdk) uses to produce `linux.bin` in the `kernel/` subdirectory.)

For example,
```bash
mkdir foo
echo "Hello world!" > foo/bar.txt
tar \
    --sort=name \
    --mtime="2022-01-01" \
    --owner=1000 \
    --group=1000 \
    --numeric-owner \
    -cf foo.tar \
    --directory=foo .
genext2fs \
    -f \
    -b 1024 \
    -a foo.tar \
    foo.ext2
cartesi-machine \
    --flash-drive="label:foo,filename:foo.ext2" \
    -- "cat /mnt/foo/bar.txt"
```
Here, a flash drive with label `foo` is initialized with the contents of an `ext2` file-system in the image file `foo.ext2`.

:::note
The `genext2fs` command on its own would would produce a file-system that is *not* reproducible, in the sense that running it in different systems, or even running it twice in the same system may produce a different `./foo.ext2` file.
This is because the utility records modification times, user and group IDs, etc.
Worse still, it would traverse the files in the `foo/` directory in an unspecified order, progressively adding them to the `foo.ext2` file-system.
Using the `-f` (faketime) option eliminates the modification times problem, but does nothing to fix the remaining issues.
Enter the `tar` command.
It sorts all files before adding them to the archive.
It also allows us to specify the modification time, user and group IDS, etc.
The `genext2fs` then takes the reproducible `tar` file and creates a reproducible `ext2` file-system from it.
:::

The Cartesi-provided `/sbin/init` mounts this as `/mnt/foo`.
The command executed in the machine simply copies the contents of `/mnt/foo/bar` to the terminal.
The output is
```
%machine.host.cmdline.flash
```

## Persistent flash drives

The emulator never modifies the ROM and RAM image files.
They are simply loaded into host memory and only this copy is exposed to changes caused by code executing in the target.
(The `--dump-pmas` command-line option can be used to inspect the modified copies for debugging purposes. See below.)

By default, the emulator does *not* modify the image files for any of the flash drives either.
However, since these image files can be very large, the emulator does not pre-allocate any host memory for flash drives.
Instead, it uses the operating system's memory mapping capabilities.
The operating system reads to host memory only those pages from the image file that are actually read by code executing in the target.
(Naturally, when a state hash is requested, all image files are read from disk in their entirety and processed. See below.)
These image files are mapped to host memory in a *copy-on-write* fashion.
When code running in the target causes the emulator to write to a mapped image file, the operating system makes a copy of the page before modification and replaces the mapping to point to the fresh copy.
The image files are never written to.
For example, running the machine
```bash
cartesi-machine \
    --flash-drive="label:foo,filename:foo.ext2" \
    -- "ls /mnt/foo/*.txt && cp /mnt/foo/bar.txt /mnt/foo/baz.txt && ls /mnt/foo/*.txt"
```
produces the output
```
%machine.host.cmdline.persistent-flash
```
indicating that the file-system was modified, at least from the perspective of the target.
However, inspecting the `foo.ext2` image file from outside the emulator shows it is unchanged.
```
e2ls -al foo.ext2:*.txt
     12  100644   501    20       13 30-Jun-2020 19:40 bar.txt

```

This behavior is appropriate when the flash drives will only be used as inputs.
For output flash drives, target changes to the drives must reflect on the associated image files.
For that purpose, the parameter `shared` can be passed to command-line option `--flash-drive`, causing the imaged files to be mapped to host memory in a *shared* fashion.
For example,
```bash
cartesi-machine \
    --flash-drive="label:foo,filename:foo.ext2,shared" \
    -- "ls /mnt/foo/*.txt && cp /mnt/foo/bar.txt /mnt/foo/baz.txt && ls /mnt/foo/*.txt"
```
produces exactly the same output as before.
However, the image file `foo.ext2` has now indeed been modified.
```
e2ls -al foo.ext2:*.txt
     12  100644   501    20       13 30-Jun-2020 19:40 bar.txt
     13  100644     0     0       13  1-Jan-1970 00:00 baz.txt

```

## Limiting execution

Typically, the `cartesi-machine` utility only returns when the Cartesi Machine halts.  For example, running
```bash
cartesi-machine
```
produces the output
```
%machine.host.cmdline.nothing
```
Here, the Cartesi-provided `/sbin/init` simply reports there is nothing to do before halting gracefully.
This takes many millions of cycles to complete: time mostly spent initializing the Linux kernel.

The machine's processor includes a control and status register (CSR), named `mcycle`, that starts at 0 and is incremented after every instruction cycle.
The maximum cycle can be specified with the command-line option `--max-mcycle=<number>`.
For example, adding the `--max-mcycle=%machine.host.cmdline.cycles-limit-exec` command-line option
```bash
cartesi-machine --max-mcycle=%machine.host.cmdline.cycles-limit-exec
```
produces the output
```
%machine.host.cmdline.limit-exec
```
Note the execution was interrupted before the splash screen was even completed.

The ability to limit computation to an arbitrary number of cycles is fundamental to the verifiability of Cartesi Machines, as is explained in detail under the [blockchain perspective](../blockchain/vg.md).

## Progress feedback

A target application can inform the host of its progress by using a Cartesi-specific `/dev/yield` Linux device.
Within the target, the Linux device can be controlled in the command-line with the utility `/opt/cartesi/bin/yield`, pre-installed in the root file-system `rootfs.ext2`.
The progress feedback is accessed via the `automatic progress <permil>` command-line option.

For example, during the execution of the loop,
```bash
cartesi-machine \
    --htif-yield-automatic \
    -- $'for i in $(seq 0 5 1000); do yield automatic progress $i; done'
```
the `cartesi-machine` utility receives control back from the emulator at every iteration, when the target executes the `yield` utility.
(The directory `/opt/cartesi/bin/` is in the default search path for executable setup by `/sbin/init`.)
If the `--htif-yield-automatic` command-line option to `cartesi-machine` is omitted, the emulator essentially ignores such yield requests from the target.
Each time `cartesi-machine` receives control due to a yield, it prints a progress message (shown at 44% below) and resumes the emulator so it can continue working.
```

         .
        / \
      /    \
\---/---\  /----\
 \       X       \
  \----/  \---/---\
       \    / CARTESI
        \ /   MACHINE
         '

Progress:  44.00
```
This feature is most useful when the emulator is controlled programmatically, via its Lua, C++, or gRPC interfaces, where Cartesi Machines typically run disconnected from the console.
In these situations, the progress device can be used to drive a dynamic user interface element that reassures users progress is being made during long, silent computations.
Its handling by `cartesi-machine`, which does have access to the console, is simply to help with prototyping and debugging.

The protocols followed by the `yield` utility to interact with the `/dev/yield` driver and by the driver itself to communicate with the HTIF device are explained in detail under the [target perspective](../target/architecture.md).
In particular, the section explains the _manual_ yield commands (enabled by the `--htif-yield-manual` command-line option) needed for proper operation of Cartesi Rollups.

## State hashes

The `cartesi-machine` utility can also be used to print Cartesi Machine state hashes.
State hashes are Merkle tree root hashes of the entire 64-bit address space of the Cartesi Machine, where the leaves are aligned 64-bit words.
(See the [Hash view of states](../blockchain/hash.md) for an explanation of Merkle trees.)
Since Cartesi Machines are transparent, the contents of this address space encompass the entire machine state, including all processor CSRs and general-purpose registers, the contents of RAM and ROM, of all flash drives, and of all other devices connected to the board.
State hashes therefore work as cryptographic signatures of the machine, and implicitly of the computation they are about to execute.

To obtain the state hash right before execution starts, use the command-line option `--initial-hash`.
Conversely, to obtain the state hash right after execution is done, use the option `--final-hash`.
For example,
```bash
cartesi-machine \
    --max-mcycle=%machine.host.cmdline.cycles-limit-exec \
    --initial-hash \
    --final-hash
```
produces the output
```
%machine.host.cmdline.state-hashes-limit-exec
```
The initial state hash `%machine.host.cmdline.state-hashes-initial...` is the Merkle tree root hash for the initial Cartesi Machine state.
Since Cartesi Machines are reproducible, the initial state hash also works as a *promise* on the result of the entire computation.
In other words, the &ldquo;final state hash&rdquo; `%machine.host.cmdline.state-hashes-final-limit-exec...` is the &ldquo;only&rdquo; possible outcome for the `--final-hash` at cycle %machine.host.cmdline.cycles-limit-exec, given the result of the `--initial-hash` operation was `%machine.host.cmdline.state-hashes-initial...`.

:::info
The scare quotes around &ldquo;only&rdquo; are pedantic.
It is true that there are a multitude of machine states that produce the same state hash.
After all, the Keccak-256 state hashes fit in 256-bits, whereas machine states can take gigabytes.
There are therefore many more possible machine states than possible state hashes.
By the pigeonhole principle, there must be multiple machines with the same hash (i.e., hash collisions).
However, given only the state hash, finding a Cartesi Machine with that state hash should be virtually impossible.
Given a Cartesi Machine and its state hash, finding a *second* (distinct) Cartesi Machine with the same state hash should also be virtually impossible.
Even finding two different Cartesi Machines that have the same state hash (any hash) should be virtually impossible.
Cryptographic hash functions, such as Keccak-256, were designed *specifically* to have these properties.
:::

Allowing the machine to run until it halts
```bash
cartesi-machine \
    --initial-hash \
    --final-hash
```
produces instead the output
```
%machine.host.cmdline.state-hashes-no-limit
```
Naturally, the initial state hash is the same as before.
However, the final state hash `%machine.host.cmdline.state-hashes-final-no-limit...` now pertains to cycle %machine.host.cmdline.state-hashes-cycles-no-limit, where the machine is halted.
This is the &ldquo;only&rdquo; possible state hash for a *halted* machine that started from state hash `%machine.host.cmdline.state-hashes-initial...`.

## Persistent Cartesi Machines

At any point in their execution, Cartesi Machines can be stored to disk.
A stored machine can later be loaded to continue its execution from where it left off.
To store a machine to a given `<directory>`, use the command-line option `--store=<directory>`.
(In `<directory>`, the `%h` escape will be replaced by the state hash in hex.)
The machine is stored as it was right before `cartesi-machine` returns to the command line.
For example, to store the machine corresponding to state hash `%machine.host.cmdline.state-hashes-final-limit-exec...`
```bash
cartesi-machine \
    --max-mcycle=%machine.host.cmdline.cycles-limit-exec \
    --store="machine-%machine.host.cmdline.state-hashes-final-limit-exec"
```
This command creates a directory `machine-%machine.host.cmdline.state-hashes-final-limit-exec/`, containing a variety of files that allow the Cartesi Machine emulator to recreate a machine state.
Every image file is copied into the directory, so no external dependencies remain.

:::note
If the machine initialization involved large image files or a considerable amount of RAM, this operation may consume significant disk space.
It will also take the time required by the copying of image files into the directory, and by the computation of the state hash.
:::

If the directory already exists, the operation will fail.
(This prevents the overwriting of a Cartesi Machine by mistake.)
Once created, the directory can be compressed and transferred to other hosts.
To restore the corresponding Cartesi Machine, use the command-line option `--load=<directory>`.
For example,
```bash
cartesi-machine \
    --load="machine-%machine.host.cmdline.state-hashes-final-limit-exec" \
    --initial-hash \
    --final-hash
```
produces the output
```
%machine.host.cmdline.persistent-machine
```
Note that, other than `--load`, no initialization command-line options were used.
These initializations were used to define the machine before it was stored: their values are implicitly encoded in the stored state.
The machine continues from where it left off, and reaches the same final state hash `%machine.host.cmdline.state-hashes-final-no-limit...`, as if it had never been interrupted.

Note also that the initial state hash `%machine.host.cmdline.state-hashes-final-limit-exec...` after `--load` matches the final state hash before `--store`.
After all, they are state hashes concerning the state of the same machine at the same cycle.
In fact, `--store` writes this state hash inside the directory, and `--load` verifies that the state hash of the restored machine matches what it found in the directory.

The `cartesi-machine-stored-hash` command-line utility can be used to extract the state hash from a stored Cartesi Machine.
The command
```bash
cartesi-machine-stored-hash machine-%machine.host.cmdline.state-hashes-final-limit-exec
```
produces the output
```
%machine.host.cmdline.persistent-stored-hash
```

## Running as root

Starting at version 4.0 of `rootfs.ext2`, the Cartesi-provided `/sbin/init` script runs the target application (or any initial command) as user `uid=1000(dapp)` group `gid=1000(dapp)`.
This can be seen by running the command:
```bash
cartesi-machine \
    -- id
```
It shows the user and group are indeed `dapp`.
```
%machine.host.cmdline.rarely-id
```
To instead run your target application as `uid=0(root) gid=0(root)`, pass the parameter `single=yes`:
```bash
cartesi-machine \
    --append-rom-bootargs="single=yes" \
    -- id
```
This produces the output:
```
%machine.host.cmdline.rarely-append-bootargs-single-id
```
It shows the user and group are now `root`.

Although running as root is not recommended, the feature can be used to perform setup tasks that require
elevated permissions.

## Cartesi Machine templates

*Templates* are one of the key uses for Cartesi Machines stored to disk.
Cartesi Machine templates are machines in which the contents of one or more flash drives are still unknown.
To put it another way, Cartesi Machine templates behave like functions whose parameters are the yet-to-be-defined contents of one or more flash drives.

As discussed in detail under [the blockchain perspective](../blockchain/hash.md), starting from template hashes, the hashes of the flash drives, and a small amount of [additional information](#sibling-hashes), it is possible to obtain the state hash of the *instantiated template*&mdash;the state hash for a Cartesi Machine with drives replaced by their actual contents.
This is how a smart contract can specify a computation to be performed off-chain over arbitrary input.
Starting from the template hash, and in possession of the flash drive hashes, it instantiates the template, generating the initial state hash for the corresponding Cartesi Machine.

As an example, consider a Cartesi Machine that operates as an arbitrary-precision arithmetic expression evaluator.
The machine will take the expression in text format, inside a raw input flash drive labelled `input`, and will copy the output in text format into a raw output flash drive, labelled `output` (`shared`, of course, so the output persists after the emulator is done).

Raw flash drives are flash drives that do not contain file-systems.
Instead, they contain data in any application-specific format.
Inside the Cartesi Machine, the `dd` or `devio` command-line utilities can be used to read data from or write data to
raw flash drives, assuming they have permission to access the underlying block device.
To simplify the examples in the documentation, we will simply run them as `root`.
(Note that this is not recommended in deployed applications.)

The `bc` command-line utility is the perfect tool to evaluate the arithmetic expressions.
The command passed to `cartesi-machine` below reads the contents of the raw input flash drive using the `dd` command-line utility, extracts a zero-terminated string from it using a tiny Lua script run by the `lua` interpreter, pipes the result to `bc`, and finally uses `dd` again to write its results to the raw output flash drive.
Here is the sample playground session
```bash
rm -f output.raw
truncate -s 4K output.raw
echo "6*2^1024 + 3*2^512" > input.raw
truncate -s 4K input.raw
cartesi-machine \
    --append-rom-bootargs="single=yes" \
    --flash-drive="label:input,length:1<<12,filename:input.raw" \
    --flash-drive="label:output,length:1<<12,filename:output.raw,shared" \
    -- $'dd status=none if=$(flashdrive input) | lua -e \'print((string.unpack("z",  io.read("a"))))\' | bc | dd status=none of=$(flashdrive output)'
lua5.3 -e 'print((string.unpack("z", io.read("a"))))' < output.raw
```

Using the `truncate` command-line utility, the session creates a 4KiB file `output.raw` containing only zeros to serve as the output drive image.
Then, it creates the `input.raw` file for use as the input drive image containing the expression `6*2^1024 + 3*2^512\n` to be evaluated.
This file is then padded with zeros to 4KiB in size by the `truncate` utility.
The session then invokes the `cartesi-machine` command-line utility to evaluate the expression.
The output of the `cartesi-machine` command is
```
%machine.host.cmdline.templates-run
```
Once the emulator returns, the session uses a tiny Lua script, run by the playground's `lua5.3` Lua interpreter, to print the contents of the output drive, which reads
```
10786158809173895446375831144734148401707861873653839436405804869463\
96054833005778796250863934445216126720683279228360145952738612886499\
73495708458383684478649003115037698421037988831222501494715481595948\
96901677837132352593468675094844090688678579236903861342030923488978\
36036892526733668721977278692363075584
```
This is indeed the result of 6&times;2<sup>1024</sup>+3&times;2<sup>512</sup>.

To create the template, simply omit the input and output image filenames.
This will cause the Cartesi Machine to assume both drives are filled with zeros.
Then, limit the computation with `--max-mcycle=0`, to prevent the Cartesi Machine from running.
Finally, use the `--store="calculator-template"` command-line option to store the Cartesi Machine template.
The `--final-hash` command-line option prints the resulting template hash.
```
cartesi-machine \
    --append-rom-bootargs="single=yes" \
    --flash-drive="label:input,length:1<<12" \
    --flash-drive="label:output,length:1<<12" \
    --max-mcycle=0 \
    --final-hash \
    --store="calculator-template" \
    -- $'dd status=none if=$(flashdrive input) | lua -e \'print((string.unpack("z", io.read("a"))))\' | bc | dd status=none of=$(flashdrive output)'
```
The result is as follows
```
%machine.host.cmdline.templates-store
```
The directory `calculator-template/` now contains the Cartesi Machine template.
And indeed, running
```bash
cartesi-machine-stored-hash calculator-template/
```
we can see from the output
```
%machine.host.cmdline.templates-hash
```
that the stored template hash is `%machine.host.cmdline.templates-trunc-hash...`.

Templates are typically used by programs that control the emulator with the C++, Lua, or gRPC interfaces.

The `--replace-flash-drive=start:<start>,length:<length>,filename:<filename>` command-line option of the `cartesi-machine` utility can be used to replace an existing flash drive right before a machine is run.
(The `--replace-memory-range` command-line option is a synonym for `--replace-flash-drive`.)
The flash drive to be replaced must be specified by its `start` and `length`.
(Labels do not identify flash drives, they only provide convenient names for partitions.)

This functionality can be used to test templates.
For example, the following command loads the calculator template, and replaces its pristine input drive with a drive containing the contents of the `input.raw` file.
Then, it replaces the pristine output drive so the machine saves results in the file `output.raw`.

```bash
rm -f output.raw
truncate -s 4K output.raw
echo "6*2^1024 + 3*2^512" > input.raw
truncate -s 4K input.raw
cartesi-machine \
    --load="calculator-template" \
    --replace-flash-drive="start:0x9000000000000000,length:1<<12,filename:input.raw" \
    --replace-flash-drive="start:0xA000000000000000,length:1<<12,filename:output.raw,shared"
lua5.3 -e 'print((string.unpack("z", io.read("a"))))' < output.raw
```
The result of running the command is, as expected,
```
10786158809173895446375831144734148401707861873653839436405804869463\
96054833005778796250863934445216126720683279228360145952738612886499\
73495708458383684478649003115037698421037988831222501494715481595948\
96901677837132352593468675094844090688678579236903861342030923488978\
36036892526733668721977278692363075584
```

## State value proofs

The `cartesi-machine` command-line utility can generate proofs concerning the contents of the machine state.
To generate a proof concerning the state as it is before the machine starts running, use the `--initial-proof=address:<number>,log2_size:<number>[,filename=<filename>]` option.
For proofs concerning the state after the emulator is done, use `--final-proof` instead.
In either case, the filename field is optional.
When provided, the proof will be written to the corresponding file.
Otherwise, the contents will be displayed on screen.

*State value proofs* are proofs that a given node in the Merkle tree of the Cartesi Machine state has a given label (i.e., a given associated hash).
Each Merkle tree node covers a contiguous range of the machine's 64-bit address space.
The size of a range is always a power of 2 (i.e., the `<log2_size>` power of 2).
Since the leaves have size 8 (for 64-bits), the valid values for `<log2_size>` are 3&hellip;64.
The range corresponding to each node starts at an `<address>` that is a multiple of its size.

For example, to generate a proof that the Cartesi Machine template above indeed contains a pristine input drive, use the command line
```bash
cartesi-machine \
	--load="calculator-template" \
    --max-mcycle=0 \
    --initial-hash \
    --initial-proof="address:0x9000000000000000,log2_size:12,filename:pristine-input-proof"
```
Recall the first flash drive, the one with the `rootfs.ext2` image file, is present by default, and is automatically placed at starting address `0x8000000000000000`.
The input flash drive is therefore the second drive.
It is automatically spaced by 2<sup>60</sup> bytes relative to the first drive, so that its starting address is `0x9000000000000000`.

The output of the command is
```
%machine.host.cmdline.proofs-pristine-run
```

In addition, the `pristine-input-proof` file now contains a JSON structure with the requested proof
```js title="pristine-input-proof"
%machine.host.cmdline.proofs-pristine-json
```
The `root_hash` value `%machine.host.cmdline.templates-trunc-hash...` is the expected initial state hash seen in the output of the `cartesi-machine` command.
The `address` value `10376293541461622784` is the same as `0x9000000000000000` in decimal.
The `log2_size` value `12` refers to the size of the 4KiB input drive.
The `target_hash` value `d8b96e5b7...` in the proof gives the hash of the input drive.

The hash of the input drive can be also computed externally with the `merkle-tree-hash` command-line utility.
The utility can produce the hash of any file with a power-of-2 size.
The `--tree-log2-size=<log2_size>` option specifies the size.
If an input file is smaller than the specified size, the utility assumes the missing data is composed entirely of bytes 0.
The utility deals efficiently with zero paddings of any size because pristine hashes for all power-of-2 sizes can be precomputed.
For example, to quickly generate the hash for a pristine input with 4KiB size, run
```bash
head -c 0 | merkle-tree-hash --tree-log2-size=12
```
to obtain
```
d8b96e5b7f6f459e9cb6a2f41bf276c7b85c10cd4662c04cbbb365434726c0a0
```
As expected, the hash values match.

The <a id="sibling-hashes"> `sibling_hashes` </a> array contains the hashes of the siblings to all nodes in the path from the root all the way down to the target node (excluding the root, which has no sibling).
In a process explained in the [blockchain perspective](../blockchain/hash.md), using the `address` field, the `target_hash` hash, and the `sibling_hashes` array, it is possible to go up the tree computing the hashes along the path, until the root hash is produced.
If the root hash obtained by this process matches the expected root hash, the proof is valid.
Otherwise, something is amiss.
(Incidentally, from the hash of its sibling, the last entry in `sibling_hashes`, it is possible to ascertain that the neighboring range to the input drive also contains 4KiB of bytes 0.)

To compute the hash for the desired `input.raw` file with contents `6*2^1024 + 3*2^512\n`, padded with zeros, run
```bash
echo "6*2^1024 + 3*2^512" | merkle-tree-hash --tree-log2-size=12
```
to obtain
```
2c92c99754e85e3e2a29edd84228a62b051f9f55a5563f8decc7c6d5d9d8ef64
```

Using a process similar to the proof verification described above, it is possible to go up the Merkle tree for the template using the `sibling_hashes` array in the proof, but starting from the hash `2c92c997...` of the desired `input.raw` image rather than hash `d8b96e5b...` of the template's pristine drive.
The result is the initial state hash for the instantiated template: the same that can be seen in the initial state hash produced by the `cartesi-machine` command-line
```bash
echo "6*2^1024 + 3*2^512" > input.raw
truncate -s 4K input.raw
cartesi-machine \
    --load="calculator-template" \
    --replace-flash-drive="start:0x9000000000000000,length:1<<12,filename:input.raw" \
    --initial-hash \
    --initial-proof="address:0x9000000000000000,log2_size:12,filename:input-proof" \
	--max-mcycle=0
```

The contents of the `input-proof` are

```js title="input-proof"
%machine.host.cmdline.proofs-input-json
```
The `target_hash` value `2c92c997...` reflects the hash computed for the input, whereas `root_hash` value `%machine.host.cmdline.proofs-input-roothash...` differs from `%machine.host.cmdline.templates-trunc-hash...` obtained for template, as expected.
Moreover, the `sibling_hashes` entries in the template Cartesi Machine and in the instantiated Cartesi Machine remain the same, reflecting the fact that there were no other changes in the machine's initial state.

Another useful proof is the one for the *output* drive, once the machine is halted.
To obtain this proof, run
```bash
rm -f output.raw
truncate -s 4K output.raw
echo "6*2^1024 + 3*2^512" > input.raw
truncate -s 4K input.raw
cartesi-machine \
    --load="calculator-template" \
    --replace-flash-drive="start:0x9000000000000000,length:1<<12,filename:input.raw" \
    --replace-flash-drive="start:0xa000000000000000,length:1<<12,filename:output.raw,shared" \
    --final-hash \
    --final-proof="address:0xa000000000000000,log2_size:12,filename:output-proof"
```

This produces the output

```
%machine.host.cmdline.proofs-output-run
```
The contents of the `output-proof` are
```js title="output-proof"
%machine.host.cmdline.proofs-output-json
```
Note how the `root_hash` field in the proof matches the final state hash `%machine.host.cmdline.proofs-output-roothash...` output by the `cartesi-machine` command-line utility.

To see that the `target_hash` field matches the `output.raw` drive, use the `merkle-tree-hash` command-line utility
```bash
merkle-tree-hash --tree-log2-size=12 < output.raw
```
to obtain
```
b15a6b8aab8a423c725f9ad55fd46c4481ba91008f3a01593192de37a7a41565
```

The `cartesi-machine` command-line utility accepts an arbitrary number of `--initial-proof` and `--final-proof` parameters.
They are computed one-by-one, and either printed or stored in the specified files, as requested.

To read more about proofs, refer to [the blockchain perspective](../blockchain/hash.md).

## Remote Cartesi Machines

The `cartesi-machine` command-line utility, as used until now, has always instantiated its own local Cartesi Machine.
However, it can also be used to control a remote Cartesi Machine.
Remote Cartesi Machines are managed by the `remote-cartesi-machine` server.
The server exposes a gRPC interface through which the `cartesi-machine` command-line utility (or any other software) can control the machine remotely.

To avoid confusion, it is best to run the server and client in separate shells in the playground container.
Leaving the existing shell for the client, open a separate shell for the server (For example, by running `docker exec -it <container-name> /bin/bash`), then run
```bash
remote-cartesi-machine \
    --server-address=localhost:8080
```
The `--server-address=<address>` command-line option specifies the address and port the server will listen to.

:::note
In this case, since we selected `localhost:8080`, the client must run in the same container in order to communicate with the server.
To be accessible from outside the container, the `--server-address` option would have to refer to an address and port that were _exposed_ by the container.
:::

To instruct the `cartesi-machine` command-line utility to connect with the server, add the command-line option
`--remote-address=<address>` to specify the remote server to connect to, and the `--checkin-address=<address>` option to specify an address the server will use to notify the client when it is ready.
The option `--remote-shutdown` causes the server to be shutdown by the client when the client exits.
(Otherwise, the server will remain available for the next client.)
All other options work as before.
Keep in mind that any image files referred to by an option passed to the command-line utility `cartesi-machine` must be accessible to the `remote-cartesi-machine` server (and not necessarily to the client).
Additionally, terminal output for the Cartesi Machine instantiated by the server will appear in the remote shell where the server was run (not the client's shell).
Terminal input, when enabled, must also happen via the remote shell.

With this in mind, running the command in the client shell
```bash
cartesi-machine \
    --remote-address=localhost:8080 \
    --checkin-address=localhost:8081 \
    --remote-shutdown
```
produces the following output on the client shell
```
%machine.host.cmdline.remote-client
```
and the following output on the server shell
```
%machine.host.cmdline.remote-server
```

The client first binds to the check-in address, connects to the remote address, and prints out the version returned by the server.
It then asks the server to instantiate a machine (by sending the configuration over) and run it.
The machine that runs in the server prints out the splash screen, boots Linux, and cedes control to the
Cartesi-provided `/sbin/init` script.
The `/sbin/init` script figures out there is nothing to do and halts the machine.
The client detects the machine is halted and shuts down the server, as requested.

When it is desirable to leave the server running and preserve the instantiated machine, omit the `--remote-shutdown`
command-line option and add the `--no-remote-destroy`.
For example, assuming the remote server has just been run:
```bash
remote-cartesi-machine \
    --server-address=localhost:8080
```
use the `cartesi-machine` command-line utility to instantiate and run a Cartesi Machine for 2^2O cycles:
```bash
cartesi-machine \
    --remote-address=localhost:8080 \
    --checkin-address=localhost:8081 \
    --no-remote-destroy \
    --max-mcycle=1Mi \
    -- echo "Still here!"
```
The client shell shows:
```
%machine.host.cmdline.remote-begin-client
```
To continue execution of the same Cartesi Machine until it ends, rather than instantiating a new one, use the `cartesi-machine` command-line utility with the option `--no-remote-create`:
```
cartesi-machine \
    --remote-address=localhost:8080 \
    --checkin-address=localhost:8081 \
    --no-remote-create
```
The client shell now shows:
```
%machine.host.cmdline.remote-end-client
```
The server shell shows the execution of both sessions:
```
%machine.host.cmdline.remote-begin-end-server
```

Remote Cartesi Machines have one ability that local Cartesi Machines lack: they can create a state _snapshot_ they can later _rollback_ to.
Snapshots and rollbacks are the foundation on which the state inspection mechanism of Rolling Cartesi Machines is based, as well as the feature that enables the rejection of inputs to state advances.
Both situations require the state of the Rolling Cartesi Machine to remain unchanged.
Before Rolling Cartesi Machines were introduced, snapshots and rollbacks were used exclusively to enable efficient dispute resolution.

## Rolling Cartesi Machines

Applications involving Rolling Cartesi Machines are not designed to interact with the `cartesi-machine` command-line utility.
Instead, they rely on a variety of software components that allow a front-end to post to the blockchain requests to advance the state of the server, that poll the blockchain for advance-state requests posted by others so a local copy of the server can be kept in sync, and that allow the front-end to inspect the state of the server.

Nevertheless, in debugging or prototyping tasks, the `cartesi-machine` command-line utility can simulate the external environment that a target application (running inside a Rolling Cartesi Machine) would encounter in production.
To use this functionality, the developer creates a sequence of advance-state requests as numbered files, or a single inspect-state request as a file, and instructs the `cartesi-machine` command-line utility to feed them to the target application.
As each request is processed, the utility stores the responses as separate files.

An advance-state request is composed by _input metadata_ and an _input_.
The input metadata include a variety of fields that are important for the operation of Cartesi Rollups (_message sender_, _block number_, _timestamp_, _epoch index_, _input index_).
The input contains only an application-specific payload.
Recall that, as responses, the target application can issue _vouchers_, _notices_, _reports_, and _exceptions_.
In contrast, an inspect state request carries only a _query_ and, as response, produces only reports and exceptions.
Like the input to an advance-state request, the query in an inspect-state request consists of an application-specific payload.

Target applications running inside Rolling Cartesi Machines communicate with the outside world using the Cartesi-specific `/dev/rollup` Linux device.
The device can be accessed directly, via `ioctl` calls to the driver, via the `/opt/cartesi/bin/rollup` command-line utility, or by means of an HTTP service.
The `/dev/rollup` device owns a number of memory ranges that are used to pass data in and out of the machine, and uses the `/dev/yield` device to return control to the host and notify it of important events.

In a nutshell, the process is as follows.
When the target application attempts to obtain the next request from the device, the `/dev/rollup` device uses the `/dev/yield` device to issue a _manual_ yield command returns control to the host (in our case, the `cartesi-machine` command-line utility).
The host then copies the next request to the appropriate memory ranges and resumes the machine, so the device can pass the request over to the target application for processing.
When the target application asks the device to output data (a voucher, notice, report, or exception), the `/dev/rollup` device copies the data to the appropriate memory ranges, then uses the `/dev/yield` device to issue an _automatic_ yield command that notifies the host that a new output is available.
The host can then collect the output (in our case, saving it to files or printing it to the terminal) and resume the machine so the target application can continue processing the request.

When debugging production code, developers can obtain from Cartesi Rollups, as files, the input metadata and input associated to each advance-state request, so the sequence can be replayed locally in the command line.
When prototyping, developers can create their own files simulating requests that test the behavior of their target application under customized conditions.

### Encoding requests

The `rollup-memory-range` command-line utility can encode input metadata, inputs, queries, vouchers, notices, and reports to files.
For example, the following commands create the input metadata and input files for two distinct advance-state requests
(saved as `epoch-0-input-metadata-0.bin`, `epoch-0-input-0.bin`, `epoch-0-input-metadata-1.bin`, and `epoch-0-input-1.bin`), and one query for an inspect state request (saved as `query.bin`):

```bash
for i in 1 2; do
rollup-memory-range encode input-metadata > epoch-0-input-metadata-$i.bin <<-EOF
    {
        "msg_sender": $(printf '"0x%040d"' $i)
        "block_number": 0,
        "time_stamp": 0,
        "epoch_index": 0,
        "input_index": $i
    }
EOF
rollup-memory-range encode input > epoch-0-input-$i.bin <<-EOF
    {
        "payload": "hello from input $i!"
    }
EOF
done
rollup-memory-range encode input > query.bin <<-EOF
{
    "payload": "hello from query!"
}
EOF
```
Listing the files created
```bash
ls *.bin
```
We see
```
epoch-0-input-1.bin  epoch-0-input-metadata-1.bin  query.bin
epoch-0-input-2.bin  epoch-0-input-metadata-2.bin
```

### Running a simple target application

The command-line utility `/opt/cartesi/bin/ioctl-echo-loop`, pre-installed in the root file-system `rootfs.ext2`, is a simple Rolling Cartesi Machine application that merely outputs (as vouchers, notices, or reports) the payload it receives as the input to advance-state or query to inspect-state.
It is perfect to showcase the input-output mechanism.

Since Rolling Cartesi Machines rely on the snapshot/rollback functionality of Remote Cartesi Machines, running a Rolling Cartesi Machine in the command line requires using the `remote-cartesi-machine` server in combination with the `cartesi-machine` client.
With the files just created by `rollup-memory-ranges` in the working directory
```bash
ls *.bin
```
```
epoch-0-input-1.bin  epoch-0-input-metadata-1.bin  query.bin
epoch-0-input-2.bin  epoch-0-input-metadata-2.bin
```
run the remote server with the command
```bash
remote-cartesi-machine \
    --server-address=localhost:8080
```

Then, from a different shell into the same container, run the client with the command
```bash
cartesi-machine \
    --remote-address=localhost:8080 \
    --checkin-address=localhost:8081 \
    --remote-shutdown \
    --rollup \
    --rollup-advance-state=epoch_index:0,input_index_begin:1,input_index_end:3,hashes \
    --rollup-inspect-state \
    -- ioctl-echo-loop --vouchers=1 --notices=1 --reports=1 --reject=1
```

The command-line option `--rollup` is a shortcut that combines a variety of settings needed by the Rolling Cartesi Machine functionality.
The command-line option `--rollup-advance-state` instructs the utility to look for input metadata and input files to use in a sequence of advance-state requests.
By default, the name of the input metadata and input files are `epoch-%e-input-metadata-%i.bin` and `epoch-%e-input-%i.bin`, respectively, where `%e` is replaced by the epoch index and `%i` by the input index.
The epoch index is given by the parameter `epoch_index=<number>`, and the input index progressively takes the values in the (open ended) range given by parameters `input_index_begin=<number>` and `input_index_end=<number>`.
In the example, two advance-state requests will be performed for epoch 0: one for input 1 and one for input 2.
The file names therefore match those of the encoded files present in the working directory.
The parameter `hashes` instructs the utility to print the state hashes between state advances, both before and after it writes the request data to the appropriate memory ranges in the machine state.
The command-line option `--rollup-inspect-state` causes the utility to create an inspect-state request right after all advance-state requests have been carried out (if any).
By default, the query is loaded from a file `query.bin`.
Finally, the command-line for `ioctl-echo-loop` instructs it to echo each payload as one voucher, one notice, and one report, and to reject the input with index 1.

As a result of these commands, the server shell simply shows the splash screen and a message from `ioctl-echo-loop` declaring what will be echoed:
```bash
%machine.host.cmdline.rolling-ioctl-echo-loop-server
```
The client shell shows a lot more activity:

```bash
%machine.host.cmdline.rolling-ioctl-echo-loop-0client
...
```
The client starts by printing information about the remote server it connected to.
It then runs the machine in a loop, occasionally transferring information in and out.

The first `manual yield rx-accepted` signals the point at which the target application attempted to obtain the first request.
In other words, the application is _ready_.

```bash
...
%machine.host.cmdline.rolling-ioctl-echo-loop-1client
...
```
Upon receiving control back from the machine at cycle %machine.host.cmdline.rolling-ioctl-echo-loop-cycles0, the client prints the epoch index 0 and input index 1, prints state hash `%machine.host.cmdline.rolling-ioctl-echo-loop-hashes0...`, loads files `epoch-0-input-metadata-1.bin` and `epoch-0-input-1.bin` into the appropriate memory ranges, prints the modified state hash `%machine.host.cmdline.rolling-ioctl-echo-loop-hashes1...`, and resumes the machine.
The `ioctl-echo-loop` application reads the payload from the request input and echoes it into one voucher, one notice, and one report.
These operations generate the different flavors of `automatic yield` that can be seen in the client output: a `tx-voucher` at cycle %machine.host.cmdline.rolling-ioctl-echo-loop-cycles1, a `tx-notice` at cycle %machine.host.cmdline.rolling-ioctl-echo-loop-cycles2, and a `tx-report` at cycle %machine.host.cmdline.rolling-ioctl-echo-loop-cycles3.
For each of them, the client receives control back from the machine.
It reads the appropriate memory range to store files `epoch-0-input-1-voucher-0.bin`, `epoch-0-input-1-notice-0.bin`, and `epoch-0-input-1-report-0.bin`, respectively.

The `manual yield rx-rejected` at cycle %machine.host.cmdline.rolling-ioctl-echo-loop-cycles4 signals that the `ioctl-echo-loop` application is done processing input index 1 of epoch 0 (and rejected it!).
During the processing of an advance-state request, when the `/dev/rollup` Linux device receives a voucher, it appends its hash into a memory array.
It does the same for the notices it receives.
Since there will be no more vouchers or notices generated for the input (it was, after all, rejected), the client saves the hash arrays into files `epoch-0-index-1-voucher-hashes.bin` and `epoch-0-index-1-notice-hashes.bin`, respectively.

In production, when an input to an advance state request is rejected, the Server Manager will rollback the Rolling Cartesi Machine to the state it was before the input was processed.
Moreover, all vouchers and notices are deleted (the reports are preserved).
To make prototyping realistic, the `cartesi-machine` client also rolls the state back when an input is rejected by the target.
This can be confirmed by the fact that the cycle counts (%machine.host.cmdline.rolling-ioctl-echo-loop-cycles0) and state hashes (`%machine.host.cmdline.rolling-ioctl-echo-loop-hashes0...`) following the epoch 0 input 1 and epoch 0 input 2 are the same.
(The files with the vouchers and notices issued before rejection, as well as the files with the arrays of hashes, are left in place for the developer's inspection.)

```bash
...
%machine.host.cmdline.rolling-ioctl-echo-loop-2client
...
```
A similar procedure is followed when processing the advance-state request with input index 2 of epoch index 0, except this time the input is accepted.
Indeed, when the `manual yield rx-accepted` at cycle %machine.host.cmdline.rolling-ioctl-echo-loop-cycles8 is received by the client, it has run out of advance-state requests to return.

```bash
...
%machine.host.cmdline.rolling-ioctl-echo-loop-3client
```
The client now moves to the inspect-state request.
It loads `query.bin`, copies it to the appropriate memory range, and resumes the machine so the `ioctl-echo-loop` application can respond to the inspect-state request.
The `automatic yield tx-report` at cycle %machine.host.cmdline.rolling-ioctl-echo-loop-cycles9 signals the application issued a report, which the client then saves as `query-report-0.bin`.

Finally, when the subsequent `manual yield rx-accepted` is received at cycle %machine.host.cmdline.rolling-ioctl-echo-loop-cycles10, the client simply shuts down the remote Cartesi Machine server and exits.

Here is the complete list of `.bin` files after the client exits:
```bash
ls *.bin
```
```
epoch-0-input-1-notice-0.bin        epoch-0-input-2-report-0.bin
epoch-0-input-1-notice-hashes.bin   epoch-0-input-2-voucher-0.bin
epoch-0-input-1-report-0.bin        epoch-0-input-2-voucher-hashes.bin
epoch-0-input-1-voucher-0.bin       epoch-0-input-2.bin
epoch-0-input-1-voucher-hashes.bin  epoch-0-input-metadata-1.bin
epoch-0-input-1.bin                 epoch-0-input-metadata-2.bin
epoch-0-input-2-notice-0.bin        query-report-0.bin
epoch-0-input-2-notice-hashes.bin   query.bin
```

### Decoding responses

The `rollup-memory-range` command-line utility can decode input metadata, inputs, queries, vouchers, notices, reports, and hashes.

For example, we can decode the files we encoded for the first advance-state request we created above with the commands:
```bash
rollup-memory-range decode input-metadata < epoch-0-input-metadata-2.bin
```
```
{
  "msg_sender":"0x0000000000000000000000000000000000000002",
  "block_number":0,
  "time_stamp":0,
  "epoch_index":0,
  "input_index":2
}
```
```bash
rollup-memory-range decode input < epoch-0-input-2.bin
```
```
{
  "payload":"hello from input 2!"
}
```
A voucher carries an _address_ and a _payload_.
The `ioctl-echo-loop` utility copies the _msg-sender_ field from the input metadata to the _address_ field of the voucher, and the payload from the input to the payload of the voucher.
We can see this by decoding the voucher `epoch-0-input-2-voucher-0.bin` file with the commands
```bash
rollup-memory-range decode voucher < epoch-0-input-2-voucher-0.bin
```
```
{
  "address":"0x0000000000000000000000000000000000000002",
  "payload":"hello from input 2!"
}
```
The results match what was expected from the `ioctl-echo-loop` utility.

Notices and reports carry only a payload.
To decode them, run, for example:
```bash
rollup-memory-range decode notice < epoch-0-input-2-notice-0.bin
```
```
{
  "payload":"hello from input 2!"
}
```
```bash
rollup-memory-range decode report < query-report-0.bin
```
```
{
  "payload":"hello from query!"
}
```
Once again, the echo program does its job as expected.

## Rolling Cartesi Machine templates

A Rolling Cartesi Machine template is a machine that has been configured to support Cartesi Rollups, is running a target application in a request-processing loop, is ready to process the next request, and has been stored.

As an example, we will create a Rolling Cartesi Machine template for an arbitrary-precision arithmetic expression evaluator that outputs, as a notices, the result of computation it receives as inputs to advance-state requests.
We will, once again, rely on the `bc` command-line utility to perform the computations.
To interact with the `/dev/rollup` Linux device (i.e., to obtain the advance-state request inputs and to generate the notices), we will use the `/opt/cartesi/bin/rollup` command-line utility.

Shell scripts become surprisingly powerful with the help of the `rollup` and `jq` command-line utilities.
A `bc`-based arbitrary precision application, for example, might look like this:
```bash title="calc.sh"
%machine.host.cmdline.rolling-calc-sh
```

The `rollup` command-line utility supports the commands `accept`, `reject`, `voucher`, `notice`, `report`, and `exception`.
It uses JSON objects as inputs and outputs.
The `accept` and `reject` commands accept or reject the previous request and output the next request.
For advance-state requests, the output is in the format
```js
{
  "request_type": "advance_state"
  "data": {
    "metadata": {
      "msg_sender": <hash>,
      "timestamp": <number>,
      "block_number": <number>,
      "epoch_index": <number>,
      "input_index": <number>
    },
    "payload": <string>
  },
}
```
Appropriately, the `notice` command generates a notice.
The input format is as follows
```js
{
  "payload": <string>
}
```
and the output (not used by `calc.sh`) gives the index of the just-output notice as follows
```js
{
  "index": <number>
}
```

The loop in the `calc.sh` script calls `rollup finish` to obtain the next request (and accept or reject the previous).
It uses `jq` to extract the `request_type` field and, if it is an `"advance_state"` request, it uses `jq` again to extract the `"payload"` field inside the `"data"` field.
This is passed to the `bc` utility, which outputs the result split into lines terminated by `\`.
The `tr` utility joins the lines back together.
The result is again fed to `jq`, which assembles the proper JSON object with a `"payload"` field that is passed to `rollup notice`.

We add the command line option `--assert-rolling-template` to help catch errors.
When enabled, it will cause `cartesi-machine` to exit with a status-code reporting failure if the generated machine is not Rolling Cartesi Machine template compatible.

To use `calc.sh` in a Rolling Cartesi Machine template, first create a filesystem with the program:
```
mkdir calc
cp calc.sh calc
chmod +x calc/calc.sh
tar \
    --sort=name \
    --mtime="2022-01-01" \
    --owner=1000 \
    --group=1000 \
    --numeric-owner \
    -cf calc.tar \
    --directory=calc .
genext2fs \
    -f \
    -b 1024 \
    -a calc.tar \
    calc.ext2
```

Then, follow a procedure similar to the creation of Cartesi Machine templates, using the command line
```bash
cartesi-machine \
    --rollup \
    --flash-drive=label:calc,filename:calc.ext2 \
    --store="rolling-calculator-template" \
    --assert-rolling-template \
    -- /mnt/calc/calc.sh
```

The result is as follows
```
%machine.host.cmdline.rolling-calc-template.template
```
The machine execution stops when the first call to `rollup finish` yields, and the machine at that state is stored in directory `"rolling-calculator-template"`.

:::note
In production, if the target application finds an irrecoverable error during initialization, it should abort with an exception.
In that case, the `cartesi-machine` command-line utility will detect the exception, print it to the console, and exit with a status-code reporting failure.
:::

To test the template, create a couple advance-state requests (input and input metadata):
```bash
rollup-memory-range encode input-metadata > epoch-0-input-metadata-1.bin <<-EOF
{
    "msg_sender": $(printf '"0x%040d"' 1)
    "block_number": 0,
    "time_stamp": 0,
    "epoch_index": 0,
    "input_index": 1
}
EOF
rollup-memory-range encode input > epoch-0-input-1.bin <<-EOF
{
    "payload": "invalid input"
}
EOF
rollup-memory-range encode input-metadata > epoch-0-input-metadata-2.bin <<-EOF
{
    "msg_sender": $(printf '"0x%040d"' 2)
    "block_number": 0,
    "time_stamp": 0,
    "epoch_index": 0,
    "input_index": 2
}
EOF
rollup-memory-range encode input  > epoch-0-input-2.bin <<-EOF
{
    "payload": "6*2^1024 + 3*2^512"
}
EOF
```

With the files just created by `rollup-memory-ranges` in the working directory, run the remote server with the command
```bash
ls *.bin
```
```
epoch-0-input-1.bin  epoch-0-input-metadata-1.bin
epoch-0-input-2.bin  epoch-0-input-metadata-2.bin
```
```bash
remote-cartesi-machine \
    --server-address=localhost:8080
```

Then, from a different shell into the same container, run the client with the command
```bash
cartesi-machine \
    --remote-address=localhost:8080 \
    --checkin-address=localhost:8081 \
    --remote-shutdown \
    --rollup \
    --rollup-advance-state=epoch_index:0,input_index_begin:1,input_index_end:3,hashes \
    --load="rolling-calculator-template"
```

The client shell shows
```
%machine.host.cmdline.rolling-calc-template.client
```
It starts by loading the machine from directory `"rolling-calculator-template"` and printing again the same yielded state that held when the server template was created.
Then, the first input is rejected, as the payload `"invalid input"` is not an expression that `bc` can understand.
Finally, the second input, with payload `"6*2^1024 + 3*2^512"`, is accepted.

Indeed, to see the result of the computation specified in the second input, run
```bash
rollup-memory-range decode notice < epoch-0-input-2-notice-0.bin | \
    jq -r .payload | \
    fold -w 68
```
to produce
```
10786158809173895446375831144734148401707861873653839436405804869463
96054833005778796250863934445216126720683279228360145952738612886499
73495708458383684478649003115037698421037988831222501494715481595948
96901677837132352593468675094844090688678579236903861342030923488978
36036892526733668721977278692363075584
```
The server shell shows only the error message output by `bc` and `rollup`.
In production, these error messages should have been captured and output as a report, rather than being allowed to leak into the console.
```
%machine.host.cmdline.rolling-calc-template.server
```

## Rarely used options

:::warning
This is an advanced section, not needed by regular users of the Cartesi platform.
:::

The command-line option `--append-rom-bootargs=<string>` can be used to append any `<string>` to the kernel command-line.
A detailed description of all kernel command-line parameters is beyond the scope of this document.
Please refer to the appropriate [section of the kernel documentation](https://www.kernel.org/doc/html/v5.5/admin-guide/kernel-parameters.html).

For example, to prevent clutter in the console, the `cartesi-machine` utility automatically adds the `quiet` option to the kernel command-line, disabling most log messages.
To override this setting and see more of the log messages output to console, use the `loglevel=<n>` parameter.
```bash
cartesi-machine \
    --append-rom-bootargs="loglevel=8"
```
The output is
```
%machine.host.cmdline.rarely-append-bootargs-loglevel
```

To clear the kernel command-line, use the option `--no-rom-bootargs`.
Notice that, without any options, the machine will not operate properly.
In particular, as explained under the [Lua interface](../host/lua.md), flash-drives use kernel command-line arguments.
For example, running the `cartesi-machine` command-line utility with no arguments produces a kernel command-line
equivalent to running the command
```bash
cartesi-machine \
    --no-rom-bootargs \
    --append-rom-bootargs=%machine.host.cmdline.default-rom-bootargs
```

The command-line option `--periodic-hashes=<number-period>[,<number-start>]` causes the command-line utility to periodically obtain and print the state hash.
The `<number-period>` argument gives the distance between hashes in cycles. The optional `<number-start>` argument gives the starting cycle for the periodic hashes. (Both `--initial-hash` and `--final-hash` are implied by this option.)

For example, to see the last 10 state hashes from the calculator machine computation, run the command
```bash
echo "6*2^1024 + 3*2^512" > input.raw
truncate -s 4K input.raw
cartesi-machine \
    --load="calculator-template" \
    --replace-flash-drive="start:0x9000000000000000,length:1<<12,filename:input.raw" \
    --periodic-hashes=1,%machine.host.cmdline.rarely-periodic-initial-cycle
```
The output is

```
%machine.host.cmdline.rarely-periodic-hashes
```

The command-line option `--dump-pmas` causes the emulator to dump the contents of all mapped spans in the address space to files.
Each span produces a file `<start>--<length>.bin`.
Every other byte in the address space has value 0.
This is useful to inspect the entire state of the machine from outside the emulator.

The command-line options `--store-config` and `--load-config` store or load a file with information that can be used to initialize the exact same Cartesi Machine that the `cartesi-machine` command-line utility will use.
The format of these configuration files is explained in detail under the [Lua interface](../host/lua.md) to Cartesi Machines.
In particular,  the `--store-config` option, without arguments, dumps to screen all the options used to define the Cartesi Machine.
This information can be very useful when debugging problems.

The remaining options in the command-line utility `cartesi-machine` are mostly useful for low-level tests and debugging.
As such, they require some context.

During verification, the blockchain mediates a *verification game* between the disputing parties.
This process is explained in detail under the [the blockchain perspective](../blockchain/vg.md).
In a nutshell, both parties started from a Cartesi Machine that has a known and agreed upon initial state hash.
(E.g., an agreed upon template that was instantiated with an agreed upon input drive.)
At the end of the computation, these parties now disagree on the state hash for the halted machine.
The state hash evolves as the machine executes steps in its fetch-execute loop.
The first stage of the verification game therefore searches for the *step of disagreement*: the particular cycle such that the parties agree on the state hash before the step, but disagree on the state hash after the step.
Once this step of disagreement is identified, one of the parties sends to the blockchain a log of state accesses that happen along the step, including cryptographic proofs for every value read from or written to the state.
This log proves to the blockchain that the execution of the step transitions the state in such a way that it reaches the state hash claimed by the submitting party.

The `--step` command-line option instructs `cartesi-machine` to dump to screen an abridged, user-friendly version of this state access log.

For the sake of completeness, consider the example in which the Cartesi Machine was stopped while it drew the splash screen.
The example below shows the step it was about to execute
```bash
cartesi-machine \
    --max-mcycle=%machine.host.cmdline.cycles-limit-exec \
    --step > /dev/null
```
and produces the log
```
%machine.host.cmdline.rarely-step
```
Understanding these logs in detail is unnecessary for all but the most low-level internal development at Cartesi.
It requires deep knowledge of not only RISC-V architecture, but also how Cartesi's emulator implements it.
The material is therefore beyond the scope of this document.

This particular example, however, was hand-picked for illustration purposes.
The RISC-V instruction being executed, `sd`, writes the 64-bit word `0x010100000000000a` to address `0x40008000` (access&nbsp;#23).
This is the memory-mapped address of HTIF's `tohost` CSR.
The value refers to the console subdevice (`DEV=0x01`) , command `putchar` (`CMD=0x01`), and causes the device to output a line-feed (`DATA=0x0a`) to the emulator's console.
I.e., the instruction is completing the row `       \    / CARTESI` in the splash screen.

The command-line option `--json-steps=<filename>` outputs a machine-readable version of the step log *for each cycle* executed by the emulator.
It is used by internal integration tests that verify the consistency between the Cartesi Machine as implemented by the off-chain emulator and as implemented by the on-chain step verification function.
Needless to say, even for brief computations, the resulting log files can be *very* large.

The `--rollup` command-line option sets the `--htif-yield-automatic` and `--htif-yield-manual` options for the `/dev/yield` device.
See the [target perspective](../target/architecture.md) for details on automatic and manual yield commands and how they are used by Cartesi Rollups.
The `--rollup` option also configures a variety of memory ranges used by the `/dev/rollup` device.
There are five memory ranges: _rollup-rx-buffer_, _rollup-input-metadata_, _rollup-tx-buffer_, _rollup-voucher-hashes_, and _rollup-notice-hashes_.
The values implied by the `--rollup` command-line option are `--rollup-rx-buffer=start:0x60000000,length:2<<20`, `--rollup-tx-buffer=start:0x60200000,length:2<<20`, `--rollup-input-metadata=start:0x60400000,length:4096`, `--rollup-voucher-hashes=start:0x60600000,length:2<<20`, and `--rollup-notice-hashes=start:0x60800000,length:2<<20`.

