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 / block-and-chunk-processing

Block and chunk processing

Block and chunk processing turns a proposed block and its shard data into a verified chain update. The flow checks that the block and chunk headers agree, obtains or rebuilds the chunk data that the node needs, applies each tracked shard transition, and commits the result with the block. It connects block and chunk work to runtime execution, state sync, and the chain heads; see Chain data processing for the wider chain flow and Epoch and validator management for producer and shard assignments.

Processing model

The system treats a block as a common frame around one chunk header for each shard. A chunk header records the state and receipt context for the next shard transition. A new chunk carries transactions and incoming work for that shard. An old chunk means that no new chunk was included for that shard at this height.

The main relationships are:

ConceptPurpose
BlockLinks the new height to its parent and commits shard-level facts through roots, masks, and other block-wide values.
Chunk headerCommits the identity and prior execution summary for one shard chunk.
Chunk bodyCarries the encoded transactions and receipts needed to rebuild a full chunk.
Chunk extraRecords the trusted result of applying a shard chunk and supplies inputs for the next chunk.
Shard updateApplies either a new chunk or an empty transition for an old chunk.

Block records

The block header binds the block to its parent and to the set of chunk headers. It also carries block-wide values such as state, outcome, transaction, and chunk-header roots. The block body carries the chunk headers plus the data used to prove the block producer's work. These links let a node check the block as one unit before it changes chain state.

References: core/…/block.rs• L49-97 core/…/block.rs• L616-659 core/…/block_header.rs• L282-385

Chunk records

The chunk header is the handoff between one shard transition and the next. It identifies the shard and the prior block, commits the encoded body, and carries the prior state, receipt, gas, validator-proposal, congestion, and bandwidth summaries. The height_included value distinguishes a chunk created for the current block from a prior header carried forward for an old chunk.

References: core/…/shard_chunk_header_inner.rs• L282-427 core/…/sharding.rs• L430-472 core/…/block.rs• L672-760

Genesis state

Genesis creates the first block and one starting chunk for each shard. It also establishes the first ChunkExtra values from the shard state roots and initial execution limits, then records the block, heads, and state roots that later chunk transitions use. A SPICE-enabled genesis also starts the SPICE execution heads.

References: chain/…/genesis.rs• L26-75 chain/…/genesis.rs• L114-169 chain/…/genesis.rs• L173-271

Chunk lifecycle

Chunk data moves from a shard producer to the nodes that need to validate or execute it. The producer builds the body from transactions and outgoing receipts, encodes it into recoverable parts, and signs its header. The shard manager distributes parts and receipt proofs. A node reconstructs the body only when it has enough data and when its shard role requires the full chunk.

The lifecycle is:

flowchart LR
    A[Previous ChunkExtra] --> B[Chunk producer]
    T[Transactions and outgoing receipts] --> B
    B --> C[Signed chunk header and encoded parts]
    C --> D[Part owners and shard trackers]
    D --> E[Merge proofs and parts]
    E --> F{Enough data and required receipts?}
    F -- No --> D
    F -- Yes --> G[Reconstruct full chunk when needed]
    G --> H[Block processing]

Chunk production

The chunk producer is selected for a shard and height by epoch data. It uses the previous chunk summary as the starting point, prepares transactions against the next shard state, adds outgoing receipts, and creates a signed chunk. Transaction preparation admits work only while chain, congestion, nonce, pending-queue, gas, size, time, and state-read limits remain valid. Each shard also gives external contract-call transactions a configured share of transaction-pool capacity, so that work class cannot consume the full pool. The body is encoded into data and parity parts so that the chunk can be recovered without every part reaching every node.

References: chain/…/chunk_producer.rs• L156-196 chain/…/chunk_producer.rs• L285-407 chain/…/mod.rs• L817-1152 chain/…/client.rs• L45-120 chain/…/client.rs• L154-179 core/…/sharding.rs• L1420-1460 core/…/reed_solomon.rs• L18-56

Chunk distribution

The shard manager sends each part to its assigned owner and sends receipt proofs to nodes that track the source or target shard. Nodes can receive data by push, forward, or request. A part owner forwards its own parts to block producers that will track the shard in the current or next epoch. This gives validators the data needed for block checks without requiring all nodes to store every shard.

