state.h
Architecture
Asynchronous Execution Model
This module implements an asynchronous state machine for proof generation and verification.
The state object (c4_state_t) is typically part of a context struct (prover_ctx_t or
verify_ctx_t) and manages external data requests that cannot be fulfilled synchronously.
Execution Flow
The main execution function (e.g., c4_prover_execute) is called repeatedly in a loop until
it returns either C4_SUCCESS or C4_ERROR. When external data is needed, the function:
- Creates a
data_request_tand adds it to the state - Returns
C4_PENDINGto signal that data is required - The host system fetches the required data
- The host system calls the execution function again
- The function resumes and processes the now-available data
This design allows the host system to use native async technologies (promises, async/await, futures, etc.) in the language bindings while keeping the C core synchronous and portable.
Request Lifecycle

Host System Implementation
The host system is responsible for executing data requests. When C4_PENDING is returned,
the host system should iterate through all pending requests using c4_state_get_pending_request()
and execute them according to the following rules:
Request Execution
For each data_request_t, the host system must:
-
Select Node: The host system maintains a list of nodes (max 16) for each
data_request_type_t- Beacon API nodes for
C4_DATA_TYPE_BEACON_API - Ethereum RPC nodes for
C4_DATA_TYPE_ETH_RPC - Checkpointz servers for
C4_DATA_TYPE_CHECKPOINTZ - etc.
- Beacon API nodes for
-
Apply Filters:
- Skip nodes where
node_exclude_mask & (1 << node_index)is set - Prefer nodes matching
preferred_client_type(if set, 0 = any client)
- Skip nodes where
-
Build Request:
- Use
methodfield for HTTP method (C4_DATA_METHOD_GET,POST, etc.) - Use
urlfield for the endpoint path (if set) - Use
payloadfor POST body (if set, typically JSON-RPC forC4_DATA_TYPE_ETH_RPC) - Set Content-Type and Accept headers based on
encoding:C4_DATA_ENCODING_JSON: application/jsonC4_DATA_ENCODING_SSZ: application/octet-stream
- Use
-
Execute Request:
- Try the selected node
- On failure: try next available node (respecting exclude mask)
- On success: set
responseandresponse_node_index - If all nodes fail: set
error
-
Caching:
- If
ttlis set (> 0), the response may be cached for the specified duration - Cache key should include request type, URL, and payload
- If
-
Set Result:
- Success: Allocate memory for
response.data, copy data, setresponse.lenandresponse_node_index - Failure: Allocate memory for
errorstring describing the failure - Important: Both
response.dataanderrorwill be freed byc4_state_free()- usemalloc/strdup
- Success: Allocate memory for
Example Implementation
See bindings/emscripten/src/index.ts function handle_request() for a complete TypeScript implementation.
Best Practices
To minimize the number of execution cycles, developers should:
- Collect all required data requests as early as possible in the execution
- Use
TRY_ADD_ASYNCto queue multiple requests before returningC4_PENDING - The host system should fetch all pending requests in parallel when possible
- Cache responses according to
ttlto avoid redundant network requests - Implement smart node selection (e.g., prefer faster nodes, track reliability)
Example Usage
prover_ctx_t* ctx = c4_prover_create("eth_getBlockByNumber", "[\"latest\", false]", chain_id, C4_PROVER_FLAG_INCLUDE_CODE);
// Execute prover in a loop:
data_request_t* data_request = NULL;
bytes_t proof = {0};
while (true) {
switch (c4_prover_execute(ctx)) {
case C4_SUCCESS:
proof = bytes_dup(ctx->proof);
break;
case C4_PENDING:
// Fetch all pending requests (can be done in parallel)
while ((data_request = c4_state_get_pending_request(&ctx->state)))
fetch_data(data_request);
break;
case C4_ERROR:
printf("Error: %s\n", ctx->state.error);
break;
}
}
c4_prover_free(ctx);
Macros for Async Control Flow
The TRY_ASYNC family of macros simplifies error handling and control flow:
TRY_ASYNC(fn): Execute function, return immediately if not C4_SUCCESSTRY_ADD_ASYNC(status, fn): Queue multiple requests, only fail on C4_ERRORTRY_2_ASYNC(fn1, fn2): Execute two functions in parallelTRY_ASYNC_FINAL(fn, cleanup): Always run cleanup regardless of resultTRY_ASYNC_CATCH(fn, cleanup): Run cleanup only on failure
These macros handle the repetitive pattern of checking status codes and allow the developer to focus on the business logic.
data_request_type_t
Defines the type of data source for a request.
typedef enum {
C4_DATA_TYPE_BEACON_API = 0, ///< Request is handled by the Beacon API
C4_DATA_TYPE_ETH_RPC = 1, ///< Request is handled by the Ethereum RPC
C4_DATA_TYPE_REST_API = 2, ///< Request is handled by a generic REST API
C4_DATA_TYPE_INTERN = 3, ///< Request is handled internally within the prover server
C4_DATA_TYPE_PROVER = 4, ///< Request is handled by the prover server
C4_DATA_TYPE_CHECKPOINTZ = 5, ///< Request is handled by a checkpointz server
C4_DATA_TYPE_CACHE = 6 ///< In-process snapshot of locally cached data; `id` identifies the entry, `response` carries the cached bytes (no I/O)
} data_request_type_t;
data_request_encoding_t
Defines the encoding format for request/response data.
typedef enum {
C4_DATA_ENCODING_JSON = 0, ///< Data is encoded in JSON format
C4_DATA_ENCODING_SSZ = 1 ///< Data is encoded in SSZ (Simple Serialize) format
} data_request_encoding_t;
data_request_method_t
HTTP methods for data requests.
typedef enum {
C4_DATA_METHOD_GET = 0, ///< HTTP GET method
C4_DATA_METHOD_POST = 1, ///< HTTP POST method
C4_DATA_METHOD_PUT = 2, ///< HTTP PUT method
C4_DATA_METHOD_DELETE = 3 ///< HTTP DELETE method
} data_request_method_t;
c4_status_t
Status codes for asynchronous operations.
typedef enum {
C4_SUCCESS = 0, ///< Operation completed successfully
C4_ERROR = -1, ///< Operation failed with an error
C4_PENDING = 2 ///< Operation is pending and requires external data
} c4_status_t;
data_request_t
Represents a single asynchronous data request in the state machine.
This structure encapsulates all information needed to make, track, and retry external data requests. Requests can be to various data sources (Beacon API, Eth RPC, etc.) and support retry logic with node exclusion.
typedef struct data_request {
chain_id_t chain_id; ///< The blockchain chain ID for this request. The creator copies it from the prover, verifier, or RPC context. For `C4_DATA_TYPE_ETH_RPC` the host selects the RPC list for this chain. `0` means the creator did not set it and is not a valid routing key.
data_request_type_t type; ///< Type of data source (Beacon API, Eth RPC, etc.)
data_request_encoding_t encoding; ///< Encoding format for request/response (JSON or SSZ)
char* url; ///< URL endpoint for the request (may be NULL for RPC)
data_request_method_t method; ///< HTTP method to use (GET, POST, etc.)
bytes_t payload; ///< Request payload data (e.g., for POST requests)
bytes_t response; ///< Response data received from the request
uint16_t response_node_index; ///< Index of the node that responded with the result
uint16_t node_exclude_mask; ///< Bitlist marking nodes to exclude when retrying (bit 0 = index 0, max 16 nodes)
uint32_t preferred_client_type; ///< Preferred beacon client type bitmask (0 = any client)
char* error; ///< Error message if request failed (NULL if no error)
struct data_request* next; ///< Pointer to next request in linked list
bytes32_t id; ///< Unique identifier for this request (32-byte hash)
uint32_t ttl; ///< Cache time-to-live in seconds (0 = not cacheable). Used server-side to cache the response (e.g. memcached) and forwarded by hosts as a `Cache-Control: max-age=<n>` request header so a shared cache/CDN never returns a response older than this bound (e.g. short bound for `latest` block proofs).
uint32_t delay; ///< Milliseconds the host must wait before (re-)executing this request (0 = no delay). Used for delayed same-node retries (e.g. oblivious node warm-up, or an Arbitrum header the feed already signed but the execution node has not imported). The HTTP server waits on a libuv timer and does not block its event loop. Bindings and the CLI sleep before issuing the request.
uint16_t retry_count; ///< Number of delayed *same-node* retries already performed (see `c4_state_retry_after`); managed by the chain module, not the host
bool validated; ///< Whether the response has been validated
} data_request_t;
c4_state_t
Global state container for asynchronous operations.
Contains all pending data requests and accumulated error messages. Used by the async state machine to track operations that require external data.
typedef struct c4_state {
data_request_t* requests; ///< Linked list of data requests (NULL if no requests)
char* error; ///< Accumulated error messages (NULL if no errors)
} c4_state_t;
c4_state_free
Frees all resources associated with a state object.
Releases all memory allocated for data requests, URLs, payloads, responses, and error messages. Safe to call with partially initialized state objects.
void c4_state_free(c4_state_t* state);
Parameters
state: Pointer to the state object to free
c4_request_free
Frees all resources associated with a data request.
Releases all memory allocated for the request URL, error message, payload, and response. Safe to call with partially initialized requests. Only use it if this is not associated with a state object, since it will not free the request from the state object.
void c4_request_free(data_request_t* req);
Parameters
req: Pointer to the request to free
c4_append_prover_request_props
Appends common remote-prover JSON fields to an open object (after method / params).
Writes: ,"version", optional ,"c4", optional zk_proof, include_code, signers,
optional last_block_hash and, for Arbitrum, optional batch_poster. Caller must
finish the JSON object with }.
to fall back to `c4_get_client_state` of the L1 chain (legacy behaviour)
also reads `batch_poster_<chain_id>` and appends it while
`current_unix_ms() - timestamp <= C4_BATCH_POSTER_MAX_AGE_MS`
verified and cached; allows the prover to omit the block proof
(`blockHash` union variant). Pass `NULL_BYTES` to omit the field.
void c4_append_prover_request_props(buffer_t* payload, bytes_t client_state, chain_id_t chain_id, uint32_t flags, bytes_t witness_key, bytes_t last_block_hash);
Parameters
payload: growable buffer; current content must not include the closing}client_state: pre-captured snapshot of the chain's client_state; passNULL_BYTESchain_id: client chain. Thec4fallback usesc4_get_l1_chain_id_for_l2. Arbitrumflags: bitmask usingC4_PROVER_REQ_FLAG_*(same bit layout asprover_flags_t)witness_key: witness bytes forsigners(may beNULL_BYTES)last_block_hash: 32-byte hash of the newest execution block header the client has
c4_state_get_data_request_by_id
Finds a data request by its unique identifier.
Performs a linear search through the request list to find a request with the matching 32-byte ID.
data_request_t* c4_state_get_data_request_by_id(c4_state_t* state, bytes32_t id);
Parameters
state: Pointer to the state objectid: 32-byte identifier to search for
Returns
Pointer to the matching request, or NULL if not found
c4_state_get_data_request_by_response
Finds a data request whose response pointer matches the given bytes.
Used to attach validated to the request that produced a consumed buffer
without changing every consume-function signature.
data_request_t* c4_state_get_data_request_by_response(c4_state_t* state, bytes_t response);
Parameters
state: Pointer to the state objectresponse: Response bytes (matched bydatapointer, not contents)
Returns
Pointer to the matching request, or NULL if not found
c4_state_cache_get
Gets a C4_DATA_TYPE_CACHE snapshot from the request list.
Walks the request list and matches only C4_DATA_TYPE_CACHE entries with a
non-empty response. A real I/O request that happens to share the same id
is skipped (unlike c4_state_get_data_request_by_id, which returns the first
id match regardless of type).
bytes_t c4_state_cache_get(c4_state_t* state, bytes32_t key);
Parameters
state: Pointer to the state objectkey: 32-byte identifier to search for
Returns
The cached bytes, or NULL_BYTES if not found
c4_state_cache_set
Stores a C4_DATA_TYPE_CACHE snapshot in the request list.
Replaces the response of an existing cache entry with the same id. If the
id belongs to a non-cache request, a new cache entry is appended at the
end of the list instead of overwriting the I/O request. Appending keeps
c4_state_get_data_request_by_id pointing at the I/O request (first match).
Callers that want the snapshot must use c4_state_cache_get.
Ownership of value.data transfers to the state (freed by c4_state_free).
bytes_t c4_state_cache_set(c4_state_t* state, bytes32_t key, bytes_t value);
Parameters
state: Pointer to the state objectkey: 32-byte identifier to store the value undervalue: The value to store
Returns
The stored value
c4_state_get_data_request_by_url
Finds a data request by its URL.
Performs a linear search through the request list to find a request with the matching URL string.
data_request_t* c4_state_get_data_request_by_url(c4_state_t* state, char* url);
Parameters
state: Pointer to the state objecturl: URL string to search for
Returns
Pointer to the matching request, or NULL if not found
c4_state_is_pending
Checks if a request is still pending.
A request is considered pending if it has no error and no response data yet.
bool c4_state_is_pending(data_request_t* req);
Parameters
req: Pointer to the request to check
Returns
true if pending, false if completed or failed
c4_state_retry_after
Schedules a delayed retry of a request on the same node.
Unlike RETRY_REQUEST, this does not set node_exclude_mask: the request
is meant to hit the same endpoint again after a short pause (e.g. an oblivious
TEE node that needs a few seconds to make the requested state available).
On success the response and error are cleared, delay is set and
retry_count is incremented, so the host re-executes the request after
waiting delay_ms milliseconds. The retry budget is bounded by max_retries
to avoid endless loops.
if (eth_is_oblivious_unavailable(response) &&
!c4_state_retry_after(req, eth_oblivious_retry_delay(req->chain_id, req->retry_count), ETH_OBLIVIOUS_MAX_RETRIES))
THROW_ERROR("oblivious node did not provide the proof in time");
bool c4_state_retry_after(data_request_t* req, uint32_t delay_ms, uint16_t max_retries);
Parameters
req: Pointer to the request to retrydelay_ms: Milliseconds the host should wait before re-executingmax_retries: Maximum number of delayed retries allowed
Returns
true if a retry was scheduled, false if the retry budget is exhausted
c4_chain_request_id
Builds a 32-byte request id bound to one chain.
The chain id is prefixed to material before hashing, so the same payload
on two chains does not share one data_request_t. material is not modified.
void c4_chain_request_id(bytes32_t out, chain_id_t chain_id, bytes_t material);
Parameters
out: 32-byte id written by this functionchain_id: chain that owns the requestmaterial: payload or URL that identifies the request on that chain
c4_state_add_request
Adds a new data request to the state.
Automatically generates a unique ID for the request if not already set (hash of payload or URL). Adds the request to the front of the linked list.
void c4_state_add_request(c4_state_t* state, data_request_t* data_request);
Parameters
state: Pointer to the state objectdata_request: Pointer to the request to add (ownership transfers to state)
c4_state_get_pending_request
Gets the first pending request from the state.
Searches through the request list and returns the first request that is still pending (has no error and no response).
data_request_t* c4_state_get_pending_request(c4_state_t* state);
Parameters
state: Pointer to the state object
Returns
Pointer to the first pending request, or NULL if none pending
c4_state_add_error
Adds an error message to the state.
Appends the error message to any existing error messages, separated by newlines. Handles NULL error parameter gracefully by using a generic message.
c4_status_t c4_state_add_error(c4_state_t* state, const char* error);
Parameters
state: Pointer to the state objecterror: Error message to add (can be NULL)
Returns
Always returns C4_ERROR
c4_state_take_requests
Moves all pending data requests from src to dst.
Appends dst's existing request list to the tail of src's request list and then
transfers ownership of the resulting list to dst. src->requests is set to NULL.
Use this when forwarding requests from a temporary sub-context (e.g. a nested
verify_ctx_t used for PAP sub-proofs) to its parent so the host can fulfil them.
No-op when src->requests is NULL.
void c4_state_take_requests(c4_state_t* dst, c4_state_t* src);
Parameters
dst: Destination state (receives the merged request list)src: Source state (request list is detached)
if
Helper function to set the error message safely, handling memory ownership. This avoids "use after free" issues in macros where the old error is read while formulating the new one.
static inline c4_status_t c4_state_set_error_msg(c4_state_t* state, char* msg) {
if (state->error) safe_free(state->error);
=
Static inline helpers for JSON validation macros to avoid static analyzer warnings. These functions handle memory ownership of the validation error string.
static inline c4_status_t c4_check_json_inline(c4_state_t* state, json_t val, const char* def, const char* prefix) {
char* err = (char*) json_validate(val, def, prefix);
c4_req_mockname
Generates a mock filename for a request (test mode only).
Creates a sanitized filename based on the request URL or payload, suitable for storing mock responses. Characters that are invalid in filenames are replaced with underscores.
Note: Only available when compiled with TEST flag.
char* c4_req_mockname(data_request_t* req);
Parameters
req: Pointer to the data request
Returns
Allocated string with the mock filename (caller must free)