verify.rs
Overview
This file provides functionality to verify blocks within the blockchain's block production and validation process. It contains mechanisms to validate the integrity, consistency, and correctness of candidate blocks before they are accepted by the node. The verification process compares candidate blocks against expected state updates and blockchain configurations, ensuring that only valid blocks propagate through the network.
The core functionality is exposed via the verify_block function, which performs comprehensive checks and produces a verification result indicating whether the block is valid, invalid, or too complex to execute within constraints. The file also provides support functions to prepare previous block metadata and debug transaction details during verification failures.
Enumerations
VerificationResult
Represents the possible outcomes of a block verification attempt.
pub enum VerificationResult {
ValidBlock,
BadBlock,
TooComplexExecution,
}
Variants:
ValidBlock: The candidate block passed all verification checks.BadBlock: The candidate block failed verification due to inconsistencies or errors.TooComplexExecution: The verification process could not complete within resource/time limits.
Methods:
is_valid(&self) -> bool: Returnstrueif the result isValidBlock, otherwisefalse.
Functions
verify_block
pub fn verify_block(
block_candidate: &AckiNackiBlock,
blockchain_config: Arc<BlockchainConfig>,
prev_block_optimistic_state: &mut OptimisticStateImpl,
node_config: Config,
refs: Vec<CrossThreadRefData>,
shared_services: SharedServices,
block_nack: Vec<Envelope<GoshBLS, NackData>>,
block_state_repo: BlockStateRepository,
accounts_repo: AccountsRepository,
metrics: Option<BlockProductionMetrics>,
wasm_cache: WasmNodeCache,
message_db: MessageDurableStorage,
) -> anyhow::Result<VerificationResult>
Performs full verification of a candidate block against the blockchain state and configuration.
Parameters:
block_candidate: The block proposed for verification.blockchain_config: Shared blockchain configuration parameters.prev_block_optimistic_state: Mutable reference to the optimistic state from the previous block, updated upon successful verification.node_config: Configuration settings specific to the node.refs: Cross-thread references needed during verification.shared_services: Shared services used during block processing.block_nack: Collection of negative acknowledgments related to the block.block_state_repo: Repository interface for block state persistence.accounts_repo: Repository interface for account state persistence.metrics: Optional metrics collector for block production.wasm_cache: Cache for WebAssembly execution nodes.message_db: Durable storage for messages.
Returns:
Ananyhow::Resultwrapping aVerificationResult, indicating verification success, failure, or complexity issues.Detailed Description:
Initializes a
TVMBlockVerifierusing a builder pattern with the provided configurations and repositories.Generates a verified block by invoking
generate_verify_blockon the verifier, which performs block execution and state validation.Handles errors indicating either:
Verification failure (
VerifyError), e.g., incomplete message processing.Execution exceeding resource/time limits (
ExecutorError::TerminationDeadlineReached).
Compares the verified block's TVM block data with the candidate's. If they differ, performs a partial equality check on key fields such as global ID, info, value flow, message queue updates, extra data, and state update hashes.
If partial equality fails, logs detailed discrepancies and returns
BadBlock.If partial equality passes (blocks differ only in non-critical ways), adjusts the verification state and returns
ValidBlock.Updates the
prev_block_optimistic_stateon successful verification.Optionally measures and logs timing information under the "timing" feature flag.
Usage Example:
let verification_result = verify_block(
&candidate_block,
blockchain_config.clone(),
&mut prev_block_state,
node_config.clone(),
cross_thread_refs,
shared_services.clone(),
block_nack,
block_state_repo.clone(),
accounts_repo.clone(),
Some(metrics),
wasm_cache.clone(),
message_storage.clone(),
)?;
if verification_result.is_valid() {
// Proceed with next steps for a valid block
} else {
// Handle invalid or too complex blocks accordingly
}
prepare_prev_block_info
pub fn prepare_prev_block_info(block_candidate: &AckiNackiBlock) -> BlockInfo
Prepares and extracts summary information about the previous block, encapsulated in a BlockInfo structure.
Parameters:
block_candidate: Reference to the candidate block for which previous block info is prepared.
Returns:
ABlockInfoinstance containing the previous block reference, including logical time (end_lt), sequence number (seq_no), root hash, and file hash.Details:
Reads block info from the candidate's TVM block.
Serializes the raw block data and computes its representation hash.
Calculates a file hash from the serialized block bytes.
Packages these values into a
BlkPrevInfo::Blockvariant wrapped asBlockInfo.
Usage Example:
let prev_block_info = prepare_prev_block_info(&block_candidate);
display_block_transactions
fn display_block_transactions(block: &AckiNackiBlock)
A helper function to output detailed transaction information from a block to tracing logs, mainly for debugging purposes during verification failures.
Parameters:
block: The block whose transactions are to be displayed.
Behavior:
Reads the
extrafield of the block's TVM block to access account blocks.Iterates over each account block and its transactions.
Logs account IDs, transaction input messages, and transaction details.
Errors during reading or iteration produce error-level logs.
Usage Context:
Called internally when verification detects discrepancies in transaction counts or content between candidate and verified blocks.
Implementation Details and Algorithms
Verification Process:
Uses
TVMBlockVerifieras the primary engine for block verification. This verifier executes the block's transactions and state transitions using the TVM (TON Virtual Machine) logic.The verification function handles errors gracefully, distinguishing between fatal verification errors, partial failures, and execution complexity issues.
Partial equality checks are performed when full block equality fails, allowing for minor acceptable differences in state updates or block metadata without rejecting the block outright.
Extensive tracing and logging are used to record verification progress and reasons for failure, aiding observability and debugging.
The block state is updated atomically to ensure consistency between verification attempts.
Hash Computations:
The file hash and representation hash computations ensure integrity and identify block uniqueness.
These hashes are used to compare blocks and detect tampering or data corruption.
Interactions with Other Components
TVMBlockVerifier
Used to perform the core block execution and verification logic.Repositories:
BlockStateRepositoryandAccountsRepositoryprovide access to persisted blockchain and account states required during verification.
OptimisticStateImpl
Mutable state representing the blockchain's optimistic state at the previous block, updated upon successful verification.MessageDurableStorage
Provides message persistence necessary for transaction execution and verification.WasmNodeCache
Caches WebAssembly nodes to optimize repeated execution during verification.SharedServicesandConfig
Injected dependencies providing node-wide services and configuration data.Envelope<GoshBLS, NackData>
Used to represent block negative acknowledgments (NACKs) for error handling.The file is part of the block production module (
crate::block::producer) and interacts with consensus, execution, and storage layers of the system.
File Structure Diagram
flowchart TD
A[verify_block] -->|calls| B[TVMBlockVerifier::generate_verify_block]
B -->|returns| C[VerificationResult]
A -->|calls| D[prepare_prev_block_info]
A -->|calls| E[display_block_transactions]
D --> F[BlkPrevInfo::Block]
E --> G[logs transaction details]
A -->|updates| H[OptimisticStateImpl]