Introducing a new way to review your PRs.

Read the announcement

near / nearcore

Reference client for NEAR Protocol

View on GitHub

20 documents · Updated Nov 23, 2026

docs / node-client-services

Node client services

The node-facing client layer keeps a NEAR node aligned with the chain and makes that state usable by the network and external callers. It coordinates chain progression, block and transaction work, read access, synchronization, archival data, and execution-related services while the runtime and storage provide chain rules and durable state. For process construction and shutdown, see Node startup and lifecycle. For public request and stream surfaces, see RPC and indexing services.

Client layer

The client layer separates chain decisions from the asynchronous work that keeps a node moving. The synchronous Client owns chain-facing state. The ClientActor provides the event and timer boundary that connects network input, synchronization, production, and downstream services (chain/…/client_actor.rs• L161-288, chain/…/client_actor.rs• L302-362).

Chain client

The chain client advances the local protocol view. It accepts blocks, approvals, optimistic blocks, and completed shard work. It asks chain and runtime services to validate or apply that work, then exposes the resulting head changes to services that depend on accepted blocks. It also holds the node's transaction pools, pending transaction constraints, shard tracking, and synchronization state (chain/…/client.rs• L115-196, chain/…/pending_transaction_queue.rs• L34-102).

Transaction envelopes can contain signed transactions or unsigned external contract calls. The client removes and restores envelopes by their stable transaction identity, while pending transaction accounting currently includes only signed transactions. This keeps external-call pool and reorganization identity distinct from the signed-transaction cost rules that are not yet extended to those calls (chain/…/client.rs• L545-640, chain/…/pending_transaction_queue.rs• L202-280).

The client records limited proof that a peer reached a height. It uses that proof when the node is current enough to know the validator set. This keeps an unverified peer claim from selecting an unsafe synchronization target (chain/…/client.rs• L1229-1253, chain/…/verified_peer_heights.rs• L8-71, chain/…/peers.rs• L36-49).

When a chunk is invalid under SPICE, the client keeps evidence of the invalid chunk instead of creating a fake empty body. This lets SPICE continue with empty execution input while preserving the header's commitment for later checks (chain/…/client.rs• L1648-1680).

References: chain/…/client.rs• L115-196 chain/…/client.rs• L545-640 chain/…/pending_transaction_queue.rs• L202-280 chain/…/client.rs• L1229-1253 chain/…/verified_peer_heights.rs• L8-71 chain/…/peers.rs• L36-49 chain/…/client.rs• L1648-1680

Client coordinator

The client coordinator is the node's main event and timer boundary. Startup waits for genesis, creates the client and its asynchronous sync and chunk-validation workers, binds their message paths, and then starts synchronization, catch-up, and recurring triggers (chain/…/client_actor.rs• L162-290, chain/…/client_actor.rs• L1081-1095).

It checks block production duties, processes completed asynchronous work, applies live configuration changes, reports node status, and notifies execution, witness validation, data distribution, and core-writing services after a block is accepted (chain/…/client_actor.rs• L1319-1417, chain/…/client_actor.rs• L1643-1659).

Completion notifications are wired into the client itself. The coordinator therefore receives apply results from ordinary block processing, synchronization, catch-up, optimistic blocks, and missing-chunk recovery through the same event boundary (chain/…/client.rs• L1450-1518, chain/…/client_actor.rs• L983-993).

Important chain triggers run before ordinary actor messages. This keeps synchronization steps, consensus timers, block production, and unfinished block processing moving when the node has a large message queue (chain/…/client_actor.rs• L1305-1317, chain/…/client_actor.rs• L1363-1417).

References: chain/…/client_actor.rs• L162-290 chain/…/client_actor.rs• L983-993 chain/…/client_actor.rs• L1081-1095 chain/…/client_actor.rs• L1319-1417 chain/…/client_actor.rs• L1643-1659

Chain progression

Chain progression turns network observations and local validator duties into a verified and advancing chain. The client first decides whether work is relevant. It then uses chain and runtime services for validation or execution. After asynchronous shard work completes, it releases the services that depend on the accepted block.

The main progression is:

flowchart LR
    A[Network blocks and approvals] --> B[Client coordinator]
    B --> C[Chain and runtime checks]
    C --> D[Shard execution and missing data]
    D --> E[Accepted block and new heads]
    E --> F[Network, API, archive, indexer, and execution services]
    F --> B

Block intake

Block intake protects the local chain before it accepts new state. The client filters duplicate, stale, or too-far-ahead blocks. It checks block identity and signatures. It rebroadcasts usable data and defers unknown parents or missing chunks instead of treating them as immediate peer failures (chain/…/client.rs• L1255-1458).

Headers and approvals can support progress before full block bodies arrive. Header responses are bounded before processing. State responses are matched to the active state-sync or catch-up operation. A delayed, oversized, or unexpected response therefore cannot be applied to the wrong state (chain/…/client_actor.rs• L627-732).

References: chain/…/client.rs• L1255-1458 chain/…/client_actor.rs• L627-732 chain/…/header.rs• L1-40

Synchronization

Synchronization brings the local chain and required shard state to the level supported by the network. The coordinator chooses a target from connected peers. When the local head is recent, a target must be backed by a verified block header. When the local head is stale, a peer's claimed height can start recovery, but epoch-sync proof and later chain checks decide what data is safe to apply (chain/…/client_actor.rs• L1683-1835, chain/…/epoch.rs• L62-176).

