zcash-htlc-builder

Crates.iozcash-htlc-builder
lib.rszcash-htlc-builder
version0.1.5
created_at2025-11-30 01:08:38.801+00
updated_at2025-11-30 22:31:09.685742+00
descriptionProduction-ready Zcash HTLC builder for atomic swaps using transparent transactions
homepagehttps://github.com/Mist-Labs/zcash-htlc-builder
repositoryhttps://github.com/Mist-Labs/zcash-htlc-builder
max_upload_size
id1957721
size184,091
Okoli Evans (OkoliEvans)

documentation

https://docs.rs/zcash-htlc-builder

README

Zcash HTLC Builder

Crates.io Documentation License Build Status

A production-ready Rust library for creating and managing Hash Time-Locked Contracts (HTLCs) on Zcash's transparent transaction layer. Built for atomic swaps and cross-chain bridges.

๐ŸŒŸ Features

  • โœ… ZIP-300 Compliant - Full HTLC script implementation
  • โœ… Bitcoin 0.29 Compatible - Works with Zcash transparent transactions
  • โœ… Database Persistence - PostgreSQL with Diesel ORM
  • โœ… Block Explorer Integration - Query UTXOs without running a full node
  • โœ… CLI Tool - Command-line interface for testing and operations
  • โœ… Type-Safe - Full Rust type safety with comprehensive error handling
  • โœ… Async/Await - Modern async Rust with Tokio
  • โœ… Config File Support - TOML/JSON configuration (no environment variables required)

๐Ÿ“ฆ Installation

Add to your Cargo.toml:

[dependencies]
zcash-htlc-builder = "0.1.5"
tokio = { version = "1", features = ["full"] }

๐Ÿš€ Quick Start

1. Setup Configuration

Create zcash-config.toml in your project root:

network = "testnet"  # or "mainnet"
rpc_url = "http://localhost:18232"
rpc_user = "your-rpc-user"
rpc_password = "your-rpc-password"
database_url = "postgresql://user:password@localhost/zcash_htlc"
database_max_connections = 10
explorer_api = "https://explorer.testnet.z.cash/api"

# Optional: Relayer Configuration (for automated HTLC management)
[relayer]
hot_wallet_privkey = "your-private-key"
hot_wallet_address = "your-zcash-address"
max_tx_per_batch = 10
poll_interval_secs = 10
max_retry_attempts = 3
min_confirmations = 1
network_fee_zec = "0.0001"

โš ๏ธ Security Warning: Never commit zcash-config.toml with real credentials to version control. Add it to .gitignore and use zcash-config.toml.example as a template.

2. Setup Database

# Create PostgreSQL database
createdb zcash_htlc

# Migrations run automatically when you first use the library

3. Basic Usage

use zcash_htlc_builder::{
    ZcashHTLCClient, ZcashConfig, HTLCParams, UTXO,
    database::Database,
};
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Load configuration from file
    let config = ZcashConfig::from_toml_file("zcash-config.toml")?;
    
    // Initialize database
    let database = Arc::new(Database::new(
        &config.database_url,
        config.database_max_connections,
    )?);
    
    // Create client
    let client = ZcashHTLCClient::new(config, database);

    // Generate keys
    let recipient_privkey = client.generate_privkey();
    let recipient_pubkey = client.derive_pubkey(&recipient_privkey)?;
    
    let refund_privkey = client.generate_privkey();
    let refund_pubkey = client.derive_pubkey(&refund_privkey)?;

    // Generate secret and hash lock
    let secret = hex::encode(rand::random::<[u8; 32]>());
    let hash_lock = client.generate_hash_lock(&secret);

    // Create HTLC parameters
    let params = HTLCParams {
        recipient_pubkey,
        refund_pubkey,
        hash_lock: hash_lock.clone(),
        timelock: 500000, // Block height
        amount: "0.01".to_string(),
    };

    // Prepare funding (replace with your actual UTXOs)
    let funding_utxos = vec![
        UTXO {
            txid: "your-txid".to_string(),
            vout: 0,
            script_pubkey: "script-hex".to_string(),
            amount: "0.02".to_string(),
            confirmations: 6,
        }
    ];

    // Create HTLC
    let result = client.create_htlc(
        params,
        funding_utxos,
        "your-change-address",
        vec!["your-funding-privkey"],
    ).await?;

    println!("โœ… HTLC Created!");
    println!("๐Ÿ“‹ HTLC ID: {}", result.htlc_id);
    println!("๐Ÿ“‹ TXID: {}", result.txid);
    println!("๐Ÿ“ P2SH Address: {}", result.p2sh_address);
    println!("๐Ÿ—๏ธ  Secret: {}", secret);

    // Later, redeem the HTLC
    let redeem_txid = client.redeem_htlc(
        &result.htlc_id,
        &secret,
        "recipient-address",
        &recipient_privkey,
    ).await?;

    println!("โœ… HTLC Redeemed: {}", redeem_txid);

    Ok(())
}

