diff --git a/src/demo.ts b/src/demo.ts index ca2f4d4..407160f 100644 --- a/src/demo.ts +++ b/src/demo.ts @@ -2,15 +2,21 @@ * demo.ts — End-to-end demonstration of the BCH xpub watcher. * * 1. Derives BCH receiving addresses from a BIP44 test xpub. - * 2. Fetches a real confirmed mainnet transaction from Blockchair. - * 3. Captures and logs all 4 required fields. + * 2. Fetches a real confirmed mainnet transaction from the self-hosted Fulcrum node. + * 3. Captures and logs all required fields. * - * Run: npx ts-node src/demo.ts + * Run: node --experimental-strip-types src/demo.ts */ import { HDKey } from '@scure/bip32'; -import { deriveAddresses, captureTransaction } from './watcher.ts'; -import axios from 'axios'; +import { + ElectrumClient, + FULCRUM_HOST, + FULCRUM_PORT, + deriveAddresses, + addressToScripthash, + captureTransaction, +} from './watcher.ts'; // BIP39 64-byte seed for "abandon abandon abandon ... about" (no passphrase) // DO NOT use for real funds. @@ -20,78 +26,76 @@ const TEST_SEED = Buffer.from( 'hex', ); +// Known confirmed mainnet transaction for integration test (block 951776). +// First output: bitcoincash:qzg0y2znj5vex92q7rsaufwmcqynfxx855d866cy6t — 1.9517377 BCH +const TEST_TXID = '07b20c779a16a3c05b18746c15638cce49558419b192936d3804518457f58eb8'; +const TEST_ADDR = 'bitcoincash:qzg0y2znj5vex92q7rsaufwmcqynfxx855d866cy6t'; + const HARDENED = 0x80000000; async function main(): Promise { - console.log('=== BCH xpub Watcher — End-to-End Demo ===\n'); + console.log('=== BCH xpub Watcher — End-to-End Demo (self-hosted Fulcrum) ===\n'); // 1. Derive xpub at m/44'/145'/0' (BCH BIP44 account, coin type 145 per SLIP-0044) const master = HDKey.fromMasterSeed(TEST_SEED); const account = master - .deriveChild(HARDENED + 44) // 44' purpose - .deriveChild(HARDENED + 145) // 145' BCH coin type - .deriveChild(HARDENED + 0); // 0' account + .deriveChild(HARDENED + 44) + .deriveChild(HARDENED + 145) + .deriveChild(HARDENED + 0); const xpub = account.publicExtendedKey; console.log("BIP44 BCH account xpub (m/44'/145'/0'):"); console.log(' ', xpub, '\n'); - // 2. Derive receiving addresses (external chain m/.../0/0..4) + // 2. Derive receiving addresses const addresses = deriveAddresses(xpub, 5); console.log("First 5 BCH receiving addresses (m/44'/145'/0'/0/0..4):"); addresses.forEach((addr, i) => console.log(` [${i}] ${addr}`)); - // 3. Capture a real confirmed mainnet transaction via Blockchair - console.log('\n--- Live Mainnet Capture Demo ---'); - console.log('Querying Blockchair for a recent confirmed BCH transaction...\n'); + console.log(`\n--- Electrum scripthashes for above addresses ---`); + addresses.forEach((addr, i) => { + const sh = addressToScripthash(addr); + console.log(` [${i}] ${sh}`); + }); + + // 3. Connect to self-hosted Fulcrum + console.log(`\n--- Connecting to Fulcrum at ${FULCRUM_HOST}:${FULCRUM_PORT} ---`); + const client = new ElectrumClient(); try { - const statsRes = await axios.get( - 'https://api.blockchair.com/bitcoin-cash/stats', - { timeout: 15_000 }, - ); - const blockId: number = statsRes.data.data.best_block_height - 1; - console.log(`Using block #${blockId}`); + await client.connect(); + console.log('Connected.\n'); - const txsRes = await axios.get( - `https://api.blockchair.com/bitcoin-cash/transactions?q=block_id(${blockId})&limit=1`, - { timeout: 15_000 }, - ); - const txRow = txsRes.data?.data?.[0]; - if (!txRow) throw new Error('No transactions returned for block ' + blockId); - const txid: string = txRow.hash; - console.log(`Selected txid: ${txid}`); + // 4. Capture a known confirmed mainnet transaction via Fulcrum + console.log(`Capturing transaction ${TEST_TXID}`); + console.log(`Expected output address: ${TEST_ADDR}\n`); + const capture = await captureTransaction(client, TEST_TXID, TEST_ADDR); - // Get full tx dashboard to find output recipient - const txDash = await axios.get( - `https://api.blockchair.com/bitcoin-cash/dashboards/transaction/${txid}`, - { timeout: 15_000 }, - ); - const txEntry = txDash.data?.data?.[txid]; - if (!txEntry) throw new Error('Transaction dashboard not found'); - const outputs = txEntry.outputs as Array<{ recipient: string; value: number }>; - if (!outputs?.length) throw new Error('No outputs found'); - const outputRecipient: string = outputs[0].recipient; - - // 4. captureTransaction — all 4 required fields - console.log(`\nCapturing for output recipient: ${outputRecipient}`); - const capture = await captureTransaction(txid, outputRecipient); - - console.log('\n=== Captured Transaction ==='); + console.log('=== Captured Transaction (via self-hosted Fulcrum) ==='); console.log(JSON.stringify(capture, null, 2)); - console.log('============================\n'); + console.log('=====================================================\n'); - console.log('All 4 required fields confirmed:'); + console.log('All required fields confirmed:'); console.log(` txid : ${capture.txid}`); console.log(` amountBCH : ${capture.amountBCH}`); console.log(` blockHash : ${capture.blockHash}`); console.log(` blockTimestamp : ${capture.blockTimestamp}`); console.log(` address : ${capture.address}`); + if (!capture.txid || !capture.blockHash || !capture.blockTimestamp) { + throw new Error('One or more required fields are missing or empty'); + } + if (capture.amountBCH <= 0) { + throw new Error(`Expected positive amountBCH, got ${capture.amountBCH}`); + } + console.log('\n✓ Integration test passed — self-hosted Fulcrum is serving transaction data.'); + } catch (err: unknown) { const msg = err instanceof Error ? err.message : String(err); console.error('\nDemo failed:', msg); process.exit(1); + } finally { + client.close(); } } diff --git a/src/watcher.ts b/src/watcher.ts index dfaf791..8539c8d 100644 --- a/src/watcher.ts +++ b/src/watcher.ts @@ -2,22 +2,17 @@ * BCH xpub watch-only transaction watcher. * * Derives receiving addresses from an xpub (BIP44 m/account/0/i path), - * polls the Blockchair BCH API for confirmed transactions, and captures - * txid, amount, block hash, block timestamp, and receiving address. + * polls the self-hosted Fulcrum Electrum server for confirmed transactions, + * and captures txid, amount, block hash, block timestamp, and receiving address. */ import { HDKey } from '@scure/bip32'; import { createHash } from 'crypto'; +import { createConnection, Socket } from 'net'; import cashaddr from 'cashaddrjs'; -import axios from 'axios'; -// Blockchair public API — no key required for moderate usage -const BLOCKCHAIR = axios.create({ - baseURL: 'https://api.blockchair.com/bitcoin-cash', - timeout: 20_000, -}); - -const SATOSHI = 1e8; +export const FULCRUM_HOST = '172.19.0.127'; +export const FULCRUM_PORT = 50001; // ── Address derivation ──────────────────────────────────────────────────────── @@ -32,15 +27,11 @@ function hash160(pubkey: Uint8Array): Buffer { * Path convention (BIP44 BCH, coin type 145): * account xpub at m/44'/145'/account' * receiving addresses at xpub/0/index - * - * @param xpub Account-level extended public key - * @param count Number of addresses to derive (default 20) - * @param testnet Use 'bchtest:' prefix when true (chipnet / testnet3) */ export function deriveAddresses(xpub: string, count = 20, testnet = false): string[] { const prefix = testnet ? 'bchtest' : 'bitcoincash'; const account = HDKey.fromExtendedKey(xpub); - const external = account.deriveChild(0); // BIP44 external (receiving) chain + const external = account.deriveChild(0); return Array.from({ length: count }, (_, i) => { const child = external.deriveChild(i); @@ -50,6 +41,90 @@ export function deriveAddresses(xpub: string, count = 20, testnet = false): stri }); } +// ── Electrum scripthash ─────────────────────────────────────────────────────── + +/** Convert a BCH P2PKH cashaddr to an Electrum scripthash (SHA256 of P2PKH script, reversed). */ +export function addressToScripthash(address: string): string { + const decoded = cashaddr.decode(address); + const h160 = Buffer.from(decoded.hash); + // P2PKH script: OP_DUP OP_HASH160 <20-byte hash160> OP_EQUALVERIFY OP_CHECKSIG + const script = Buffer.concat([ + Buffer.from([0x76, 0xa9, 0x14]), + h160, + Buffer.from([0x88, 0xac]), + ]); + return Buffer.from(createHash('sha256').update(script).digest()).reverse().toString('hex'); +} + +// ── Electrum JSON-RPC client ────────────────────────────────────────────────── + +export class ElectrumClient { + private socket: Socket; + private buffer = ''; + private nextId = 1; + private pending = new Map void; + reject: (e: Error) => void; + }>(); + + constructor(host = FULCRUM_HOST, port = FULCRUM_PORT) { + this.socket = createConnection(port, host); + this.socket.setEncoding('utf8'); + this.socket.setTimeout(30_000); + this.socket.on('data', (chunk: string) => { + this.buffer += chunk; + const lines = this.buffer.split('\n'); + this.buffer = lines.pop() ?? ''; + for (const line of lines) { + if (!line.trim()) continue; + try { + const msg = JSON.parse(line) as { + id: number; + result?: unknown; + error?: { code: number; message: string }; + }; + const p = this.pending.get(msg.id); + if (p) { + this.pending.delete(msg.id); + if (msg.error) p.reject(new Error(`Electrum ${msg.error.code}: ${msg.error.message}`)); + else p.resolve(msg.result); + } + } catch { /* ignore subscription notifications and partial lines */ } + } + }); + const rejectAll = (err: Error) => { + for (const p of this.pending.values()) p.reject(err); + this.pending.clear(); + }; + this.socket.on('error', rejectAll); + this.socket.on('timeout', () => { + rejectAll(new Error('Electrum socket timeout')); + this.socket.destroy(); + }); + this.socket.on('close', () => rejectAll(new Error('Electrum connection closed'))); + } + + async connect(): Promise { + await new Promise((resolve, reject) => { + this.socket.once('connect', resolve); + this.socket.once('error', reject); + }); + await this.call('server.version', ['using-cash-spike/1.0', '1.4']); + } + + call(method: string, params: unknown[]): Promise { + return new Promise((resolve, reject) => { + const id = this.nextId++; + this.pending.set(id, { resolve, reject }); + this.socket.write(JSON.stringify({ id, method, params }) + '\n'); + }); + } + + close(): void { + this.socket.destroy(); + } +} + // ── Types ───────────────────────────────────────────────────────────────────── export interface CapturedTransaction { @@ -65,75 +140,54 @@ export interface CapturedTransaction { address: string; } -// ── Blockchair API helpers ──────────────────────────────────────────────────── +// ── Fulcrum API helpers ─────────────────────────────────────────────────────── -/** Strip 'bitcoincash:' or 'bchtest:' prefix for use in Blockchair URLs. */ -function stripPrefix(addr: string): string { - const colon = addr.indexOf(':'); - return colon >= 0 ? addr.slice(colon + 1) : addr; -} - -// In-process cache: block_id → block_hash to avoid duplicate lookups. -const blockHashCache = new Map(); - -async function fetchBlockHash(blockId: number): Promise { - if (blockHashCache.has(blockId)) return blockHashCache.get(blockId)!; - const res = await BLOCKCHAIR.get(`/dashboards/block/${blockId}`); - const block = res.data?.data?.[blockId]?.block as { hash: string } | undefined; - if (!block?.hash) throw new Error(`Block hash not found for block ${blockId}`); - blockHashCache.set(blockId, block.hash); - return block.hash; +/** Fetch all confirmed transaction IDs for an Electrum scripthash. */ +export async function fetchConfirmedTxids( + client: ElectrumClient, + scripthash: string, +): Promise { + const history = await client.call('blockchain.scripthash.get_history', [scripthash]) as Array<{ + tx_hash: string; + height: number; + }>; + // height > 0 = confirmed; 0 or -1 = mempool + return history.filter(h => h.height > 0).map(h => h.tx_hash); } /** - * Capture full details of a confirmed transaction from Blockchair. - * Returns all 4 required fields: txid, amountBCH, blockHash, blockTimestamp, address. + * Capture full details of a confirmed transaction via Fulcrum. + * Matches the watched address by P2PKH scriptPubKey hex rather than address string + * to avoid any cashaddr/legacy format ambiguity. */ export async function captureTransaction( + client: ElectrumClient, txid: string, watchedAddress: string, ): Promise { - const res = await BLOCKCHAIR.get(`/dashboards/transaction/${txid}`); - const txEntry = res.data?.data?.[txid]; - if (!txEntry) throw new Error(`Blockchair: transaction ${txid} not found`); - - const tx = txEntry.transaction as { - hash: string; - block_id: number | null; - time: string; + const tx = await client.call('blockchain.transaction.get', [txid, true]) as { + txid: string; + vout: Array<{ value: number; scriptPubKey: { hex: string } }>; + blockhash?: string; + blocktime?: number; }; - const outputs = txEntry.outputs as Array<{ - recipient: string; - value: number; - }>; + if (!tx) throw new Error(`Fulcrum: transaction ${txid} not found`); - // Fetch block hash from block_id (Blockchair BCH doesn't include block_hash inline) - const blockHash = tx.block_id != null ? await fetchBlockHash(tx.block_id) : 'unconfirmed'; - - // Match output to our watched address (normalize by stripping prefix) - const plainWatched = stripPrefix(watchedAddress); - const matched = outputs.find(o => stripPrefix(o.recipient) === plainWatched); + // Build expected P2PKH script from the watched address's hash160 + const { hash } = cashaddr.decode(watchedAddress); + const h160hex = Buffer.from(hash).toString('hex'); + const expectedScript = `76a914${h160hex}88ac`; + const matched = tx.vout.find(o => o.scriptPubKey.hex === expectedScript); return { - txid: tx.hash, - amountBCH: (matched?.value ?? 0) / SATOSHI, - blockHash, - blockTimestamp: tx.time, + txid: tx.txid, + amountBCH: matched?.value ?? 0, + blockHash: tx.blockhash ?? 'unconfirmed', + blockTimestamp: tx.blocktime ? new Date(tx.blocktime * 1000).toISOString() : '', address: watchedAddress, }; } -/** - * Fetch all confirmed transaction IDs for a BCH address via Blockchair. - */ -async function fetchConfirmedTxids(address: string): Promise { - const plain = stripPrefix(address); - const res = await BLOCKCHAIR.get(`/dashboards/address/${plain}`); - const entry = res.data?.data?.[plain]; - // Blockchair returns transactions in descending order (newest first) - return (entry?.transactions ?? []) as string[]; -} - // ── Main watch loop ─────────────────────────────────────────────────────────── /** @@ -141,11 +195,6 @@ async function fetchConfirmedTxids(address: string): Promise { * * On startup, seeds the seen-tx set from existing confirmed transactions so * only *new* confirmations trigger a capture log. - * - * @param xpub Account-level BCH xpub - * @param addressCount Number of receiving addresses to watch (default 20) - * @param pollMs Polling interval in milliseconds (default 30 s) - * @param testnet Use bchtest prefix / chipnet */ export async function watchXpub( xpub: string, @@ -153,31 +202,37 @@ export async function watchXpub( pollMs = 30_000, testnet = false, ): Promise { + const client = new ElectrumClient(); + await client.connect(); + console.log(`Connected to Fulcrum at ${FULCRUM_HOST}:${FULCRUM_PORT}`); + console.log('Deriving addresses from xpub...'); const addresses = deriveAddresses(xpub, addressCount, testnet); + const scripthashes = addresses.map(addr => addressToScripthash(addr)); console.log(`\nWatching ${addresses.length} BCH ${testnet ? 'testnet' : 'mainnet'} addresses:`); addresses.forEach((addr, i) => console.log(` [${i}] ${addr}`)); const seen = new Set(); - // Seed so we don't re-alert on pre-existing transactions console.log('\nSeeding seen-tx set from existing history...'); - for (const addr of addresses) { - const txids = await fetchConfirmedTxids(addr); + for (const sh of scripthashes) { + const txids = await fetchConfirmedTxids(client, sh); txids.forEach(id => seen.add(id)); } console.log(`Seeded with ${seen.size} existing tx(s). Watching for new confirmations...\n`); while (true) { - for (const address of addresses) { + for (let i = 0; i < addresses.length; i++) { + const address = addresses[i]; + const scripthash = scripthashes[i]; try { - const txids = await fetchConfirmedTxids(address); + const txids = await fetchConfirmedTxids(client, scripthash); for (const txid of txids) { if (!seen.has(txid)) { seen.add(txid); console.log(`\n✓ New confirmed transaction on ${address}`); - const capture = await captureTransaction(txid, address); + const capture = await captureTransaction(client, txid, address); console.log('--- Captured ---'); console.log(JSON.stringify(capture, null, 2)); console.log('----------------\n');