UNPKG

@nawab_kibria/bitcoin-lib

Version:

A comprehensive Bitcoin HD wallet library with BIP84, BIP44, BIP49 support, mnemonic generation and restoration

347 lines (257 loc) โ€ข 10.4 kB
# @nawab_kibria/bitcoin-lib A comprehensive, production-ready Bitcoin wallet library with full support for all major Bitcoin address formats. Built with TypeScript and thoroughly tested. ## ๐Ÿš€ Installation ```bash npm install @nawab_kibria/bitcoin-lib ``` ## ๐Ÿ“š What's Available This library provides four main classes that work together to provide complete Bitcoin wallet functionality: ### 1. WalletManager - Complete Wallet Solution ### 2. BitcoinWallet - Address Generation & HD Wallet Management ### 3. TransactionBuilder - Transaction Creation & Signing ### 4. ElectrumClient - Blockchain Connectivity --- ## ๐ŸŽฏ WalletManager - All-in-One Interface The **WalletManager** is the main class that provides all 9 core Bitcoin wallet features in a single, easy-to-use interface. ### โœ… Core Features 1. **Generate Wallet** - Create new wallets with mnemonic and extended keys 2. **Export Wallet** - Export extended keys and mnemonics 3. **Import Wallet** - Import from extended keys or mnemonics 4. **Fetch Balance** - Get balance for any address 5. **Fetch UTXOs** - Retrieve unspent transaction outputs 6. **Create Transaction** - Build and sign transactions 7. **Estimate Fees** - Real-time network fee estimation 8. **Broadcast Transaction** - Send transactions to the network 9. **Transaction History** - Get complete transaction history ### ๐Ÿ”ง Quick Start ```typescript import { WalletManager } from '@nawab_kibria/bitcoin-lib'; import * as bitcoin from 'bitcoinjs-lib'; // Configure wallet manager const walletManager = new WalletManager({ electrumServer: { host: 'localhost', port: 50001, ssl: false }, network: bitcoin.networks.regtest, defaultAddressType: 'native_segwit' }); // 1. Generate a new wallet const wallet = walletManager.generateWallet(); console.log('Mnemonic:', wallet.mnemonic); // 2. Connect to Electrum server await walletManager.connect(); // 3. Derive addresses const address = walletManager.deriveAddress(0, 'native_segwit'); console.log('Address:', address.address); // 4. Check balance const balance = await walletManager.fetchBalance(address.address); console.log('Balance:', balance.confirmed, 'sats'); // 5. Create and broadcast transaction const tx = await walletManager.createTransaction( fromAddress, toAddress, amount, feeRate, privateKey, 'native_segwit' ); const result = await walletManager.broadcastTransaction(tx.hex); console.log('TXID:', result.txid); ``` ### ๐Ÿ“– WalletManager API **Constructor Options:** ```typescript interface WalletManagerConfig { electrumServer: { host: string; port: number; ssl?: boolean; }; network?: bitcoin.Network; defaultAddressType?: 'legacy' | 'segwit' | 'native_segwit'; } ``` **Main Methods:** - `generateWallet()` - Generate new wallet with mnemonic - `importWallet(mnemonic, derivationPath?)` - Import from mnemonic - `exportWallet()` - Export wallet data - `connect()` / `disconnect()` - Manage Electrum connection - `deriveAddress(index, type?, change?)` - Derive addresses - `fetchBalance(address)` - Get address balance - `fetchUTXOs(address)` - Get unspent outputs - `createTransaction(from, to, amount, feeRate, privateKey, type)` - Build transaction - `broadcastTransaction(txHex)` - Broadcast to network - `estimateFee(blocks?)` - Get current fee rates - `getTransactionHistory(address)` - Get transaction history --- ## ๐Ÿ”‘ BitcoinWallet - HD Wallet & Address Generation The **BitcoinWallet** class handles hierarchical deterministic wallet creation and address generation for all Bitcoin address types. ### โœจ Address Types Supported - **Legacy (P2PKH)** - `1...` addresses using BIP44 (`m/44'/0'/0'/0/x`) - **SegWit (P2SH-P2WPKH)** - `3...` addresses using BIP49 (`m/49'/0'/0'/0/x`) - **Native SegWit (P2WPKH)** - `bc1q...` addresses using BIP84 (`m/84'/0'/0'/0/x`) ### ๐Ÿ”ง Usage ```typescript import { BitcoinWallet } from '@nawab_kibria/bitcoin-lib'; import * as bitcoin from 'bitcoinjs-lib'; // Generate a new wallet const wallet = BitcoinWallet.generate(bitcoin.networks.bitcoin); console.log('Mnemonic:', wallet.mnemonic); // Or create from existing mnemonic const existingWallet = BitcoinWallet.fromMnemonic( 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about', bitcoin.networks.bitcoin ); // Generate addresses of all types const legacyAddresses = wallet.generateLegacyAddresses(3); const segwitAddresses = wallet.generateSegwitAddresses(3); const nativeSegwitAddresses = wallet.generateNativeSegwitAddresses(3); console.log('First Native SegWit Address:', nativeSegwitAddresses[0].address); // Output: bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq ``` ### ๐Ÿ“– BitcoinWallet API **Static Methods:** - `BitcoinWallet.generate(network?)` - Generate new wallet with random mnemonic - `BitcoinWallet.fromMnemonic(mnemonic, network?)` - Create wallet from existing mnemonic **Instance Methods:** - `generateLegacyAddresses(count, network?)` - Generate P2PKH addresses - `generateSegwitAddresses(count, network?)` - Generate P2SH-P2WPKH addresses - `generateNativeSegwitAddresses(count, network?)` - Generate P2WPKH addresses - `getAddressByPath(path, type, network?)` - Generate address by custom path - `getWalletKeys(network?)` - Get all wallet keys (xpub/xprv, zpub/zprv, etc.) - `setNetwork(network)` - Change wallet's default network --- ## ๐Ÿ”จ TransactionBuilder - Transaction Creation & Signing The **TransactionBuilder** class handles UTXO selection, transaction building, fee estimation, and signing for all address types. ### ๐Ÿ”ง Usage ```typescript import { TransactionBuilder } from '@nawab_kibria/bitcoin-lib'; import * as bitcoin from 'bitcoinjs-lib'; const builder = new TransactionBuilder(bitcoin.networks.regtest); // Build a transaction const result = await builder.buildTransaction({ fromAddress: 'bc1q...', toAddress: 'bc1q...', amount: 50000, // satoshis feeRate: 1, // sat/vB utxos: utxoArray, privateKey: 'your-private-key-wif', addressType: 'native_segwit' }); console.log('Transaction Hex:', result.hex); console.log('Transaction ID:', result.txid); ``` ### ๐Ÿ“– TransactionBuilder API **Methods:** - `buildTransaction(params)` - Build and sign complete transaction - `estimateTransactionSize(inputs, outputs, addressType)` - Estimate transaction size - `selectUTXOs(utxos, targetAmount, feeRate)` - Smart UTXO selection - `createPSBT(params)` - Create Partially Signed Bitcoin Transaction - `signPSBT(psbt, privateKey, addressType)` - Sign PSBT **Transaction Parameters:** ```typescript interface TransactionParams { fromAddress: string; toAddress: string; amount: number; // satoshis feeRate: number; // sat/vB utxos: UTXO[]; privateKey: string; // WIF format addressType: 'legacy' | 'segwit' | 'native_segwit'; changeAddress?: string; } ``` --- ## ๐ŸŒ ElectrumClient - Blockchain Connectivity The **ElectrumClient** class provides connectivity to Electrum servers for blockchain data and transaction broadcasting. ### ๐Ÿ”ง Usage ```typescript import { ElectrumClient, createElectrumClient } from '@nawab_kibria/bitcoin-lib'; // Create and connect to Electrum server const client = createElectrumClient({ host: 'localhost', port: 50001, ssl: false }); await client.connect(); // Get address balance const balance = await client.getBalance('bc1q...'); console.log('Confirmed:', balance.confirmed); console.log('Unconfirmed:', balance.unconfirmed); // Get UTXOs const utxos = await client.getUTXOs('bc1q...'); // Broadcast transaction const result = await client.broadcast('020000000001...'); console.log('TXID:', result.txid); // Get transaction history const history = await client.getHistory('bc1q...'); await client.disconnect(); ``` ### ๐Ÿ“– ElectrumClient API **Connection Methods:** - `connect()` - Connect to Electrum server - `disconnect()` - Disconnect from server - `isConnected()` - Check connection status **Blockchain Methods:** - `getBalance(address)` - Get address balance - `getUTXOs(address)` - Get unspent transaction outputs - `getHistory(address)` - Get transaction history - `getTransaction(txid)` - Get transaction details - `broadcast(txHex)` - Broadcast transaction - `estimateFee(blocks?)` - Get fee estimation **Batch Methods:** - `getBalanceBatch(addresses)` - Get multiple balances - `getUTXOsBatch(addresses)` - Get multiple UTXO sets --- ## ๐Ÿงช Standards Compliance This library implements and complies with all major Bitcoin standards: - โœ… **BIP39** - Mnemonic phrase generation - โœ… **BIP32** - Hierarchical Deterministic wallets - โœ… **BIP44** - Multi-Account Hierarchy (Legacy) - โœ… **BIP49** - Derivation scheme for P2WPKH-nested-in-P2SH - โœ… **BIP84** - Derivation scheme for P2WPKH (Native SegWit) ## ๐ŸŒ Network Support - **Bitcoin Mainnet** - Production network (`bitcoin.networks.bitcoin`) - **Bitcoin Testnet** - Testing network (`bitcoin.networks.testnet`) - **Bitcoin Regtest** - Local development (`bitcoin.networks.regtest`) ## ๐Ÿงช Testing Run the comprehensive test suite: ```bash # Run all tests npm test # Run with coverage npm run test:coverage # Run examples npm run example:wallet-manager npm run example:complete-wallet npm run example:electrum npm run example:transaction ``` ## ๐Ÿ“ Examples The library includes comprehensive examples: ```bash # Complete wallet demonstration npm run example:complete-wallet # Wallet manager features npm run example:wallet-manager # Electrum connectivity npm run example:electrum # Transaction building npm run example:transaction # BIP84 compliance npm run example:bip84 ``` ## ๐Ÿ”’ Security Features - **Deterministic Generation** - Reproducible wallets from seed - **Proper Key Handling** - Secure cryptographic operations - **Input Validation** - Safe parameter handling - **Error Management** - Comprehensive error handling - **Memory Security** - Proper cleanup of sensitive data ## ๐Ÿ“Š Production Ready This library is **production-ready** with: - โœ… **90+ comprehensive tests** - โœ… **Perfect BIP compliance** - โœ… **TypeScript type safety** - โœ… **Professional documentation** - โœ… **Comprehensive examples** ## ๐Ÿ“„ License MIT License - see [LICENSE](LICENSE) file for details. --- **Start building modern Bitcoin applications today!** ๐Ÿš€