Target choice depends on how much of a peer's claim the node can trust. During stale recovery, the peer selector favors a target near the median of eligible advertised heights and avoids peers that recently failed to serve requested data. When the local head is recent, the coordinator caps each peer's advertised height by the verified height recorded from approval-bearing blocks, then chooses the highest usable verified target. This prevents an unproved claim or a small set of outliers from driving normal sync (chain/…/client_actor.rs• L1766-1817, chain/…/peers.rs• L51-175).

The sync handler runs one progression from far recovery to normal operation:

  1. Epoch sync verifies a recent trusted epoch proof and bootstraps the epoch manager when needed.
  2. Header sync finds a common chain path and downloads headers.
  3. State sync restores the state for each shard the node must track.
  4. Block sync downloads and processes the remaining block bodies.
  5. The node leaves sync mode when its head reaches the selected target.

Epoch sync does not trust the height that caused the request. The proof must come from the expected peer, fit the peer's claimed range, match validator handoffs and final-block endorsements, and pass Merkle and epoch-data checks. A valid proof can either select a normal sync phase or show that the local store is beyond its safe horizon and must be reset (chain/…/epoch.rs• L100-176, chain/…/epoch.rs• L178-284, chain/…/epoch.rs• L286-527).

State synchronization restores the state for each shard the node needs to track. It obtains synchronization blocks, downloads and validates shard headers and state parts, applies the parts, rebuilds the local state view, and asks the chain to finalize the result. Each shard can download and apply parts in parallel, retry failed parts, report progress, and resume an interrupted apply from durable progress markers (chain/…/mod.rs• L73-175, chain/…/mod.rs• L305-443, chain/…/shard.rs• L55-247). If the verified network head moves too far past the sync point, the client abandons that state sync and returns to epoch sync instead of applying an unusable snapshot (chain/…/mod.rs• L231-249, chain/…/mod.rs• L317-346).

State-sync block requests record the peer that received each request. When a request times out, the selector records that peer as having failed to serve the data before the node retries with another eligible peer. This keeps state sync from repeatedly preferring a peer that advertised progress but did not provide the required block (chain/…/mod.rs• L252-303).

Peer state-sync requests use the snapshot identity advertised by the serving peer. The requester derives that identity from the sync hash and the active protocol's snapshot rule. Both sides must use the same chain reference when locating a snapshot (chain/…/network.rs• L201-223, chain/…/network.rs• L321-385). Responses are correlated by shard, sync hash, part or header, and the peer selected by the network. Busy, failed, or unsent requests stop waiting so the sync layer can retry; a response from another peer is rejected (chain/…/network.rs• L42-65, chain/…/network.rs• L67-188). State sync also has a shared external-storage connection for state headers and parts. It uses one canonical path format for reads, writes, and checks that a dump exists (chain/…/external.rs• L46-161, chain/…/external.rs• L165-264).

State requests served to peers are limited to known recent epochs and are rate limited. This prevents the node from serving state for an invalid sync point or spending unbounded resources on requests (chain/…/state_request_actor.rs• L21-40, chain/…/state_request_actor.rs• L91-172, chain/…/state_request_actor.rs• L213-283).

The node reports the latest verified header epoch to the network when header sync is close enough to the selected target. This lets snapshot hosts discard claims for epochs that the node has not yet reached. The node leaves sync mode when it catches up or has no usable peer target. The same coordinator then resumes normal chain duties and can announce a validator identity when the next epoch requires it (chain/…/client_actor.rs• L1917-1999, chain/…/client_actor.rs• L1081-1095).

References: chain/…/client_actor.rs• L1683-1835 chain/…/epoch.rs• L62-176 chain/…/epoch.rs• L178-284 chain/…/epoch.rs• L286-527 chain/…/verified_peer_heights.rs• L27-71 chain/…/handler.rs• L66-201 chain/…/mod.rs• L231-346 chain/…/mod.rs• L352-443 chain/…/network.rs• L42-223 chain/…/network.rs• L321-385 chain/…/shard.rs• L55-247 chain/…/external.rs• L46-161 chain/…/state_request_actor.rs• L91-172 chain/…/peers.rs• L51-175

Block production

A validator uses the client layer to turn consensus approvals and ready shard chunks into blocks. The coordinator checks that the node is not syncing. It checks the assigned producer duty, waits for the required shard readiness, and produces and broadcasts the block when the duty is local. SPICE adds a readiness check for its execution and certification progress (chain/…/client_actor.rs• L1176-1294).

Chunk production selects valid transactions and outgoing receipts for a shard. In SPICE mode, transaction admission uses the last certified executed state and its congestion data. This lets the producer keep transaction selection consistent with the state that is safe to read while the consensus head may be ahead (chain/…/chunk_producer.rs• L477-624). The same preparation path can run external contract calls before packing, with limits that keep one call or one chunk from consuming all preparation time. At an epoch boundary, the preparation context carries the boundary state so external-call admission stays aligned with the account updates applied at that boundary (chain/…/chunk_producer.rs• L489-603, chain/…/prepare_transactions.rs• L19-33).

