Skip to content

The event handler

How event_handler turns forwarded events into destination transactions: the queue, the workers, batching, the gas pool, acknowledgements and the rows in bridge_results.csv.

You will learn / You need

You will learn: the startup checks, the two modes, how a batch is built and submitted, how gas coins are claimed and retired, how the third phase is sent, and where each CSV timing comes from. You need: Track B or Track C finished (The static relayer, Sending bridge requests), and the listener deep dive.

Where the code lives

File What it holds
stealth_name_service/backend/testing_backend/src/bin/event_handler.rs The binary: config, HTTP routes, queue, workers, GasPool, submit_batch(), acknowledgements, CSV.
stealth_name_service/backend/testing_backend/src/bridge/event.rs intent_from_event(), request_id_from_event(), append_intent_call().
stealth_name_service/backend/testing_backend/src/bridge/intent.rs CrossChainIntent, encode(), signing_message().
stealth_name_service/backend/testing_backend/src/bridge/signer.rs IntentSigner: raw ed25519 or secp256k1 signatures over the intent message.
stealth_name_service/backend/testing_backend/src/bridge/aa.rs BridgeAaAccount: on-chain checks, build_transaction(), submit().
stealth_name_service/backend/testing_backend/src/consensus/auth.rs DeliveryKey: HMAC check of committee deliveries.

Modes

EVENT_HANDLER_MODE selects how an event becomes a call.

static (default) bridge
Call Fixed EVENT_HANDLER_TARGET with EVENT_HANDLER_ARGS_JSON The call the event's intent describes
Sender EVENT_HANDLER_SIGNER from the keystore The BridgeAA account
Authorisation Keystore signature (sign_secure) bridge_authenticator checks relayer signatures on chain
Events per transaction 1 Up to BATCH_SIZE
Acknowledgement Never When BRIDGE_PROTOCOL_PHASES=3

BRIDGE_PROTOCOL_PHASES=3 without bridge mode is a startup error.

Startup

main() refuses to start on any configuration it can detect as wrong, so a run fails at boot rather than one event at a time.

flowchart TD
    A["read env"] --> B{"CONSENSUS_ENABLED?"}
    B -- yes --> C["DeliveryKey::from_env()"]
    B -- no --> D
    C --> D["signer in keystore?"]
    D --> E{"mode"}
    E -- bridge --> F["build_bridge_config()<br/>chain id + ACL checks"]
    E -- static --> G
    F --> G{"phases = 3?"}
    G -- yes --> H["build_ack_config()<br/>ack gas pool"]
    G -- no --> I
    H --> I["GasPool::preload()<br/>destination coins"]
    I --> J["remove bridge_results.csv"]
    J --> K["spawn iota_worker"]
    K --> L["bind 0.0.0.0:5000"]

build_bridge_config() resolves BRIDGE_AA_ACCOUNT_ID with BridgeAaAccount::resolve() and checks two things against the live object: the account's chain id equals BRIDGE_TARGET_CHAIN_ID, and the ACL holds an entry for (BRIDGE_SOURCE_CHAIN_ID, the relayer's address). Either failure would make every transaction abort in the authenticator (EWrongTargetChain, ESenderNotInAcl), so it stops startup.

build_ack_config() does the same for the return leg: it reads EVENT_LISTENER_PACKAGE_ID (the only place the handler uses it) and, for BRIDGE_ACK_SIGNER=aa, checks the source-side account's chain id and its ACL entry for (target chain id, destination BridgeAA address). It preloads a second gas pool on the source network; zero coins is an error.

In bridge mode, a BridgeAA that owns no gas coins is an error (BridgeAA … owns no gas coins…). Fewer coins than EVENT_HANDLER_CONCURRENCY is a warning.

Queue and workers

sequenceDiagram
    participant S as sender (listener or committee)
    participant H as HTTP route
    participant Q as mpsc queue
    participant W as iota_worker
    participant B as submit_batch task
    S->>H: POST /api/handle_event
    H->>Q: try_send(EventPayload)
    alt queue has room
        H-->>S: 202 queued
    else full
        H-->>S: 429 overloaded
    end
    W->>Q: recv_many(buf, batch_size)
    W->>W: acquire semaphore permit
    W->>B: spawn with gas_slot
    B->>B: build, sign, submit, ack
    B->>B: write_bridge_records()
  • The queue is a bounded mpsc channel of QUEUE_CAPACITY (150000).
  • One iota_worker task drains it. recv_many() returns as soon as at least one event is ready, up to batch_size (BATCH_SIZE in bridge mode, 1 in static mode). Batches are not padded or delayed.
  • A Semaphore of EVENT_HANDLER_CONCURRENCY (default 8) limits batches in flight. Each batch runs in its own task.
  • Each batch gets the next gas_slot from a counter and a block of request numbers.

From event to call: append_call()

  • Static. parse_target() and parse_argument() build the fixed call. The event content is ignored.
  • Bridge. intent_from_event() in src/bridge/event.rs reads the event's parsed_json into a CrossChainIntent. It refuses an event whose source_chain_id is not the configured source chain or whose target chain is not this relayer's, before anything is signed. The handler then signs signing_message(aa.address(), intent.encode()) with IntentSigner and appends the call with append_intent_call(). The call's inputs are the intent's argument bytes, passed verbatim as pure inputs, so the authenticator's byte comparison succeeds.

