Local Machine
A local Cartesi machine is the one that runs in-process. It can be created by using the following utility methods:
// create a new machine from a configuration
function create(config: MachineConfig, runtimeConfig?: MachineRuntimeConfig): CartesiMachine;
// load machine snapshot saved to a directory
function load(dir: string, runtimeConfig?: MachineRuntimeConfig): CartesiMachine;
// create an empty machine, which later must be created or loaded
function empty(): CartesiMachine;The following sections will show step by step how to create and run a very simple local machine. It uses the Linux kernel linux.bin and a pre-built rootfs.ext2 file as the root filesystem.
Creating a machine
The machine defined below uses 128Mb of RAM, the Linux kernel file, and a single filesystem as root.
The entrypoint is a simple execution of the classic "Hello world!" message.
import { } from "@cartesi/machine";
// create a basic machine that prints Hello world
const = ({
: {
: 0x8000000, // 128MB of RAM
: { : "linux.bin" },
},
: [
{
: { : "rootfs.ext2" },
},
],
: {
: "echo Hello world!", // simply prints to the console
},
});Running a machine
The next step of this simple example is to run the machine until it yields or halts.
import { } from "@cartesi/machine"; // [!code --]
import { , } from "@cartesi/machine"; // [!code ++]
// create a basic machine that prints Hello world
const = ({
: {
: 0x8000000, // 128MB of RAM
: { : "linux.bin" },
},
: [
{
: { : "rootfs.ext2" },
},
],
: {
: "echo Hello world!", // simply prints to the console
},
});
// run the machine until it yields or halts (default is MAX_MCYCLE)
const = .();
switch () {
case .:
.("Machine yielded manually");
break;
case .:
.("Machine halted");
break;
default:
.(`Machine halted: ${}`);
}
.(); Calculating the hash
The machine hash can be calculated using the getRootHash() method of the machine, like below:
import { , } from "@cartesi/machine";
// create a basic machine that print Hello world
const = ({
: {
: 0x8000000, // 128MB of RAM
: { : "linux.bin" },
},
: [
{
: { : "rootfs.ext2" },
},
],
: {
: "echo Hello world!",
},
});
// run the machine until it yields or halts (default is MAX_MCYCLE)
const = .();
switch () {
case .:
.("Machine yielded manually");
break;
case .:
.("Machine halted");
break;
default:
.(`Machine halted: ${}`);
}
.();
// calculate machine root hash
const = .();
.(); The complete CartesiMachine API is available in the API section.
Memory Management
The API automatically handles memory management for machine objects. When a machine instance is garbage collected by Node.js, its underlying C resources are automatically cleaned up.
However, you can also explicitly free the resources held by a machine object by calling its destroy() method. This is useful if you want to immediately release native resources without waiting for garbage collection.
Thread Safety
The C API is not thread-safe. All operations should be performed from the same thread that created the machine object.