| Crates.io | kaccy-bitcoin |
| lib.rs | kaccy-bitcoin |
| version | 0.1.0 |
| created_at | 2026-01-18 22:16:42.918792+00 |
| updated_at | 2026-01-18 22:16:42.918792+00 |
| description | Bitcoin integration for Kaccy Protocol - HD wallets, UTXO management, and transaction building |
| homepage | https://github.com/cool-japan/kaccy |
| repository | https://github.com/cool-japan/kaccy |
| max_upload_size | |
| id | 2053219 |
| size | 1,548,442 |
Comprehensive Bitcoin integration for Kaccy Protocol.
This crate provides a complete Bitcoin integration solution including Bitcoin Core RPC client, HD wallet management, transaction monitoring, Lightning Network support, Layer 2 integrations, privacy features, and advanced Bitcoin functionalities.
clientBitcoin Core RPC client with automatic reconnection:
BitcoinClient - Connection to Bitcoin Core node with exponential backoff retryget_network_info, get_block_height)estimate_smart_fee)hd_walletHD wallet and address generation (BIP32/BIP84):
HdWallet - BIP84 native SegWit hierarchical deterministic walletm/84'/0'/0'/0/{order_index}monitorPayment monitoring and confirmation tracking:
PaymentMonitor - Watches for incoming transactions via pollingConfirmationTracker - Multi-level confirmation tracking (1, 3, 6 confirmations)TransactionMatcher - Match incoming transactions to orders by addresslightningLightning Network integration:
LndClient - REST client for LND integrationLightningProvider - Trait abstraction for multiple implementationsLightningPaymentManager - Invoice creation and payment monitoringpsbtPSBT (Partially Signed Bitcoin Transactions):
PsbtBuilder - Generate unsigned transactionsPsbtManager - Withdrawal and payout managementmultisigMulti-signature wallet support:
MultisigWallet - M-of-N multi-signature configurationsCustodyManager - Tiered custody based on balance thresholdsSignatureCoordinator - Collect signatures from multiple partiestaprootTaproot integration (BIP 341/342):
TaprootManager - Key pair generation and managementdescriptorOutput descriptor wallet support:
DescriptorWallet - Modern Bitcoin Core descriptor integrationpayjoinPayJoin support (BIP 78):
PayJoinCoordinator - Sender and receiver coordinationcoinjoinCoinJoin integration:
CoinJoinCoordinator - Multi-participant session managementstacksStacks (STX) integration:
StacksClient - Mainnet/testnet supportContractDeploymentManager - Contract lifecycle managementStacksTokenBridge - BTC <-> STX token bridgingrskRSK integration:
RskClient - Mainnet/testnet/regtest supportPegManager - BTC-pegged token (rBTC) managementtimelockTime-locked transactions and HTLCs:
HtlcManager - Hash Time-Locked Contractsatomic_swapAtomic swap protocol:
AtomicSwapManager - Trustless cross-chain exchangemempoolMempool and reorganization monitoring:
MempoolMonitor - Track unconfirmed transactionsAddressWatcher - Detect incoming unconfirmed paymentsReorgTracker - Chain reorganization detectionactivity_monitorSuspicious activity detection:
ActivityMonitor - Large transaction detectiontx_limitsTransaction limit enforcement:
LimitEnforcer - Per-user and platform-wide limitsnotificationsAdmin notification system:
AdminNotificationService - Broadcast channel for alertsNotificationPriority - Levels (Low/Medium/High/Critical)batch_optimizerBatched withdrawal optimization:
BatchOptimizer - Aggregate multiple user withdrawalsutxoUTXO management and optimization:
UtxoManager - UTXO listing and filteringtx_parserTransaction parsing and analysis:
TransactionParser - Parse incoming transactionsParsedTransaction - Full transaction detailsrbfReplace-By-Fee tracking:
RbfTracker - Monitor transaction replacementstransaction_managerIntegrated transaction management:
TransactionManager - Combines limits, UTXO, and activity monitoringerrorComprehensive Bitcoin-specific error types with detailed error handling.
use kaccy_bitcoin::{BitcoinClient, HdWallet, PaymentMonitor, MonitorConfig};
use std::sync::Arc;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Connect to Bitcoin Core with automatic reconnection
let client = Arc::new(BitcoinClient::new(
"http://localhost:8332",
"rpcuser",
"rpcpassword",
)?);
// Initialize HD wallet (BIP84 native SegWit)
let wallet = HdWallet::new(&std::env::var("WALLET_XPUB")?)?;
// Generate unique address for order
let order_id = uuid::Uuid::new_v4();
let address = wallet.derive_address(order_id)?;
println!("Deposit to: {}", address);
// Start payment monitoring with confirmation tracking
let config = MonitorConfig::default();
let monitor = PaymentMonitor::new(client, config);
monitor.start().await?;
Ok(())
}
use kaccy_bitcoin::{LndClient, InvoiceRequest, LightningPaymentManager};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let lnd = LndClient::new("https://localhost:8080", "macaroon_hex").await?;
// Create invoice for order
let invoice_req = InvoiceRequest {
amount_sats: 50_000,
description: "Order #12345".to_string(),
expiry_secs: Some(3600),
};
let invoice = lnd.create_invoice(invoice_req).await?;
println!("Pay invoice: {}", invoice.payment_request);
// Monitor payment status
let payment_mgr = LightningPaymentManager::new(lnd);
let status = payment_mgr.check_payment(&invoice.payment_hash).await?;
Ok(())
}
use kaccy_bitcoin::{MultisigWallet, MultisigConfig, CustodyManager};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create 2-of-3 multisig configuration
let config = MultisigConfig {
required_signatures: 2,
total_keys: 3,
network: bitcoin::Network::Bitcoin,
};
let pubkeys = vec![
"platform_pubkey".to_string(),
"user_pubkey".to_string(),
"cold_storage_pubkey".to_string(),
];
let multisig = MultisigWallet::new(config, pubkeys)?;
let address = multisig.get_address()?;
// Tiered custody management
let custody_mgr = CustodyManager::new(config);
let level = custody_mgr.determine_custody_level(1_000_000)?;
Ok(())
}
use kaccy_bitcoin::{PsbtManager, WithdrawalRequest, FeeEstimation};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let psbt_mgr = PsbtManager::new(client, wallet);
// Create withdrawal transaction
let request = WithdrawalRequest {
user_id: uuid::Uuid::new_v4(),
destination: "bc1q...".to_string(),
amount: 100_000,
fee_rate: FeeEstimation::Medium,
};
let psbt = psbt_mgr.create_withdrawal(request).await?;
// Sign with hardware wallet and broadcast
let signed = psbt_mgr.finalize_and_extract(psbt).await?;
Ok(())
}
use kaccy_bitcoin::{TaprootManager, TaprootConfig};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = TaprootConfig::default();
let taproot_mgr = TaprootManager::new(config);
// Generate Taproot key pair
let keypair = taproot_mgr.generate_keypair()?;
// Create key-path address (most efficient and private)
let address = taproot_mgr.create_key_path_address(&keypair)?;
println!("Taproot address: {}", address);
Ok(())
}
use kaccy_bitcoin::{AtomicSwapManager, AtomicSwapConfig, SwapRole};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = AtomicSwapConfig::default();
let swap_mgr = AtomicSwapManager::new(config);
// Initiate atomic swap
let swap = swap_mgr.initiate_swap(
"counterparty_pubkey",
100_000, // amount in sats
"refund_address",
).await?;
println!("Swap ID: {}", swap.swap_id);
println!("Payment hash: {}", hex::encode(&swap.payment_hash));
Ok(())
}
use kaccy_bitcoin::{BatchOptimizer, BatchStrategy, BatchWithdrawal};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let optimizer = BatchOptimizer::new();
let withdrawals = vec![
BatchWithdrawal {
user_id: uuid::Uuid::new_v4(),
address: "bc1q...".to_string(),
amount: 50_000,
priority: false,
},
// ... more withdrawals
];
// Optimize batch for minimum fees
let batch = optimizer.optimize(withdrawals, BatchStrategy::MinimizeFees)?;
println!("Fee savings: {} sats", batch.efficiency.fee_savings);
Ok(())
}
Core configuration:
BITCOIN_RPC_URL - Bitcoin Core RPC endpoint (default: http://localhost:8332)BITCOIN_RPC_USER - RPC usernameBITCOIN_RPC_PASSWORD - RPC passwordBITCOIN_NETWORK - Network type (mainnet, testnet, regtest, signet)WALLET_XPUB - Extended public key for address derivation (BIP84)Lightning Network:
LND_REST_URL - LND REST API endpointLND_MACAROON - LND macaroon hex stringLND_TLS_CERT_PATH - Path to LND TLS certificateLayer 2:
STACKS_API_URL - Stacks API endpointRSK_RPC_URL - RSK node RPC endpointMost modules provide configuration structs with sensible defaults:
// Monitor configuration
let config = MonitorConfig {
poll_interval_secs: 30,
min_confirmations: 6,
..Default::default()
};
// Reconnection configuration
let reconnect_config = ReconnectConfig {
max_retries: 5,
initial_delay_ms: 1000,
max_delay_ms: 60000,
};
// HTLC configuration
let htlc_config = HtlcConfig {
default_timelock_blocks: 144,
min_timelock_blocks: 6,
max_timelock_blocks: 2016,
};
kaccy-bitcoin/
├── src/
│ ├── lib.rs # Crate root with public exports
│ │
│ ├── Core Modules
│ ├── client.rs # Bitcoin Core RPC client
│ ├── hd_wallet.rs # BIP84 HD wallet
│ ├── wallet.rs # Wallet manager
│ ├── monitor.rs # Payment monitoring
│ ├── confirmation.rs # Confirmation tracking
│ ├── matcher.rs # Transaction matching
│ ├── connection_pool.rs # RPC connection pooling
│ ├── cache.rs # Transaction/UTXO/block caching
│ │
│ ├── Transaction Management
│ ├── psbt.rs # PSBT building and signing
│ ├── multisig.rs # Multi-signature wallets
│ ├── taproot.rs # Taproot addresses
│ ├── descriptor.rs # Output descriptors
│ ├── tx_parser.rs # Transaction parsing
│ ├── rbf.rs # Replace-By-Fee tracking
│ ├── advanced_rbf.rs # Advanced RBF with batching
│ ├── fee_bumping.rs # CPFP and RBF fee bumping
│ │
│ ├── Advanced Features
│ ├── lightning.rs # Lightning Network
│ ├── timelock.rs # HTLCs and timelocks
│ ├── atomic_swap.rs # Atomic swaps
│ ├── submarine_swaps.rs # Lightning-onchain swaps
│ ├── payjoin.rs # PayJoin privacy
│ ├── coinjoin.rs # CoinJoin privacy
│ ├── dlc.rs # Discreet Log Contracts
│ ├── miniscript_support.rs # Miniscript policies
│ │
│ ├── Wallet Features
│ ├── coin_control.rs # Manual UTXO selection
│ ├── gap_limit.rs # BIP44 gap limit tracking
│ ├── transaction_history.rs # Transaction history & export
│ ├── hwi.rs # Hardware wallet integration
│ ├── key_management.rs # Key rotation & recovery
│ │
│ ├── Layer 2
│ ├── stacks.rs # Stacks integration
│ ├── rsk.rs # RSK integration
│ │
│ ├── Network Support
│ ├── p2p.rs # P2P protocol integration
│ ├── compact_filters.rs # BIP 157/158 filters
│ ├── signet.rs # Signet support
│ ├── testnet4.rs # Testnet4 support
│ │
│ ├── Monitoring & Security
│ ├── mempool.rs # Mempool monitoring
│ ├── activity_monitor.rs # Suspicious activity
│ ├── tx_limits.rs # Transaction limits
│ ├── notifications.rs # Admin notifications
│ ├── health.rs # Health check system
│ ├── audit.rs # Audit logging
│ │
│ ├── Optimization
│ ├── utxo.rs # UTXO management
│ ├── batch_optimizer.rs # Batch withdrawals
│ ├── transaction_manager.rs # Integrated management
│ │
│ ├── Observability
│ ├── metrics.rs # Prometheus metrics
│ ├── structured_logging.rs # Request/response logging
│ │
│ ├── Testing
│ ├── testing.rs # Test helpers & utilities
│ │
│ └── error.rs # Error types
│
└── Cargo.toml
1. User initiates purchase
└─> Generate unique BTC address (HD wallet BIP84 derivation)
└─> Display address to user
└─> Cache address for future lookups
2. User sends BTC to address
└─> MempoolMonitor detects unconfirmed transaction
└─> Mark order as "pending" immediately
└─> TransactionMatcher validates amount
└─> Detect underpayment/overpayment
└─> Send admin notification if discrepancy
3. Wait for confirmations (ConfirmationTracker)
└─> 1 confirmation: Mark order as "confirming"
└─> 3 confirmations: Update confidence level
└─> 6 confirmations: Mark order as "confirmed"
└─> Broadcast confirmation events
4. Execute trade
└─> Update token supply
└─> Credit user balance
└─> Create trade record
└─> Store transaction ID
1. User requests Lightning payment
└─> Generate invoice with amount and expiry
└─> Return payment request to user
2. User pays invoice
└─> LightningPaymentManager monitors invoice status
└─> Detect payment immediately upon receipt
└─> No confirmations needed (instant finality)
3. Execute trade
└─> Credit user balance instantly
└─> Create trade record
└─> Store payment hash
1. User requests withdrawal
└─> CustodyManager determines required custody level
└─> Check withdrawal limits (LimitEnforcer)
└─> ActivityMonitor checks for suspicious patterns
2. Create PSBT
└─> PsbtBuilder creates unsigned transaction
└─> Select optimal UTXOs (UtxoManager)
└─> Estimate fees based on target confirmation
3. Collect signatures
└─> SignatureCoordinator manages signature collection
└─> Platform signs first
└─> User/hardware wallet signs
└─> Cold storage signs if required (high-value)
4. Broadcast transaction
└─> Finalize PSBT
└─> Extract signed transaction
└─> Broadcast to Bitcoin network
└─> Monitor confirmation status
Core Bitcoin libraries:
bitcoincore-rpc - Bitcoin Core RPC clientbitcoin - Bitcoin primitives and transaction handlingtokio - Async runtimeserde / serde_json - SerializationAdditional dependencies:
reqwest - HTTP client for Lightning/L2 APIsuuid - Unique identifierschrono - Timestamp handlingthiserror - Error type derivationtracing - Structured loggingasync-trait - Async trait supportbase64 / hex - Encoding utilitiesrand - Random number generation# Run all tests
cargo test -p kaccy-bitcoin
# Run specific module tests
cargo test -p kaccy-bitcoin --test taproot
cargo test -p kaccy-bitcoin --test atomic_swap
# Run with output
cargo test -p kaccy-bitcoin -- --nocapture
Requires running Bitcoin Core in regtest mode:
# Start Bitcoin Core regtest
bitcoind -regtest -daemon \
-rpcuser=rpcuser \
-rpcpassword=rpcpassword \
-fallbackfee=0.00001
# Create wallet
bitcoin-cli -regtest -rpcuser=rpcuser -rpcpassword=rpcpassword createwallet "test"
# Run tests
BITCOIN_NETWORK=regtest \
BITCOIN_RPC_URL=http://localhost:18443 \
BITCOIN_RPC_USER=rpcuser \
BITCOIN_RPC_PASSWORD=rpcpassword \
cargo test -p kaccy-bitcoin
Current test coverage: 254 tests across all modules
Licensed under the same terms as the Kaccy Protocol project.