Rust区块浏览器客户端库esplora-client的使用:比特币和闪电网络数据查询与交互

Rust区块浏览器客户端库esplora-client的使用:比特币和闪电网络数据查询与交互

概述

rust-esplora-client是一个比特币Esplora API客户端库,支持明文、TLS和洋葱服务器,提供阻塞或异步操作方式。

最低支持的Rust版本(MSRV)

该库应能在Rust 1.63.0及以上版本编译通过。要使用MSRV构建,需要固定以下依赖版本:

cargo update -p reqwest --precise "0.12.4"
cargo update -p minreq --precise "2.13.2"
cargo update -p home --precise "0.5.5"
cargo update -p url --precise "2.5.0"
cargo update -p tokio --precise "1.38.1"
cargo update -p security-framework-sys --precise "2.11.1"
cargo update -p native-tls --precise "0.2.13"
cargo update -p ring --precise "0.17.12"
cargo update -p flate2 --precise "1.0.35"
cargo update -p once_cell --precise "1.20.3"
cargo update -p tracing-core --precise "0.1.33"
cargo update -p parking_lot --precise "0.12.3"
cargo update -p parking_lot_core --precise "0.9.10"
cargo update -p lock_api --precise "0.4.12"
cargo update -p socket2@0.6.0 --precise "0.5.10"
cargo update -p webpki-roots@1.0.2 --precise "1.0.1"

安装

在项目目录中运行以下Cargo命令:

cargo add esplora-client

或者在Cargo.toml中添加以下行:

esplora-client = "0.12.1"

示例代码

以下是使用esplora-client查询比特币和闪电网络数据的完整示例:

use esplora_client::{Builder, AsyncClient};
use bitcoin::{BlockHash, Txid};
use std::str::FromStr;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 创建异步客户端
    let client = Builder::new("https://blockstream.info/api")
        .build_async()?;

    // 获取最新区块高度
    let height = client.get_height().await?;
    println!("Latest block height: {}", height);

    // 获取最新区块哈希
    let block_hash = client.get_block_hash(height).await?;
    println!("Latest block hash: {}", block_hash);

    // 获取区块信息
    let block = client.get_block(&block_hash).await?;
    println!("Block info: {:?}", block);

    // 查询特定交易
    let txid = Txid::from_str("e3bf3d07d4b0375638d5f1db5255fe07ba2c4cb067cd81b84ee974b6585fb468")?;
    let tx = client.get_tx(&txid).await?;
    println!("Transaction details: {:?}", tx);

    // 查询交易状态
    let tx_status = client.get_tx_status(&txid).await?;
    println!("Transaction status: {:?}", tx_status);

    // 查询交易输出
    let tx_out = client.get_tx_out(&txid, 0).await?;
    println!("Transaction output: {:?}", tx_out);

    // 查询地址余额
    let address = "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa";
    let address_balance = client.get_address_balance(address).await?;
    println!("Address balance: {:?}", address_balance);

    // 查询地址交易历史
    let address_txs = client.get_address_txs(address).await?;
    println!("Address transactions: {:?}", address_txs);

    Ok(())
}

完整示例代码

以下是一个更完整的示例,展示了esplora-client的更多功能:

use esplora_client::{Builder, AsyncClient};
use bitcoin::{BlockHash, Txid, Address};
use std::str::FromStr;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 1. 初始化异步客户端
    let client = Builder::new("https://blockstream.info/api")
        .build_async()?;

    // 2. 获取区块链基本信息
    println!("=== 区块链基本信息 ===");
    let height = client.get_height().await?;
    println!("当前区块高度: {}", height);
    
    let block_hash = client.get_block_hash(height).await?;
    println!("最新区块哈希: {}", block_hash);
    
    let block_header = client.get_block_header(&block_hash).await?;
    println!("区块头信息: {:?}", block_header);

    // 3. 查询区块详细信息
    println!("\n=== 区块详细信息 ===");
    let block = client.get_block(&block_hash).await?;
    println!("区块交易数量: {}", block.txdata.len());
    println!("区块版本: {}", block.header.version);
    println!("区块时间戳: {}", block.header.time);

    // 4. 查询交易信息
    println!("\n=== 交易信息查询 ===");
    let txid = Txid::from_str("e3bf3d07d4b0375638d5f1db5255fe07ba2c4cb067cd81b84ee974b6585fb468")?;
    
    let tx = client.get_tx(&txid).await?;
    println!("交易输入数量: {}", tx.input.len());
    println!("交易输出数量: {}", tx.output.len());
    
    let tx_status = client.get_tx_status(&txid).await?;
    println!("交易确认数: {}", tx_status.confirmed.unwrap_or_default().height);
    
    // 5. 查询地址信息
    println!("\n=== 地址信息查询 ===");
    let address = Address::from_str("1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa")?.assume_checked();
    
    let balance = client.get_address_balance(&address).await?;
    println!("地址余额: {} satoshis", balance.funded);
    
    let txs = client.get_address_txs(&address).await?;
    println!("交易数量: {}", txs.len());
    
    // 6. 查询未确认交易
    println!("\n=== 未确认交易 ===");
    let mempool = client.get_mempool().await?;
    println!("内存池交易数量: {}", mempool.count);
    
    Ok(())
}