The client can prepare transactions before the next production request. It runs one preparation job per shard, replaces stale work, and uses the result only when its block and shard inputs still match. The job can use the parent chunk's new trie nodes for early external contract calls. If the work starts too late or is cancelled, normal production prepares the transactions instead (chain/…/client_actor.rs• L1420-1452, chain/…/chunk_producer.rs• L703-863, chain/…/prepare_transactions.rs• L19-33, chain/…/prepare_transactions.rs• L103-179, chain/…/prepare_transactions.rs• L201-265).

SPICE also slows production when certification falls behind execution. The delay grows with the certification gap and stops at a configured maximum. This makes block production apply back-pressure while the node catches up (chain/…/timer.rs• L10-18, chain/…/timer.rs• L74-123).

After production, the client starts local processing and sends the block through the same chain path used for a received block. This keeps produced and received blocks subject to the same validation and execution flow (chain/…/client_actor.rs• L1514-1553).

References: chain/…/client_actor.rs• L1176-1294 chain/…/client_actor.rs• L1420-1452 chain/…/client_actor.rs• L1514-1553 chain/…/chunk_producer.rs• L477-624 chain/…/chunk_producer.rs• L703-863 chain/…/prepare_transactions.rs• L19-33 chain/…/prepare_transactions.rs• L103-179 chain/…/prepare_transactions.rs• L201-265 chain/…/timer.rs• L10-18 chain/…/timer.rs• L74-123

Pending transaction view

The pending transaction view keeps uncertified included transactions visible to later chunk production. It stores per-shard constraints for account cost, nonce, gas-key cost, and access-key use. Certification removes the relevant chunk. Startup or reorganization can clear and rebuild the view from the current chain (chain/…/pending_transaction_queue.rs• L30-102, chain/…/pending_transaction_queue.rs• L202-353, chain/…/client.rs• L642-743).

The view separates durable block-level facts from session-local checks made while selecting a new chunk. Runtime validation remains the final account-level check. The pending limit applies per account, while ordinary nonce checks stay scoped to the key that carries the nonce. A self-signed bootstrap also contributes an account-scoped nonce floor. Unsigned external contract calls are outside this accounting until they have pending cost support (chain/…/pending_transaction_queue.rs• L67-102, chain/…/pending_transaction_queue.rs• L355-515).

References: chain/…/pending_transaction_queue.rs• L30-102 chain/…/pending_transaction_queue.rs• L202-353 chain/…/pending_transaction_queue.rs• L355-515 chain/…/chunk_producer.rs• L509-561 chain/…/client.rs• L545-640 chain/…/client.rs• L642-743

Service interfaces

The client layer exposes focused actors instead of one general-purpose entry point. Each actor owns a different kind of work and exchanges typed messages with the client, network, shard manager, runtime, or API layer. The crate surface exports the main client, coordinator, view client, RPC handler, state request service, validation services, indexer message assembly, and archival modules (chain/…/lib.rs• L1-64).

Read service

The view client provides a read-only view of committed chain and state data. It resolves block and finality references, maps account requests to shards, runs runtime queries against the selected state, and returns blocks, chunks, execution outcomes, proofs, validator data, gas data, and state changes (chain/…/view_client_actor.rs• L87-109, chain/…/view_client_actor.rs• L220-317, chain/…/view_client_actor.rs• L394-530).

For SPICE-enabled chains, a consensus head can exist before its state is executed. The read service therefore resolves finality and block references through the latest executed ancestor. It reports when a requested height is no longer available on a non-archive node (chain/…/view_client_actor.rs• L220-317, chain/…/view_client_actor.rs• L383-419). Query errors preserve the distinction between an unknown account and an uninitialized account. This gives API callers a precise result for accounts that exist only as an address (chain/…/view_client_actor.rs• L437-471).

Transaction status depends on local shard coverage. If the node tracks the target shard, the service reads local outcomes. Otherwise it sends a bounded request to a validator that can serve the shard and reports that the local node does not track it while waiting for a response (chain/…/view_client_actor.rs• L660-740).

References: chain/…/view_client_actor.rs• L87-109 chain/…/view_client_actor.rs• L220-317 chain/…/view_client_actor.rs• L383-419 chain/…/view_client_actor.rs• L394-530 chain/…/view_client_actor.rs• L660-740 chain/…/view_client_actor.rs• L759-908

Network interface

The network interface maps peer protocol messages to the client service that can handle them. Blocks, headers, approvals, state responses, and network information go to the client coordinator. Read requests go to the view client. Transactions go to the RPC handler, while chunk endorsements go to their dedicated handler (chain/…/adapter.rs• L9-31).

This mapping is the boundary between peer transport and chain behavior. The network layer defines message contracts. The client layer decides how each message changes local progress or produces a response (chain/…/client.rs• L22-54, chain/…/client.rs• L114-200).

References: chain/…/adapter.rs• L9-31 chain/…/client.rs• L22-54 chain/…/client.rs• L114-200 chain/…/network.rs• L32-49

Transaction intake service

The transaction intake service validates signed transactions and external contract calls before it places work in the local pool or routes it to a validator for the target shard. It uses the current protocol state for basic checks, uses certified state and congestion data for SPICE checks, and avoids storing a transaction when this node is not a suitable producer (chain/…/rpc_handler.rs• L131-159, chain/…/rpc_handler.rs• L168-215, chain/…/rpc_handler.rs• L221-355).