Alternative: JSON Configuration

You can also use JSON format:

{
  "network": "testnet",
  "rpc_url": "http://localhost:18232",
  "rpc_user": "user",
  "rpc_password": "password",
  "database_url": "postgresql://localhost/zcash_htlc",
  "database_max_connections": 10,
  "explorer_api": "https://explorer.testnet.z.cash/api"
}

Load with:

let config = ZcashConfig::from_json_file("zcash-config.json")?;

๐Ÿ› ๏ธ CLI Tool

The library includes a command-line tool for testing and operations.

Installation

cargo install zcash-htlc-builder

Usage

All CLI commands use the config file from your project root or via custom path.

Generate Keys

zcash-htlc-cli keygen
# Or with custom config:
zcash-htlc-cli keygen ./my-config.toml

Generate Hash Lock

zcash-htlc-cli hashlock "my-secret-phrase"

Output:

๐Ÿ”’ Hash Lock:
  Secret:    my-secret-phrase
  Hash Lock: 6e9f78c1c24acdee688a360f1212c9b9989e7469d6a6e39e4ed7ca279f0c7846

Create HTLC

zcash-htlc-cli create

Redeem HTLC

zcash-htlc-cli redeem <htlc_id> <secret> <recipient_address> <privkey>

Refund HTLC

zcash-htlc-cli refund <htlc_id> <refund_address> <privkey>

Broadcast Raw Transaction

zcash-htlc-cli broadcast <hex-encoded-tx>

Environment Variable Override

You can set ZCASH_CONFIG environment variable to specify config file location:

export ZCASH_CONFIG=./production-config.toml
zcash-htlc-cli keygen

๐Ÿ“š Examples

Check the examples/ directory for complete working examples:

# Run the full HTLC flow example
cargo run --example test_htlc_flow

Output:

๐Ÿงช Testing HTLC Flow
๐Ÿ“ Step 1: Generating Keys
  ๐Ÿ‘ค Recipient Private Key: 489175b18cd8f36e...
  ๐Ÿ‘ค Recipient Public Key:  02f6b9fc88bf40a5c...
  ๐Ÿฆ Relayer Private Key:  c980fd0225a51ec8...
  ๐Ÿฆ Relayer Public Key:   03bb93b3c358ba56e...
๐Ÿ” Step 2: Generating Secret and Hash Lock
  ๐Ÿ—๏ธ  Secret:    8f2c59d64b11f329...
  ๐Ÿ”’ Hash Lock: 346a7d2128ff4d1b...
...

๐Ÿ—๏ธ Architecture

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚         ZcashHTLCClient (Main API)          โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  โ€ข create_htlc()                            โ”‚
โ”‚  โ€ข redeem_htlc()                            โ”‚
โ”‚  โ€ข refund_htlc()                            โ”‚
โ”‚  โ€ข generate_privkey()                       โ”‚
โ”‚  โ€ข derive_pubkey()                          โ”‚
โ”‚  โ€ข generate_hash_lock()                     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
          โ”‚           โ”‚           โ”‚
          โ–ผ           โ–ผ           โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   Builder    โ”‚ โ”‚  Signer  โ”‚ โ”‚   Database   โ”‚
โ”‚              โ”‚ โ”‚          โ”‚ โ”‚              โ”‚
โ”‚ โ€ข HTLC TX    โ”‚ โ”‚ โ€ข Sign   โ”‚ โ”‚ โ€ข HTLCs      โ”‚
โ”‚ โ€ข Redeem TX  โ”‚ โ”‚ โ€ข Verify โ”‚ โ”‚ โ€ข Operations โ”‚
โ”‚ โ€ข Refund TX  โ”‚ โ”‚ โ€ข Keys   โ”‚ โ”‚ โ€ข UTXOs      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

๐Ÿ’พ Database Schema

Table Description
zcash_htlcs HTLC state and metadata
htlc_operations Transaction operations (create/redeem/refund)
relayer_utxos UTXOs managed by relayer's hot wallet
indexer_checkpoints Blockchain sync state

โš™๏ธ Configuration Options

Core Configuration

