bitcoin-sdk

Crates.iobitcoin-sdk
lib.rsbitcoin-sdk
version0.2.0
created_at2025-10-12 13:20:50.289246+00
updated_at2025-10-26 00:13:03.742555+00
descriptionbitcoin rust sdk
homepage
repositoryhttps://github.com/0xhappyboy/bitcoin-sdk
max_upload_size
id1879281
size131,985
happy₿oy (0xhappyboy)

documentation

README

Bitcoin NetWork SDK

The bitcoin network SDK is based on the most basic cryptographic library and includes commonly used API functions.

License

简体中文 | English

Example

Creating a Bitcoin client and getting blockchain information

use bitcoin_lib::{BitcoinClient, BitcoinClientType};

pub async fn example_blockchain_info() -> anyhow::Result<()> {
    // Create a local testnet client
    let client = BitcoinClient::new_local(BitcoinClientType::Testnet);
    // Get blockchain information
    let blockchain_info = client.get_blockchain_info().await?;
    println!("Chain: {}", blockchain_info.chain);
    println!("Blocks: {}", blockchain_info.blocks);
    println!("Best block hash: {}", blockchain_info.bestblockhash);
    println!("Difficulty: {}", blockchain_info.difficulty);
    Ok(())
}

Generate new addresses and verify addresses

use bitcoin_lib::{BitcoinClient, BitcoinClientType, BitcoinCrypto};

pub async fn example_address_operations() -> anyhow::Result<()> {
    let client = BitcoinClient::new_local(BitcoinClientType::Testnet);
    let legacy_address = client.get_new_address(Some("test"), Some("legacy")).await?;
    println!("Legacy address: {}", legacy_address);
    let bech32_address = client.get_new_address(Some("test"), Some("bech32")).await?;
    println!("Bech32 address: {}", bech32_address);
    let is_valid_legacy = BitcoinCrypto::validate_address(&legacy_address);
    let is_valid_bech32 = BitcoinCrypto::validate_address(&bech32_address);
    println!("Legacy address valid: {}", is_valid_legacy);
    println!("Bech32 address valid: {}", is_valid_bech32);
    if let Ok(address_type) = BitcoinCrypto::get_address_type(&legacy_address) {
        println!("Address type: {:?}", address_type);
    }
    Ok(())
}

Generating Addresses from Private Keys

use bitcoin_lib::{BitcoinCrypto, BitcoinClientType};

pub fn example_crypto_operations() -> anyhow::Result<()> {
    let private_key_hex = "private key hex";
    let private_key_bytes = hex::decode(private_key_hex)?;
    let private_key: [u8; 32] = private_key_bytes.try_into().unwrap();
    let compressed_public_key = BitcoinCrypto::private_to_public(&private_key, true)?;
    println!("Compressed public key: {}", hex::encode(&compressed_public_key));
    let p2pkh_address = BitcoinCrypto::public_key_to_p2pkh_address(
        &compressed_public_key,
        BitcoinClientType::Testnet
    )?;
    println!("P2PKH address: {}", p2pkh_address);
    let bech32_address = BitcoinCrypto::public_key_to_bech32_address(
        &compressed_public_key,
        BitcoinClientType::Testnet
    )?;
    println!("Bech32 address: {}", bech32_address);
    let wif = BitcoinCrypto::private_key_to_wif(
        &private_key,
        true,
        BitcoinClientType::Testnet
    )?;
    println!("WIF: {}", wif);
    Ok(())
}

Transaction Operations - Query UTXO and Create Transactions

use bitcoin_lib::{BitcoinClient, BitcoinClientType};
use std::collections::HashMap;

pub async fn example_transaction_operations() -> anyhow::Result<()> {
    let client = BitcoinClient::new_local(BitcoinClientType::Testnet);
    // List unspent transaction outputs
    let unspent = client.list_unspent(1, 9999999, None).await?;
    println!("Found {} unspent outputs:", unspent.len());
    for utxo in &unspent {
        println!("  TXID: {}, Vout: {}, Amount: {}", utxo.txid, utxo.vout, utxo.amount);
    }
    // Create a raw transaction (example - needs actual UTXOs)
    if !unspent.is_empty() {
        let inputs = vec![
            crate::CreateTxInput {
                txid: unspent[0].txid.clone(),
                vout: unspent[0].vout,
                sequence: None,
            }
        ];
        let mut outputs = HashMap::new();
        // Send to a test address (replace with actual address)
        outputs.insert("tb1qexample...".to_string(), 0.001);
        let raw_tx = client.create_raw_transaction(inputs, outputs).await?;
        println!("Raw transaction: {}", raw_tx);
    }
    Ok(())
}

Serialization and hashing

use bitcoin_lib::{Serialization, BitcoinCrypto};

pub fn example_serialization_operations() -> anyhow::Result<()> {
    // Test data for hashing
    let test_data = b"Hello, Bitcoin!";
    // Calculate SHA256 hash
    let sha256_hash = BitcoinCrypto::sha256(test_data);
    println!("SHA256: {}", hex::encode(sha256_hash));
    // Calculate double SHA256 hash
    let double_sha256_hash = BitcoinCrypto::double_sha256(test_data);
    println!("Double SHA256: {}", hex::encode(double_sha256_hash));
    // Calculate hash160
    let hash160 = BitcoinCrypto::hash160(test_data);
    println!("Hash160: {}", hex::encode(hash160));
    // Variable-length integer serialization
    let small_int = 150u64;
    let large_int = 100000u64;
    let serialized_small = Serialization::serialize_varint(small_int);
    let serialized_large = Serialization::serialize_varint(large_int);
    println!("Serialized {}: {:?}", small_int, serialized_small);
    println!("Serialized {}: {:?}", large_int, serialized_large);
    // Deserialize variable-length integers
    let (deserialized_small, bytes_used_small) = Serialization::deserialize_varint(&serialized_small)?;
    let (deserialized_large, bytes_used_large) = Serialization::deserialize_varint(&serialized_large)?;
    println!("Deserialized small: {}, bytes used: {}", deserialized_small, bytes_used_small);
    println!("Deserialized large: {}, bytes used: {}", deserialized_large, bytes_used_large);

    Ok(())
}

Batch RPC calls

use bitcoin_lib::{BitcoinClient, BitcoinClientType};
use serde_json::Value;

pub async fn example_batch_calls() -> anyhow::Result<()> {
    let client = BitcoinClient::new_local(BitcoinClientType::Testnet);
    // Prepare multiple RPC requests
    let requests = vec![
        ("getblockcount".to_string(), Value::Null),
        ("getbestblockhash".to_string(), Value::Null),
        ("getnetworkinfo".to_string(), Value::Null),
        ("getmempoolinfo".to_string(), Value::Null),
    ];
    // Execute batch call
    let results = client.batch_call(requests).await?;

    for (i, result) in results.iter().enumerate() {
        println!("Result {}: {}", i, result);
    }

    Ok(())
}
Commit count: 0

cargo fmt