This service keeps transaction routing tied to near-term producer assignments. A node can accept a valid request locally, forward it to current or next-epoch producers, or report that it cannot track the target shard. The transaction pool and chunk producer still define which envelope types can be retained and later included (chain/…/rpc_handler.rs• L294-355, chain/…/rpc_handler.rs• L357-415, chain/…/chunk_producer.rs• L460-609).

References: chain/…/rpc_handler.rs• L131-215 chain/…/rpc_handler.rs• L221-355 chain/…/rpc_handler.rs• L357-415 chain/…/chunk_producer.rs• L460-609

SPICE execution service

The SPICE execution service turns processed blocks into per-shard execution work. A coordinator keeps one executor for each shard tracked in the current or next layout. Each executor owns a parked-block queue, in-flight work, and network receipt buffer. It waits until prior execution results, prior shard state, and all incoming receipt proofs are available. It then applies the chunk asynchronously and returns the result to the coordinator (chain/…/coordinator.rs• L41-68, chain/…/coordinator.rs• L154-247, chain/…/per_shard.rs• L75-108, chain/…/per_shard.rs• L166-241).

SPICE can commit shards independently. The coordinator reconciles executors at layout boundaries, routes early receipts only to shards tracked at the relevant chain points, and finalizes a block only after all shards tracked for that block have durable execution results. A completed shard persists receipt proofs, witnesses, and contract-access data. It then emits endorsements, witness data, and outgoing receipts for the network and local shard fanout (chain/…/coordinator.rs• L199-243, chain/…/coordinator.rs• L271-381, chain/…/per_shard.rs• L400-508, chain/…/storage.rs• L19-30, chain/…/storage.rs• L64-96).

The service recovers the execution head from disk after a crash between shard apply and block finalization. A shard that enters the tracking set after state catch-up waits until its catch-up finishes. The coordinator then replays the canonical blocks that the shard still needs, while leaving forks and already-finalized work out of the replay. Executors for shards that stop being tracked are evicted, and late apply results for them are dropped (chain/…/coordinator.rs• L228-243, chain/…/coordinator.rs• L271-375, chain/…/per_shard.rs• L197-241, chain/…/chunk_executor_actor.rs• L2098-2515).

At the SPICE activation boundary, the service converts the last pre-SPICE shard results into the endorsements, receipt proofs, and witness data needed by the first SPICE block. The bootstrap can run again after restart because its network sends are not durable (chain/…/coordinator.rs• L249-268, chain/…/boundary.rs• L9-41, chain/…/boundary.rs• L24-55).

References: chain/…/coordinator.rs• L41-68 chain/…/coordinator.rs• L199-243 chain/…/coordinator.rs• L271-381 chain/…/per_shard.rs• L75-108 chain/…/per_shard.rs• L166-241 chain/…/per_shard.rs• L400-508 chain/…/storage.rs• L19-30 chain/…/storage.rs• L64-96 chain/…/boundary.rs• L9-41 chain/…/boundary.rs• L24-55 chain/…/chunk_executor_actor.rs• L2098-2515

SPICE data distribution

The SPICE data distributor moves receipt proofs, state witnesses, and contract data between producers and the validators that need them. It checks message identity, signatures, shard membership, commitments, and sender roles before it reconstructs data or forwards it to execution and witness validation (chain/…/data_distributor_actor.rs• L148-204, chain/…/data_distributor_actor.rs• L307-426, chain/…/data_distributor_actor.rs• L577-793). It also sends contract-access information before witness parts so validators can request missing code while they rebuild the witness (chain/…/data_distributor_actor.rs• L282-304).

The data manager is the fetch engine for receipt proofs that a node does not produce locally. It identifies each receipt proof by source chunk and destination shard. It tracks chain heights, item state, producer commitments, authenticated senders, outstanding pulls, and bounded parts for blocks not yet processed (chain/…/data_id.rs• L7-16, chain/…/mod.rs• L125-152, chain/…/orphans.rs• L13-24).

Its policy layer describes which data matters to this node, who produces it, when a chain event makes it pullable, and when storage proves that it is complete. Receipt-proof pulls wait until the source chunk is certified. Requests are bounded, retried after timeout, rotated across producers, and removed only after delivery and storage confirmation (chain/…/fetch.rs• L17-105, chain/…/pull.rs• L43-150, chain/…/mod.rs• L230-315, chain/…/mod.rs• L447-466). The serving side now uses the same policy boundary for receipt proofs and state witnesses. A producer serves stored data only to the validator set that applies that data, including the destination set across a shard split (chain/…/serve.rs• L11-51, chain/…/serve.rs• L27-68, chain/…/serve.rs• L25-45).

Partial data can arrive before the referenced block is present. The manager authenticates and parks receipt-proof parts until the block is processed. The distributor retains witness parts and rechecks them against the block's epoch keys and shard roles when the block arrives. Witness distribution also supports a wider all-stake fallback when certification is late. The distributor removes requests for dead forks or already certified witnesses so stale work does not remain active (chain/…/orphans.rs• L21-113, chain/…/data_distributor_actor.rs• L631-793, chain/…/data_distributor_actor.rs• L833-911, chain/…/data_distributor_actor.rs• L984-1080, chain/…/data_distributor_actor.rs• L1120-1299). Contract-code requests are checked against the recorded state transition and served in bounded responses, so a validator can complete witness validation without accepting unrelated code (chain/…/data_distributor_actor.rs• L1453-1499, chain/…/partial_witness_actor.rs• L1134-1262).