功能说明

  1. 客户端构建:支持同步和异步客户端构建
  2. 区块查询:获取区块高度、哈希和详细信息
  3. 交易查询:获取交易详情、状态和输出
  4. 地址查询:查询地址余额和交易历史
  5. 闪电网络支持:通过Esplora API查询闪电网络相关数据

注意事项

  1. 该库需要Rust 1.63.0或更高版本
  2. 支持多种网络连接方式(明文、TLS和洋葱服务器)
  3. 提供阻塞和异步两种操作模式
  4. 使用时需遵守MIT许可证条款

1 回复

Rust区块浏览器客户端库esplora-client使用指南

esplora-client是一个Rust库,用于与Esplora区块浏览器API交互,支持比特币和闪电网络数据查询与交互。

安装

在Cargo.toml中添加依赖:

[dependencies]
esplora-client = "0.5"

基本用法

1. 创建客户端

use esplora_client::{Builder, AsyncClient};

let client = Builder::new("https://blockstream.info/api")
    .build_async()
    .unwrap();

2. 查询区块信息

// 获取最新区块高度
let height = client.get_height().await?;
println!("Latest block height: {}", height);

// 获取区块哈希
let block_hash = client.get_block_hash(height).await?;
println!("Block hash: {}", block_hash);

// 获取区块详情
let block = client.get_block(&block_hash).await?;
println!("Block details: {:?}", block);

3. 查询交易信息

// 获取交易详情
let txid = "your_transaction_id_here";
let transaction = client.get_tx(txid).await?;
println!("Transaction details: {:?}", transaction);

// 获取交易状态
let tx_status = client.get_tx_status(txid).await?;
println!("Transaction status: {:?}", tx_status);

4. 查询地址信息

// 获取地址余额
let address = "your_bitcoin_address_here";
let balance = client.get_address_balance(address).await?;
println!("Address balance: {:?}", balance);

// 获取地址交易历史
let txs = client.get_address_txs(address).await?;
println!("Address transactions: {:?}", txs);

闪电网络功能

1. 查询闪电网络通道

// 获取通道详情
let channel_id = "your_channel_id_here";
let channel = client.get_channel(channel_id).await?;
println!("Channel details: {:?}", channel);

2. 查询节点信息

// 获取节点详情
let node_id = "your_node_id_here";
let node = client.get_node(&node_id).await?;
println!("Node details: {:?}", node);

高级用法

批量查询

use esplora_client::BatchAsyncClient;

let batch_client = client.batch();
let futures = vec![
    batch_client.get_height(),
    batch_client.get_block_hash(700000),
    batch_client.get_address_balance(address),
];

let results = batch_client.send().await?;
println!("Batch results: {:?}", results);

自定义请求

use esplora_client::api::query;

let response: serde_json::Value = query(
    &client.client(),
    "GET",
    "/your/custom/endpoint",
    None
).await?;
println!("Custom response: {:?}", response);

错误处理

match client.get_tx("invalid_txid").await {
    Ok(tx) => println!("Transaction: {:?}", tx),
    Err(esplora_client::Error::Api(esplora_client::ApiError::NotFound)) => {
        println!("Transaction not found");
    }
    Err(e) => eprintln!("Error: {}", e),
}

完整示例代码

use esplora_client::{Builder, AsyncClient, BatchAsyncClient};
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // 1. 创建客户端
    let client = Builder::new("https://blockstream.info/api")
        .build_async()
        .unwrap();
    
    // 2. 查询区块信息
    let height = client.get_height().await?;
    println!("最新区块高度: {}", height);
    
    let block_hash = client.get_block_hash(height).await?;
    println!("区块哈希: {}", block_hash);
    
    let block = client.get_block(&block_hash).await?;
    println!("区块详情: {:?}", block);
    
    // 3. 查询交易信息
    let txid = "example_txid_here"; // 替换为实际交易ID
    let transaction = client.get_tx(txid).await?;
    println!("交易详情: {:?}", transaction);
    
    // 4. 查询地址信息
    let address = "example_address_here"; // 替换为实际地址
    let balance = client.get_address_balance(address).await?;
    println!("地址余额: {:?}", balance);
    
    // 5. 批量查询示例
    let batch_client = client.batch();
    let futures = vec![
        batch_client.get_height(),
        batch_client.get_block_hash(700000),
        batch_client.get_address_balance(address),
    ];
    
    let results = batch_client.send().await?;
    println!("批量查询结果: {:?}", results);
    
    Ok(())
}

注意事项

  1. 使用异步客户端时确保在异步上下文中运行
  2. 考虑API的速率限制
  3. 对于生产环境,建议使用自托管的Esplora实例

esplora-client提供了丰富的功能来查询比特币和闪电网络数据,是构建比特币相关应用的强大工具。

回到顶部