References: chain/…/shards_manager_actor.rs• L2142-2225 chain/…/logic.rs• L20-37 chain/…/logic.rs• L76-98

Chunk reconstruction

The shard manager first checks the chunk header and the Merkle proofs for parts and receipts. It waits for the data threshold before reconstruction. A node that tracks the shard decodes the body and persists the full chunk. A node that only owns parts can finish its part of the protocol without decoding the full body.

References: chain/…/shards_manager_actor.rs• L1777-1816 chain/…/shards_manager_actor.rs• L1899-1975 core/…/sharding.rs• L1281-1388

Block lifecycle

Block processing separates checks from state changes. The synchronous phase verifies the block and prepares one shard job for each relevant chunk. The asynchronous phase applies those jobs. The final phase combines their results with the block and commits them through one chain update.

sequenceDiagram
    participant P as Block input
    participant C as Chain
    participant R as Runtime
    participant S as Store
    P->>C: Block and chunk headers
    C->>C: Check parent, header, body, chunks, and availability
    C->>R: Apply shard jobs in parallel
    R-->>C: Shard update results
    C->>S: Save chunk results and block
    C->>C: Update heads and release dependent blocks

Block admission

The chain first checks the block hash and signature. It then validates the header against its parent and epoch context, checks block-wide roots and timing, and checks the chunk relationships and endorsements required by the active protocol. In SPICE epochs it also validates the SPICE-specific header commitments. It checks that the node has the chunk bodies it must process. The block is admitted to shard application only after these checks succeed.

Blocks with an unknown parent or missing required chunk data do not change chain state. The chain keeps them in the matching wait pool and retries them when the parent or chunk arrives. This keeps incomplete network delivery separate from invalid block data.

References: chain/…/chain.rs• L765-842 chain/…/chain.rs• L887-1059 chain/…/chain.rs• L1114-1190 chain/…/chain.rs• L1715-1806 chain/…/chain.rs• L2426-2520

Chunk validation

Validation checks that every new chunk points to the block parent and that every old chunk matches the prior block's header. It also compares a new header with the previous ChunkExtra. This protects the state root, outcome root, validator proposals, gas values, receipt root, congestion data, bandwidth requests, and resharding proposal from silent drift. Encoded body validation recomputes the transaction and receipt content and compares its encoded root and length with the header. In SPICE blocks, core statements must reference still-uncertified chunks, use valid validator signatures, and pair a certifying endorsement set with the matching execution result. Protocol-specific execution commitments receive their own checks when the active epoch enables them.

References: chain/…/chain.rs• L1114-1145 chain/…/chain.rs• L3382-3631 chain/…/validate.rs• L70-188 chain/…/validate.rs• L256-282 chain/…/core.rs• L639-833

SPICE fallback certification

SPICE keeps chunk execution results uncertified until validator endorsements move the certification frontier. A chunk normally uses its designated shard validators. If they do not certify it within the fallback delay, more than one third of the total epoch stake can certify it instead. A fallback-only chunk skips the delay and always uses the total-stake rule. This gives a stalled designated group a bounded path to progress while still requiring stake from outside that group when needed.

Fallback-only chunks are assigned to one shard at periodic slot heights. The selected shard rotates with the epoch so the extra endorsement work does not target every shard at once. Validation rejects a result at exactly one third of total stake, rejects a result without enough matching endorsements, and rejects certification of a child while an older chunk for the same shard remains uncertified.

References: chain/…/all_stake_fallback.rs• L16-70 chain/…/all_stake_fallback.rs• L106-158 chain/…/core.rs• L687-833 chain/…/all_stake_fallback.rs• L594-671 chain/…/all_stake_fallback.rs• L674-785

Chunk application

