From 10f9ebc0d047f1599f4665fda0b073c449bb8f64 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Sat, 27 Jun 2026 08:41:08 -0700 Subject: Add Boltz submarine + reverse swaps (Lightning <-> on-chain) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Non-custodial swaps via Boltz, fully client-side: hal holds the swap key + preimage and claims (reverse) / refunds (submarine) on-chain via the taproot script path, so Boltz can never strand funds. - src/swap.js: tapleaf/tree construction (byte-exact vs boltz-core vectors), swap P2TR address derivation (MuSig2 internal key + taptweak), script-path claim/refund tx builder, bolt11 decode, Boltz api-v2 client, and a polling SwapManager (reverse auto-claim; submarine fund + status + refund). - wallet.js: deterministic swap-key derivation (dedicated chain) + persistence. - api.js: configurable Boltz REST/WS endpoints. - app.js: ⚡ Swap tab — Receive over LN (reverse) + Pay an invoice (submarine). - tools/swap-*.test.js: vectors, live-address, and end-to-end regtest tests. Verified end-to-end on regtest against a local Boltz wired to coinos's bc + a dedicated CLN/hold node. Co-Authored-By: Claude Opus 4.8 --- tools/swap-e2e-reverse.test.js | 78 ++++++++++++++++++++++++++++++++++++++++ tools/swap-e2e-submarine.test.js | 56 +++++++++++++++++++++++++++++ tools/swap-live.test.js | 57 +++++++++++++++++++++++++++++ tools/swap-manager.test.js | 43 ++++++++++++++++++++++ tools/swap-vectors.test.js | 42 ++++++++++++++++++++++ 5 files changed, 276 insertions(+) create mode 100644 tools/swap-e2e-reverse.test.js create mode 100644 tools/swap-e2e-submarine.test.js create mode 100644 tools/swap-live.test.js create mode 100644 tools/swap-manager.test.js create mode 100644 tools/swap-vectors.test.js (limited to 'tools') diff --git a/tools/swap-e2e-reverse.test.js b/tools/swap-e2e-reverse.test.js new file mode 100644 index 0000000..e3cd082 --- /dev/null +++ b/tools/swap-e2e-reverse.test.js @@ -0,0 +1,78 @@ +// End-to-end REVERSE swap (hal receives over Lightning) on regtest: +// 1. hal requests a reverse swap (preimage it controls) +// 2. coinos `cl` pays the hold invoice (HTLC locked) +// 3. Boltz locks funds on-chain to the swap address +// 4. hal claims them on-chain via the taproot SCRIPT PATH (preimage + sig) +// 5. Boltz extracts the preimage, settles the LN payment +// Proves buildSwapSpend (reverse claim) against the live stack. +// Run (stack up): bun tools/swap-e2e-reverse.test.js +import { $ } from 'bun'; +import { secp256k1 } from '@noble/curves/secp256k1'; +import * as btc from '@scure/btc-signer'; +import { sha256 } from '@noble/hashes/sha2'; +import { randomBytes, bytesToHex, hexToBytes } from '@noble/hashes/utils'; +import { hash160, swapP2TR, buildSwapSpend, REGTEST } from '../src/swap.js'; + +const BOLTZ = 'http://localhost:9001'; +const ESPLORA = 'http://localhost:3000'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const jget = async (u) => { const r = await fetch(u); return r.ok ? r.json() : null; }; +const post = async (p, b) => { + const r = await fetch(BOLTZ + p, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(b) }); + const j = await r.json(); if (!r.ok) throw new Error(`${p}: ${JSON.stringify(j)}`); return j; +}; + +// hal's claim key, preimage, and a destination address it controls. +const claimPriv = secp256k1.utils.randomPrivateKey(); +const claimPub = secp256k1.getPublicKey(claimPriv, true); +const preimage = randomBytes(32); +const destPriv = secp256k1.utils.randomPrivateKey(); +const destAddr = btc.p2wpkh(secp256k1.getPublicKey(destPriv, true), REGTEST).address; + +const amount = 120000; +const swap = await post('/v2/swap/reverse', { + invoiceAmount: amount, from: 'BTC', to: 'BTC', + claimPublicKey: bytesToHex(claimPub), preimageHash: bytesToHex(sha256(preimage)), +}); +console.log('swap', swap.id, 'lockup', swap.lockupAddress, 'onchain', swap.onchainAmount); + +const boltzPub = hexToBytes(swap.refundPublicKey); +const d = swapP2TR({ kind: 'reverse', preimageHash160: hash160(preimage), boltzPub33: boltzPub, halPub33: claimPub, lockTime: swap.timeoutBlockHeight, network: 'regtest' }); +if (d.address !== swap.lockupAddress) throw new Error('address mismatch — abort'); + +// Pay the hold invoice from cl (backgrounded — it stays pending until we claim). +console.log('paying hold invoice from cl…'); +Bun.spawn(['docker', 'exec', 'cl', 'lightning-cli', '--regtest', 'pay', swap.invoice], { stdout: 'ignore', stderr: 'ignore' }); + +// Wait for Boltz to lock funds on-chain to the swap address. +let utxo = null; +for (let i = 0; i < 40; i++) { + await sleep(1000); + const us = await jget(`${ESPLORA}/address/${swap.lockupAddress}/utxo`); + if (us && us.length) { utxo = us[0]; break; } +} +if (!utxo) throw new Error('lockup not seen on-chain (esplora)'); +console.log('lockup utxo', utxo.txid, 'vout', utxo.vout, 'value', utxo.value); + +// Claim it on-chain via the script path. +const fee = 300; +const claimHex = buildSwapSpend({ + pay: d.pay, leaf: d.claimLeaf, halPriv: claimPriv, preimage, + lockupTxid: utxo.txid, lockupVout: utxo.vout, lockupValue: utxo.value, + destAddress: destAddr, fee, network: 'regtest', +}); +const br = await fetch(`${ESPLORA}/tx`, { method: 'POST', body: claimHex }); +const claimTxid = await br.text(); +if (!br.ok) throw new Error('broadcast failed: ' + claimTxid); +console.log('claim broadcast', claimTxid); + +// Verify hal's destination received the funds. +let got = null; +for (let i = 0; i < 15; i++) { + await sleep(1000); + const us = await jget(`${ESPLORA}/address/${destAddr}/utxo`); + if (us && us.length) { got = us[0]; break; } +} +if (!got) throw new Error('destination did not receive claim'); +console.log(`\nPASS — hal received ${got.value} sat on-chain at ${destAddr} (reverse swap claimed via script path)`); +process.exit(0); diff --git a/tools/swap-e2e-submarine.test.js b/tools/swap-e2e-submarine.test.js new file mode 100644 index 0000000..265721d --- /dev/null +++ b/tools/swap-e2e-submarine.test.js @@ -0,0 +1,56 @@ +// End-to-end SUBMARINE swap (hal spends over Lightning) on regtest: +// 1. `cl` issues an invoice (the payee/merchant) +// 2. hal creates a submarine swap for it (refund key it controls) +// 3. hal funds the on-chain lockup with expectedAmount (here: from bc) +// 4. Boltz detects the lockup, pays the LN invoice, and claims the lockup +// 5. the invoice is paid → hal's on-chain spend reached a LN payee +// Proves swap creation + address + the funded-lockup → Boltz-pays path. +// (Refund-path signing is the same buildSwapSpend validated by the reverse E2E.) +// Run (stack up): bun tools/swap-e2e-submarine.test.js +import { $ } from 'bun'; +import { secp256k1 } from '@noble/curves/secp256k1'; +import { ripemd160 } from '@noble/hashes/legacy'; +import { bytesToHex, hexToBytes } from '@noble/hashes/utils'; +import { swapP2TR } from '../src/swap.js'; + +const BOLTZ = 'http://localhost:9001'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const post = async (p, b) => { + const r = await fetch(BOLTZ + p, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(b) }); + const j = await r.json(); if (!r.ok) throw new Error(`${p}: ${JSON.stringify(j)}`); return j; +}; +const bcli = (...a) => $`docker exec bc bitcoin-cli -regtest -rpcuser=admin1 -rpcpassword=123 ${a}`.text(); +const clcli = (...a) => $`docker exec cl lightning-cli --regtest ${a}`.text(); + +// cl (payee) issues an invoice hal wants to pay. +const amount = 120000; +const inv = JSON.parse(await clcli('invoice', String(amount * 1000), `hal-${Date.now()}`, 'submarine test')); + +// hal's refund key + submarine swap. +const refundPriv = secp256k1.utils.randomPrivateKey(); +const refundPub = secp256k1.getPublicKey(refundPriv, true); +const swap = await post('/v2/swap/submarine', { invoice: inv.bolt11, from: 'BTC', to: 'BTC', refundPublicKey: bytesToHex(refundPub) }); +console.log('swap', swap.id, 'lockup', swap.address, 'expected', swap.expectedAmount); + +// Verify the lockup address before funding (don't-trust-verify). +const d = swapP2TR({ kind: 'submarine', preimageHash160: ripemd160(hexToBytes(inv.payment_hash)), boltzPub33: hexToBytes(swap.claimPublicKey), halPub33: refundPub, lockTime: swap.timeoutBlockHeight, network: 'regtest' }); +if (d.address !== swap.address) throw new Error('address mismatch — abort'); +console.log('lockup address verified ✓'); + +// Fund the lockup (in real hal this is wallet coin-selection; here: from bc). +await bcli('-rpcwallet=coinos', 'sendtoaddress', swap.address, (swap.expectedAmount / 1e8).toFixed(8)); +const mineAddr = (await bcli('-rpcwallet=coinos', 'getnewaddress')).trim(); +await bcli('generatetoaddress', '1', mineAddr); // confirm (maxZeroConfAmount=0) +console.log('lockup funded + confirmed; waiting for Boltz to pay the invoice…'); + +// Boltz should detect the lockup, pay the LN invoice, and claim. +let paid = false; +for (let i = 0; i < 45; i++) { + await sleep(1000); + const ls = JSON.parse(await clcli('listinvoices')); + const mine = ls.invoices?.find((x) => x.payment_hash === inv.payment_hash); + if (mine?.status === 'paid') { paid = true; break; } +} +if (!paid) throw new Error('invoice not paid by Boltz within timeout'); +console.log(`\nPASS — Boltz paid hal's submarine invoice (${amount} sat) after the on-chain lockup. hal spent on-chain → LN payee.`); +process.exit(0); diff --git a/tools/swap-live.test.js b/tools/swap-live.test.js new file mode 100644 index 0000000..f56105a --- /dev/null +++ b/tools/swap-live.test.js @@ -0,0 +1,57 @@ +// Live integration check against the local Boltz (http://localhost:9001) + +// regtest CLN. Confirms Hal's locally-derived swap address + tapleaves match +// Boltz's lockupAddress + swapTree for BOTH flows — proving the MuSig2 +// internal-key order ([boltzKey, halKey]), the taptweak, and leaf construction. +// Run (regtest Boltz stack up): bun tools/swap-live.test.js +import { $ } from 'bun'; +import { secp256k1 } from '@noble/curves/secp256k1'; +import { sha256 } from '@noble/hashes/sha2'; +import { ripemd160 } from '@noble/hashes/legacy'; +import { randomBytes, bytesToHex, hexToBytes } from '@noble/hashes/utils'; +import { hash160, swapP2TR, buildSwapTree } from '../src/swap.js'; + +const BOLTZ = process.env.BOLTZ_API || 'http://localhost:9001'; +const post = async (p, b) => { + const r = await fetch(BOLTZ + p, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(b) }); + const j = await r.json(); + if (!r.ok) throw new Error(`${p} -> ${r.status} ${JSON.stringify(j)}`); + return j; +}; +const kp = () => { const sk = secp256k1.utils.randomPrivateKey(); return { sk, pk: secp256k1.getPublicKey(sk, true) }; }; +let fail = 0; +const eq = (n, g, w) => { if (g === w) console.log(` ok ${n}`); else { fail++; console.log(`FAIL ${n}\n got: ${g}\n want: ${w}`); } }; + +// ---------- REVERSE (hal receives over LN; hal claims) ---------- +{ + const claim = kp(); + const preimage = randomBytes(32); + const res = await post('/v2/swap/reverse', { + invoiceAmount: 100000, from: 'BTC', to: 'BTC', + claimPublicKey: bytesToHex(claim.pk), preimageHash: bytesToHex(sha256(preimage)), + }); + const boltzPub = hexToBytes(res.refundPublicKey); // Boltz refunds on reverse + const d = swapP2TR({ kind: 'reverse', preimageHash160: hash160(preimage), boltzPub33: boltzPub, halPub33: claim.pk, lockTime: res.timeoutBlockHeight, network: 'regtest' }); + eq('reverse lockup address', d.address, res.lockupAddress); + eq('reverse claim leaf', bytesToHex(d.claimLeaf), res.swapTree.claimLeaf.output); + eq('reverse refund leaf', bytesToHex(d.refundLeaf), res.swapTree.refundLeaf.output); +} + +// ---------- SUBMARINE (hal spends over LN; hal refunds) ---------- +{ + const inv = JSON.parse(await $`docker exec clb lightning-cli --regtest invoice 100000000 hal-sub-${Date.now()} test`.text()); + const payHash = inv.payment_hash; + const refund = kp(); // hal's refund key + const res = await post('/v2/swap/submarine', { + invoice: inv.bolt11, from: 'BTC', to: 'BTC', refundPublicKey: bytesToHex(refund.pk), + }); + const boltzPub = hexToBytes(res.claimPublicKey); // Boltz claims on submarine + // tapscript embeds hash160(preimage) = ripemd160(payment_hash) + const ph160 = ripemd160(hexToBytes(payHash)); + const d = swapP2TR({ kind: 'submarine', preimageHash160: ph160, boltzPub33: boltzPub, halPub33: refund.pk, lockTime: res.timeoutBlockHeight, network: 'regtest' }); + eq('submarine lockup address', d.address, res.address); + eq('submarine claim leaf', bytesToHex(d.claimLeaf), res.swapTree.claimLeaf.output); + eq('submarine refund leaf', bytesToHex(d.refundLeaf), res.swapTree.refundLeaf.output); +} + +console.log(fail ? `\n${fail} FAILED` : '\nall good'); +process.exit(fail ? 1 : 0); diff --git a/tools/swap-manager.test.js b/tools/swap-manager.test.js new file mode 100644 index 0000000..7a83be1 --- /dev/null +++ b/tools/swap-manager.test.js @@ -0,0 +1,43 @@ +// Drives the SwapManager reverse flow end-to-end with a minimal wallet shim: +// startReverse -> pay the hold invoice from cl -> manager auto-claims on-chain. +// Run (stack up): bun tools/swap-manager.test.js +import { HDKey } from '@scure/bip32'; +import * as btc from '@scure/btc-signer'; +import { secp256k1 } from '@noble/curves/secp256k1'; +import { randomBytes } from '@noble/hashes/utils'; +import { SwapManager, REGTEST } from '../src/swap.js'; + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const ESPLORA = 'http://localhost:3000'; +// Fresh random seed per run (real wallet persists swaps so swapNode indices +// increment; this shim's store is in-memory, so randomize to avoid preimage reuse). +const acct = HDKey.fromMasterSeed(randomBytes(64)).derive("m/84'/1'/0'"); + +let store = []; +const wallet = { + loadSwaps: () => store, + saveSwaps: (l) => { store = l; }, + nextSwapIndex: () => store.reduce((m, s) => Math.max(m, (s.swapIndex ?? -1) + 1), 0), + swapNode: (i) => acct.deriveChild(2).deriveChild(i), + freshReceive: () => ({ address: btc.p2wpkh(secp256k1.getPublicKey(acct.deriveChild(0).deriveChild(7).privateKey, true), REGTEST).address }), + api: { + addressUtxos: async (a) => { const r = await fetch(`${ESPLORA}/address/${a}/utxo`); return r.ok ? r.json() : []; }, + broadcast: async (hex) => { const r = await fetch(`${ESPLORA}/tx`, { method: 'POST', body: hex }); const t = await r.text(); if (!r.ok) throw new Error(t); return t; }, + }, +}; + +const sm = new SwapManager({ wallet, network: 'regtest', getApi: () => 'http://localhost:9001', feeRate: 2, onUpdate: () => {} }); +const rec = await sm.startReverse(120000); +console.log('startReverse ->', rec.id, rec.status, 'lockup', rec.lockupAddress); + +console.log('paying hold invoice from cl…'); +Bun.spawn(['docker', 'exec', 'cl', 'lightning-cli', '--regtest', 'pay', rec.invoice], { stdout: 'ignore', stderr: 'ignore' }); + +for (let i = 0; i < 60; i++) { + await sleep(1000); + const r = sm.list().find((s) => s.id === rec.id); + if (r.status === 'claimed') { console.log(`\nPASS — SwapManager auto-claimed: ${r.received} sats, txid ${r.claimTxid}`); process.exit(0); } + if (r.lastError && i % 5 === 0) console.log(' …', r.lastError); +} +console.log('FAIL — not claimed:', JSON.stringify(sm.list())); +process.exit(1); diff --git a/tools/swap-vectors.test.js b/tools/swap-vectors.test.js new file mode 100644 index 0000000..147b114 --- /dev/null +++ b/tools/swap-vectors.test.js @@ -0,0 +1,42 @@ +// Verify Hal's swap tapscript/tree construction byte-for-byte against +// boltz-core's published test vectors (boltz-core/src/bitcoin/scripts/*.rs). +// Run: bun tools/swap-vectors.test.js +import { + submarineClaimLeaf, reverseClaimLeaf, refundLeaf, swapMerkleRoot, + hexToBytes, bytesToHex, +} from '../src/swap.js'; +import { p2tr, taprootListToTree } from '@scure/btc-signer/payment'; + +let pass = 0, fail = 0; +const eq = (name, got, want) => { + if (got === want) { pass++; console.log(` ok ${name}`); } + else { fail++; console.log(`FAIL ${name}\n got: ${got}\n want: ${want}`); } +}; + +// --- swap_tree.rs vector --- +const claimPk = hexToBytes('814fe2b5ce0e3fe5787fade9a4357a743c4ce6de473e5f29daf42112e47db25a'); +const refundPk = hexToBytes('0095b23ac89f523cdbcd791d3325ada7ddb30fd6134bb7fff22ba1e00414cb7d'); +const ph = hexToBytes('34e64e5b1373a872019ee2c7791cf4264d1079de'); // hash160(preimage) + +eq('submarine claim leaf', + bytesToHex(submarineClaimLeaf(ph, claimPk)), + 'a91434e64e5b1373a872019ee2c7791cf4264d1079de8820814fe2b5ce0e3fe5787fade9a4357a743c4ce6de473e5f29daf42112e47db25aac'); + +// Cross-check our two-leaf merkle root against @scure's own taproot tree +// builder (BIP341) for the same leaves — proves the TapBranch/sort logic. +const claim = submarineClaimLeaf(ph, claimPk); +const refund = refundLeaf(refundPk, 123); +const scureRoot = bytesToHex( + p2tr(claimPk, taprootListToTree([{ script: claim }, { script: refund }]), undefined, true).tapMerkleRoot, +); +eq('merkle root matches @scure tree builder', bytesToHex(swapMerkleRoot(claim, refund)), scureRoot); + +// --- reverse_tree.rs vector --- +const rClaimPk = hexToBytes('97f2ea5402afd2e90130e84d97e455f67493a956c20faedce32086516ef9f12e'); +const rPh = hexToBytes('761de3d1f1f54cc8b3beec0a1ad03820a2e12b90'); +eq('reverse claim leaf', + bytesToHex(reverseClaimLeaf(rPh, rClaimPk)), + '82012088a914761de3d1f1f54cc8b3beec0a1ad03820a2e12b90882097f2ea5402afd2e90130e84d97e455f67493a956c20faedce32086516ef9f12eac'); + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail ? 1 : 0); -- cgit v1.2.3