Field Type Required Description
network string โœ… Yes "testnet" or "mainnet"
rpc_url string โœ… Yes Zcash RPC endpoint
rpc_user string โŒ No RPC username or API key
rpc_password string โŒ No RPC password
database_url string โœ… Yes PostgreSQL connection string
database_max_connections number โŒ No Max DB connections (default: 10)
explorer_api string โŒ No Block explorer API URL

Relayer Configuration (Optional)

Field Type Required Description
hot_wallet_privkey string โš ๏ธ Yes* Private key for funding
hot_wallet_address string โš ๏ธ Yes* Address for funding
max_tx_per_batch number โŒ No Max transactions per batch (default: 10)
poll_interval_secs number โŒ No Polling interval in seconds (default: 10)
network_fee_zec string โŒ No Network fee in ZEC (default: "0.0001")

*Required only if running automated relayer

๐Ÿ”’ Security Considerations

Private Key Management

  • โ›” Never commit zcash-config.toml with real keys to version control
  • ๐Ÿ” Use hardware wallets for production mainnet operations
  • ๐Ÿ—„๏ธ Store keys securely (HSM, encrypted storage, environment secrets)
  • ๐Ÿ”„ Rotate keys regularly

Timelock Safety

  • โฐ Always set timelocks with sufficient buffer (consider network congestion)
  • ๐Ÿ“Š Monitor block height before attempting refunds
  • โœ… Account for at least 6 confirmations

Transaction Verification

  • ๐Ÿ” Always verify transactions before signing
  • ๐Ÿ’ฐ Check amounts, addresses, and scripts carefully
  • ๐Ÿงช Test on testnet first

Database Security

  • ๐Ÿ”‘ Use strong PostgreSQL credentials
  • ๐Ÿ” Enable SSL for database connections in production
  • ๐Ÿ’พ Regularly backup database

๐ŸŒ Network Configuration

Testnet

Property Value
RPC Port 18232
Faucet testnet.zecfaucet.com
Explorer blockexplorer.one/zcash/testnet

Mainnet

Property Value
RPC Port 8232
Explorer blockexplorer.one/zcash/mainnet

๐Ÿงช Testing

# Run all tests
cargo test

# Run specific test
cargo test test_build_htlc_script

# With logging
RUST_LOG=debug cargo test

# Run examples
cargo run --example test_htlc_flow

๐Ÿ“ฆ Dependencies

Crate Version Purpose
bitcoin 0.29 Transaction building (Zcash compatible)
secp256k1 0.24 Cryptographic signatures
diesel 2.1 PostgreSQL ORM
tokio 1.0 Async runtime
reqwest 0.11 HTTP client for RPC
serde 1.0 Serialization/deserialization
toml 0.8 TOML configuration parsing

๐Ÿ› Troubleshooting

"Failed to read config file"

  • โœ… Ensure zcash-config.toml exists in project root
  • โœ… Check file permissions
  • โœ… Verify TOML syntax with a validator

"Database connection failed"

  • โœ… Verify PostgreSQL is running: pg_isready
  • โœ… Check database credentials in config
  • โœ… Ensure database exists: createdb zcash_htlc

"RPC connection failed"

  • โœ… Check RPC credentials
  • โœ… Ensure correct port (18232 for testnet, 8232 for mainnet)

"HTLC creation failed"

  • โœ… Verify sufficient balance in funding UTXOs
  • โœ… Check that UTXOs are confirmed (at least 1 confirmation)
  • โœ… Ensure private keys match funding addresses

๐Ÿค Contributing

Contributions welcome! Please:

  1. ๐Ÿด Fork the repository
  2. ๐ŸŒฟ Create a feature branch (git checkout -b feature/amazing-feature)
  3. โœ… Write tests for new functionality
  4. ๐Ÿงช Ensure cargo test and cargo clippy pass
  5. ๐Ÿ“ Update documentation
  6. ๐Ÿš€ Submit a pull request

Development Setup

# Clone repository
git clone https://github.com/Mist-Labs/zcash-htlc-builder.git
cd zcash-htlc-builder

# Install dependencies
cargo build

# Run tests
cargo test

# Run clippy
cargo clippy -- -D warnings

# Format code
cargo fmt

๐Ÿ“‹ Changelog

See CHANGELOG.md for version history.

๐Ÿ“„ License

This project is licensed under the Apache-2.0 License - see the LICENSE file for details.

๐Ÿ“š Resources

๐Ÿ’ฌ Support

๐Ÿ™ Acknowledgments

Built with โค๏ธ for the Zcash ecosystem by Mist Labs


โญ If you find this library useful, please star the repository!

Commit count: 0

cargo fmt