For a new chunk, the runtime applies transactions and incoming receipts against the previous shard state. Before execution, the chain checks continuity with the prior ChunkExtra and confirms transaction validity for the block. For an old chunk, it runs the empty shard transition and carries the prior chunk summary forward while allowing required block-level state changes. The shard tracker limits this work to shards the node tracks now or will track next. When the node will produce the next chunk, the runtime can return post-state data with the block time and epoch context needed to prepare that chunk early. Optimistic results can satisfy the normal path when their execution context matches. SPICE blocks use certified execution data rather than the normal local shard-job path.

The normal path builds one job per shard that the node must apply. Its cache key covers the block execution context, the block's chunk hashes, and the shard identity. A matching optimistic result can therefore be reused, but a result from a different block context cannot satisfy the block. SPICE builds its apply context from the previous block's certified execution results, including the congestion and bandwidth inputs that govern transaction admission for the new block.

After a new-chunk job finishes, chunk postprocessing records the new ChunkExtra with the state, receipt, outcome, and apply statistics needed by later blocks. It also writes the flat-state delta and receipt metadata. The shared persistence step keeps the completion marker with the refcounted state and receipt writes, so a retry after a crash can apply the shard again without counting those references twice. Optional outcome, receipt-to-transaction, state-change, and trie-change records follow the node's storage policy.

References: chain/…/chain.rs• L3439-3564 chain/…/chain.rs• L3598-3757 chain/…/chain.rs• L3759-3868 chain/…/chunk_application.rs• L24-200 chain/…/chunk_application.rs• L229-354 chain/…/update_shard.rs• L18-42 chain/…/update_shard.rs• L90-235

Block application

The chain schedules relevant shard jobs in parallel and waits for all results before postprocessing. Postprocessing checks that shared scheduler state agrees across shard results, stores chunk summaries and state changes, records incoming receipt proofs, and saves state-sync information when needed. It also seeds the SPICE activation boundary, records SPICE certification data, and records the block that certifies finalized chunk results. It then stores the block, advances the header and final heads when justified, and updates the body head when the block is the new tip. These normal chain writes share the ChainUpdate commit boundary, so a failed update does not leave a partial chain state. A block on a side fork is still stored, but it does not replace a higher or equal-height head.

ChainUpdate collects the results before it writes them. New-chunk results use the shared chunk persistence path, while old-chunk results carry forward their prior summary and apply their empty transition. Their chain-only records are merged into the same pending store update. The normal update is committed only after block data, epoch data, certification records, and head changes have been prepared. The SPICE executor uses the same per-shard persistence contract but commits each shard's apply as its own atomic unit. Its block-level step advances execution heads first, then updates flat storage and memory-trie cleanup after those heads are durable.

References: chain/…/chain.rs• L1246-1297 chain/…/chain.rs• L1800-1836 chain/…/chain.rs• L1900-1924 chain/…/chain_update.rs• L40-175 chain/…/chain_update.rs• L212-352 chain/…/chain_update.rs• L386-449 chain/…/chunk_application.rs• L46-148 chain/…/block_application.rs• L11-45

SPICE activation boundary

The SPICE activation boundary carries shard execution history from the pre-SPICE path into the SPICE path. The last pre-SPICE block seeds one uncertified chunk record per shard with its designated endorsements missing. The first SPICE block seeds the SPICE execution heads and carries those boundary records into its own certification record. This preserves the certification history across the protocol change.

Boundary synthesis rebuilds a pre-SPICE execution result from the stored chunk result and the outgoing receipts that the next execution context must commit. It also finds receipts carried by chunks that target shards did not yet apply. A boundary state witness includes the anchor transactions, source receipt proofs, recorded state transitions for later old-chunk applications, and undelivered receipt proofs. The system checks that the proofs reproduce the receipts recorded by the local apply. When a certified pre-SPICE result is available, a node compares it with its local synthesis only when it applied and still has the relevant shard artifacts; otherwise the result is not locally checkable.

Boundary validation accepts a witness only for the last pre-SPICE block and the active shard layout. It checks the transition sequence, transaction root, receipt commitments, and each replayed post-state root. This lets the new execution model preserve chunk order and undelivered receipts across the protocol boundary. The pre-SPICE test helpers build chains with new and carried chunk headers to exercise this boundary shape.

