// A small JSON-RPC client for the local regtest bitcoind (tools/regtest/README.md), authenticated with its cookie. import { readFileSync } from 'node:fs'; import { homedir } from 'node:os'; import { join } from 'node:path'; export const DATADIR = process.env.LINEAGE_REGTEST ? join(process.env.LINEAGE_REGTEST, 'bitcoin') : join(homedir(), 'lineage-regtest', 'bitcoin'); export function bitcoind({ url = 'http://127.0.0.1:18443', datadir = DATADIR, wallet = null } = {}) { let id = 0; return async (method, ...params) => { const cookie = readFileSync(join(datadir, 'regtest', '.cookie'), 'utf8').trim(); const res = await fetch(wallet ? `${url}/wallet/${wallet}` : url, { method: 'POST', headers: { Authorization: `Basic ${Buffer.from(cookie).toString('base64')}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '1.0', id: ++id, method, params }), }); const body = await res.json().catch(() => null); if (!body || body.error) throw new Error(`${method}: ${body?.error?.message ?? `HTTP ${res.status}`}`); return body.result; }; }