Skip to content

Latest commit

 

History

History
300 lines (235 loc) · 7.37 KB

File metadata and controls

300 lines (235 loc) · 7.37 KB

Coin Smith 🔨

A robust Bitcoin transaction builder written in Rust that handles UTXO selection, fee calculation, and PSBT generation with support for multiple script types and advanced features like RBF and locktime.

📋 Overview

Coin Smith is a developer-friendly Bitcoin transaction construction tool that provides both CLI and web interfaces. It implements intelligent coin selection algorithms, accurate fee estimation, and generates industry-standard Partially Signed Bitcoin Transactions (PSBTs).

Key Features

  • 🪙 Smart Coin Selection: Efficient UTXO selection with configurable strategies
  • 💰 Accurate Fee Calculation: Precise virtual byte calculation for all script types
  • 🔐 Multi-Script Support: P2WPKH, P2PKH, P2SH-P2WPKH, and P2TR (Taproot)
  • ♻️ RBF Support: Replace-By-Fee signaling for transaction replacement
  • ⏱️ Locktime Handling: Both block height and Unix timestamp locktimes with anti-fee-sniping
  • 📦 PSBT Generation: Standards-compliant Partially Signed Bitcoin Transaction output
  • 🌐 Dual Interface: Command-line tool and web application
  • 🧪 Comprehensive Testing: Extensive fixture-based test suite

🚀 Quick Start

Prerequisites

  • Rust 1.70+ and Cargo
  • Bash shell (for convenience scripts)

Installation

  1. Clone the repository

    git clone <repository-url>
    cd 2026-developer-challenge-2-coin-smith-EliteCoder18
  2. Build the project

    ./setup.sh

    This compiles both CLI and web binaries in release mode.

📖 Usage

CLI Interface

Process Bitcoin transaction fixtures from JSON files:

./cli.sh fixtures/basic_change_p2wpkh.json

Input Format (JSON):

{
  "network": "mainnet",
  "utxos": [
    {
      "txid": "...",
      "vout": 0,
      "value_sats": 100000,
      "script_pubkey_hex": "...",
      "script_type": "p2wpkh",
      "address": "bc1q..."
    }
  ],
  "payments": [
    {
      "address": "bc1q...",
      "script_pubkey_hex": "...",
      "script_type": "p2wpkh",
      "value_sats": 70000
    }
  ],
  "change": {
    "address": "bc1q...",
    "script_pubkey_hex": "...",
    "script_type": "p2wpkh"
  },
  "fee_rate_sat_vb": 5.0,
  "rbf": true,
  "locktime": 840000,
  "current_height": 840000,
  "policy": {
    "max_inputs": 5
  }
}

Output Format:

{
  "ok": true,
  "network": "mainnet",
  "strategy": "default",
  "selected_inputs": [...],
  "outputs": [...],
  "change_index": 1,
  "fee_sats": 560,
  "fee_rate_sat_vb": 5.0,
  "vbytes": 112,
  "rbf_signaling": true,
  "locktime": 839999,
  "locktime_type": "block_height",
  "psbt_base64": "cHNidP8B...",
  "warnings": []
}

Web Interface

Start the web server:

./web.sh

Then open your browser to http://127.0.0.1:3000 for an interactive transaction builder interface.

Environment Variables:

  • PORT: Web server port (default: 3000)

🏗️ Project Structure

coin-smith/
├── cli/              # Command-line interface
│   └── src/
│       └── main.rs   # CLI entry point
├── core/             # Core transaction logic
│   └── src/
│       ├── lib.rs            # Module exports
│       ├── models.rs         # Data structures
│       ├── validation.rs     # Input validation
│       ├── coin_selection.rs # UTXO selection algorithm
│       ├── builder.rs        # Transaction construction
│       ├── fee.rs            # Fee calculation
│       ├── locktime.rs       # Locktime logic
│       ├── psbt.rs           # PSBT generation
│       └── error.rs          # Error handling
└── web/              # Web server
    └── src/
        ├── main.rs           # Server entry point
        ├── routes/           # API endpoints
        └── templates/        # HTML templates

fixtures/             # Test fixtures
├── basic_change_p2wpkh.json
├── multi_payment_change.json
├── rbf_basic.json
├── locktime_block_height.json
└── ...

🔧 Technical Details

Coin Selection Algorithm

Coin Smith implements a greedy coin selection strategy that:

  1. Filters UTXOs based on policy constraints (e.g., max_inputs)
  2. Selects UTXOs in order until sufficient funds are available
  3. Calculates change output accounting for fee requirements
  4. Validates minimum output values (dust threshold)

Fee Calculation

Virtual bytes (vBytes) are calculated using accurate witness accounting:

Script Type Input vBytes Output vBytes
P2WPKH 68 31
P2PKH 148 34
P2SH-P2WPKH 91 32
P2TR 57.5 43

Base transaction overhead: 10.5 vBytes

RBF Signaling

When RBF is enabled, all inputs use sequence number 0xFFFFFFFD (4294967293) to signal replaceability per BIP 125.

Locktime Strategy

  • Anti-Fee-Sniping: By default, sets locktime to current_height - 1
  • Custom Locktime: Supports explicit block height or Unix timestamp
  • Sequence Numbers: Adjusted based on locktime type and RBF signaling

Supported Script Types

  • P2WPKH: Native SegWit (bech32)
  • P2PKH: Legacy addresses
  • P2SH-P2WPKH: Nested SegWit
  • P2TR: Taproot (bech32m)

🧪 Testing

The project includes 26+ comprehensive test fixtures covering:

  • Basic change creation
  • Multiple payment outputs
  • Mixed input/output script types
  • RBF scenarios
  • Locktime variants (block height, Unix timestamp)
  • Large UTXO pools
  • Edge cases (send-all, dust change)
  • Anti-fee-sniping

Run all tests:

cd coin-smith
cargo test

Run specific fixture:

./cli.sh fixtures/rbf_basic.json

📚 Example Scenarios

Basic Transaction with Change

./cli.sh fixtures/basic_change_p2wpkh.json

Multiple Payments

./cli.sh fixtures/multi_payment_change.json

RBF-Enabled Transaction

./cli.sh fixtures/rbf_basic.json

Custom Locktime

./cli.sh fixtures/locktime_block_height.json

Send All (No Change)

./cli.sh fixtures/send_all_dust_change.json

🛠️ Development

Build Debug Version

cd coin-smith
cargo build

Run Tests with Output

cargo test -- --nocapture

Check Code

cargo check
cargo clippy
cargo fmt

📦 Dependencies

  • bitcoin (0.32.2): Bitcoin primitives and transaction handling
  • serde / serde_json: JSON serialization
  • axum: Web framework (web interface)
  • tokio: Async runtime (web interface)

🤝 Contributing

Contributions are welcome! Please ensure:

  • All tests pass
  • Code is formatted with cargo fmt
  • No clippy warnings
  • New fixtures added for new features

📄 License

See LICENSE file for details.

🎯 Use Cases

  • Wallet Development: Integrate transaction building into Bitcoin wallets
  • Payment Processing: Batch payment construction
  • Testing: Generate test transactions for Bitcoin applications
  • Education: Learn Bitcoin transaction structure and PSBT format
  • Automation: Script-based transaction creation

🔗 Resources


Built with ❤️ using Rust