References: chain/…/chain_update.rs• L284-313 chain/…/boundary.rs• L20-34 chain/…/boundary.rs• L81-161 chain/…/boundary_synthesis.rs• L34-89 chain/…/boundary_synthesis.rs• L108-269 chain/…/boundary_synthesis.rs• L273-303 chain/…/boundary_synthesis.rs• L305-520 chain/…/boundary_synthesis.rs• L534-580 chain/…/pre_spice.rs• L21-180 chain/…/pre_spice.rs• L234-387

Deferred data and coordination

Processing can pause when the node lacks a parent, a chunk body, or state for a shard it will soon track. These cases are coordination states, not ordinary validation failures. The pools retain the work until the missing dependency arrives or the work becomes too old.

Missing chunks

When a required chunk is absent, the chain records the block against each missing chunk hash and asks the chunk system to fetch the data. Each accepted chunk removes one dependency. When the last dependency arrives, the block returns to normal processing in height order. A bounded pool prevents an unbounded backlog. A node only creates this wait state for data needed by a shard or part that it tracks. A chunk already recorded as invalid is treated as a known invalid input rather than requested again.

References: chain/…/chain.rs• L1148-1190 chain/…/chain.rs• L1688-1798 chain/…/missing_chunks.rs• L43-165

Orphan blocks

An orphan is a block whose parent is not yet known. The chain performs limited checks before storing it. When the parent is accepted, the chain retries dependent orphans and may request their nearby missing chunks. Epoch-boundary blocks can also remain in this state until the node has caught up with the shard state required for the next epoch. This preserves forward progress without treating an out-of-order network message as an invalid block.

References: chain/…/chain.rs• L2453-2480 chain/…/chain.rs• L2643-2686 chain/…/orphan.rs• L73-102 chain/…/orphan.rs• L390-424

Optimistic execution

Optimistic processing starts shard application from a block's expected metadata before the complete block is available. When the full block arrives, the normal path can reuse matching results. The chain derives a cache key from the execution context, all chunk hashes, and the shard identity, then checks the result before reuse. This reduces the time between block arrival and chain update, but it still requires the normal block checks before commitment. This path is disabled for SPICE blocks.

References: chain/…/chain.rs• L1300-1517 chain/…/chain.rs• L3400-3643

State synchronization

State synchronization restores a shard from a trusted state boundary and then rebuilds the missing block range. The first restored chunk is applied as a new chunk. Later heights use old-chunk transitions until the sync block is reached. The chain checks the reconstructed new-chunk summary against the sync block's committed header before it accepts the restored state.

The state-sync finalize path uses the same postprocessing rules as block application for a restored new chunk. A SPICE state-sync response carries no chunk to apply through this path. The SPICE-specific finalization path handles that case instead. For the later block range, old-chunk transitions update the state root and chunk summary without requiring a chunk body.

References: chain/…/chain.rs• L1622-1677 chain/…/chain_update.rs• L476-600 chain/…/chain_update.rs• L603-686

Epoch boundaries and resharding

Epoch changes coordinate block processing with state availability for the next shard assignment. The first block of an epoch can wait for state sync before it applies all shards. After catch-up, the chain applies the stored work for the next-epoch shards and starts resharding where required. Head changes also update epoch sync records and produce an epoch light-client block when the new head crosses an epoch boundary.

References: chain/…/chain.rs• L2651-2682 chain/…/chain.rs• L3070-3104 chain/…/chain_update.rs• L263-350

Data retention

Data retention removes old block and chunk records without removing state that active chain processing still needs. The cleanup rules account for canonical blocks, discarded forks, shard-layout changes, SPICE certification, and the difference between hot and archival data.

Chunk data cleanup

Canonical cleanup advances the chunk tail and removes old chunk bodies, partial data, receipt data, and related headers after the retention point. Fork cleanup removes block-linked data and reverts state inserted by the fork. Cleanup also includes both the current and next shard layouts when a resharding boundary can leave data under either layout.

References: chain/…/garbage_collection.rs• L440-468 chain/…/garbage_collection.rs• L470-525 chain/…/garbage_collection.rs• L560-660 chain/…/garbage_collection.rs• L663-799

SPICE evidence cleanup

