single_block_producer.rs
Overview
This file implements the functionality for producing a single block within a blockchain system. It defines a generic trait BlockProducer that outlines the contract for block production and provides a concrete implementation TVMBlockProducer tailored for a TVM-based blockchain environment. The block production process involves pre-processing of input states and messages, building the new block, managing cross-thread references, handling slashing messages, and performing load balancing checks.
The file orchestrates interactions between various components such as message storage, blockchain configuration, block state repositories, shared services, and WASM caching to produce a valid block. It ensures that block production respects execution time limits and parallelization constraints while managing thread activity and cross-thread communication.
Key Components
Trait: BlockProducer
Defines the interface for producing a single block.
Associated Types
OptimisticState: The type representing the optimistic state of the blockchain.Message: The type representing messages processed during block production.
Method: produce
fn produce<'a, I>(
self,
thread_identifier: ThreadIdentifier,
parent_state: Self::OptimisticState,
refs: I,
control_rx_stop: InstrumentedReceiver<()>,
message_db: MessageDurableStorage,
time_limits: &ExecutionTimeLimits,
block_round: BlockRound,
parent_block_state: BlockState,
) -> anyhow::Result<(
AckiNackiBlock,
Self::OptimisticState,
Vec<(Cell, ActiveThread)>,
CrossThreadRefData,
Vec<Stamp>,
ExtMsgFeedbackList,
BlockState,
)>
where
I: std::iter::Iterator<Item = &'a CrossThreadRefData> + Clone,
CrossThreadRefData: 'a;
Parameters:
self: The block producer instance. Consumed to ensure one-time use.thread_identifier: Identifier of the thread for which the block is produced.parent_state: The optimistic state of the parent block.refs: Iterator over cross-thread reference data required for block production.control_rx_stop: Instrumented receiver for stop signals to interrupt block production.message_db: Durable storage for external messages.time_limits: Execution time limits for block production phases.block_round: The current round number for block production.parent_block_state: The state of the parent block.
Returns: A tuple containing:
AckiNackiBlock: The produced block with associated metadata.Updated optimistic state after block production.
Vector of active threads represented as
(Cell, ActiveThread)pairs.Updated cross-thread reference data.
Vector of processed external message stamps.
List of feedback for external messages.
Updated block state reflecting the newly produced block.
Usage Example:
let produced_result = block_producer.produce(
thread_id,
parent_state,
refs_iter,
control_receiver,
message_storage,
&time_limits,
block_round,
parent_block_state,
)?;
Struct: TVMBlockProducer
Concrete implementation of the BlockProducer trait for TVM-based blockchains.
Fields
active_threads: Vector of(Cell, ActiveThread)tuples representing currently active threads.blockchain_config: Shared reference to the blockchain configuration.message_queue: Map of account addresses to queues of pending messages.producer_node_id: Identifier of the node producing the block.thread_count_soft_limit: Soft limit on the number of threads to manage.parallelization_level: Level of parallelization allowed during block production.block_keeper_epoch_code_hash: Epoch code hash used by the block keeper.block_keeper_preepoch_code_hash: Pre-epoch code hash used by the block keeper.epoch_block_keeper_data: Vector of epoch-specific block keeper data.shared_services: Shared services container for accessing common resources.block_nack: List of negative acknowledgements (NACK) envelopes for handling slashing.accounts: Repository managing account states.block_state_repository: Repository managing block states.metrics: Optional block production metrics collector.wasm_cache: Cache for WASM execution nodes.
Methods
print_block_info
fn print_block_info(block: &tvm_block::Block)
Logs information about the generated block including generation time, incoming/outgoing message counts, and account blocks.
Parameters:
block- Reference to the block to log information from.Usage: Called internally after successful block generation to output block details.
produce (implementation of BlockProducer trait)
Implements the full block production workflow:
Pre-processing Phase:
Processes parent state, incoming references, and slashing messages (NACKs).
Creates wallet slash messages for nodes identified from NACK reasons.
Calls the preprocessor (
crate::block::preprocessing::preprocess) for state preparation.
Block Building Phase:
Initializes a
BlockBuilderwith parameters including gas limits, accounts, and WASM cache.Builds the block using the message queue and blockchain configuration.
Logs the produced block info.
Post-processing Phase:
Performs load balancing checks via shared services to decide if thread splitting or collapsing is required.
Updates cross-thread reference data and block state accordingly.
Prepares the final
AckiNackiBlockwith all relevant metadata.
Parameters: Same as the trait definition.
Returns: Same as the trait definition.
Error Handling: Uses
anyhow::Resultfor error propagation.Instrumentation: Uses
tracingspans to provide detailed observability of production phases.The method consumes the
TVMBlockProducerinstance to prevent reuse, ensuring thread safety and correctness.
Important Implementation Details and Algorithms
Slashing Message Handling: The producer collects NACK messages and converts them into wallet slash messages to penalize misbehaving nodes. This logic extracts node identity data from the NACK reason and prepares corresponding slash messages.
Cross-thread Reference Management: Throughout the block production workflow, the system maintains and updates cross-thread reference data to ensure consistency across threads.
Load Balancing Checks: After block building, the producer invokes a load balancing service to determine whether thread structures need to be adjusted (split or collapse). The producer updates the block state and cross-thread references based on the proposed thread actions.
Gas Limit Enforcement: The block builder respects the block gas limit derived from the blockchain configuration to ensure blocks do not exceed resource constraints.
Use of Execution Time Limits: The production respects configured execution time limits to maintain performance and responsiveness.
Concurrency Considerations: The use of
InstrumentedReceiverfor stop signals enables graceful interruption of block production, supporting multi-threaded environments.
Interactions with Other System Components
BlockBuilder: The
BlockBuilderclass is used to construct the block based on the prepared state and messages.SharedServices: Provides access to services like load balancing and cross-thread reference data management.
MessageDurableStorage: Supplies persistent storage for external messages required during block processing.
BlockStateRepository: Maintains and updates block states before and after production.
AccountsRepository: Manages accounts state used during block construction.
WasmNodeCache: Caches WASM execution nodes to optimize smart contract execution during block production.
Telemetry and Tracing: Uses telemetry utilities and the
tracingcrate for logging and performance instrumentation.Slashing Mechanism: Integrates slashing messages via
BlockKeeperSlashDataand wallet message creation.
Mermaid Class Diagram
classDiagram
class BlockProducer {
<<trait>>
produce()
}
class TVMBlockProducer {
-active_threads: Vec<(Cell, ActiveThread)>
-blockchain_config: Arc<BlockchainConfig>
-message_queue: HashMap<AccountAddress, VecDeque<(Stamp, tvm_block::Message)>>
-producer_node_id: NodeIdentifier
-thread_count_soft_limit: usize
-parallelization_level: usize
-block_keeper_epoch_code_hash: String
-block_keeper_preepoch_code_hash: String
-epoch_block_keeper_data: Vec<BlockKeeperData>
-shared_services: SharedServices
-block_nack: Vec<Envelope<GoshBLS, NackData>>
-accounts: AccountsRepository
-block_state_repository: BlockStateRepository
-metrics: Option<BlockProductionMetrics>
-wasm_cache: WasmNodeCache
+print_block_info(block: &tvm_block::Block)
+produce()
}
BlockProducer <|.. TVMBlockProducer
This diagram illustrates the trait BlockProducer and its implementation TVMBlockProducer, showing the main fields and methods of the latter. It highlights the key properties used for block production and the core methods involved.
For details on related concepts such as optimistic state management, message handling, execution time limits, and block building algorithms, see these topics: