Skip to content

The backend HTTP server

How testing_backend starts, which caches it keeps, and what happens between an HTTP request and the transaction on chain.

You will learn / You need

You will learn: the startup sequence, the shape of AppState, the three caches, the request path down to execute_transaction_with_retry(), and why every replica owns its own coins. You need: Track A finished (Running a load test), and the HTTP reference for the request and response fields.

Where the code lives

File What it holds
stealth_name_service/backend/testing_backend/src/main.rs The testing_backend binary: request types, AppState, the handlers, cache warming, main().
stealth_name_service/backend/testing_backend/src/aa_handler.rs CoinCache, plus the legacy abstract_account execution path.
stealth_name_service/backend/testing_backend/src/grpc_ext.rs GrpcClientPool, resolve_object_arg_cacheable(), fetch_gas_coins_with_retry(), execute_transaction_with_retry().
stealth_name_service/backend/testing_backend/src/server.rs ExecResp, TxItem, build_exec_response(), extract_gas_coin_ref_from_effects().
stealth_name_service/backend/testing_backend/src/ptb_args.rs, src/pure_args.rs JSON argument encoding. See Building PTBs from JSON.
stealth_name_service/backend/testing_backend/src/backend_log.rs Log levels from BACKEND_DEBUG_LEVEL.

Startup

main() in src/main.rs binds the HTTP server first and warms the coin caches afterwards, in the background. The code comment explains why: warming 1000 agents took 13 s on a healthy node and 50–80 s on a loaded one, and a container that had not opened its port in time was killed by the healthcheck.

flowchart TD
    A["load .env, log level"] --> B["ENABLE_AA?<br/>legacy init"]
    B --> C["two gRPC pools<br/>devnet + testnet"]
    C --> D["load iota.keystore"]
    D --> E["coin_offset from HOSTNAME"]
    E --> F["first NUM_AGENTS key-pair addresses"]
    F --> G["build AppState"]
    G --> H["spawn warm_ptb_caches()"]
    G --> I["bind 0.0.0.0:5000<br/>(or 8443 with TLS)"]
    H --> J["caches_warm = true<br/>/ready answers 200"]
  1. gRPC pools. build_grpc_pool() opens GRPC_POOL_SIZE connections (minimum 1) to https://grpc.devnet.iota.cafe:443 and as many to https://grpc.testnet.iota.cafe:443. GrpcClientPool::get() hands them out round-robin.
  2. Keystore. iota.keystore is read from the working directory.
  3. Replica partition. The first number in HOSTNAME, minus one, is the replica index. The replica's coin_offset is that index times COINS_PER_REPLICA (default 50). With no number in HOSTNAME the replica logs a warning and uses slot 1.
  4. Agents. The backend keeps only keystore addresses backed by a key pair, then the first NUM_AGENTS of them (default 0). Address-only account entries are skipped, so they do not push real agents out of the set.
  5. Server. Actix runs ACTIX_WORKERS workers (default 4), with a backlog of 4096, at most 30000 connections, a 75 s keep-alive, a 30 s request timeout and a JSON body limit of 8192 * 8192 bytes. ENABLE_HTTPS switches to TLS on port 8443.

Deprecated

With ENABLE_AA=true the backend also initialises the legacy abstract_account account from the AA_* variables and registers /api/SendAAPTB. That path is deprecated; use Track C instead: One-time bridge setup. SPONSOR_ADDRESS belongs to the same legacy path (only aa_init reads it); the backend's own preload uses SENDER_ADDRESS.

AppState

One AppState per process, shared by every Actix worker.

Field Type Purpose
iota_client_testnet, iota_client_devnet Arc<GrpcClientPool> Connections to each network. The request's ptb[0].network picks one.
keystore RwLock<FileBasedKeystore> Signs every /api/SendPTB transaction.
gas_coin_semaphore Semaphore of GAS_COIN_SEMAPHORE_SIZE (100) Caps concurrent coin listings on the fallback path.
ptb_coin_caches_testnet, ptb_coin_caches_devnet RwLock<Arc<HashMap<IotaAddress, Arc<CoinCache>>>> One CoinCache per sender. Empty until warming finishes; written once per network.
caches_warm AtomicBool Backs GET /ready.
coin_offset, coins_per_replica usize This replica's coin window.
immutable_object_cache_testnet, immutable_object_cache_devnet ImmutableObjectCache Resolved ["immutable", id] arguments.
aa_account_*, coin_cache_devnet Legacy path only (deprecated).

The caches

Coin caches (CoinCache)

A gas coin is an owned object, and a transaction must name its exact version. CoinCache in src/aa_handler.rs keeps one slot per coin, each holding the full ObjectRef (id, version, digest) behind its own mutex, and a confirmed flag per slot.

  • Loading. preload_n_offset() lists every gas coin of the address, sorts them by object id and keeps [offset, offset + limit). Sorting the full list matters: the node does not list coins in id order, and sorting a truncated prefix gave replicas overlapping windows. An address with no more than offset coins gives this replica an empty cache rather than another replica's coins.
  • First use. get_ref_or_fetch() issues one get_objects RPC the first time a slot is used and marks it confirmed. The startup snapshot may already be stale: another replica, or an earlier run, may have moved the coin.
  • After each transaction. extract_gas_coin_ref_from_effects() in src/server.rs reads the coin's new version and digest out of the effects, and update_ref() writes it back. From then on the slot costs zero RPCs.