References: chain/…/data_distributor_actor.rs• L148-204 chain/…/data_distributor_actor.rs• L282-426 chain/…/data_distributor_actor.rs• L577-793 chain/…/data_distributor_actor.rs• L833-911 chain/…/data_distributor_actor.rs• L984-1080 chain/…/data_distributor_actor.rs• L1120-1299 chain/…/data_distributor_actor.rs• L1453-1499 chain/…/data_id.rs• L7-16 chain/…/mod.rs• L125-152 chain/…/orphans.rs• L21-113 chain/…/serve.rs• L11-51 chain/…/fetch.rs• L17-105 chain/…/serve.rs• L27-68 chain/…/serve.rs• L25-45 chain/…/pull.rs• L43-150 chain/…/partial_witness_actor.rs• L1134-1262

Stateless witness service

The stateless witness service distributes and reassembles state witnesses for chunk validators. A producer sends contract-access data before witness parts. Validators validate and store relevant parts. The designated owner forwards its part, and the tracker combines enough parts to decode a witness before it sends the result to chunk validation (chain/…/partial_witness_actor.rs• L254-345, chain/…/partial_witness_actor.rs• L483-645, chain/…/partial_witness_tracker.rs• L539-605). The SPICE chunk validator now performs the final witness checks after it has the block context, prior execution results, and any contract code needed by the witness. It can validate several candidates for one chunk and stops work after its own endorsement is recorded (chain/…/chunk_validator_actor.rs• L65-117, chain/…/chunk_validator_actor.rs• L336-359, chain/…/chunk_validator_actor.rs• L738-846).

Witness and contract-distribution messages use the wire version active for their epoch. Newer messages carry parent and grandparent anchors so the receiver can resolve the producer from chain data instead of relying only on a sampler. The receiver checks relevance, part bounds, payload size, validator assignment, anchor consistency, and signatures. If the anchor is not available because the node is behind, it drops the message and lets normal chain sync recover the work (chain/…/partial_witness_actor.rs• L68-109, chain/…/partial_witness_actor.rs• L508-563, chain/…/partial_witness_actor.rs• L650-750, chain/…/validate.rs• L59-163, chain/…/validate.rs• L267-345).

The tracker also joins contract code with witness parts. It sends a completed witness onward when all needed inputs are present. A missing code response can expire into best-effort validation, while progress keeps the request alive. Separate chain anchors remain separate work so a message from another fork cannot pin or complete the local witness (chain/…/partial_witness_tracker.rs• L61-87, chain/…/partial_witness_tracker.rs• L398-466, chain/…/partial_witness_tracker.rs• L845-910).

References: chain/…/partial_witness_actor.rs• L68-109 chain/…/partial_witness_actor.rs• L254-345 chain/…/partial_witness_actor.rs• L483-645 chain/…/partial_witness_actor.rs• L650-750 chain/…/partial_witness_tracker.rs• L61-87 chain/…/partial_witness_tracker.rs• L398-466 chain/…/partial_witness_tracker.rs• L539-605 chain/…/partial_witness_tracker.rs• L738-832 chain/…/validate.rs• L59-163 chain/…/validate.rs• L267-345 chain/…/chunk_validator_actor.rs• L65-117 chain/…/chunk_validator_actor.rs• L336-359 chain/…/chunk_validator_actor.rs• L738-846

Node-facing connections

nearcore assembles the client layer with the chain, runtime, epoch manager, shard tracker, storage, network, and API services. It returns handles for the main client, view client, RPC handler, state request service, shard tracker, and selected background controls through one NearNode service boundary (nearcore/…/lib.rs• L341-360, nearcore/…/lib.rs• L390-471, nearcore/…/lib.rs• L644-674, nearcore/…/lib.rs• L875-886).

The neard executable provides the process entry point. It prepares process-wide runtime conditions and delegates command handling to the CLI before nearcore assembles the node services (neard/…/main.rs• L47-87). The detailed startup and shutdown sequence belongs to Node startup and lifecycle.

Node configuration

Node configuration translates the config file and genesis data into the settings used by chain progression and client services. It defines the chain identity, tracked-shard policy, synchronization and consensus limits, storage and archive mode, API address, and data retention behavior (nearcore/…/config.rs• L224-464, nearcore/…/config.rs• L720-874).

NearConfig resolves defaults and legacy tracked-shard settings before service assembly. These resolved values determine which shard data the node can process and serve. They also determine which outcomes, receipts, state changes, and snapshots the node retains for reads and recovery (nearcore/…/config.rs• L547-696, nearcore/…/config.rs• L785-805, nearcore/…/config.rs• L925-995).

References: nearcore/…/config.rs• L224-464 nearcore/…/config.rs• L547-696 nearcore/…/config.rs• L720-874 nearcore/…/config.rs• L925-995

Service assembly

Assembly creates shared chain resources first and binds services to them in dependency order. The main client receives the live processing runtime and storage. The view client can use a split-storage view when archival settings require it. The network is attached after client senders exist. The HTTP API is attached after the client and peer services are ready (nearcore/…/lib.rs• L420-523, nearcore/…/lib.rs• L548-674, nearcore/…/lib.rs• L725-760, nearcore/…/lib.rs• L779-836).

The resulting relationship is:

