block.rs
Overview
This file defines the Block struct representing blockchain block records stored in a SQLite database and provides asynchronous methods to query these blocks. The main functionality revolves around retrieving blocks from the database with various filtering, ordering, and pagination options. It leverages SQLx for database interactions and supports integration with GraphQL query arguments defined elsewhere.
Block Struct
The Block struct models the blocks table in the SQLite database, with fields corresponding to columns in the table. It derives Clone, Debug, and FromRow traits to support cloning, debugging, and direct deserialization from SQL query results.
Fields
rowid: i64
Internal SQLite row ID (primary key), skipped in SQLx mapping.id: String
Unique block identifier (block_id), not nullable.after_merge,after_split,before_split,key_block,flags,gen_catchain_seqno,gen_software_version,gen_utime,gen_utime_ms_part,gen_validator_list_hash_short,global_id,min_ref_mc_seqno,prev_key_block_seqno,prev_ref_seq_no,status,tr_count,version,want_merge,want_split,workchain_id
Optional integer metadata fields describing various block properties.aggregated_signature,signature_occurrences,boc,data
Optional binary large objects (BLOB) storing cryptographic signatures, block content, and other data.chain_order,end_lt,file_hash,gen_software_capabilities,in_msgs,out_msgs,parent,prev_alt_ref_seq_no,prev_alt_ref_end_lt,prev_alt_ref_file_hash,prev_alt_ref_root_hash,prev_ref_end_lt,prev_ref_file_hash,prev_ref_root_hash,producer_id,root_hash,shard,share_state_resource_address,start_lt,thread_id
Optional string fields representing various hashes, references, messaging data, chain ordering, and shard details.seq_no: i64
Block sequence number, not nullable.
The fields closely follow the blockchain domain model, storing details such as cryptographic signatures, references to previous blocks, transaction counts, merge/split states, and timestamps.
Methods
list
pub async fn list(
pool: &SqlitePool,
where_clause: String,
order_by: String,
limit: Option<i32>,
) -> anyhow::Result<Vec<Block>>
Retrieves a list of blocks from the database applying a custom SQL WHERE clause and ordering.
Parameters:
pool: Reference to a SQLx SQLite connection pool.where_clause: SQLWHEREconditions as a string (e.g.,"WHERE seq_no > 100").order_by: SQLORDER BYclause (e.g.,"ORDER BY seq_no DESC").limit: Optional limit on the number of rows to retrieve; ifNone, defaults to the project'sQUERY_BATCH_SIZE.
Returns:
Result<Vec<Block>, anyhow::Error>— Vector of blocks matching the criteria or an error.Usage example:
let blocks = Block::list(
&pool,
"WHERE seq_no > 100".to_string(),
"ORDER BY seq_no DESC".to_string(),
Some(10)
).await?;
Implementation details:
Constructs a SQL query string from the parameters.
Uses
QueryBuilderfrom SQLx to build and execute the query.Collects results asynchronously into a vector.
Logs SQL and errors using the
tracingcrate.
latest_block
pub async fn latest_block(pool: &SqlitePool) -> anyhow::Result<Option<Block>>
Retrieves the most recent block in the database based on descending chain_order.
Parameters:
pool: Reference to a SQLx SQLite connection pool.
Returns:
Result<Option<Block>, anyhow::Error>— The latest block if any exists, elseNone.Usage example:
if let Some(block) = Block::latest_block(&pool).await? {
println!("Latest block ID: {}", block.id);
}
Implementation details:
Executes a SQL query ordering by
chain_orderdescending with a limit of 1.Utilizes
fetch_optionalto handle no result gracefully.
blockchain_blocks
pub async fn blockchain_blocks(
pool: &SqlitePool,
args: &BlockchainBlocksQueryArgs,
) -> anyhow::Result<Vec<Block>>
Retrieves blockchain blocks filtered and paginated based on GraphQL query arguments.
Parameters:
pool: Reference to a SQLx SQLite connection pool.args: Reference toBlockchainBlocksQueryArgs(defined in another module) encapsulating pagination and filtering options.
Returns:
Result<Vec<Block>, anyhow::Error>— Vector of filtered blocks or an error.Usage example:
let blocks = Block::blockchain_blocks(&pool, &args).await?;
Implementation details:
Extracts pagination direction and limit from
args.pagination.Constructs a dynamic SQL
WHEREclause based on optional filters likeafter,before, sequence number range, and transaction count boundaries.Supports pagination directions
Forward(ascending) andBackward(descending).Builds and executes a SQL query with the constructed filters and ordering.
Reverses the result list if pagination direction is backward to maintain consistent ordering.
Logs SQL trace information.
Algorithm Highlights:
Dynamic SQL query construction involves building a vector of conditional strings (
where_ops) based on provided filters.Converts numeric values to string representations for proper SQL syntax using helper
u64_to_string.Ensures safe and flexible querying tailored to various front-end pagination and filtering needs.
Interaction with Other Modules
defaults: Provides constants likeQUERY_BATCH_SIZEfor default query limits.helpers::u64_to_string: Utility to convertu64values into strings, used for SQL query construction.schema::graphql::query::PaginateDirection: Enum defining pagination direction (ForwardorBackward), used inblockchain_blocks.schema::graphql_ext::blockchain_api::blocks::BlockchainBlocksQueryArgs: Struct representing GraphQL query arguments for fetching blocks, encapsulating pagination and filters.
This file is primarily a backend data access layer component supporting the blockchain API and GraphQL queries by providing structured access to block data stored in SQLite.
Important Implementation Details
Uses SQLx's
FromRowtrait for ORM-like automatic mapping between SQL rows and Rust structs.Makes use of asynchronous database queries for non-blocking I/O operations.
Employs Rust's
anyhowcrate for error handling, returning rich error contexts.Uses SQL string formatting carefully to avoid SQL injection (note: direct string interpolation is used here; in production, parameterized queries are safer).
Implements custom pagination logic supporting bi-directional navigation through blockchain data.
Logs SQL queries and errors at various levels (
debug,trace,error) for observability.
Mermaid Class Diagram
classDiagram
class Block {
+rowid: i64
+id: String
+after_merge: Option<i64>
+after_split: Option<i64>
+aggregated_signature: Option<Vec<u8>>
+before_split: Option<i64>
+boc: Option<Vec<u8>>
+chain_order: Option<String>
+end_lt: Option<String>
+file_hash: Option<String>
+flags: Option<i64>
+gen_catchain_seqno: Option<i64>
+gen_software_version: Option<i64>
+gen_software_capabilities: Option<String>
+gen_utime: Option<i64>
+gen_utime_ms_part: Option<i64>
+gen_validator_list_hash_short: Option<i64>
+global_id: Option<i64>
+in_msgs: Option<String>
+key_block: Option<i64>
+min_ref_mc_seqno: Option<i64>
+out_msgs: Option<String>
+parent: String
+prev_alt_ref_seq_no: Option<i64>
+prev_alt_ref_end_lt: Option<String>
+prev_alt_ref_file_hash: Option<String>
+prev_alt_ref_root_hash: Option<String>
+prev_key_block_seqno: Option<i64>
+prev_ref_seq_no: Option<i64>
+prev_ref_end_lt: Option<String>
+prev_ref_file_hash: Option<String>
+prev_ref_root_hash: Option<String>
+producer_id: Option<String>
+root_hash: Option<String>
+seq_no: i64
+signature_occurrences: Option<Vec<u8>>
+shard: Option<String>
+share_state_resource_address: Option<String>
+start_lt: Option<String>
+status: Option<i64>
+tr_count: Option<i64>
+version: Option<i64>
+want_merge: Option<i64>
+want_split: Option<i64>
+workchain_id: Option<i64>
+data: Option<Vec<u8>>
+thread_id: Option<String>
+list()
+latest_block()
+blockchain_blocks()
}
References
For more on GraphQL query arguments and pagination, see BlockchainBlocksQueryArgs and PaginateDirection.
For details on utility conversions used in SQL queries, see u64_to_string.
For default batch sizes and query configurations, see defaults.