SPICE keeps some evidence longer than ordinary chunk data. State-transition data remains while it can support the final block's relevant chunks, and witnesses remain until the final head has passed the last certified block. Invalid-chunk evidence and SPICE endorsement and execution records follow their own cleanup points so validation can finish before the data is removed.

References: chain/…/garbage_collection.rs• L309-437 chain/…/garbage_collection.rs• L802-888 chain/…/garbage_collection.rs• L940-1023

Change checklist

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

  • A change to a chunk header field can affect chunk production, block roots, previous ChunkExtra checks, encoded-body checks, and block serialization together.
  • A change to height_included or old-chunk handling must preserve the same new-versus-old meaning in block validation, runtime application, state-sync replay, and postprocessing.
  • A change to part ownership or shard tracking must keep distribution, forwarding, request targets, receipt proofs, and reconstruction needs aligned.
  • A change to chunk application persistence must keep the completion summary with its refcounted state and receipt writes, while preserving the different commit scopes for normal chain updates and SPICE per-shard updates.
  • A change to SPICE apply context must keep current-shard to previous-shard mapping aligned for congestion data, bandwidth requests, gas price, and resharding boundaries.
  • A change to SPICE block postprocessing must keep durable execution-head updates ahead of flat-storage advancement and memory-trie cleanup.
  • A change to epoch or shard layout timing must be checked across chunk producer selection, missing-chunk lookup, state sync, resharding, and head updates.
  • A change to the SPICE fallback rule must keep the designated assignment, fallback delay, total-stake threshold, fallback-only slot schedule, execution-result requirement, and ancestry ordering consistent.
  • A change to the SPICE path must keep block admission, core-statement checks, execution commitments, certification records, and the choice between certified results and local shard jobs consistent.
  • A change to runtime state inputs must keep normal database reads, state-sync replay, optimistic cache keys, and chunk-result commitments aligned.
  • A change to early next-chunk preparation must keep block time and epoch context aligned with gas, congestion, bandwidth, and shard-state inputs.
  • A change to per-shard transaction-pool limits must preserve the capacity share for external contract-call transactions across pool creation, transaction reintroduction, and resharding.
  • A change to epoch-boundary updates must keep validator proposals, epoch sync proofs, shard layout, and epoch light-client records on the same parent-block context.
  • A change to SPICE activation-boundary data must keep seeded uncertified chunks, execution heads, synthesized execution results, undelivered receipt proofs, witness transition order, and replayed state roots aligned.
  • A change to cleanup thresholds must preserve the data needed for state sync, witness production, certification, and both current and next shard layouts.

Important failure modes