flowchart TD
    S[Storage and genesis] --> E[Epoch manager]
    E --> T[Shard tracker]
    T --> R[Runtime]
    R --> C[Client coordinator]
    R --> V[View client]
    C --> N[Peer manager]
    V --> A[JSON-RPC API]
    C --> A
    R --> X[Shard, sync, archive, and execution services]
    X --> C

References: nearcore/…/lib.rs• L420-523 nearcore/…/lib.rs• L548-674 nearcore/…/lib.rs• L725-760 nearcore/…/lib.rs• L779-836

Cloud archival

Cloud archival moves finalized chain data from the local hot store to cloud storage and can restore that data into a local store. The writer follows the finalized head in batches. It archives block data and the tracked shard data that the node is configured to retain. Readers rebuild the local rows needed for chain reads (chain/…/cloud_archival_writer.rs• L107-126, chain/…/cloud_archival_writer.rs• L331-404, chain/…/cloud_historical_reader.rs• L16-198).

The reader restores a range from an anchor below the requested start. It can install a shard snapshot and apply later state changes while checking that each applied state root matches the archived record. The current snapshot lookup still expects the archived state header to provide a chunk inclusion height. A SPICE state-sync header without that chunk cannot use this lookup path yet (chain/…/cloud_archival_utils.rs• L208-236, chain/…/cloud_archival_utils.rs• L239-269, chain/…/cloud_archival_utils.rs• L389-460, chain/…/cloud_historical_reader.rs• L116-200).

References: chain/…/cloud_archival_writer.rs• L107-126 chain/…/cloud_archival_writer.rs• L331-405 chain/…/cloud_archival_utils.rs• L208-236 chain/…/cloud_archival_utils.rs• L239-269 chain/…/cloud_archival_utils.rs• L389-460 chain/…/cloud_historical_reader.rs• L16-200 chain/…/cloud_recent_reader.rs• L55-105

Status and observability

The client coordinator is the source for node status, sync state, network summaries, validator identity, chain heads, and detailed debug views. For SPICE, status uses the latest executed ancestor and its certified state root rather than an unexecuted consensus head. Health checks also report a syncing node or a node with no recent block as unhealthy (chain/…/client_actor.rs• L795-940). The API asks the coordinator for these views rather than reading client state directly. This keeps status answers aligned with the state used for chain progression (chain/…/client_actor.rs• L963-979).

The client reports progress through metrics and telemetry helpers. These signals cover block and chunk production, transaction preparation, sync requirements, peer service quality, witness handling, SPICE data, archival heads, API receipt-to-transaction work, and system health. They also distinguish witness wire versions and malformed SPICE data requests so operators can see protocol and peer-data problems (chain/…/info.rs• L44-99, chain/…/info.rs• L298-483, chain/…/metrics.rs• L11-81, chain/…/metrics.rs• L675-920).

References: chain/…/client_actor.rs• L795-940 chain/…/client_actor.rs• L963-979 chain/…/info.rs• L44-99 chain/…/info.rs• L298-483 chain/…/metrics.rs• L11-81 chain/…/metrics.rs• L675-920

API and indexer boundary

The JSON-RPC service turns external methods into typed messages for the client, view client, transaction service, and peer manager. Read requests can stay local or route through a configured sharded RPC pool based on the target block and shard. Transaction methods use the transaction service and can poll view results until the requested execution level is reached (chain/…/lib.rs• L435-517, chain/…/lib.rs• L614-830, chain/…/lib.rs• L1595-1686).

The node-side indexer assembly uses the same node handles instead of a separate chain. It selects tracked new chunks, fetches the block's protocol and shard data, joins signed transactions with execution outcomes and receipts, adds instant receipts and state changes, and returns one complete StreamerMessage to the indexer consumer. The standalone near-indexer package depends on the node client and nearcore with JSON-RPC support, so indexer processes use the same client-facing chain services and protocol feature gates (chain/…/Cargo.toml• L14-31, chain/…/Cargo.toml• L45-50). Unsigned external contract calls are currently omitted from the chunk data because their execution outcomes and indexer model are not supported yet (chain/…/indexer.rs• L84-120, chain/…/indexer.rs• L123-245, chain/…/indexer.rs• L248-299).

For SPICE-enabled protocol versions, the current assembly returns the block and shard state-change views without chunk and execution-outcome data. Indexer support for that path is incomplete (chain/…/indexer.rs• L118-121, chain/…/lib.rs• L40-53). Outcomes that do not match a streamed chunk are logged as leftovers and are not included in the message (chain/…/indexer.rs• L209-237).

References: chain/…/lib.rs• L435-517 chain/…/lib.rs• L614-830 chain/…/lib.rs• L1595-1686 chain/…/indexer.rs• L84-120 chain/…/indexer.rs• L123-245 chain/…/indexer.rs• L209-237 chain/…/indexer.rs• L248-299 chain/…/lib.rs• L40-53 chain/…/Cargo.toml• L14-31 chain/…/Cargo.toml• L45-50

Change checklist

