System Overview
captaind is built as a modular, async Rust application that coordinates off-chain Bitcoin transactions. The architecture separates concerns into distinct components that communicate through well-defined interfaces.Core Components
Server Core
The mainServer struct coordinates all components:
Location: server/src/lib.rs
Responsibilities:
- Initialize and manage all subsystems
- Handle RPC requests from clients
- Coordinate round execution
- Manage server state and configuration
- Provide thread-safe access to shared resources
server_key: Server’s signing key for VTXOsmailbox_key: Key for unblinding mailbox identifiersrounds_wallet: BDK wallet for round fundingwatchman_wallet: Optional wallet for forfeit claimsdb: Database connection poolbitcoind: Bitcoin Core RPC client
Round Coordinator
Manages the payment round lifecycle: Location:server/src/round/mod.rs
Round States:
- CollectingPayments: Accept user payment submissions
- SigningVtxoTree: Collect user signatures on VTXO tree
- Finished: Round completed (success, empty, or error)
perform_round(): Execute a single roundreceive_payments(): Collect user payment requestsreceive_vtxo_signatures(): Collect VTXO tree signaturessign_on_chain_transaction(): Sign and broadcast round tx
Database Layer
PostgreSQL-based persistence for all server state: Location:server/src/database/
Core Tables:
vtxo: User VTXOs and their statesround: Completed rounds with funding transactionsvirtual_transaction: Off-chain transaction datalightning_invoice: Lightning payment trackingwallet_changeset: BDK wallet stateintegration_*: Integration manager tables
Sync Manager
Tracks Bitcoin blockchain state: Location:server/src/sync/mod.rs
Responsibilities:
- Poll Bitcoin Core for new blocks
- Detect chain reorganizations
- Notify listeners of chain events
- Maintain chain tip state
VtxoExitFrontier: Tracks VTXO exit transactions for watchman- (Extensible for custom listeners)
TX Index & Nursery
Transaction monitoring and broadcasting: Location:server/src/txindex/
TX Index:
- Tracks transaction confirmation status
- Monitors mempool state
- Detects transaction conflicts
TxNursery):
- Broadcasts transactions to Bitcoin network
- Handles rebroadcasting for stuck transactions
- Manages transaction lifecycle
RPC Server
Three gRPC interfaces for different audiences: Location:server/src/rpcserver/
1. Public Ark API (port 3535)
File:ark.rs
Services:
ArkService: Core Ark operations (info, board, rounds)MailboxService: Mailbox message retrievalLightningService: Lightning payments
2. Admin API (port 3536)
File:admin.rs
Services:
WalletAdminService: Query wallet statusRoundAdminService: Trigger rounds manually
3. Integration Manager API (port 3537)
File:intman.rs
Service: IntegrationManagerService
API for third-party integrations (e.g., faucets, merchants).
Fee Estimator
Dynamic fee rate management: Location:server/src/fee_estimator.rs
Features:
- Polls Bitcoin Core for fee estimates
- Provides fast/regular/slow fee rates
- Falls back to configured rates if estimator unavailable
- Caches estimates to reduce RPC calls
Watchman
Automated VTXO forfeit claiming: Location:server/src/watchman/
Components:
- VtxoExitFrontier: Set of VTXOs being monitored
- WatchmanSigner: Creates claim transactions
- Daemon: Main processing loop
- Wait: VTXO not yet claimable
- Progress: Broadcast next transaction in VTXO tree
- Claim: Claim VTXO directly to server wallet
- Integrated with captaind (default)
- Standalone
watchmandprocess (separate binary)
Lightning Integration
Core Lightning node management: Location:server/src/ln/
ClnManager:
- Connects to multiple CLN nodes
- Routes payments across nodes (priority-based)
- Tracks invoice state
- Handles hold invoices for receives
VTXO Pool
Pre-issued VTXO management: Location:server/src/vtxopool.rs
Purpose: Provide instant liquidity for users
Operations:
- Issue VTXOs to pool when below target
- Track pool utilization
- Expire and reclaim old pool VTXOs
Wallet Management
BDK-based Bitcoin wallets: Location:server/src/wallet.rs
Wallet Types (WalletKind):
Rounds: Funds round transactions and server operationsWatchman: Pays fees for forfeit claimsForfeits: (Deprecated, merged into Rounds)
- Wraps BDK
Wallet - Persists state to PostgreSQL
- Provides transaction building helpers
- Manages UTXO locking
Data Flow
Payment Round Data Flow
Board (Onboarding) Data Flow
Concurrency & Threading
Runtime Management
RuntimeManager (server/src/system.rs):
- Tracks all background tasks
- Handles graceful shutdown
- Monitors critical vs non-critical workers
Async Architecture
Built on Tokio async runtime:- All I/O operations are async
- Database queries use connection pooling
- Round coordinator runs in dedicated task
- Each RPC connection spawns a task
Locking Strategy
VTXOs in Flux (flux.rs):
Security Considerations
Key Management
- Server Key: Derived from mnemonic, never leaves memory
- Mailbox Key: Separate key for mailbox privacy
- Ephemeral Keys: Temporary cosign keys with expiry
Access Control
- Public API: No authentication (protocol-level security)
- Admin API: Localhost-only by default
- Integration API: API key required
Database Security
- Connection pooling prevents connection exhaustion
- Prepared statements prevent SQL injection
- Triggers enforce data integrity
Network Security
- TLS for CLN connections (mTLS)
- gRPC with TLS support (configure separately)
- Firewall rules for RPC ports
Observability
Logging
Structured logging withserver-log crate:
Metrics
OpenTelemetry metrics:- Round counts and durations
- Wallet balances
- Lightning payment volumes
- Database connection pool stats
Tracing
Distributed tracing for:- Round execution
- RPC requests
- Payment processing
Scalability Considerations
Bottlenecks
- Database: Most queries are indexed, but round storage can be slow
- Round Coordinator: Single-threaded, processes rounds sequentially
- Bitcoin Core RPC: Network calls can add latency
Optimization Strategies
- Connection pooling: Reuse database and RPC connections
- Async I/O: Non-blocking network operations
- Batch operations: Group database writes
- Caching: Fee estimates, block height
Horizontal Scaling
Not currently supported. Each captaind instance:- Must have exclusive database access
- Runs independent rounds
- Cannot share state with other instances
Development Resources
Code Organization
Key Dependencies
- ark-lib: Core Ark protocol implementation
- bitcoin: Bitcoin primitives
- bdk_wallet: Bitcoin wallet functionality
- tokio: Async runtime
- tonic: gRPC framework
- tokio-postgres: PostgreSQL client
- tracing: Observability