mod.rs
Overview
This file defines core data structures and logic related to the construction and management of blockchain blocks within a shard environment. It focuses on preparing blocks (PreparedBlock), managing thread execution results (ThreadResult), and orchestrating the block building process (BlockBuilder). The file also introduces error types related to block execution and provides supporting constructs for message handling, account state updates, and cross-thread interactions in a concurrent block production context.
Public Structs and Their Usage
PreparedBlock
Represents a fully or partially constructed block ready for further processing or committing to the chain state.
Fields:
block: Block
The actual blockchain block data structure.remain_fees: Grams
Remaining fees after block execution.state: OptimisticStateImpl
The optimistic shard state after applying block transactions.is_empty: bool
Indicates if the block contains any meaningful transactions.active_threads: Vec<(Cell, ActiveThread)>
Active execution threads involved in the block processing.tx_cnt: usize
Number of transactions included in the block.block_keeper_set_changes: Vec<BlockKeeperSetChange>
Changes in the block keeper set relevant for consensus or network state.cross_thread_ref_data: CrossThreadRefData
Data necessary for cross-thread communication and references.accounts_number_diff: Option<i64>(conditional compilation)
Difference in the number of accounts monitored, useful for metrics.
ThreadResult
Encapsulates the outcome of executing a single thread of transactions.
Fields:
transaction: Transaction
The transaction processed in this thread.lt: u64
Logical time associated with the transaction.account_root: Cell
Root cell of the account's state after processing.account_id: AccountAddress
Address of the account involved.minted_shell: i128
Amount of tokens minted during execution.initial_dapp_id: Option<DAppIdentifier>
Initial decentralized application identifier, if any.initial_code_hash: Option<UInt256>
Initial code hash of the smart contract.initial_account: Option<Account>
Initial account state, populated only for epoch contracts.in_msg_is_ext: bool
Flag indicating if the incoming message is external.in_msg: Message
The incoming message processed.
ActiveThread
Keeps track of currently executing threads during block production.
Fields:
result_rx: InstrumentedReceiver<anyhow::Result<ThreadResult>>
Receiver channel for getting thread execution results asynchronously.message: Message
The message driving this thread's execution.vm_execution_is_block_related: Arc<Mutex<bool>>
Shared flag indicating if VM execution is related to the block.block_production_was_finished: Arc<Mutex<bool>>
Shared flag indicating if block production has completed.
EngineTraceInfoData
Provides detailed tracing information for VM execution steps, useful for debugging or telemetry.
Fields:
info_type: String
Type of trace info (e.g., opcode execution).step: u32
The step number in the execution.cmd_str: String
The command executed as a string.stack: Vec<String>
Stack state at this step.gas_used: String
Gas used up to this command.gas_cmd: String
Gas cost of this command.cmd_code_rem_bits: u32
Remaining bits in the command code.cmd_code_hex: String
Command code represented in hex.cmd_code_cell_hash: String
Hash of the command code cell.cmd_code_offset: u32
Offset in the code of this command.
BlockBuilder
Primary structure that manages block construction within a shard and thread context.
Fields (key highlights):
thread_id: ThreadIdentifier
Identifier of the thread for which the block is being built.shard_state: Arc<ShardStateUnsplit>
Current shard state before building the block.accounts: ShardAccounts
Account states involved in the block.block_info: BlockInfo
Metadata about the block being produced.rand_seed: UInt256
Random seed used for deterministic operations.new_messages: BTreeMap<MessageIndex, (Message, Option<Cell>)>
Messages produced during block execution.in_msg_descr: InMsgDescrandout_msg_descr: OutMsgDescr
Descriptions of input and output messages processed.block_gas_limit: u64
Gas limit for the block to control resource usage.total_gas_used: u64
Total gas consumed so far in block production.copyleft_rewards: CopyleftRewards
Rewards distribution information.control_rx_stop: Option<InstrumentedReceiver<()>>
Optional channel to receive stop signals for block building.parallelization_level: usize
Degree of parallel execution allowed.tx_cnt: usize
Number of transactions processed.wasm_cache: WasmNodeCache
Cache used to accelerate WebAssembly execution.accounts_repository: AccountsRepository
Repository interface to manage account data.dapp_credit_map: HashMap<DAppIdentifier, DappConfig>
Configuration map for decentralized applications.consumed_internal_messagesand produced_internal_messages_to_*
Track internal messages consumed or produced across threads.metrics: Option<BlockProductionMetrics>
Optional metrics collection for block production.accounts_number_diff: i64(conditional compilation)
Tracks changes in account counts.
Methods
is_limits_reached(&mut self) -> bool
Checks if the block builder should stop producing the block due to external stop requests or gas limits.
Returns
trueif:A stop request was received via the control channel.
The total gas used exceeds the block gas limit.
Returns
falseotherwise.
Usage Example
let mut builder = BlockBuilder::new(...);
if builder.is_limits_reached() {
// Stop further processing
}
Error Types
ExecuteError
Enumerates possible errors during execution in block building context.
Variants:
AccountWasMovedRerouteInternalMessage
Indicates an account has moved to another thread; internal message should be rerouted.AccountWasMovedIgnoreExternalMessage
Account moved to another thread; external message should be ignored.WrongDestinationThread(AccountRouting)
The destination account does not belong to the expected thread state.
Important Implementation Details
Concurrency and Parallel Execution:
TheBlockBuildermanages concurrent execution via thread identifiers and message routing, using synchronization primitives such asArc<Mutex<>>for shared flags. It supports parallelization controlled byparallelization_level.Gas Limit Enforcement:
Gas consumption is monitored continuously, and block production halts once the gas limit is reached or an external stop is requested.Cross-Thread Message Management:
Internal messages sent to accounts in other threads are tracked separately to ensure correct routing and state consistency.WebAssembly Execution Optimization:
Thewasm_cachestores compiled modules or execution state for efficient repeated execution of smart contracts.Metrics and Monitoring:
Optional metrics collection enables monitoring of block production efficiency and account state changes.Use of
InstrumentedReceiver:
Channels wrapped with instrumentation enable telemetry and observability for asynchronous operations such as thread result reception and control signaling.
Interactions with Other Modules
tvm_block: Provides foundational blockchain structures likeBlock,Account,Transaction, and message descriptors.tvm_types: Supplies low-level data types such asCell,UInt256, andUsageTree.crate::block::producer::wasm::WasmNodeCache: Used for caching WebAssembly execution nodes.crate::repository::accounts::AccountsRepository: Manages persistent account state.crate::block_keeper_system::BlockKeeperSetChange: Tracks changes to the block keeper set for consensus.crate::message::identifier::MessageIdentifierandWrappedMessage: For internal message identification and wrapping.crate::types: Defines types likeAccountAddress,AccountRouting,DAppIdentifier, andThreadIdentifierused extensively in routing and identification.crate::creditconfig::DappConfig: Configuration for decentralized applications used in credit and minting logic.
The BlockBuilder serves as a central orchestrator integrating these modules to build blocks respecting shard and thread boundaries, message passing semantics, and gas/resource constraints.
Visual Diagram
classDiagram
class PreparedBlock {
+block: Block
+remain_fees: Grams
+state: OptimisticStateImpl
+is_empty: bool
+active_threads: Vec<(Cell, ActiveThread)>
+tx_cnt: usize
+block_keeper_set_changes: Vec<BlockKeeperSetChange>
+cross_thread_ref_data: CrossThreadRefData
}
class ThreadResult {
+transaction: Transaction
+lt: u64
+account_root: Cell
+account_id: AccountAddress
+minted_shell: i128
+initial_dapp_id: Option<DAppIdentifier>
+initial_code_hash: Option<UInt256>
+initial_account: Option<Account>
+in_msg_is_ext: bool
+in_msg: Message
}
class ActiveThread {
+result_rx: InstrumentedReceiver
+message: Message
+vm_execution_is_block_related: Arc<Mutex<bool>>
+block_production_was_finished: Arc<Mutex<bool>>
}
class BlockBuilder {
+thread_id: ThreadIdentifier
+shard_state: Arc<ShardStateUnsplit>
+accounts: ShardAccounts
+block_info: BlockInfo
+rand_seed: UInt256
+new_messages: BTreeMap
+in_msg_descr: InMsgDescr
+out_msg_descr: OutMsgDescr
+block_gas_limit: u64
+total_gas_used: u64
+copyleft_rewards: CopyleftRewards
+parallelization_level: usize
+tx_cnt: usize
+wasm_cache: WasmNodeCache
+accounts_repository: AccountsRepository
+metrics: Option<BlockProductionMetrics>
+consumed_internal_messages: HashMap
+produced_internal_messages_to_the_current_thread: HashMap
+produced_internal_messages_to_other_threads: HashMap
}
PreparedBlock --> "many" ActiveThread : has
ActiveThread --> ThreadResult : produces
BlockBuilder --> PreparedBlock : builds
BlockBuilder --> ActiveThread : manages
BlockBuilder --> BlockInfo : uses
BlockBuilder --> AccountsRepository : uses
This diagram shows the relationship between the primary entities managing block construction and execution threads, highlighting that BlockBuilder is the main controller that manages multiple ActiveThread instances which produce ThreadResults culminating in a PreparedBlock.