When these files or sections are changed, remember to consider these:

  • When a client message changes, update the network sender map and every API or service sender that can create that message.
  • When asynchronous apply completion wiring changes, keep ordinary block processing, missing-chunk recovery, optimistic blocks, state sync, and catch-up connected to the coordinator's completion path.
  • When transaction envelope variants or transaction identity rules change, keep pool removal, reintroduction, pending accounting, runtime execution, transaction status, and indexer output aligned.
  • When shard tracking or epoch lookup changes, check transaction routing, view queries, sync target choice, state requests, archival shard selection, and sharded RPC node selection together.
  • When accepted-block timing changes, preserve the handoff to chunk execution, witness validation, data distribution, core-writing, indexer, notifications, and metrics.
  • When SPICE execution-head or per-shard readiness rules change, check startup recovery, receipt buffering and verification, local receipt fanout, layout changes, finalization, and data expiry together.
  • When a shard enters or leaves tracking, check state catch-up completion, canonical block replay, parked work, final execution head movement, flat-storage updates, and fork handling together.
  • When early transaction preparation inputs or limits change, keep parent post-state and new-node use, one-job-per-shard replacement, cancellation, input matching, and normal-production fallback aligned.
  • When epoch-boundary preparation context changes, keep the producer's dry-run admission consistent with the account updates applied during chunk execution.
  • When SPICE apply context changes, keep the gas-price source used for chunk production, pending accounting, and execution consistent.
  • When SPICE per-shard artifacts change, keep receipt-proof keys, witness and contract-access writes, distributor reads, and the atomicity of paired witness artifacts aligned.
  • When SPICE data types or DataId identity rules change, update the fetch and serve policies, durable completion checks, commitment validation, authenticated sender checks, orphan release, and distributor handoff together.
  • When SPICE pull timing or producer rotation changes, keep request bounds, timeout state, answer recording, and completion cleanup aligned.
  • When witness or contract-distribution versions change, keep the epoch version gate, anchor lookup, height and shard-key checks, forwarding rules, signature checks, contract-code response routing, and best-effort timeout behavior aligned.
  • When state-sync proof or snapshot identity changes, update peer validation, requester-side hash derivation, and peer-side snapshot advertisement together.
  • When state-sync download or apply behavior changes, keep per-shard retries, cancellation, durable applied-part markers, flat-storage setup, memtrie loading, and chain finalization consistent.
  • When state-sync request ownership or timeout handling changes, keep the selected peer, retry path, failure cooldown, response correlation, and stale-sync decision aligned.
  • When cloud archive batch or head rules change, check writer initialization, reader resume points, garbage-collection limits, trie-root checks, snapshot header assumptions, and resharding boundaries together.
  • When node-side indexer assembly changes, keep view-client sender contracts, shard tracking, protocol-version handling, receipt and outcome joins, instant receipt lookup, unsigned-envelope handling, and near-indexer stream expectations aligned.
  • When node configuration or daemon service assembly changes, keep the resolved tracked-shard policy, retained data, NearNode handles, and network, API, and background-service bindings aligned.

Important failure modes

TriggerConsequenceGuard
A recent node uses a peer's unverified advertised height as a sync targetThe node can select a target that is not backed by known chain evidenceUse verified peer heights while the local head is recent
A peer with an extreme advertised height drives stale recoverySync can follow an outlier instead of the height supported by most peersSelect near the median for claimed heights and keep recently failing peers out of the preferred set
An epoch-sync proof comes from the wrong peer, falls outside the allowed age, or fails endorsement or Merkle checksThe node can bootstrap from false epoch data or waste work on an invalid responseValidate peer identity, freshness, validator handoffs, signatures, and Merkle data before applying the proof
A block-headers response exceeds the requested boundThe peer can consume excess processing or violate the sync message contractReject oversized responses before header processing
A state-sync block request times outThe node can keep retrying a peer that does not serve the required blockRecord the requested peer and place it in the failure cooldown before retrying
A verified network head moves beyond the state-sync horizonThe node can apply a snapshot that peers no longer serveAbandon shard state-sync tasks and return to epoch sync
The node lacks a required parent, chunk, execution result, or receipt proofBlock or shard progress waits for data and retries laterKeep missing work in the chain, sync, or per-shard execution queues
A validator tries to produce while the node is syncingThe node skips production and waits for sync progressCheck sync status before block production
Early preparation uses stale parent state or an old block contextThe producer can admit or order transactions against the wrong stateUse parent post-state inputs and match the shard update key and block context before using the result
A transaction targets an untracked shardThe node cannot validate or include it locallyRoute it to a validator for the target shard or report that the shard is not tracked
A state request names an unknown or old sync hashThe request is rejected or receives no responseAccept only known recent epochs and apply request throttling
A requester derives a snapshot id different from the peer's advertised idState-sync peer discovery fails even though a usable snapshot existsDerive the request id with the same protocol rule used by snapshot hosts
A state-sync response arrives from a peer other than the selected peerThe response can be applied to the wrong requestCorrelate the response with shard, sync hash, part or header, and expected peer
A state-sync part download fails or the node restarts during applyThe shard remains incomplete or can repeat workRetry failed parts and use durable applied-part markers only while the apply is unfinished
A chunk executor applies a newly tracked shard before its catch-up state is completeThe shard can execute against a state that is not ready for the current chain pointWait for catch-up completion and replay the needed canonical blocks afterward
A SPICE execution path uses a different gas-price context from chunk productionA transaction can be admitted at one price and charged at anotherUse the previous block's gas-price context for the apply path and certified state for SPICE admission
A receipt arrives before its source execution result or before its destination executor existsThe receipt waits for verification or is dropped when the node does not track the destination shardBuffer by source block and create an executor only for a currently relevant tracked shard
A block is queued for a shard that is not in its layout or is at or below the final execution headThe executor can apply work that cannot advance the local chainDrop blocks outside the shard layout or final-execution ancestry before dispatch
A crash occurs between per-shard apply and block finalizationDurable shard results exist but the execution head is behind themRecover the execution head from disk before scheduling new work
Witness and contract-access data do not commit togetherA downstream validator or distributor can read an incomplete execution artifact setSave the paired artifacts in one store transaction
A receipt-proof item is pulled before its source chunk is certifiedThe node may request data for work that cannot advance the certified chainGate pulls on source-chunk certification
A partial-data sender is not a producer or signs with an invalid keyThe node could accept data from the wrong validator contextBind the sender to the item's producer set and verify its allowed epoch keys
A receipt-proof part has a bad Merkle proof, commitment, width, or decoded identityThe item settles as invalid or remains incompleteVerify the signed message, part proof, commitment hash, and DataId before delivery
Partial data arrives before its block is processedThe data cannot yet be checked against the block's epoch and shard viewPark it with a bounded orphan cache and release it when the block trigger arrives
Partial data belongs to a dead fork or is below the final execution headThe node keeps requesting data that can never be appliedRemove forked items and expire items at or below the final execution head
A witness part arrives from another anchor under the same chunk keyThe wrong witness can pin assembly state or block the needed witnessKeep entries keyed by their chain anchor and complete them independently
Required contract code never arrivesA witness candidate stays pending and cannot produce an endorsementBound pending candidates and code requests, validate each ready candidate separately, and stop candidates after the node has endorsed the chunk
An external call is treated as a distinct transaction when a state-init variant is stripped or restoredPool reconciliation can remove or re-add the wrong call across a reorganizationUse the stable call identity for pool and reorg handling while retaining full bytes for chain commitments
An unsigned external contract call reaches a pending-accounting or indexer path that supports only signed transactionsThe call is omitted from pending cost accounting or indexer transaction outputFilter unsupported envelopes explicitly and extend each consumer before enabling the path
A SPICE-enabled block reaches the node-side indexer assemblerThe streamer message omits chunk and execution-outcome data for that blockTreat SPICE indexer support as incomplete until the assembler handles that protocol path
Cloud archival restore needs a SPICE snapshot header with no chunk inclusion heightThe reader cannot find a usable snapshot and archival restore stopsKeep archive snapshot format and SPICE state-sync snapshot rules aligned before enabling that restore path