The signing message is the domain tag bridge_abstract_account::CrossChainIntent::v1, then the 32-byte account address, then the BCS intent. The Move packages shows the Move side.

Submitting a batch: submit_batch()

flowchart TD
    A["batch of events"] --> B["append_call() per event"]
    B -- "error" --> R1["row: build_call"]
    B --> C["budget = gas_budget × included"]
    C --> D{"GasPool::claim()"}
    D -- none --> R2["rows: no_gas"]
    D -- coin --> E["submit<br/>(3 attempts)"]
    E -- error --> R3["retire or refresh coin<br/>rows: execute_retry_exhausted"]
    E -- effects --> F["update coin ref"]
    F --> G{"status"}
    G -- failure --> R4["rows: on_chain_revert"]
    G -- success --> H["release coin"]
    H --> I{"3 phases?"}
    I -- yes --> J["submit_ack_batch()"]
    I -- no --> K["rows: success"]
    J --> K

Every event that failed append_call() is dropped from the batch and gets its own build_call row. The rest share one transaction. The budget is LOADTEST_GAS_BUDGET_BRIDGE (default 5000000) times the number of events included, not times BATCH_SIZE.

Static mode signs with sign_secure() and calls execute_transaction_with_retry(). Bridge mode calls bridge_aa::submit(), which builds a MoveAuthenticator with two pure inputs (the BCS intents and the BCS signatures) and the BridgeAA object, and executes it with the same retry helper.

The failure_stage column records where a row failed:

failure_stage When
build_call The event could not become a call: bad JSON, chain mismatch, signing error.
no_gas Every coin in the pool is retired, or the coin's reference could not be read.
execute_retry_exhausted Submission failed three times.
on_chain_revert The transaction executed and failed, for example an authenticator abort.

The gas pool (GasPool)

GasPool wraps the backend's CoinCache and adds what the backend lacks: one async lock per coin, held from claim until the effects are in, and a retired flag per coin.

stateDiagram-v2
    [*] --> Live: preload
    Live --> Claimed: claim() locks it
    Claimed --> Live: effects update ref
    Claimed --> Retired: balance below budget
    Live --> Retired: retire_underfunded() at start
    Retired --> [*]
Function Behaviour
GasPool::preload() Loads EVENT_HANDLER_GAS_COINS (default 1000) coins with CoinCache::preload_n().
retire_underfunded() At worker start, retires every coin that cannot pay one full batch (gas_budget × BATCH_SIZE).
pick() / pick_live() The k-th live coin, k = gas_slot % live. A retired block does not push its load onto one neighbour.
claim() Tries up to len coins from pick(), takes the first whose lock is free and that is still live.
refresh() Re-reads the coin from chain after a failed submit.
disable() Retires a coin; logs gas coin drained below budget -- retiring it….

On a submission error the handler decides whether the coin is to blame. parse_gas_shortfall() reads Balance of gas object X is lower than the needed amount: Y; gas_failure_retires_coin() retires the coin only if its balance is below the retirement threshold, or if the message cannot be parsed. An execution that ran out of gas blames the budget, not the coin (is_execution_out_of_gas()), and is logged as DEST GAS or ACK GAS on powers of ten (1, 10, 100, …) so a long run does not flood the log.

The source comment on gas_failure_retires_coin() says (event_handler.rs:693) that max_auth_gas caps a BridgeAA batch at 2 intents. The code enforces no cap, so a larger BATCH_SIZE is accepted at startup. In practice, batches of more than 2 intents have failed on max gas. The exact limit likely depends on the IOTA network and on the transaction type. Start BridgeAA runs with BATCH_SIZE=2, and raise it only after a test run succeeds. See Gas coins.

Acknowledgements (third phase)

With BRIDGE_PROTOCOL_PHASES=3, a successful destination transaction is followed by one acknowledgement transaction on the source chain for the whole batch. The destination coin is released first.

ack_intent() builds the return intent with the chain ids inverted (source = destination chain, target = source chain) and three arguments: BCS of the target chain id, of the request_id, and of the destination digest as ASCII bytes. Only events whose request_id parses as an address are acknowledged.

BRIDGE_ACK_SIGNER AckMode Transaction
eoa (default) Eoa Relayer key signs; one bridge_source::acknowledge call per event, with the frozen SourceConfig (BRIDGE_SOURCE_CONFIG_ID).
aa Aa A source-side BridgeAA sends one acknowledge_pure call per event, each backed by a signed intent.

submit_ack_batch() claims a coin from the ack pool with the same gas_slot, uses BRIDGE_ACK_GAS_BUDGET (default 2000000) per event, and retires or refreshes like the destination path. A failed acknowledgement logs acknowledgement batch failed; destination calls are still recorded as successful. The ack columns (ack_tx_digest, ack_off_chain_time, ack_blockchain_processing_time, ack_client_receive_time_ms, total_3phase_time_seconds) stay empty; only ack_signer is filled. The destination row stays successful. See Acknowledgements.

