### 01-core-architecture/01-components.txt *GenVM* Components Overview *************************** Introduction ============ GenVM is a WebAssembly-based virtual machine that executes intelligent contracts through a dual-mode execution model. The architecture separates deterministic blockchain operations from non-deterministic AI/web operations using a supervisor pattern with multiple isolated *sub-VM*s. Architecture Overview ===================== The system consists of: * **Supervisor**: Manages multiple *sub-VM* instances for different execution contexts * **:term:`Sub-VM` instances**: Execute code in deterministic mode, non-deterministic mode, or sandboxed environments * **:term:`Runners `**: Define execution environments and dependencies for contracts, supporting multiple formats (WASM, ZIP archives, text-based with headers) The supervisor enforces resource limits, manages memory isolation between *sub-VM* instances, and handles result validation through consensus mechanisms. *Runners* provide configurable execution environments that can depend on other *runners* and specify initialization actions for contract deployment. ### 01-core-architecture/02-vm.txt *Sub-VM* Architecture ********************* Overview ======== GenVM is built on a modified WebAssembly runtime that enables the execution of "Intelligent Contracts" - smart contracts capable of performing both deterministic blockchain operations and non- deterministic AI/web operations while maintaining consensus. The VM's core innovation is its dual-mode execution model that isolates deterministic and non-deterministic operations. WebAssembly Foundation ====================== GenVM uses WebAssembly as its core execution environment, providing: * **Language Agnostic Execution**: Support for multiple programming languages compiled to WASM * **Security**: Memory-safe execution with controlled access to system resources * **Performance**: Near-native execution speed with efficient compilation * **Portability**: Consistent behavior across different hardware architectures VM Execution Modes ================== *GenVM* uses dual execution model that separates deterministic and non-deterministic operations. [graph] Deterministic Mode ------------------ **Purpose**: Executes blockchain consensus logic that must produce identical results across all validators. **Characteristics**: * Reproducible execution across all network participants * Access to blockchain state (storage, balances, ...) * Standard computational operations and business logic * Inter-contract communication and message passing **Restrictions**: - No access to external networks or services - Controlled randomness and time access - Software-based floating point operations - No file system access beyond virtual file system Non-Deterministic Mode ---------------------- **Purpose**: Executes operations that may produce different results, so that they require consensus validation. **Characteristics**: * AI inference and ML operations * Web scraping and HTTP requests * External data source access **Isolation**: - Separate VM instance to prevent state contamination * Results passed back to deterministic mode are leader-substituted * No direct access to blockchain state * No file system access beyond virtual file system * Communication only through validated results VM Instance Management ====================== Supervisor Architecture ----------------------- GenVM uses a supervisor pattern to manage multiple VM instances **Resource Management**: * Memory limits per execution mode (4GB for deterministic VMs, 4GB for non-deterministic VMs) * Time gas metering and consumption tracking * Execution timeouts Memory Model ============ Linear Memory Management ------------------------ Each VM instance operates with WebAssembly's linear memory model. **Memory Isolation**: * Strict boundaries between VM instances * No shared memory between deterministic and non-deterministic modes * Strict memory allocation limits Storage Interface ----------------- * Storage operations * Custom Calldata Encoding format for deterministic serialization Gas and Resource Metering ========================= GenVM implements a sophisticated three-dimensional gas model to ensure fair resource allocation and prevent abuse. Execution Modes =============== Leader Execution ---------------- When a node acts as a leader: 1. **Full Execution**: Runs both deterministic and non-deterministic operations 2. **Result Proposal**: Proposes non-deterministic operation results to validators 3. **Consensus Participation**: Provides ground truth for validator verification Validator Execution ------------------- When a node acts as a validator: 1. **Deterministic Execution**: Runs consensus logic normally, using leader-provided results 2. **Non-Deterministic Validation**: Executes validator functions to verify leader results 3. **Consensus Voting**: Votes on acceptance of leader-proposed results Validation Strategies --------------------- Multiple validation strategies for non-deterministic results are available Error Handling ============== Error Categories ---------------- Error Fingerprinting -------------------- **Consensus Security**: When WebAssembly execution fails and backtraces are enabled, GenVM automatically generates a cryptographic fingerprint of the memory state to prevent nodes from cheating by skipping actual execution. **Cryptographic Hashing**: Uses BLAKE3 cryptographic hash function to generate deterministic fingerprints of memory regions. **Fingerprint Structure**: **Components**: * **Call Stack Frames**: Module name and function index for each frame in the call stack (0 corresponds to last frame where error occurred) * **Memory Fingerprints**: BLAKE3 hash (32 bytes) of each WebAssembly memory region per wasm module, ordered as wasm memory indexes * **Module Organization**: Fingerprints organized by wasm module instance name **Result Format**: Error results with fingerprints are encoded in Calldata Encoding as: { "message": "", "fingerprint": } **Coverage**: Fingerprinting applies to VMError and UserError results but not InternalError cases. **Anti-Cheating Mechanism**: Error fingerprints provide consensus participants with proof that actual execution occurred up to the point of failure, making it computationally infeasible for malicious nodes to fabricate execution results without performing the actual computation. ### 01-core-architecture/index.txt Core Architecture ***************** Overview of GenVM's core architectural components and design patterns. * *GenVM* Components Overview * Introduction * Architecture Overview * *Sub-VM* Architecture * Overview * WebAssembly Foundation * VM Execution Modes * VM Instance Management * Memory Model * Gas and Resource Metering * Execution Modes * Error Handling ### 02-execution-environment/01-wasm.txt WASM Utilization **************** Enabled WASM Features and Proposals =================================== 1. Core Modules 2. Bulk Memory 3. Sign Extension 4. Mutable Globals 5. Multi Value 6. SIMD 7. Saturating Float to Int Conversions Deterministic Mode Additional Limitations ========================================= Only following "f32.*" and "f64.*" operations are allowed: * "f32.store", "f64.store" * "f32.load", "f64.load" * "f32.const", "f64.const" * "f32.reinterpret_i32", "f64.reinterpret_i64" * "i32.reinterpret_f32", "i64.reinterpret_f64" Any other floating point operation is considered non-deterministic and is not allowed in Deterministic Mode. Non-Deterministic Mode does not have these limitations, allowing all floating point operations. RAM Consumption =============== Each WASM table element imposes *gvm-def-consts-value-memory-limiter- consts-table-entry* RAM Consumption. Each WASM Memory costs length of bytes it has. WASM "memory.grow" instruction which would exceed limit returns -1 ### 02-execution-environment/02-wasip1.txt WASI Preview 1 Implementation ***************************** Overview ======== GenVM implements WebAssembly System Interface (WASI) Preview 1 to provide standardized system-level functionality to WebAssembly modules. The implementation includes modifications for deterministic execution required by blockchain consensus while maintaining compatibility with standard WASI applications. WASI Preview 1 Foundation ========================= Standard Interface ------------------ * **System Calls**: * File system operations (open, read, write, close) * Process management (exit, args, environment) * Time and clock access * Random number generation * Socket and network operations * **Data Types**: * Standard WASI types for file descriptors, time, and sizes * Cross-platform compatibility abstractions * Error code standardization * Memory layout specifications Deterministic Modifications =========================== Time and Randomness Control --------------------------- * **Controlled Time Access**: * Deterministic time functions for consensus requirements * Time zone and locale standardization * **Deterministic Randomness**: * Deterministic randomness for deterministic operations * Cryptographically secure random number generation in non- deterministic mode Regular system interface ------------------------ Virtual File System ~~~~~~~~~~~~~~~~~~~ * Isolated file system namespace per contract execution * Memory-based file system for deterministic behavior * Read-only access to runtime libraries and dependencies * Controlled file system state for reproducible execution Environment Variables ~~~~~~~~~~~~~~~~~~~~~ * Controlled environment variable access * Deterministic environment setup * Security filtering of sensitive variables * Standardized locale and language settings Command Line Arguments ~~~~~~~~~~~~~~~~~~~~~~ * Controlled argument passing to WebAssembly modules * Deterministic argument parsing and validation * Security filtering of dangerous arguments * Standardized argument format and encoding WASI Specification Compliance ============================= * **Interface Compatibility**: * Full compatibility with WASI Preview 1 specification * Standard function signatures and behavior * Compatible error handling and reporting * Consistent data type definitions * **Ecosystem Integration**: * Support for WASI-targeting compilers * Compatibility with existing WASI libraries * Tool chain integration and support * Community standard compliance Always Erroring Operations ========================== Fail with "Acces" error code: * "sock_accept" * "sock_recv" * "sock_send" * "sock_shutdown" Fail with "Rofs" error code: * "fd_allocate" * "fd_fdstat_set_flags" * "fd_fdstat_set_rights" * "fd_filestat_set_size" * "fd_filestat_set_times" * "path_create_directory" * "path_filestat_set_times" * "path_link" * "path_remove_directory" * "path_symlink" * "path_unlink_file" Fail with "Badf" error code: * "path_readlink" Fail with "Notsup" error code: * "poll_oneoff" * "proc_raise" * "sched_yield" * "fd_pwrite" Functions ========= "random_get" Function --------------------- Deterministic mode: mt19937 that is initialized with "GenLayer" as 8 ascii octets. Non-deterministic mode: cryptographically secure random number generator, with optional fallback to pseudo-random numbers, if secure source is exhausted or unavailable. "proc_exit" Function -------------------- 1. "proc_exit(0)" is equivalent to Return of "null" value. 2. "proc_exit(x)" where x \neq 0 results in VMError "path_open" Function -------------------- "path_filestat_get" Function ---------------------------- "fd_readdir" Function --------------------- "fd_tell" Function ------------------ "fd_datasync" Function ---------------------- Does nothing and always returns success. "fd_sync" Function ------------------ Does nothing and always returns success. "fd_seek" Function ------------------ "fd_renumber" Function ---------------------- "fd_prestat_dir_name" Function ------------------------------ "fd_prestat_get" Function ------------------------- 1. If file descriptor does not exist, returns "Badf" error code 2. Returns "Notsup" otherwise "fd_write" Function ------------------- "fd_pread" Function ------------------- "fd_read" Function ------------------ "fd_filestat_get" Function -------------------------- "fd_fdstat_get" Function ------------------------ "fd_close" Function ------------------- "fd_advise" Function -------------------- Does nothing and always returns success. "clock_time_get" Function ------------------------- Returns transaction unix timestamp in **both** modes "clock_res_get" Function ------------------------ Always returns "1" "environ_sizes_get" Function ---------------------------- "environ_get" Function ---------------------- "args_sizes_get" Function ------------------------- "args_get" Function ------------------- Virtual File System =================== Initial State ------------- * *FD* 0 is a file that contains Calldata Encoded extended message * *FD* 1 is "stdout" * *FD* 2 is "stderr" * *FD* 3 is directory "/" (file system root) Deterministic Mode *FD* Allocation and Deallocation =================================================== Pseudocode ---------- allocate() → FD: if free_pool.is_empty(): consume_ram() next_id += 1 allocated.insert(next_id) return next_id else: fd = free_pool.pop() allocated.insert(fd) return fd deallocate(fd: FD): require: fd ∈ allocated allocated.remove(fd) free_pool.push(fd) Allocating a new *FD* implies RAM Consumption of *gvm-def-consts- value-memory-limiter-consts-fd-allocation*. Invariants ---------- 1. \texttt{allocated}\cap\texttt{free_pool} = \emptyset 2. \texttt{next_id} \ge \operatorname{max}(\texttt{allocated}\cup\texttt{free_pool}) 3. All returned descriptors are unique until deallocated Warning: Non-Deterministic Mode is not obligated to follow this pattern ### 02-execution-environment/03-wasi_genlayer_sdk/01-functions.txt Functions ********* "storage_read" ============== Reads data from contract storage at the specified slot and index. Requirements ------------ 1. *Sub-VM* must be in deterministic mode 2. *Sub-VM* must have read storage permission 3. index + buf_len must not overflow "storage_write" =============== Writes data to contract storage at the specified slot and index. Requirements ------------ 1. *Sub-VM* must be in deterministic mode 2. *Sub-VM* must have write storage permission 3. index + buf_len must not overflow 4. *Sub-VM* Storage slot must not be locked, unless the sender is in "upgraders" "get_balance" ============= Queries the balance of a specified contract address. Result value is a 32 octets long little-endian unsigned integer "get_self_balance" ================== Gets the current contract's balance, adjusted for the current transaction context. It is following: balance_before_transaction + message.value - value_consumed_by_current_tx Result value is a 32 octets long little-endian unsigned integer Requirements ------------ * Contract must be in deterministic mode "gl_call" ========= Primary GenLayer WASI SDK function handling most intelligent contract operations. Takes serialized Calldata Encoded message buffer and dispatches to various blockchain operations based on message type. Parameters: "request" (calldata buffer), "request_len" (buffer length), "result_fd" (output file descriptor) Returns * "error_success" on success * "error_inval" for invalid requests * "error_forbidden" for permission violations * "error_inbalance" for insufficient balance See gl_call Messages for the list of available messages. ### 02-execution-environment/03-wasi_genlayer_sdk/02-gl_call.txt "gl_call" Messages ****************** "EthSend" Message ================= Sends transaction to Ethereum address with optional value transfer. Payload ------- { "EthSend": { "address": Address, // 20-byte target address "calldata": Bytes, // EVM calldata "value": U256 // Wei to transfer } } Requirements ------------ 1. deterministic 2. send_messages 3. Sufficient contract balance for value transfer "EthCall" Message ================= Calls Ethereum contract method (read-only operation). Payload ------- { "EthCall": { "address": Address, // 20-byte target contract address "calldata": Bytes // EVM calldata } } Requirements ------------ 1. deterministic 2. call_others "CallContract" Message ====================== Calls another GenLayer Intelligent Contract. Payload ------- { "CallContract": { "address": Address, // 20-byte target contract address "calldata": Calldata, // Method call in calldata format "state": Number // Storage type: 0=default, 1=latest_final, 2=latest_non_final } } Requirements ------------ 1. deterministic 2. call_others Creates new *sub-VM* instance for contract execution. See Permissions for permission inheritance details. "PostMessage" Message ===================== Posts message to GenLayer contract for later execution. Payload ------- { "PostMessage": { "address": Address, // 20-byte target contract address "calldata": Calldata, // Method call in calldata format "value": U256, // Wei to transfer "on": String // "finalized" or "accepted" } } Requirements ------------ 1. deterministic 2. send_messages 3. Sufficient contract balance for value transfer "DeployContract" Message ======================== Deploys new intelligent contract to blockchain. Payload ------- { "DeployContract": { "calldata": Calldata, // Constructor arguments in calldata format "code": Bytes, // Contract bytecode "value": U256, // Wei to transfer "on": String, // "finalized" or "accepted" "salt_nonce": U256 // Salt for CREATE2-style deterministic addressing } } Requirements ------------ 1. deterministic 2. send_messages 3. Sufficient contract balance for value transfer Supports CREATE2-style deployment with salt nonce for deterministic addressing. "RunNondet" Message =================== Executes non-deterministic code with leader/validator consensus. Creates Non-Deterministic Mode VM instance with restricted permissions. See Switching To gvm-def-non-det-mode and Permissions for more details. Payload ------- { "RunNondet": { "data_leader": Bytes, // Code/data for leader execution "data_validator": Bytes // Code/data for validator execution } } Requirements ------------ 1. spawn_nondet "Sandbox" Message ================= Executes code in sandboxed environment with restricted permissions. Payload ------- { "Sandbox": { "data": Bytes, // Code/data for sandbox execution "allow_write_ops": Bool // Whether to allow write operations } } Creates isolated VM instance. See Permissions for permission inheritance details. "WebRender" Message =================== Renders web content using GenVM web module. Payload ------- { "WebRender": { "mode": String, // "text", "html", or "screenshot" "url": String, // URL to render "wait_after_loaded": String // Wait duration, e.g. "5s" or "500ms" } } Requirements ------------ 1. Non-Deterministic Mode execution 2. Web module availability "WebRequest" Message ==================== Makes HTTP requests using GenVM web module. Payload ------- { "WebRequest": { "method": String, // "GET", "POST", "HEAD", "DELETE", "OPTIONS", or "PATCH" "url": String, // Request URL "headers": Map, // String -> Bytes mapping of headers "body": Bytes | null, // Optional request body "sign": Bool // Whether to sign the request (default: false) } } Response -------- { "status": Number, // HTTP status code "headers": Map, // String -> Bytes mapping of response headers "body": Bytes // Response body } Requirements ------------ 1. Non-Deterministic Mode execution 2. Web module availability "ExecPrompt" Message ==================== Executes LLM prompts using GenVM LLM module. Payload ------- { "ExecPrompt": { "response_format": String, // "text" (default) or "json" "prompt": String, // The prompt text "images": Array // Array of image bytes (max 2) } } Requirements ------------ 1. Non-Deterministic Mode execution 2. LLM module availability Supports up to 2 images per prompt. Consumes fuel based on LLM usage. "ExecPromptTemplate" Message ============================ Executes structured LLM prompt templates with type-specific validation. Payload ------- One of the following template types: // Comparative template (expects boolean response) { "ExecPromptTemplate": { "template": "EqComparative", "leader_answer": String, "validator_answer": String, "principle": String } } // Non-comparative validator template { "ExecPromptTemplate": { "template": "EqNonComparativeValidator", "task": String, "criteria": String, "input": String, "output": String } } // Non-comparative leader template { "ExecPromptTemplate": { "template": "EqNonComparativeLeader", "task": String, "criteria": String, "input": String } } Requirements ------------ 1. Non-Deterministic Mode execution 2. LLM module availability Comparative templates expect boolean responses. Non-comparative templates expect text responses. "EmitEvent" Message =================== Emits blockchain events with topics and data. Payload ------- { "EmitEvent": { "topics": Array, // Array of 32-byte topics (max 4) "blob": Map // String -> Calldata mapping of event data } } Requirements ------------ 1. deterministic 2. GenVM version 0.1.5 or higher Topics must be exactly 32 bytes each. "Rollback" Message ================== Deprecated. Use "UserError" instead. "UserError" Message =================== Triggers contract UserError with custom error message. Payload ------- { "UserError": Any // Error message } Causes VM to exit with "UserError". Terminates contract execution immediately. "Return" Message ================ Returns value from contract execution and terminates. Payload ------- { "Return": Calldata // Return value in calldata format } Causes VM to exit with "ContractReturn". Encodes return value using Calldata Encoded format. "Trace.Message" Message ======================= Logs a debug message with timing information including: * Custom message text * Total elapsed time since VM start * Time elapsed since last trace call Payload ------- { "Trace": { "Message": String // Debug message text } } Note: Implementations may choose to ignore this message and return an error. Requirements ------------ 1. GenVM version 0.1.10 or higher 2. *GenVM* implementation is allowed ignore this message "Trace.RuntimeMicroSec" Sub-Message =================================== In Non-Deterministic Mode returns the elapsed execution time in microseconds since VM start. In Deterministic Mode, it always returns "0". Payload ------- { "Trace": "RuntimeMicroSec" } Note: Implementations may choose to ignore this message and return an error. Requirements ------------ 1. GenVM version 0.1.10 or higher 2. *GenVM* implementation is allowed ignore this message ### 02-execution-environment/03-wasi_genlayer_sdk/03-schemas.txt Response Schemas **************** Operations that return data via file descriptor use specific encoding formats based on operation type. Sub-VM Result Encoding ====================== Operations that spawn sub-VMs ("CallContract", "RunNondet", "Sandbox") return results through a file descriptor with the following binary format: [result_code: u8][data: bytes] Where "result_code" is a *gvm-def-enum-result-code*: * *gvm-def-enum-value-result-code-return* ("0"): Successful execution * *gvm-def-enum-value-result-code-user-error* ("1"): Contract- initiated error via "Rollback" * *gvm-def-enum-value-result-code-vm-error* ("2"): VM-level error The "data" portion depends on the result code: * **return**: Calldata Encoded return value * **user_error**: UTF-8 encoded error message string (from "Rollback" message) * **vm_error**: UTF-8 encoded *gvm-def-str-trie-vm-error* string Module Result Encoding ====================== Operations that invoke external modules ("WebRender", "WebRequest", "ExecPrompt", "ExecPromptTemplate") return results as Calldata Encoded data with a success/error wrapper: // On success { "ok": } // On error { "error": } The "" structure depends on the operation: "WebRender" Response -------------------- Returns one of the following based on render mode: // For mode "text" {"ok": {"text": String}} // For mode "html" (returns HTTP response) {"ok": {"response": Response}} // For mode "screenshot" {"ok": {"image": Bytes}} Where "Response" is: { "status": Number, // HTTP status code (u16) "headers": Map, // String -> Bytes mapping "body": Bytes // Response body } "WebRequest" Response --------------------- { "ok": { "status": Number, // HTTP status code (u16) "headers": Map, // String -> Bytes mapping of response headers "body": Bytes // Response body } } "ExecPrompt" Response --------------------- // When response_format is "text" {"ok": String} // When response_format is "json" {"ok": Object} "ExecPromptTemplate" Response ----------------------------- // For EqComparative template (boolean result) {"ok": Bool} // For EqNonComparativeValidator template (boolean result) {"ok": Bool} // For EqNonComparativeLeader template (text result) {"ok": String} Module Error Format ------------------- When a module operation fails, the error is returned as: { "error": } Where "" may contain error details from the module. ### 02-execution-environment/03-wasi_genlayer_sdk/index.txt *GenLayer WASI SDK* WASI Interface ********************************** Overview ======== The *GenLayer WASI SDK* WASI interface provides blockchain-specific functionality to WebAssembly contracts through a custom WASI extension. This interface enables contracts to interact with blockchain state, execute non-deterministic operations, and participate in consensus mechanisms while maintaining security and isolation. Interface Design ================ Throughput-heavy operations are exposed as regular wasm functions. Others functions are hidden behind "gl_call" function, which accepts Calldata Encoded message and returns an error code. Interface Definition ==================== #include static const uint32_t error_success = 0 static const uint32_t error_overflow = 1 static const uint32_t error_inval = 2 static const uint32_t error_fault = 3 static const uint32_t error_ilseq = 4 static const uint32_t error_io = 5 static const uint32_t error_forbidden = 6 static const uint32_t error_inbalance = 7 __attribute__((import_module("genlayer_sdk"))) uint32_t storage_read(char const* slot, uint32_t index, char* buf, uint32_t buf_len); __attribute__((import_module("genlayer_sdk"))) uint32_t storage_write( char const* slot, int32_t index, char const* buf, uint32_t buf_len ); __attribute__((import_module("genlayer_sdk"))) uint32_t get_balance(char const* address, char* result); __attribute__((import_module("genlayer_sdk"))) uint32_t get_self_balance(char* result); __attribute__((import_module("genlayer_sdk"))) uint32_t gl_call(char const* request, uint32_t request_len, uint32_t* result_fd); Backwards Compatibility ======================= Passing invalid request to "gl_call" results in "error_inval". Passing data that turned out to be compatible with future version is filtered out by version limitation. And will result in "error_inval" if method wasn't available at given version * Functions * "storage_read" * "storage_write" * "get_balance" * "get_self_balance" * "gl_call" * "gl_call" Messages * "EthSend" Message * "EthCall" Message * "CallContract" Message * "PostMessage" Message * "DeployContract" Message * "RunNondet" Message * "Sandbox" Message * "WebRender" Message * "WebRequest" Message * "ExecPrompt" Message * "ExecPromptTemplate" Message * "EmitEvent" Message * "Rollback" Message * "UserError" Message * "Return" Message * "Trace.Message" Message * "Trace.RuntimeMicroSec" Sub-Message * Response Schemas * Sub-VM Result Encoding * Module Result Encoding ### 02-execution-environment/04-runners.txt *Runners* ********* *Runners* specify execution environments for GenVM contracts. *Runner* Architecture ===================== Identification and Packaging ---------------------------- Each *runner* is identified by ":". "human- readable-id" is provided for convenience. "hash" is a sha3-256 hash of its contents Hash Format ----------- Hash is SHA3 256-bit hash, converted to a string with following algorithm: def digest_to_hash_id(got_hash: bytes) -> str: chars = '0123456789abcdfghijklmnpqrsvwxyz' bytes_count = len(got_hash) base32_len = (bytes_count * 8 - 1) // 5 + 1 my_hash_arr = [] for n in range(base32_len - 1, -1, -1): b = n * 5 i = b // 8 j = b % 8 c = (got_hash[i] >> j) | (0 if i >= bytes_count - 1 else got_hash[i + 1] << (8 - j)) my_hash_arr.append(chars[c & 0x1F]) return ''.join(my_hash_arr) This ensures that it contains no fs-illegal characters and is case insensitive. Runner Layout ============= For any of the layouts a file list is constructed. Each file in this name has: * a name 1. it must not start with "/" 2. path separator must be "/" 3. it must not contain "." or ".." path components * contents (raw bytes slice) 1. ZIP Archive -------------- Used if runner bytes represent a ZIP archive * If successful, extracts the archive contents and processes it as a structured *runner* package * This format supports complex *runners* with multiple files, dependencies, and configuration * Only allowed compression is "stored" (no compression) 2. Raw WASM ----------- Used if runner bytes represent a wasm file (magic matches) Creates a minimal *runner* configuration version = v0.1.0 runner.json = { "StartWasm": "file" } file = # source bytes 3. Text-based ------------- Used if neither of previous worked. Must be a valid utf-8 encoded string Comment Header Format ~~~~~~~~~~~~~~~~~~~~~ The contract source code must begin with comment lines using one of the supported comment syntaxes: * "//" (C-style comments) * "#" (Shell/Python-style comments) * "--" (SQL/Lua/Haskell-style comments) The comment header consists of: 1. **Version Line** (first comment line): Must start with "v" followed by version information 2. **:term:`Runner` Configuration** (subsequent comment lines): JSON configuration for the *runner* Resulting structure ~~~~~~~~~~~~~~~~~~~ version = # first line if started with version, else default runner.json = # consequent comment lines with removed comment prefix. All whitespaces are kept as-is file = # source bytes Example ~~~~~~~ # v1.0.0 # { # "Depends": "python:latest", # "StartWasm": "python.wasm" # } exit(30) "version" file ============== This file must contain a single line with the version of "genvm" in "v.." format. If this file is not present, the default version is used. "runner.json" File ================== The "runner.json" file defines a recursive structure of initialization actions that configure the execution environment for a contract. Schema is available in runner.json JSON Schema. It must be a valid JSON object with described below structure AddEnv ------ Adds an environment variable to the GenVM environment with variable interpolation support using "${}" syntax. Example ~~~~~~~ { "AddEnv": { "name": "DEBUG", "val": "true" } } MapFile ------- Maps files or directories from an archive to specific paths in the GenVM filesystem. Properties ~~~~~~~~~~ * "file" (string): Path within the archive. If ending with "/", recursively maps all files in the directory * "to" (string): Absolute destination path in the GenVM filesystem Example ~~~~~~~ { "MapFile": { "file": "config/", "to": "/etc/myapp/" } } Creating a single file mapping implies RAM Consumption of 1. *gvm-def-consts-value-memory-limiter-consts-file-mapping*. 2. file name length in octets SetArgs ------- Sets process arguments for the GenVM environment. **Type:** Array of strings Example ~~~~~~~ { "SetArgs": ["exe-name", "--verbose", "--config", "/path/to/config"] } LinkWasm -------- Links a WebAssembly file to make it available in GenVM. **Type:** String (path to WebAssembly file) { "LinkWasm": "path/in/arch/to/module.wasm" } If function _initialize is present, it will be called immediately after linking. StartWasm --------- Starts a specific WebAssembly file in GenVM. **Type:** String (path to WebAssembly file) Example ~~~~~~~ { "StartWasm": "path/in/arch/to/module.wasm" } This is a terminal action in the runner configuration. It results in linking the module and calling "_start" function. Depends ------- Specifies a dependency on another *runner* by its ID and hash. Example ~~~~~~~ { "Depends": "cpython:123" } Dependencies are processed only once, for the first request Seq --- Executes a sequence of initialization actions. { "Seq": [ { "SetArgs": ["exe-name", "--verbose", "--config", "/path/to/config"] }, { "StartWasm": "path/in/arch/to/module.wasm" } ] } When ---- Conditionally executes an action based on WebAssembly execution mode. Properties ~~~~~~~~~~ * "cond": WebAssembly mode, either "det" (deterministic) or "nondet" (non-deterministic) * "action": Action to execute when condition is met Example ~~~~~~~ { "When": { "cond": "det", "action": { "AddEnv": {"name": "MODE", "val": "deterministic"} } } } With ---- Sets a *runner* as current without executing its action, useful for reusing files or creating *runner* locks. Example ~~~~~~~ { "With": { "runner": "base-environment", "action": { "MapFile": {"file": "patched.foo", "to": "foo" } } } } Startup ======= Runner actions are executed left-recursively, until StartWasm is reached. If it was not reached, it will result in a VMError with "error_inval" code. Loading a *runner* implies RAM Consumption of its size in octets. Each loading in a single contract, but different *sub-VM* instances, leads to additional RAM consumption. Deterministic Mode and Non- Deterministic Mode have separate RAM limits. ### 02-execution-environment/index.txt Execution Environment ********************* Runtime environments and language support for GenVM contracts. * WASM Utilization * Enabled WASM Features and Proposals * *gvm-def-det-mode* Additional Limitations * RAM Consumption * WASI Preview 1 Implementation * Overview * WASI Preview 1 Foundation * Deterministic Modifications * WASI Specification Compliance * Always Erroring Operations * Functions * Virtual File System * *gvm-def-det-mode* *FD* Allocation and Deallocation * *GenLayer WASI SDK* WASI Interface * Overview * Interface Design * Interface Definition * Backwards Compatibility * *Runners* * *Runner* Architecture * Runner Layout * "version" file * "runner.json" File * Startup ### 03-vm/01-result.txt VM Execution Result ******************* Result Kinds ============ -[ Return ]- Represents successful execution of a *sub-VM* -[ VMError ]- Represents a VM produced error, such as non-zero exit code or exceeding resource limits. It uses predefined string error codes. -[ UserError ]- Represents a user-produced error in utf-8 format. InternalError ============= It is a special Result Kinds that represents an internal error in the VM, such as: *Host* communication failures or *Module* unavailability. Internal errors are not visible by the contracts. Most likely *Host* will vote *timeout* if encounters such an error Non-Deterministic Block Result Encoding ======================================= * Return: Arbitrary structure in Calldata Encoding * UserError: utf-8 string * VMError: utf-8 string Contract Result Encoding ======================== Return ------ Arbitrary structure in Calldata Encoding UserError and VMError --------------------- Calldata Encoding encoding of { "message": "", "fingerprint": { "frames": [ { "module_name": "", "func": "" } ], "module_instances": { "": { "memories": [ "" ] } } } } For sake of preventing skipping execution for error results, validators are obligated to calculate VM fingerprint on error. Fingerprint is serialized using Calldata Encoding to be deterministic, and has following structure: 1. Frames are ordered from most recent to oldest one (most likely, "_start") 2. Function index is an index of function in WASM module 3. Memories are ordered by their index in WASM module 4. Memories are hashed using BLAKE3 hash function, which is cryptographically secure and provides acceptable performance ### 03-vm/02-sandboxing.txt Sandboxing ********** For the sake of executing prompt-generated code, users are provided with ability to spawn a separate *sub-VM* for executing it. This *sub-VM*: 1. Has the same non-deterministic level as parent *sub-VM* 2. Can not switch into non-deterministic mode 3. Can be configured to be able to update storage (privilege escalation is forbidden) Users can catch both VMError and UserError produced by it, but storage writes can not be reverted ### 03-vm/03-ram-limiting.txt Resource Limiting ***************** Deterministic Mode and Non-Deterministic Mode have two separate RAM budgets. Each budget starts at 4294967295 octets (4 GiB). All *sub-VM* instances within the same mode share the same budget. RAM Consumption =============== Every resource allocation subtracts from the RAM budget of the current VM Execution Modes. When an allocation would cause the remaining budget to become negative, the *sub-VM* exits with VMError with *gvm- def-str-trie-value-vm-error-OOM-RAM* message. The following operations consume RAM: * **WASM memory growth**: each page (65536 octets) costs its size in bytes * **WASM table growth**: each table entry costs *gvm-def-consts-value- memory-limiter-consts-table-entry* octets * **File mapping**: *gvm-def-consts-value-memory-limiter-consts-file- mapping* octets base cost plus the length of the filename in bytes * **File descriptor allocation**: *gvm-def-consts-value-memory- limiter-consts-fd-allocation* octets per descriptor RAM Release =========== File content memory is released when the corresponding file descriptor is closed via "fd_close". When a *sub-VM* finishes execution, all remaining RAM consumed by it is released back to the shared budget. Other Limits ============ In addition to the RAM budget, the following hard limits apply: * Maximum *sub-VM* nesting depth: *gvm-def-consts-value-top-limits-vm- recursion* * Maximum "RunNondet" calls per execution: *gvm-def-consts-value-top- limits-nondet-blocks* * Maximum open file descriptors per *sub-VM*: *gvm-def-consts-value- top-limits-max-fds* * Maximum locked storage slots: *gvm-def-consts-value-top-limits- locked-slots* * Minimum remaining RAM to issue a "WebRequest": *gvm-def-consts- value-top-limits-web-request-min-space* octets * Minimum remaining RAM to issue a "WebRender": *gvm-def-consts-value- top-limits-web-render-min-space* octets Exceeding any of these limits causes the *sub-VM* to exit with VMError. ### 03-vm/04-determinism-mode-switching.txt Switching To Non-Deterministic Mode *********************************** When requesting a non-deterministic execution, new *sub-VM* is created. Leader Mode =========== Returns back Result Kinds produced by *sub-VM* as-is. Sync Mode ========= Returns back leaders result as is. Validator Mode ============== This *sub-VM* must Return a "bool" value, if validator accepts the result of the leader *sub-VM* execution. Any other results have the same effect as producing "bool(false)". Returns back leaders result. ### 03-vm/05-permissions.txt Permissions *********** Each *sub-VM* instance has a set of boolean permissions that control what operations it can perform. Permissions are inherited from the parent VM when spawning child *sub-VM* instances, with certain restrictions applied depending on the context. "deterministic" =============== When set, the VM is executing in Deterministic Mode. Many operations require this permission, including storage writes, sending messages, calling other contracts, and emitting events. "read_storage" ============== Allows reading contract storage slots. When unset, any attempt to read storage will fail with a "Forbidden" error. "write_storage" =============== Allows writing to contract storage slots. Requires deterministic as well. "send_messages" =============== Allows sending messages to other addresses. This permission is required by "EthSend", "PostMessage", and "DeployContract" operations. Requires deterministic as well. "call_others" ============= Allows calling other contracts. This permission is required by "EthCall" and "CallContract" operations. Requires deterministic as well. "spawn_nondet" ============== Allows spawning Non-Deterministic Mode *sub-VM* instances via "RunNondet". Permission Changes on Sub-VM Creation ===================================== Different operations modify permissions when creating child *sub-VM* instances: "CallContract" -------------- Inherits all parent permissions except: * write_storage is **disabled** "RunNondet" ----------- The non-deterministic *sub-VM* has: * deterministic is **disabled** * read_storage is **inherited** * write_storage is **disabled** * spawn_nondet is **disabled** * call_others is **disabled** * send_messages is **disabled** "Sandbox" --------- The sandboxed *sub-VM* has: * deterministic is **inherited** * read_storage is **inherited** * write_storage is **inherited** if "allow_write_ops" is set, otherwise **disabled** * spawn_nondet is **disabled** * call_others is **disabled** * send_messages is **inherited** if "allow_write_ops" is set, otherwise **disabled** ### 03-vm/index.txt VM Specification **************** * VM Execution Result * Result Kinds * InternalError * Non-Deterministic Block Result Encoding * Contract Result Encoding * Sandboxing * Resource Limiting * RAM Consumption * RAM Release * Other Limits * Switching To *gvm-def-non-det-mode* * Leader Mode * Sync Mode * Validator Mode * Permissions * "deterministic" * "read_storage" * "write_storage" * "send_messages" * "call_others" * "spawn_nondet" * Permission Changes on Sub-VM Creation ### 04-contract-interface/01-calldata.txt Calldata Encoding ***************** Calldata is a format used within GenVM to exchange data between contracts and VMs. It is designed to be safe to load, dynamically typed and JSON-like, binary and compact, and supports blockchain specific types. Types ===== Calldata is one of: 1. Arbitrary big integer 2. Raw bytes 3. UTF-8 string 4. Array of Calldata 5. Mapping from strings to Calldata 6. Address (20 bytes) Format ====== ULEB128 Encoding ---------------- "Unsigned little endian base 128" is a variable-length code compression used to store arbitrarily large integers. **Encoding**: Split number into groups of 7 bits, little-endian, zero extend the biggest one. For each except the biggest one (rightmost), set 8th bit to one and concatenate. **Examples**: * 0 ↔ 0x00 * 1 ↔ 0x01 * 128 ↔ 0x80 0x01 Calldata Encoding ----------------- Each calldata value starts with a ULEB128 number, which is treated as follows: +--------------------------+--------------------+-------------------------------+-------------------------------------------------+ | least significant 3 bits | interpreted as | number shifted by this 3 bits | followed by | | | type | | | |==========================|====================|===============================|=================================================| | 0 | atom | 0 ⇒ "null" 1 ⇒ "false" 2 ⇒ | nothing nothing nothing 20 bytes of address | | | | "true" 3 ⇒ followed by | reserved for future use | | | | address _ ⇒ reserved for | | | | | future use | | +--------------------------+--------------------+-------------------------------+-------------------------------------------------+ | 1 | positive int or 0 | "value" | nothing | +--------------------------+--------------------+-------------------------------+-------------------------------------------------+ | 2 | negative int | "abs(value) - 1" | nothing | +--------------------------+--------------------+-------------------------------+-------------------------------------------------+ | 3 | bytes | "length" | "bytes[length]" | +--------------------------+--------------------+-------------------------------+-------------------------------------------------+ | 4 | string | "length" | "bytes[length]" of utf8 encoded string | +--------------------------+--------------------+-------------------------------+-------------------------------------------------+ | 5 | array | "length" | "calldata[length]" | +--------------------------+--------------------+-------------------------------+-------------------------------------------------+ | 6 | map | "length" | "Pair(FastString, calldata)[length]" sorted by | | | | | keys | +--------------------------+--------------------+-------------------------------+-------------------------------------------------+ | 7 | reserved for | | | | | future use | | | +--------------------------+--------------------+-------------------------------+-------------------------------------------------+ **FastString** is encoded as ULEB128 length followed by UTF-8 encoded bytes (difference is that it does not have a type). ### 04-contract-interface/02-abi.txt Application Binary Interface **************************** The GenVM Application Binary Interface defines how contracts expose their functionality to external callers and how different contracts interact with each other. The ABI provides a standardized way to encode method calls, handle parameters, and manage contract schemas while supporting both deterministic and non-deterministic operations. Method Calling Convention ========================= Method calls use Calldata Encoding format with following convention: # deployment { "args": Array | absent, "kwargs": Map | absent, } # not deployment { "method": String | absent "args": Array | absent, "kwargs": Map | absent, } Special Methods =============== All special methods start with a "#" character. Currently there are: * *gvm-def-enum-value-special-method-get-schema* may expose contract schema, that provides definition of existing methods. This method must Return a string containing a JSON object, that follows a schema. * *gvm-def-enum-value-special-method-errored-message* called when execution of an emitted message, that had a value, was not successful ### 04-contract-interface/03-storage.txt Storage System ************** GenVM's storage system provides persistent state management for intelligent contracts. It is language-agnostic. Storage Architecture ==================== 1. Storage is scoped to an address 2. Storage is organized into *Storage Slot*s: blocks of "4294967296" octets (4GB) 3. For given address, each *Storage Slot* has a unique identifier called *SlotID* which is a 32-octet value 4. Reading uninitialized memory returns zeroes 5. Storage is linear, meaning that each slot provides a contiguous block of memory Default Derivation Algorithm ============================ Note: This is a proposed default algorithm, but using it is not mandatory. Consider following structure: x: str y: str Both "x" and "y" may occupy arbitrary amount of space. For that reason variable-length content is stored at an *indirection*: separate *Storage Slot* which *SlotID* is computed based on previous location, using following algorithm: *sha3_256(slot_id, offset_in_slot_as_4_bytes_little_endian)*. This means that that it is: *sha3_256(slot_id, [0, 0, 0, 0])* for "x" and *sha3_256(slot_id, [0, 0, 0, 4])* for "y". 4 is because maximum length of string is bound by 4GB and there is no point in storing it at indirection. Note that any data that uses an indirection must occupy at least one byte in it's residing slot Root Slot ========= *Storage Slot* with *SlotID* of all zeroes is called Root Slot. It uses Default Derivation Algorithm to store the following data: * "contract_instance": (offset 0) Reference to the contract instance data. * "code": (offset 1) The contract's code. Slot contains 4 bytes little-endian length followed by data * "locked_slots": (offset 2) A list of storage *SlotID*s that cannot be modified by non-upgraders. Slot contains 4 bytes little-endian length followed length arrays of 32 byte *SlotID*s * "upgraders": (offset 3) A list of addresses that are authorized to modify the contract code and locked slots. Slot contains 4 bytes little-endian length followed length arrays of 20 byte addresses Upgrade permissions and slot locking is described in Contract Upgradability ### 04-contract-interface/04-upgradability.txt Contract Upgradability ********************** *GenVM* provides a native contract upgradability system that allows contracts to be modified after deployment while maintaining security guarantees and clear access controls. Data that is necessary for this process resides in Root Slot. Upgrade Control Mechanism ========================= The upgrade system works through access control during write transactions: 1. At start of execution *GenVM* reads the "upgraders" list of Root Slot. It does not lead to RAM Consumption 2. If the sender is not in the "upgraders" list of Root Slot, *GenVM* reads "locked_slots" and will prevent writing to them. It implies 32*n RAM Consumption, where n is the number of locked slots. This memory is never released. 3. *GenVM* reads the "code" field of Root Slot and executes it. It causes exactly "code" size in octets RAM Consumption ### 04-contract-interface/05-execution-flow.txt Contract Execution Flow *********************** This document describes the complete execution flow for GenVM contracts, from deployment to method invocation and result processing. The flow involves multiple components working together to provide a seamless contract execution experience. 1. Contract Deployment (if needed) ================================== * *Host* writes contract code to blockchain storage, according to Root Slot definition * Code includes runner specification and dependencies 2. Contract Loading =================== *GenVM* does the following steps: 1. Receives contract address from message 2. Reads contract's locked slots and code from storage 3. Checks upgradability-related data from Contract Upgradability 4. Creates empty VFS, empty arguments list and empty environment variables map 5. Inspects contract runner as in Runners 6. Processes actions until StartWasm is encountered 3. WebAssembly Execution ======================== * GenVM starts WebAssembly *module* with stdin containing Calldata Encoded extended-message * Executes entry point ("_start") with calldata from *host* 4. Contract Entry Point Processing ================================== The contract startup requires specific fields in the Calldata Encoded extended-message: * "entry_kind": Determines execution context * *gvm-def-enum-value-entry-kind-main*: Regular contract entry for standard method calls, "entry_data" contains method call information as described in Method Calling Convention * *gvm-def-enum-value-entry-kind-sandbox*: Contract decides for itself how to handle the payload in "entry_data" * *gvm-def-enum-value-entry-kind-consensus-stage*: Contract decides for itself how to handle the payload in "entry_data" to call validator consensus functions with "entry_stage_data" * "entry_data": Blob of bytes containing method call information * "entry_stage_data": Consensus information for validator nodes * "null" for leader nodes * "{leaders_result: }" for validator nodes Extended-Message Format ----------------------- pub struct ExtendedMessage { pub contract_address: calldata::Address, pub sender_address: calldata::Address, pub origin_address: calldata::Address, /// View methods call chain. /// It is empty for entrypoint (refer to [`contract_address`]) pub stack: Vec, pub chain_id: num_bigint::BigInt, pub value: num_bigint::BigInt, pub is_init: bool, /// Transaction timestamp pub datetime: chrono::DateTime, #[serde(serialize_with = "entry_kind_as_int")] pub entry_kind: public_abi::EntryKind, #[serde(with = "serde_bytes")] pub entry_data: Vec, pub entry_stage_data: calldata::Value, } ### 04-contract-interface/index.txt Contract Interface ****************** Interfaces and protocols for contract interaction and data management. * Calldata Encoding * Types * Format * Application Binary Interface * Method Calling Convention * Special Methods * Storage System * Storage Architecture * Default Derivation Algorithm * Root Slot * Contract Upgradability * Upgrade Control Mechanism * Contract Execution Flow * 1. Contract Deployment (if needed) * 2. Contract Loading * 3. WebAssembly Execution * 4. Contract Entry Point Processing ### appendix/index.txt Appendix ******** * "runner.json" JSON Schema ### appendix/runner-schema.txt "runner.json" JSON Schema ************************* { "$id": "https://raw.githubusercontent.com/yeagerai/genvm/refs/heads/main/doc/schemas/runner.json", "$schema": "http://json-schema.org/draft-07/schema#", "title": "GenVM runner.json", "oneOf": [ { "$ref": "#/definitions/InitAction" } ], "definitions": { "WasmMode": { "enum": ["det", "nondet"] }, "InitAction": { "description": "A single rule for loading.", "type": "object", "allOf": [ { "type": "object", "properties": { "$schema": { "type": "string" } } }, { "oneOf": [ { "required": [ "AddEnv" ] }, { "required": [ "MapFile" ] }, { "required": [ "SetArgs" ] }, { "required": [ "LinkWasm" ] }, { "required": [ "StartWasm" ] }, { "required": [ "Depends" ] }, { "required": [ "Seq" ] }, { "required": [ "When" ] }, { "required": [ "With" ] } ] } ], "properties": { "AddEnv": { "description": "Adds environment variable", "type": "object", "properties": { "name": { "type": "string", "description": "variable name" }, "val": { "type": "string", "description": "variable value, can use ${} to access currently set env variables" } } }, "MapFile": { "description": "Makes file available at specified path in genvm", "type": "object", "properties": { "file": { "type": "string", "description": "path within an archive, if it ends with `/`, it will map all files in that directory recursively" }, "to": { "type": "string", "description": "absolute path in genvm fs" } } }, "SetArgs": { "description": "sets process arguments for genvm", "type": "array", "items": { "type": "string" } }, "LinkWasm": { "description": "Link wasm file to be available from genvm", "type": "string" }, "StartWasm": { "description": "Start wasm file in genvm", "type": "string" }, "Depends": { "description": "Depend on other runner by id:hash", "type": "string" }, "Seq": { "description": "Execute sequence", "type": "array", "items": { "$ref": "#/definitions/InitAction" } }, "When": { "description": "Conditionally execute action", "type": "object", "properties": { "cond": { "$ref": "#/definitions/WasmMode" }, "action": { "$ref": "#/definitions/InitAction" } } }, "With": { "description": "Makes given runner current without executing it's action. It means that MapFile will fork with files from this archive. Useful for creating lock files", "type": "object", "properties": { "runner": { "type": "string" }, "action": { "$ref": "#/definitions/InitAction" } } } }, "additionalProperties": false } } } ### glossary.txt Glossary ******** Calldata GenVM's binary serialization format for exchanging data between contracts and VMs. GenLayer WASI SDK System interface providing blockchain-specific operations and primitives for contracts. GenVM GenLayer's virtual machine that enables Intelligent Contracts with non-deterministic capabilities. Intelligent Contract Smart contract capable of performing non-deterministic operations while maintaining blockchain consensus. Runner Language-specific execution environment that provides runtime support for different programming languages within GenVM. Sub-VM Single WebAssembly virtual machine instance within GenVM. Storage Slot Block of linear memory of length 2^32 octets SlotID 32 octets that identify *Storage Slot* (for given address) FD File descriptor ### index.txt GenVM Specification ******************* Note: Single text file docs for AI This specification describes abstract GenLayer's virtual machine, that runs *Intelligent Contract*s. The specification has been split into multiple sections for better organization and maintainability. Contents: ^^^^^^^^^ * Glossary * Core Architecture * *GenVM* Components Overview * Introduction * Architecture Overview * *Sub-VM* Architecture * Overview * WebAssembly Foundation * VM Execution Modes * VM Instance Management * Memory Model * Gas and Resource Metering * Execution Modes * Error Handling * Execution Environment * WASM Utilization * Enabled WASM Features and Proposals * *gvm-def-det-mode* Additional Limitations * RAM Consumption * WASI Preview 1 Implementation * Overview * WASI Preview 1 Foundation * Deterministic Modifications * WASI Specification Compliance * Always Erroring Operations * Functions * Virtual File System * *gvm-def-det-mode* *FD* Allocation and Deallocation * *GenLayer WASI SDK* WASI Interface * Overview * Interface Design * Interface Definition * Backwards Compatibility * *Runners* * *Runner* Architecture * Runner Layout * "version" file * "runner.json" File * Startup * VM Specification * VM Execution Result * Result Kinds * InternalError * Non-Deterministic Block Result Encoding * Contract Result Encoding * Sandboxing * Resource Limiting * RAM Consumption * RAM Release * Other Limits * Switching To *gvm-def-non-det-mode* * Leader Mode * Sync Mode * Validator Mode * Permissions * "deterministic" * "read_storage" * "write_storage" * "send_messages" * "call_others" * "spawn_nondet" * Permission Changes on Sub-VM Creation * Contract Interface * Calldata Encoding * Types * Format * Application Binary Interface * Method Calling Convention * Special Methods * Storage System * Storage Architecture * Default Derivation Algorithm * Root Slot * Contract Upgradability * Upgrade Control Mechanism * Contract Execution Flow * 1. Contract Deployment (if needed) * 2. Contract Loading * 3. WebAssembly Execution * 4. Contract Entry Point Processing * Appendix * "runner.json" JSON Schema