warm_ptb_caches() builds the per-agent caches for both networks in parallel, at most PRELOAD_CONCURRENCY (50) listings at a time. It then adds one cache on testnet for SENDER_ADDRESS, the bridge sender, with twice the coins and twice the offset, so replica r owns [r*2N, r*2N + 2N). Agents whose preload fails or finds no coins are logged and left out. caches_warm is set even after a partial warm, so /ready never blocks a run forever.

Immutable object cache (ImmutableObjectCache)

Every bridge request passes the frozen SourceConfig as ["immutable", "0x…"]. Without a cache that is one get_objects RPC per request for an object that never changes. parse_argument_cached() in src/ptb_args.rs caches the resolved ObjectArg per object id, but only when resolve_object_arg_cacheable() reports it safe: a frozen object (its reference never changes) or a shared object (only its fixed initial_shared_version goes into the argument). An owned object is re-resolved every time. The cache is per network and per process.

The fallback path

A sender with no cache entry (warming not finished, address not among the agents, or no coins in this replica's window) takes the slow path. The request waits for a permit of gas_coin_semaphore, then fetch_gas_coins_with_retry() lists all the sender's coins (3 attempts, backoff 100 ms × 2ⁿ), sorts them by id and picks index (coin_offset + request_number % coins_per_replica) % coins. The same offset keeps fallback replicas on separate coins.

The request path

sequenceDiagram
    participant C as Client
    participant H as handle_send_ptb
    participant P as build_ptb_from_calls
    participant K as CoinCache
    participant N as IOTA node
    C->>H: POST /api/SendPTB
    H->>P: ptb[0].calls
    P->>N: object lookups (uncached only)
    P-->>H: ProgrammableTransaction
    H->>K: get_ref_or_fetch(request_number % slots)
    K-->>H: gas ObjectRef
    H->>H: sign with keystore key of auth.address
    H->>N: execute_transaction_with_retry (3 attempts)
    N-->>H: effects, digest, checkpoint height
    H->>K: update_ref(new gas ref)
    H-->>C: 200 ExecResp

execute_ptb_handler() in src/main.rs:

  1. Parses ptb[0].network (testnet or devnet, anything else is an error) and auth.address. Only the first ptb entry is used.
  2. build_ptb_from_calls() turns each call into a MoveCall command, with parse_target(), parse_argument_cached() and parse_type_args().
  3. Stamps send_time_ms and before_network. off_chain_time is the time spent so far.
  4. Picks the gas coin: slot request_number % slots of the sender's cache, or the fallback path.
  5. Builds TransactionData with auth.gas_budget and the fixed GAS_PRICE (1000), signs it with sign_secure() and measures the BCS size.
  6. Times execute_transaction_with_retry() alone (blockchain_processing_time). That function resubmits the same signed transaction up to 3 times, with backoff 200 ms × 2ⁿ, and reads the checkpoint height from the response header.
  7. Writes the new gas reference back into the cache slot.
  8. build_exec_response() fills the response: network_latency is the window from before_network to the end, and pre_submission_time is network_latency − blockchain_processing_time, floored at 0. status is Success or Failure: … from execution_result().

The field list is in the HTTP reference.

Replicas and why caches are per replica

docker-compose.backend.yml runs 10 replicas. Each replica is its own process with its own memory, so nothing it caches is visible to the others. Two replicas that signed against the same coin version would both submit, and one would fail on a version the other had already consumed. The design avoids that by construction rather than by coordination:

  • each replica owns a disjoint window of every sender's coins, derived from its Swarm slot;
  • the window is computed from the full coin list in id order, so every replica sees the same order;
  • the first use of each slot re-reads the coin from chain, so a stale startup snapshot is never signed.

Inside one replica there is no lock held across a submission. Two requests in flight from the same sender whose request_number values are equal modulo the slot count use the same coin. That is why LOADTEST_PIPELINE_DEPTH must not exceed COINS_PER_REPLICA. The relayer's GasPool adds the missing lock; see The event handler.

Failure handling

Situation What happens
Any error before or during submission 500 with {"error": "<message>", "status_code": 500}.
Move abort or other execution failure 200; the failure is in transactions[0].status as Failure: …. The gas reference is still refreshed from the effects.
No coins on the fallback path No gas coins available for sender <address>.
Execution fails after 3 attempts Failed to execute transaction after 3 retries: …. The cached gas reference is not updated.
Effects carry no new gas reference Warning [PTB] Warning: could not refresh cached gas coin ref …; the slot keeps its old reference.
Warming fails for one agent Startup warning; that agent uses the fallback path.

Configuration knobs

All in Configuration: Backend, plus NUM_AGENTS, which the backend also reads to decide how many keystore addresses to warm. Compile-time constants in src/main.rs: GAS_PRICE (1000), GAS_COIN_SEMAPHORE_SIZE (100), PRELOAD_CONCURRENCY (50).

Tests that pin the behaviour

The request path needs a live node, so its unit tests are narrow:

Test File Pins
the_bridge_sample_payload_matches_the_request_type src/main.rs agent/payloads/bridge_request.json still parses as HttpPostPayload, and its pure arguments encode.
type_args_are_parsed_into_the_move_call src/main.rs type_args strings become TypeInputs; a bad one is an error.
immutable_object_id_matches_only_the_immutable_tag src/ptb_args.rs Only ["immutable", id] is a cache candidate.
immutable_object_cache_starts_empty src/ptb_args.rs A fresh cache holds nothing.

CoinCache, warming and the replica partition have no unit tests; they are exercised by load runs.