Key files

FileWhy to read it
chain/…/client.rsDefines chain-facing client state, block processing, transaction-pool handoff, pending accounting, sync evidence, network chain information, and the handoff from block input to chain processing.
chain/…/client_actor.rsShows client assembly, coordinator startup, priority triggers, sync target selection, header response handling, production duties, status, accepted-block notifications, and asynchronous apply completion handling.
chain/…/chunk_producer.rsShows shard transaction selection, certified-state admission in SPICE, epoch-boundary preparation context, receipt roots, and chunk creation.
chain/…/prepare_transactions.rsShows early transaction preparation from parent state, cancellation, input matching, per-call and per-chunk limits, and result handoff.
chain/…/rpc_handler.rsShows transaction validation, shard routing, pool admission, and certified-state checks for SPICE.
chain/…/view_client_actor.rsDefines committed reads, query errors, and transaction status used by APIs.
chain/…/handler.rsShows the ordered sync phases, their handoffs, and the transition back to epoch sync when state sync becomes stale.
chain/…/epoch.rsShows epoch-sync proof validation, bootstrap, and stale-store reset decisions.
chain/…/peers.rsShows sync peer target selection, median height behavior, and failure cooldowns.
chain/…/mod.rsShows state-sync block request ownership, stale-sync detection, per-shard progress, cancellation, and finalization.
chain/…/shard.rsShows per-shard state download, parallel apply, resume rules, flat storage, and finalization.
chain/…/network.rsShows state-sync peer request correlation, snapshot identity, and response ownership.
chain/…/state_request_actor.rsShows validation and throttling for state served to peers.
chain/…/coordinator.rsShows tracked-shard executor reconciliation, recovery, receipt routing, local fanout, snapshot announcements, and block finalization.
chain/…/per_shard.rsShows parked-block readiness, asynchronous shard apply, durable artifact production, endorsements, witness distribution, and outgoing receipts.
chain/…/storage.rsShows the durable keys and atomic writes for SPICE receipt proofs, witnesses, and contract-access data.
chain/…/testonly.rsShows the synchronous harness that drives executor tasks, apply-completion events, core writing, and produced receipt or endorsement messages in integration tests.
chain/…/data_distributor_actor.rsShows SPICE data validation, reconstruction, fork recovery, fetching, serving, fallback, contract-code exchange, and distribution.
chain/…/chunk_validator_actor.rsShows SPICE witness readiness, contract-code waits, candidate validation, endorsements, and bounded pending work.
chain/…/chunk_executor_actor.rsShows the required ordering and retry behavior for per-shard execution, receipts, endorsements, forks, tracked-shard changes, and catch-up replay.
chain/…/indexer.rsShows how node state becomes an indexer stream message and where unsupported transaction or SPICE paths stop.
nearcore/…/config.rsShows how node settings and genesis become client, storage, sync, archive, and API configuration.
nearcore/…/lib.rsShows how shared resources and client-facing service handles are assembled.