### Install Lcoin using Git and NPM Source: https://github.com/bcoin-org/lcoin/blob/litecoin/README.md This snippet demonstrates the basic installation process for Lcoin. It involves cloning the repository, navigating into the directory, installing dependencies using npm, and running the Lcoin executable. ```bash git clone git://github.com/bcoin-org/lcoin.git cd lcoin npm install ./bin/lcoin ``` -------------------------------- ### Run Lightweight SPV Litecoin Node with Lcoin Source: https://context7.com/bcoin-org/lcoin/llms.txt This snippet illustrates how to set up and operate a Simplified Payment Verification (SPV) node using Lcoin's SPVNode class. SPV nodes are resource-efficient, downloading only block headers and merkle proofs. The example shows node initialization, connection, event handling for blocks and transactions, and broadcasting transactions. ```javascript var SPVNode = require('lcoin/lib/node/spvnode'); var node = new SPVNode({ network: 'testnet', db: 'memory', checkpoints: true }); async function main() { await node.open(); await node.connect(); // SPV nodes only receive blocks matching the bloom filter node.on('block', function(block) { console.log('Received block: %s', block.rhash()); }); node.on('tx', function(tx) { console.log('Received matching transaction: %s', tx.txid()); }); // Start syncing headers node.startSync(); // Broadcast transactions (not verified locally) await node.sendTX(tx); } main(); ``` -------------------------------- ### Query Blockchain Data via HTTP REST API Endpoints (Bash) Source: https://context7.com/bcoin-org/lcoin/llms.txt This snippet shows how to query blockchain data using the HTTP REST API endpoints exposed by a running lcoin node. It includes examples for getting node information, UTXOs, transactions, blocks, and broadcasting transactions. Uses `curl` for requests. ```bash # Get node information curl http://localhost:9332/ \ -H 'Authorization: Basic ' # Response: # { # "version": "1.0.0-beta.15", # "network": "testnet", # "chain": { "height": 1500000, "tip": "...", "progress": 0.99 }, # "pool": { "host": "127.0.0.1", "port": 19335, ... }, # "mempool": { "tx": 150, "size": 50000 } # } # Get UTXOs by address curl http://localhost:9332/coin/address/LhyLNfBkoKshT7R8Pce6vkB9T2cP2o84hx # Get specific UTXO curl http://localhost:9332/coin// # Get transaction by hash curl http://localhost:9332/tx/ # Get transactions by address curl http://localhost:9332/tx/address/LhyLNfBkoKshT7R8Pce6vkB9T2cP2o84hx # Get block by hash or height curl http://localhost:9332/block/ # Broadcast transaction curl -X POST http://localhost:9332/broadcast \ -H 'Content-Type: application/json' \ -d '{"tx": ""}' # Bulk query UTXOs curl -X POST http://localhost:9332/coin/address \ -H 'Content-Type: application/json' \ -d '{"addresses": ["addr1", "addr2"]}' ``` -------------------------------- ### Run Full Litecoin Node with Lcoin Source: https://context7.com/bcoin-org/lcoin/llms.txt This snippet demonstrates how to instantiate and run a full Litecoin node using the FullNode class from the Lcoin library. It covers node configuration, opening the node, connecting to the P2P network, synchronizing the blockchain, and querying blockchain data. Dependencies include the 'lcoin' library. ```javascript var FullNode = require('lcoin/lib/node/fullnode'); // Create a full node instance var node = new FullNode({ network: 'testnet', // 'main', 'testnet', or 'regtest' db: 'leveldb', // Database backend ('leveldb' or 'memory') prefix: '/home/user/.lcoin', // Data directory checkpoints: true, // Use checkpoints for faster sync prune: false, // Enable blockchain pruning indexTX: true, // Index transactions by hash indexAddress: true, // Index transactions by address apiKey: 'secret-key', // HTTP API authentication key listen: true // Listen for incoming peer connections }); async function main() { // Open the node (loads chain, mempool, etc.) await node.open(); // Connect to the P2P network await node.connect(); // Listen for new blocks node.on('connect', function(entry, block) { console.log('Block %s (%d) added to chain.', entry.rhash(), entry.height); }); // Listen for new transactions in mempool node.on('tx', function(tx) { console.log('Transaction %s added to mempool.', tx.txid()); }); // Start blockchain synchronization node.startSync(); // Query blockchain data var block = await node.getBlock('0000000000000000...'); // Get block by hash var coin = await node.getCoin(txHash, outputIndex); // Get UTXO var tx = await node.getTX(txHash); // Get transaction // Broadcast a transaction await node.sendTX(tx); } main(); ``` -------------------------------- ### Manage Wallets with WalletDB in JavaScript Source: https://context7.com/bcoin-org/lcoin/llms.txt Demonstrates how to use the WalletDB module to manage multiple wallets, including opening the database, creating wallets and accounts, checking balances, sending transactions, and retrieving transaction history. It requires the 'lcoin/lib/wallet/walletdb' module. ```javascript var WalletDB = require('lcoin/lib/wallet/walletdb'); var MTX = require('lcoin/lib/primitives/mtx'); var Outpoint = require('lcoin/lib/primitives/outpoint'); var walletdb = new WalletDB({ network: 'testnet', db: 'leveldb', prefix: '/home/user/.lcoin/wallet' }); async function main() { await walletdb.open(); // Create a new wallet var wallet = await walletdb.create({ id: 'mywallet', passphrase: 'secret' }); console.log('Wallet ID:', wallet.id); console.log('Receive address:', wallet.getAddress().toString()); // Create a named account within the wallet var account = await wallet.createAccount({ name: 'savings' }); console.log('Account name:', account.name); console.log('Account receive address:', account.getReceive().toString()); // Get wallet balance var balance = await wallet.getBalance(); console.log('Confirmed:', balance.confirmed); console.log('Unconfirmed:', balance.unconfirmed); // Create and send a transaction var tx = await wallet.send({ rate: 10000, // Satoshis per KB outputs: [{ address: 'LhyLNfBkoKshT7R8Pce6vkB9T2cP2o84hx', value: 50000 }] }); console.log('Sent transaction:', tx.txid()); // Get transaction history var history = await wallet.getHistory(); history.forEach(function(tx) { console.log('TX:', tx.hash); }); } main(); ``` -------------------------------- ### Build and Sign Transactions with MTX in JavaScript Source: https://context7.com/bcoin-org/lcoin/llms.txt Shows how to use the MTX (Mutable Transaction) class to build, sign, and fund transactions. It covers generating keys, creating transactions, adding inputs and outputs, funding with automatic coin selection, signing with a private key, verifying the transaction, and converting it to an immutable TX for broadcasting. It requires the 'lcoin' module. ```javascript var bcoin = require('lcoin'); // Generate keys and addresses var master = bcoin.hd.generate(); var key = master.derive("m/44'/2'/0'/0/0"); var keyring = new bcoin.keyring(key.privateKey); // Create a coinbase transaction (for testing) var cb = new bcoin.mtx(); cb.addInput({ prevout: new bcoin.outpoint(), script: new bcoin.script(), sequence: 0xffffffff }); cb.addOutput({ address: keyring.getAddress(), value: 50000 }); // Convert coinbase output to available coin var coin = bcoin.coin.fromTX(cb, 0, -1); var coins = [coin]; // Create a new transaction var mtx = new bcoin.mtx(); // Add output (recipient) mtx.addOutput({ address: 'LhyLNfBkoKshT7R8Pce6vkB9T2cP2o84hx', value: 10000 }); // Fund the transaction with automatic coin selection await mtx.fund(coins, { rate: 10000, // Fee rate in satoshis per KB changeAddress: keyring.getAddress() }); // Sign all inputs mtx.sign(keyring); // Verify the transaction if (mtx.verify()) { console.log('Transaction is valid'); } // Convert to immutable TX for broadcasting var tx = mtx.toTX(); console.log('Transaction ID:', tx.txid()); console.log('Transaction hex:', tx.toRaw().toString('hex')); console.log('Fee:', mtx.getFee(), 'satoshis'); ``` -------------------------------- ### Interact with Wallet and Node APIs using HTTP Client (JavaScript) Source: https://context7.com/bcoin-org/lcoin/llms.txt This snippet demonstrates how to use the HTTP client to interact with lcoin wallet and node APIs. It covers creating wallets, managing accounts, sending transactions, and querying node information. Requires the 'lcoin/lib/http' module. ```javascript var HTTP = require('lcoin/lib/http'); // Create wallet HTTP client var wallet = new HTTP.Wallet({ network: 'regtest', apiKey: 'your-api-key', id: 'primary' // Wallet ID }); async function main() { // Create a new wallet var newWallet = await wallet.create({ id: 'test-wallet', passphrase: 'secret' }); console.log('Created wallet:', newWallet.id); // Get wallet info var info = await wallet.getInfo(); console.log('Wallet balance:', info.balance); // Create account var account = await wallet.createAccount('savings'); console.log('New address:', account.receiveAddress); // Get balance var balance = await wallet.getBalance(); console.log('Confirmed:', balance.confirmed); console.log('Unconfirmed:', balance.unconfirmed); // Send transaction var tx = await wallet.send({ rate: 10000, outputs: [{ address: 'LhyLNfBkoKshT7R8Pce6vkB9T2cP2o84hx', value: 50000 }] }); console.log('Sent TX:', tx.hash); // Get transaction details var details = await wallet.getTX(tx.hash); console.log('TX details:', details); // Use node RPC client var nodeInfo = await wallet.client.getInfo(); console.log('Node version:', nodeInfo.version); // Execute RPC methods var template = await wallet.client.rpc.execute('getblocktemplate', []); console.log('Block template:', template); } main(); ``` -------------------------------- ### Handle Bitcoin Scripts with Lcoin's Script Class (JavaScript) Source: https://context7.com/bcoin-org/lcoin/llms.txt This snippet demonstrates how to use the Lcoin Script class to create P2PKH, P2SH, and multisig output scripts. It also shows how to parse script types, check for specific script types (P2PKH, P2SH, multisig), and retrieve addresses from a script. Dependencies include the 'lcoin' library. ```javascript var bcoin = require('lcoin'); var Script = bcoin.script; var opcodes = Script.opcodes; // Create P2PKH output script var pubkeyHash = Buffer.from('...', 'hex'); var p2pkh = Script.fromPubkeyhash(pubkeyHash); console.log('P2PKH script:', p2pkh.toString()); // OP_DUP OP_HASH160 OP_EQUALVERIFY OP_CHECKSIG // Create P2SH output script var scriptHash = Buffer.from('...', 'hex'); var p2sh = Script.fromScripthash(scriptHash); // Create multisig script var pubkeys = [pubkey1, pubkey2, pubkey3]; var multisig = Script.fromMultisig(2, 3, pubkeys); console.log('2-of-3 multisig:', multisig.toString()); // OP_2 OP_3 OP_CHECKMULTISIG // Parse script type var script = Script.fromRaw(Buffer.from('...', 'hex')); console.log('Script type:', script.getType()); // 'pubkeyhash', 'scripthash', etc. // Check script types if (script.isPubkeyhash()) { console.log('P2PKH script'); } if (script.isScripthash()) { console.log('P2SH script'); } if (script.isMultisig()) { var [m, n] = script.getMultisig(); console.log(`${m}-of-${n} multisig`); } // Get addresses from script var address = script.getAddress(); console.log('Script address:', address.toString()); ``` -------------------------------- ### Generate Hierarchical Deterministic Keys with HD in JavaScript Source: https://context7.com/bcoin-org/lcoin/llms.txt Illustrates how to use the HD module for BIP32/BIP44 hierarchical deterministic key derivation, including generating a master key, creating one from a mnemonic phrase, deriving child keys using BIP44 paths, and exporting public keys (xpub) for watch-only wallets. It depends on the 'lcoin' module. ```javascript var bcoin = require('lcoin'); // Generate a new HD master key var master = bcoin.hd.generate(); console.log('Master xpriv:', master.toBase58()); // Generate from mnemonic phrase (BIP39) var mnemonic = new bcoin.hd.Mnemonic({ phrase: 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about' }); var masterFromMnemonic = bcoin.hd.fromMnemonic(mnemonic); // Derive child keys using BIP44 path // m/44'/2'/0'/0/0 (Litecoin mainnet, first account, external, first address) var key = master.derive("m/44'/2'/0'/0/0"); // Get the private and public keys console.log('Private key (WIF):', key.privateKey.toString('hex')); // Create a keyring for signing var keyring = new bcoin.keyring(key.privateKey); console.log('Address:', keyring.getAddress().toString()); // Derive hardened and non-hardened paths var account = master.derive("m/44'/2'/0'"); // Hardened derivation var external = account.derive(0); // Non-hardened var address0 = external.derive(0); var address1 = external.derive(1); // Export xpub for watch-only wallets var xpub = account.toPublic(); console.log('Account xpub:', xpub.toBase58()); ``` -------------------------------- ### Generate and Validate Litecoin Addresses (JavaScript) Source: https://context7.com/bcoin-org/lcoin/llms.txt This snippet demonstrates the Address class for handling Litecoin address encoding, decoding, and validation. It shows how to create addresses from strings, public keys, and scripts, and how to validate addresses for specific networks. Requires the 'lcoin' module. ```javascript var bcoin = require('lcoin'); var Address = bcoin.address; var Script = bcoin.script; var crypto = bcoin.crypto; // Create address from string var addr = Address.fromString('LhyLNfBkoKshT7R8Pce6vkB9T2cP2o84hx'); console.log('Type:', addr.getType()); // 'pubkeyhash' console.log('Hash:', addr.getHash('hex')); // Create P2PKH address from public key var pubkey = Buffer.from('02...', 'hex'); var hash = crypto.hash160(pubkey); var p2pkh = Address.fromHash(hash, Address.types.PUBKEYHASH, -1, 'main'); console.log('P2PKH:', p2pkh.toString()); // Create P2SH address from script var redeemScript = Script.fromMultisig(2, 3, [pubkey1, pubkey2, pubkey3]); var scriptHash = crypto.hash160(redeemScript.toRaw()); var p2sh = Address.fromHash(scriptHash, Address.types.SCRIPTHASH, -1, 'main'); console.log('P2SH:', p2sh.toString()); // Validate address for network try { var validated = Address.fromString('LhyLNf...', 'main'); console.log('Valid mainnet address'); } catch (e) { console.log('Invalid address'); } // Address types // Address.types.PUBKEYHASH - P2PKH (starts with L on mainnet) // Address.types.SCRIPTHASH - P2SH (starts with M on mainnet) // Address.types.WITNESS - Bech32 SegWit addresses ``` -------------------------------- ### HTTP Client - Wallet and Node API Client Source: https://context7.com/bcoin-org/lcoin/llms.txt This section details the usage of the HTTP client for interacting with Licoin wallets and nodes, including creating wallets, managing accounts, sending transactions, and querying node information. ```APIDOC ## HTTP Client - Wallet and Node API Client This module provides REST API clients for interacting with running nodes and wallets. ### Wallet API Examples ```javascript var HTTP = require('lcoin/lib/http'); // Create wallet HTTP client var wallet = new HTTP.Wallet({ network: 'regtest', apiKey: 'your-api-key', id: 'primary' // Wallet ID }); async function main() { // Create a new wallet var newWallet = await wallet.create({ id: 'test-wallet', passphrase: 'secret' }); console.log('Created wallet:', newWallet.id); // Get wallet info var info = await wallet.getInfo(); console.log('Wallet balance:', info.balance); // Create account var account = await wallet.createAccount('savings'); console.log('New address:', account.receiveAddress); // Get balance var balance = await wallet.getBalance(); console.log('Confirmed:', balance.confirmed); console.log('Unconfirmed:', balance.unconfirmed); // Send transaction var tx = await wallet.send({ rate: 10000, outputs: [{ address: 'LhyLNfBkoKshT7R8Pce6vkB9T2cP2o84hx', value: 50000 }] }); console.log('Sent TX:', tx.hash); // Get transaction details var details = await wallet.getTX(tx.hash); console.log('TX details:', details); } main(); ``` ### Node RPC Client Examples ```javascript // Use node RPC client (assuming wallet client is already initialized) var nodeInfo = await wallet.client.getInfo(); console.log('Node version:', nodeInfo.version); // Execute RPC methods var template = await wallet.client.rpc.execute('getblocktemplate', []); console.log('Block template:', template); ``` ``` -------------------------------- ### Handle P2P Network Connections with Peer Class Source: https://context7.com/bcoin-org/lcoin/llms.txt The Peer class manages individual peer connections for P2P network communication. It requires network configuration and an agent string. It can connect to peers, handle incoming packets (like 'block', 'inv', 'tx'), and respond to events such as connection opening, errors, and disconnection. ```javascript var Peer = require('lcoin/lib/net/peer'); var NetAddress = require('lcoin/lib/primitives/netaddress'); var Network = require('lcoin/lib/protocol/network'); var network = Network.get('testnet'); var peer = Peer.fromOptions({ network: 'testnet', agent: 'my-lcoin-client/1.0.0', hasWitness: function() { return false; } }); // Connect to a specific peer var addr = NetAddress.fromHostname('127.0.0.1:19335', 'testnet'); peer.connect(addr); peer.tryOpen(); // Handle errors peer.on('error', function(err) { console.error('Peer error:', err); }); // Handle incoming packets peer.on('packet', function(msg) { console.log('Received:', msg.cmd); if (msg.cmd === 'block') { var block = msg.block.toBlock(); console.log('Block hash:', block.rhash()); } if (msg.cmd === 'inv') { // Request full data for inventory items peer.getData(msg.items); } if (msg.cmd === 'tx') { console.log('Transaction:', msg.tx.txid()); } }); // Handle successful connection peer.on('open', function() { console.log('Connected to peer'); // Request genesis block peer.getBlock([network.genesis.hash]); // Request mempool contents peer.sendMempool(); }); peer.on('close', function() { console.log('Peer disconnected'); }); ``` -------------------------------- ### HTTP REST API Endpoints Source: https://context7.com/bcoin-org/lcoin/llms.txt This section outlines the available REST API endpoints for querying blockchain data from a running Licoin full node. ```APIDOC ## HTTP REST API Endpoints The HTTP server exposes REST endpoints for querying blockchain data when running a full node. ### GET / **Description**: Get node information. **Method**: GET **Endpoint**: `http://localhost:9332/` **Headers**: - `Authorization`: `Basic ` **Response Example (200 OK)**: ```json { "version": "1.0.0-beta.15", "network": "testnet", "chain": { "height": 1500000, "tip": "...", "progress": 0.99 }, "pool": { "host": "127.0.0.1", "port": 19335, ... }, "mempool": { "tx": 150, "size": 50000 } } ``` ### GET /coin/address/{address} **Description**: Get UTXOs by address. **Method**: GET **Endpoint**: `http://localhost:9332/coin/address/LhyLNfBkoKshT7R8Pce6vkB9T2cP2o84hx` ### GET /coin/{txhash}/{index} **Description**: Get a specific UTXO. **Method**: GET **Endpoint**: `http://localhost:9332/coin//` ### GET /tx/{txhash} **Description**: Get transaction by hash. **Method**: GET **Endpoint**: `http://localhost:9332/tx/` ### GET /tx/address/{address} **Description**: Get transactions by address. **Method**: GET **Endpoint**: `http://localhost:9332/tx/address/LhyLNfBkoKshT7R8Pce6vkB9T2cP2o84hx` ### GET /block/{hash-or-height} **Description**: Get block by hash or height. **Method**: GET **Endpoint**: `http://localhost:9332/block/` ### POST /broadcast **Description**: Broadcast a transaction. **Method**: POST **Endpoint**: `http://localhost:9332/broadcast` **Headers**: - `Content-Type`: `application/json` **Request Body**: - **tx** (string) - Required - The raw transaction hex. **Request Example**: ```json { "tx": "" } ``` ### POST /coin/address **Description**: Bulk query UTXOs by addresses. **Method**: POST **Endpoint**: `http://localhost:9332/coin/address` **Headers**: - `Content-Type`: `application/json` **Request Body**: - **addresses** (array of strings) - Required - A list of addresses to query. **Request Example**: ```json { "addresses": ["addr1", "addr2"] } ``` ``` -------------------------------- ### Address Generation and Validation Source: https://context7.com/bcoin-org/lcoin/llms.txt This section covers the Address class, which handles Litecoin address encoding, decoding, validation, and creation for various address types. ```APIDOC ## Address - Address Generation and Validation The Address class handles Litecoin address encoding, decoding, and validation for various address types. ### Creating an Address from String ```javascript var bcoin = require('lcoin'); var Address = bcoin.address; // Create address from string var addr = Address.fromString('LhyLNfBkoKshT7R8Pce6vkB9T2cP2o84hx'); console.log('Type:', addr.getType()); // 'pubkeyhash' console.log('Hash:', addr.getHash('hex')); ``` ### Creating Addresses from Public Key or Script ```javascript var bcoin = require('lcoin'); var Address = bcoin.address; var Script = bcoin.script; var crypto = bcoin.crypto; // Create P2PKH address from public key var pubkey = Buffer.from('02...', 'hex'); var hash = crypto.hash160(pubkey); var p2pkh = Address.fromHash(hash, Address.types.PUBKEYHASH, -1, 'main'); console.log('P2PKH:', p2pkh.toString()); // Create P2SH address from script var redeemScript = Script.fromMultisig(2, 3, [pubkey1, pubkey2, pubkey3]); var scriptHash = crypto.hash160(redeemScript.toRaw()); var p2sh = Address.fromHash(scriptHash, Address.types.SCRIPTHASH, -1, 'main'); console.log('P2SH:', p2sh.toString()); ``` ### Validating an Address ```javascript var bcoin = require('lcoin'); var Address = bcoin.address; // Validate address for network try { var validated = Address.fromString('LhyLNf...', 'main'); console.log('Valid mainnet address'); } catch (e) { console.log('Invalid address'); } ``` ### Address Types - `Address.types.PUBKEYHASH`: P2PKH (starts with L on mainnet) - `Address.types.SCRIPTHASH`: P2SH (starts with M on mainnet) - `Address.types.WITNESS`: Bech32 SegWit addresses ``` -------------------------------- ### Manage Blockchain Database with Chain Class Source: https://context7.com/bcoin-org/lcoin/llms.txt The Chain class manages the blockchain database, handling block validation and providing chain state queries. It requires network and database configuration. It can open, close, and query chain information like height and tip, as well as retrieve block entries by height or hash. ```javascript var Chain = require('lcoin/lib/blockchain/chain'); var chain = new Chain({ network: 'testnet', db: 'leveldb', prefix: '/home/user/.lcoin', prune: false, checkpoints: true }); async function main() { await chain.open(); // Get chain tip console.log('Chain height:', chain.height); console.log('Chain tip:', chain.tip.rhash()); // Get block entry by height var entry = await chain.getEntry(0); // Genesis block console.log('Genesis hash:', entry.rhash()); console.log('Genesis time:', new Date(entry.time * 1000)); // Get block entry by hash var entry = await chain.getEntry('hash...'); // Get full block from database var block = await chain.db.getBlock(entry.hash); console.log('Block transactions:', block.txs.length); // Check if a block is on the main chain var isMainChain = await chain.isMainChain(entry); // Get block locator for sync var locator = await chain.getLocator(); // Iterate through ancestors var ancestor = await entry.getAncestor(100); await chain.close(); } main(); ``` -------------------------------- ### Mine Blocks with Miner Class Source: https://context7.com/bcoin-org/lcoin/llms.txt The Miner class generates block templates and mines blocks. It depends on the Chain class and requires an address for coinbase transactions and optional coinbase flags. It can create block templates, mine blocks using CPU, and add mined blocks to the chain. ```javascript var Chain = require('lcoin/lib/blockchain/chain'); var Miner = require('lcoin/lib/mining/miner'); var chain = new Chain({ network: 'regtest' }); var miner = new Miner({ chain: chain, addresses: ['mfWxJ45yp2SFn7UciZyNpvDKrzbhyfKrY8'], coinbaseFlags: 'mined-by-lcoin' }); async function main() { await miner.open(); // Create a block template var template = await miner.createBlock(); console.log('Template height:', template.height); console.log('Template difficulty:', template.getDifficulty()); console.log('Template transactions:', template.items.length); // Mine a block using CPU var job = await miner.cpu.createJob(); var block = await job.mineAsync(); console.log('Mined block:', block.rhash()); console.log('Block nonce:', block.nonce); // Add mined block to chain await chain.add(block); console.log('New chain tip:', chain.tip.rhash()); } main(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.