Committee deliveries

With CONSENSUS_ENABLED, /api/handle_event accepts only signed deliveries (handle_committee_delivery()):

Check Failure
A DeliveryGate exists 500 committee gate not configured
x-committee-signature is a valid HMAC-SHA256 of the body under CONSENSUS_DELIVERY_KEY 403
Body parses as an event 400 delivery body is not an event
Body carries committee metadata 400 delivery has no consensus metadata
SHA-256 of the body not yet seen 202 duplicate (not queued again)

A delivery that is refused with 429 is forgotten again, so the committee's retry is accepted later. The digests live in a RecentSet of RECENT_CAPACITY (1000000). See The committee.

Rows in bridge_results.csv

RecordContext stamps each event and submit_batch() fills the row. Times are milliseconds since the epoch, durations in seconds unless the column says _ms.

Column How it is computed
detection_lag_ms detected_at_ms − source_event_timestamp_ms. A missing detected_at_ms falls back to the worker start. A missing source timestamp counts as 0, so the column holds the whole detection time in epoch milliseconds (a huge value), not 0.
queue_residency_ms Worker start − enqueued_at_ms.
network_latency Receive − send of the destination transaction.
pre_submission_time network_latency − blockchain_processing_time, floored at 0.
total_bridge_time_seconds Destination receive − source event time.
total_3phase_time_seconds Ack receive − source event time.
tx_count Events in the transaction.
gas columns Of the whole transaction, not per event.

write_bridge_records() writes one batch under one lock and one file open; the header is written once. csv_quoted() doubles embedded quotes. With consensus on, CONSENSUS_CSV_COLUMNS are appended. Column meanings are in the CSV reference.

Configuration knobs

Group Link
Mode, signer, network, concurrency, batch size, gas coins Event handler
BRIDGE_AA_*, chain ids Bridge account
BRIDGE_PROTOCOL_PHASES, BRIDGE_ACK_* Acknowledgement
CONSENSUS_ENABLED, CONSENSUS_DELIVERY_KEY Consensus committee

Compile-time constants: QUEUE_CAPACITY (150000), GAS_PRICE (1000), DEFAULT_CONCURRENCY (8), DEFAULT_BATCH_SIZE (100), DEFAULT_GAS_COINS (1000).

Tests that pin the behaviour

In src/bin/event_handler.rs:

Area Tests
Config network_flip_is_its_own_inverse, protocol_phases_parses_two_and_three_only, ack_mode_labels_are_stable
Timing record_context_extracts_request_id_from_the_event, record_context_computes_detection_lag_from_the_event_not_the_worker_clock, record_context_queue_residency_is_worker_start_minus_enqueued, failure_record_always_reports_not_successful_with_no_ack_fields
Acknowledgement ack_intent_args_are_the_exact_bcs_the_call_receives, ack_intent_chain_ids_are_inverted_not_copied, ack_intent_ptb_inputs_are_byte_identical_to_the_signed_args, ack_pool_check_flags_an_unusable_or_short_pool
Gas pool pick_is_round_robin_over_a_healthy_pool, pick_skips_retired_coins_without_remapping_the_pool, a_block_of_retired_coins_does_not_funnel_onto_its_neighbour, pick_returns_none_only_when_every_coin_is_drained, a_coin_above_the_threshold_survives_a_shortfall, an_execution_out_of_gas_blames_the_budget_not_the_coin, out_of_gas_alarm_logs_on_powers_of_ten, a_coin_that_cannot_fund_a_full_batch_is_retired, only_a_drained_coin_is_retired_everything_else_is_repaired
CSV csv_fields_with_embedded_quotes_stay_one_field, csv_header_is_unchanged_without_consensus, consensus_rows_are_as_wide_as_their_header, consensus_rows_parse_with_the_header
Deliveries payload_parses_with_and_without_committee_metadata, with_consensus_enabled_only_signed_deliveries_are_executed, a_resent_delivery_is_executed_once, a_delivery_refused_for_a_full_queue_is_taken_again_later, without_consensus_direct_events_are_accepted_as_before

In src/bridge/event.rs: decodes_the_reference_event, decoded_event_reproduces_the_golden_intent_bytes, rejects_an_event_from_another_source_chain, rejects_an_event_bound_for_another_target_chain, ptb_inputs_are_the_signed_bytes_verbatim, repeated_arguments_share_one_input_but_keep_their_positions, and others. In src/bridge/intent.rs: encode_matches_the_move_decoder_layout, signing_message_prepends_raw_tag_and_raw_address. In src/bridge/signer.rs: ed25519_signature_verifies_over_the_raw_message, secp256k1_signature_verifies_over_the_sha256_digest, secp256r1_keys_are_rejected_up_front. In src/bridge/aa.rs: intent_slice_encodes_as_a_move_vector_of_byte_vectors, acl_key_encodes_as_u64_then_address, and the ignored live test bridge_aa_prechecks_match_a_live_devnet_account.