TriggerConsequenceGuard
Block roots do not match its chunk headers or bodyThe block is rejected before shard applicationRecompute block roots and compare them during admission
New chunk points to a different parent than the blockThe chunk cannot be trusted for this blockValidate each new chunk's previous block hash
Old chunk differs from the prior block's headerA skipped shard could change without a new chunkRequire exact old-header carry-forward
Required chunk parts or receipts do not arriveThe block waits instead of changing chain stateTrack dependencies in the bounded missing-chunks pool
Fewer than the data threshold of parts are availableThe full chunk cannot be rebuiltRequest or forward more parts before reconstruction
Chunk header disagrees with the prior ChunkExtraState or receipt continuity breaksCompare prior execution summaries with the new header
Shard state for the next epoch is not readyThe epoch-boundary block cannot apply all needed shardsHold the block for state sync or catch-up
Certified execution data does not match the active protocol pathThe block is rejected or local shard work is not selectedRequire protocol-specific commitment checks before application
Runtime state reads or reconstructed state differ from the committed contextThe chunk cannot produce an acceptable state transitionValidate the execution inputs and compare the resulting chunk summary
A next-chunk preparation callback uses the wrong block time or epoch contextThe producer prepares work under rules that do not match the next chain positionPass the applied block's time and epoch data with the post-state
A shard result fails after other shard results are readyThe block must not commit only part of its stateApply results through one ChainUpdate commit boundary
A chunk completion marker is written without its refcounted state or receipt writesA retry can count the same references twice or leave the shard marked complete without its dataKeep the completion marker and refcounted writes in one store update
SPICE derives congestion or bandwidth data from the wrong previous shard layoutTransaction admission and execution use inputs for a different shardMap each current shard to its previous execution result before building the apply context
SPICE advances flat storage or memory-trie cleanup before execution heads are durableReaders can observe storage that does not match the certified execution frontierCommit execution-head updates before post-commit storage work
Runtime uses the wrong epoch or shard-layout contextValidator changes, state access, or resharding can apply to the wrong chain stateResolve context from the previous block and use a layout-qualified shard identity
A shard transaction pool is created before its external contract-call capacity share is configuredThe pool uses an unintended capacity policySet the pool policy before creating per-shard pools
A fallback endorsement set has exactly one third or less of total epoch stakeIts execution result is not accepted as certificationRequire more than one third of the all-stake assignment
A fallback-only chunk is certified with only its designated validatorsThe execution result remains uncertifiedApply the all-stake rule to fallback-only slots
A block tries to certify a child while an older chunk remains uncertifiedThe certification frontier skips a shard transitionReject the child result until the older chunk is certified
A boundary witness names the wrong pre-SPICE block or omits an implicit transitionThe activation-boundary chunk cannot be validatedMatch the witness to the last pre-SPICE block and replay every expected transition
The first SPICE block lacks the seeded parent certification rowBoundary chunks are dropped from certification trackingRequire the last pre-SPICE row before recording the first SPICE block
Cleanup removes witness or transition data before its certification or state-sync useLater witness production or recovery cannot completeRetain data through the final and certification frontiers
State sync sends a SPICE response through the ordinary chunk-finalize pathThe response is rejected because it has no chunk to applyRoute SPICE state finalization through its dedicated path

Key files

FileWhy to read it
core/…/block.rsDefines the block and chunk view and the block-wide consistency checks.
core/…/sharding.rsDefines chunk headers, bodies, encoding, and new-versus-old chunk meaning.
chain/…/chunk_producer.rsShows how a producer creates a chunk from prior shard state and receipts.
chain/…/client.rsShows how completed chunks reach the client and how each shard's transaction pool applies capacity and resharding rules.
chain/…/shards_manager_actor.rsShows how parts and receipt proofs move, validate, and rebuild into chunks.
chain/…/genesis.rsShows how the first block, chunks, chunk summaries, and initial heads are established.
chain/…/chain.rsOwns block admission, shard scheduling, deferred processing, optimistic execution, state-sync catch-up, and postprocessing coordination.
chain/…/chunk_application.rsDefines the shared per-shard apply persistence contract and builds SPICE execution inputs from prior certified chunk results.
chain/…/block_application.rsShows how SPICE advances execution heads and then updates storage after the durable commit.
chain/…/validate.rsDefines continuity checks between chunk headers, chunk bodies, and prior summaries.
chain/…/all_stake_fallback.rsDefines when stalled or fallback-only chunks can use total epoch stake for certification.
chain/…/core.rsCoordinates SPICE endorsements, execution results, uncertified chunks, and certification validation.
chain/…/boundary.rsSeeds activation-boundary certification state and the SPICE execution heads.
chain/…/boundary_synthesis.rsRebuilds pre-SPICE execution results, receipt proofs, and boundary witnesses from stored apply data.
chain/…/boundary_chunk_validation.rsShows how boundary witnesses and their implicit old-chunk transitions are checked.
chain/…/pre_spice.rsProvides the pre-SPICE chain shapes used to exercise activation-boundary behavior.
chain/…/update_shard.rsDefines the new-chunk and old-chunk shard update paths.
chain/…/mod.rsApplies shard state transitions, prepares chunk transactions, enforces state-read limits, and supplies epoch-aware execution results.
chain/…/chain_update.rsShows how shard results, state-sync results, SPICE boundary records, and block data become one committed chain update.
chain/…/garbage_collection.rsShows when chunk, state-transition, witness, fork, and SPICE evidence data can be removed.
chain/…/missing_chunks.rsShows how blocks wait for missing chunk dependencies and become ready again.