aboutsummaryrefslogtreecommitdiffstats
path: root/tools/ark
diff options
context:
space:
mode:
Diffstat (limited to 'tools/ark')
-rw-r--r--tools/ark/custody-foreign-test.js102
-rw-r--r--tools/ark/custody-test.js55
-rw-r--r--tools/ark/dust-shapes-test.js59
-rw-r--r--tools/ark/isolate-dust-test.js98
-rw-r--r--tools/ark/offboard-split-test.js128
-rw-r--r--tools/ark/refresh-test.js9
-rw-r--r--tools/ark/rescue-claimed-test.js3
-rw-r--r--tools/ark/round-outputs-check-test.js33
8 files changed, 486 insertions, 1 deletions
diff --git a/tools/ark/custody-foreign-test.js b/tools/ark/custody-foreign-test.js
new file mode 100644
index 0000000..148622d
--- /dev/null
+++ b/tools/ark/custody-foreign-test.js
@@ -0,0 +1,102 @@
+// On a server that does not honor a coin past its timelock (Second, a custom
+// captaind) "coinos holds my coins" is not a tier: whatever is stored, the
+// tier in force is "self" (or "exit" when chosen), the card offers only those
+// two, and the renewal pass registers backstops and renews what is due.
+// Real app with a local Ark manager stub; nothing is sent anywhere.
+// Run: bun tools/ark/custody-foreign-test.js
+import assert from 'node:assert/strict';
+import puppeteer from '../puppeteer.js';
+import { generateMnemonic } from '@scure/bip39';
+import { wordlist } from '@scure/bip39/wordlists/english';
+
+const bundle = await Bun.build({ entrypoints: ['src/app.js'], target: 'browser', minify: true,
+ plugins: [{ name: 'custody-foreign-test', setup(build) {
+ build.onLoad({ filter: /src\/app\.js$/ }, async ({ path }) => ({ loader: 'js', contents: await Bun.file(path).text() + `
+window.coopApp = { ui, wallet, ctx, render, enterWallet, openWalletSettings, get ready() { return !_bootDeciding; },
+ setSpending: (on = true) => { const a = activeAccount(); if (a) { if (on) a.kind = 'spending'; else delete a.kind; } } };
+` }));
+ build.onLoad({ filter: /src\/features\/ark\.js$/ }, async ({ path }) => ({ loader: 'js', contents:
+ (await Bun.file(path).text()).replace(" return {\n id: 'ark',", `
+ window.coopFeature = { setManager: (mgr) => { ark = mgr; }, getCustody, applyCustody, maybeAutoRefresh, autoRefreshCalls: [] };
+ return {\n id: 'ark',`) }));
+ build.onLoad({ filter: /src\/video-compress\.js$/ }, () => ({ loader: 'js', contents: 'export async function compressVideo(f) { return f; }' }));
+ } }] });
+assert(bundle.success, bundle.logs.join('\n'));
+const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style>${await Bun.file('src/style.css').text()}</style><div id="app"></div><script type="module">${await bundle.outputs[0].text()}</script>`;
+const server = Bun.serve({ port: 0, fetch: (req) => new URL(req.url).pathname === '/'
+ ? new Response(html, { headers: { 'Content-Type': 'text/html' } }) : new Response(null, { status: 404 }) });
+const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--no-sandbox'] });
+try {
+ const page = await browser.newPage(), errors = [];
+ page.on('pageerror', (e) => errors.push(e.message));
+ await page.setViewport({ width: 390, height: 844 });
+ const cdp = await page.createCDPSession();
+ await cdp.send('Network.enable');
+ await cdp.send('Network.setBlockedURLs', { urls: ['wss://*', 'ws://*'] });
+ await page.setRequestInterception(true);
+ page.on('request', (r) => r.url().startsWith(server.url.origin) || r.url().startsWith('data:') ? r.continue() : r.abort());
+ await page.evaluateOnNewDocument(() => {
+ localStorage.setItem('btc-wallet-network', 'regtest');
+ // a custom server: no honorsExpired on its record, like Second's preset
+ localStorage.setItem('btc-wallet-ark-provider:regtest', 'custom');
+ localStorage.setItem('btc-wallet-ark-custom:regtest', JSON.stringify({ ark: 'http://localhost:3535', esplora: 'http://localhost:30002' }));
+ });
+ await page.goto(server.url.href, { waitUntil: 'domcontentloaded' });
+ await page.waitForFunction(() => window.coopApp?.ready);
+ await page.evaluate(async (mn) => {
+ await coopApp.enterWallet(mn, '', { fresh: true, generated: true });
+ coopApp.ui.onb = null; localStorage.removeItem('btc-wallet-onb-step');
+ coopApp.wallet.scan = async () => {};
+ const table = [{ thresholdBlocks: 0, ppm: 0 }, { thresholdBlocks: 288, ppm: 2000 }, { thresholdBlocks: 1008, ppm: 4000 }, { thresholdBlocks: 2016, ppm: 5000 }];
+ window.coopManager = {
+ honorsExpired: false,
+ state: { vtxos: [
+ { id: 'coin-0', amountSat: 20000, state: 'spendable', expiryHeight: 973921, depth: 2 }, // weeks left
+ { id: 'coin-1', amountSat: 5000, state: 'spendable', expiryHeight: 969760, depth: 1 }, // 9 blocks from its timelock
+ ], actions: [], movements: [], scheduled: [] },
+ info: { network: 'regtest', vtxoExpiryDelta: 4032, roundIntervalSecs: 3600, refreshFees: { baseFeeSat: 0, ppmExpiryTable: table } }, _tipH: 969751,
+ chain: { tipHeight: async () => 969751 },
+ vtxos() { return this.state.vtxos; },
+ _decoded(v) { return { genesis: new Array(v.depth || 1).fill({}), policy: { type: 'pubkey' } }; },
+ balance() { return { spendableSat: 25000, pendingSat: 0, boardingSat: 0, expiredSat: 0 }; },
+ refreshFee(inputs, tip) {
+ let u = 0;
+ for (const v of inputs) u += v.amountSat * (table.filter((e) => e.thresholdBlocks <= v.expiryHeight - tip).pop()?.ppm ?? 0);
+ return Math.ceil(u / 1e6);
+ },
+ async ensureScheduledRefreshes(margin, max, grid) { coopFeature.autoRefreshCalls.push(['ensure', margin, max, grid]); return 0; },
+ async refresh(ids) { coopFeature.autoRefreshCalls.push(['refresh', ids]); return 'refresh-1'; },
+ unseenReceives() { return []; }, ackReceives() {},
+ address() { return 'test-ark-address'; },
+ };
+ coopFeature.setManager(coopManager);
+ coopApp.setSpending(true);
+ coopApp.openWalletSettings('spending');
+ }, generateMnemonic(wordlist));
+ await page.waitForSelector('.ark-custody');
+
+ // nothing stored: the tier in force is "self", and the card offers no custodial option
+ assert.equal(await page.evaluate(() => coopFeature.getCustody()), 'self');
+ assert.equal(await page.evaluate(() => coopApp.wallet.loadFeatureState('arkCustody', null)), null, 'nothing was written to the record');
+ const opts = await page.$$eval('#ark-custody-select option', (os) => os.map((o) => [o.value, o.selected]));
+ assert.deepEqual(opts, [['self', true], ['exit', false]]);
+ console.log('✓ a server that does not honor expired coins has no "coinos holds my coins" tier; "self" is in force');
+
+ // the stored default from a coinos wallet does not switch renewals off here
+ await page.evaluate(() => coopApp.wallet.saveFeatureState('arkCustody', 'custodial'));
+ assert.equal(await page.evaluate(() => coopFeature.getCustody()), 'self');
+ console.log('✓ a stored "custodial" choice reads as "self" on such a server');
+
+ // the renewal pass runs: backstop orders are registered and the coin at its timelock renews now
+ const calls = await page.evaluate(async () => { coopFeature.autoRefreshCalls.length = 0; await coopFeature.maybeAutoRefresh(coopManager); return coopFeature.autoRefreshCalls; });
+ assert.deepEqual(calls[0], ['ensure', 6, 8, 1], 'backstop orders registered (regtest margin 6)');
+ assert.deepEqual(calls[1], ['refresh', ['coin-1']], 'the coin close to its timelock is renewed now');
+ console.log('✓ automatic renewal runs on such a server with nothing opted into');
+
+ // the exit tier can still be chosen, and is kept
+ await page.evaluate(() => coopFeature.applyCustody('exit'));
+ assert.equal(await page.evaluate(() => coopFeature.getCustody()), 'exit');
+ assert.equal(await page.evaluate(() => coopApp.wallet.loadFeatureState('arkCustody', null)), 'exit');
+ console.log('✓ "exit" can be chosen there and is saved');
+ assert.deepEqual(errors, [], 'no page errors');
+} finally { await browser.close(); server.stop(true); }
diff --git a/tools/ark/custody-test.js b/tools/ark/custody-test.js
index f8106b7..68e7191 100644
--- a/tools/ark/custody-test.js
+++ b/tools/ark/custody-test.js
@@ -93,4 +93,59 @@ const coin = (id, amountSat, expiryHeight, extra = {}) => ({ id, amountSat, expi
await assert.rejects(validateVtxo(v, { serverPubkey: serverPub, chain, acceptExpired: true }), (e) => e instanceof VtxoValidationError && /not confirmed/.test(e.message), 'past the expiry check, on to the anchor');
console.log('✓ validateVtxo: acceptExpired lets a coin past its timelock through the expiry check');
}
+
+// deep coins: the server's depth cap and its base-fee waiver, mirrored
+{
+ const m = mk(true);
+ m.info.refreshFees.deepWaiverDepth = 60;
+ m.info.maxVtxoExitDepth = 100;
+ m.exitDepth = (v) => v.depth || 0;
+ m._tipMemo = async () => 1000;
+ const shallow = coin('s', 5000, 2000, { depth: 7 }), deep = coin('d', 4000, 2000, { depth: 60 });
+ const capped = coin('x', 3000, 2000, { depth: 100 }), near = coin('n', 2500, 2000, { depth: 92 });
+ const expiredDeep = coin('e', 6000, 900, { depth: 70 });
+ m.state.vtxos = [shallow, deep, capped, near, expiredDeep];
+ assert.equal(m.refreshFee([deep], 1000), 0, 'a refresh of deep coins alone pays no base fee');
+ assert.equal(m.refreshFee([deep, expiredDeep], 1000), 0);
+ assert.equal(m.refreshFee([deep, shallow], 1000), 300, '…one shallow coin in the set and it pays');
+ assert.equal(m.refreshFee([shallow], 1000), 300);
+ assert.deepEqual(m.deepCoins().map((v) => v.id).sort(), ['d', 'e', 'n', 'x'], 'deep = at the waiver depth or within 8 hops of the cap, expired or not');
+ assert.deepEqual(m._selectInputs(2900).map((v) => v.id), ['d'], 'a coin at the cap is never an input (the cosign would be refused)');
+ m.state.vtxos = [capped];
+ assert.throws(() => m._selectInputs(1000), /waiting to be renewed/, 'and the shortfall says why');
+ m.state.vtxos = [shallow, deep, capped, near, expiredDeep];
+ // the worker's orders: one per deep coin still inside its timelock, two blocks out
+ const orders = [];
+ m.scheduleRefresh = async (ids, h) => { orders.push([ids.join(), h]); (m.state.scheduled ||= []).push({ inputIds: ids, unlockHash: 'u' + ids }); };
+ assert.equal(await m.ensureDeepRefreshes(3), 3);
+ assert.deepEqual(orders, [['x', 1002], ['n', 1002], ['d', 1002]], 'deepest first, at tip + 2; the expired one waits for the app');
+ assert.equal(await m.ensureDeepRefreshes(3), 0, 'covered coins are not ordered twice');
+ // no waiver and no cap advertised: nothing is deep
+ const plain = mk(true); plain.exitDepth = () => 999; plain.state.vtxos = [coin('p', 5000, 2000)];
+ assert.deepEqual(plain.deepCoins(), []);
+ assert.equal(plain.refreshFee(plain.state.vtxos, 1000), 300, 'no waiver advertised: the base fee stands however deep');
+ console.log('✓ deep coins: no base fee for a refresh of deep coins alone, a capped coin is never spent, the worker orders them flattened');
+}
+
+// Lightning sends: a wallet that renews its own coins spends the nearest
+// expiry first; the custodial default keeps the smallest coin that covers it
+{
+ const m = mk(true);
+ m.info.lnSendFees = { baseFeeSat: 0, minFeeSat: 0, ppmExpiryTable: [] };
+ m.state.vtxos = [coin('young', 3000, 2000), coin('old', 9000, 1100), coin('older', 2000, 1050), coin('past', 8000, 900)];
+ const ids = (amt) => m._selectLnInputs(m.state.vtxos, 1000, amt, 0).inputs.map((v) => v.id);
+ assert.deepEqual(ids(2500), ['young'], 'custodial: the smallest coin that covers it');
+ assert.deepEqual(ids(12000), ['old', 'young'], 'custodial: largest first');
+ m.lnOldestFirst = () => true;
+ assert.deepEqual(ids(1500), ['older'], 'self: the nearest expiry that covers it');
+ assert.deepEqual(ids(2500), ['old'], '…skipping one too small');
+ assert.deepEqual(ids(10000), ['older', 'old'], 'self: gathers nearest expiry first');
+ assert.deepEqual(ids(13000), ['older', 'old', 'young'], 'coins inside their timelock carry it alone when they can');
+ // a pile of old crumbs that would breach the input cap: largest-first instead
+ m.state.vtxos = [...Array.from({ length: MAX_SEND_INPUTS + 2 }, (_, i) => coin('crumb' + i, 100, 1010)), coin('big', 6000, 3000)];
+ assert.deepEqual(ids(6050).slice(0, 1), ['big'], 'too many old crumbs for one payment: largest first');
+ assert.equal(ids(6050).length, 2);
+ console.log('✓ Lightning sends: nearest expiry first when renewing your own coins, smallest-that-covers otherwise');
+}
+
console.log('\n✅ custody tiers behave');
diff --git a/tools/ark/dust-shapes-test.js b/tools/ark/dust-shapes-test.js
new file mode 100644
index 0000000..d5a9f5f
--- /dev/null
+++ b/tools/ark/dust-shapes-test.js
@@ -0,0 +1,59 @@
+// The arkoor shapes whose dust isolation changed for server-0.9.0 (!2822),
+// sent through a real server: each from a wallet holding ONE coin, so the
+// split is exactly the one named.
+// 400 → 100 (+300 change) every output dust: both isolated
+// 500 → 100 (+400 change) the change can't pad the dust: isolated whole
+// 1000 → 100 (+900 change) the change pads the dust (unchanged)
+// 300 → 100 (+200 change) dust input: nothing isolated (unchanged)
+// Each payment arrives, and the change is spent onward (the coin is real).
+// Usage: bun tools/ark/dust-shapes-test.js (ARK_URL to point at another captaind)
+import { execSync } from 'node:child_process';
+import { generateMnemonic, mnemonicToSeedSync } from '@scure/bip39';
+import { wordlist } from '@scure/bip39/wordlists/english';
+import { HDKey } from '@scure/bip32';
+import { ArkManager } from '../../src/ark/manager.js';
+
+const ARK = process.env.ARK_URL || 'http://127.0.0.1:3535';
+const ESPLORA = 'http://127.0.0.1:30002';
+const ALICE = `${process.env.HOME}/bark/target/debug/bark --datadir ${process.env.HOME}/ark-regtest/alice`;
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+let ok = true;
+const check = (name, cond, detail = '') => { console.log(` ${cond ? '✓' : '✗'} ${name}${detail ? ' — ' + detail : ''}`); if (!cond) ok = false; };
+
+const newWallet = async () => {
+ let raw = null;
+ const account = HDKey.fromMasterSeed(mnemonicToSeedSync(generateMnemonic(wordlist))).derive("m/86'/0'/9'");
+ return new ArkManager({ account, storage: { load: () => (raw ? JSON.parse(raw) : null), save: (s) => { raw = JSON.stringify(s); } }, arkUrl: ARK, esploraUrl: ESPLORA }).init();
+};
+const waitBalance = async (m, want, tries = 15) => {
+ for (let i = 0; i < tries && m.balance().spendableSat < want; i++) { await m.sync(); await sleep(1500); }
+ return m.balance().spendableSat;
+};
+
+const sink = await newWallet();
+let sunk = 0;
+// a bank of ours with one big coin pays each wallet: one coin each, always
+// (alice's CLI wallet pays from whatever coins it holds, sometimes several)
+const bank = await newWallet();
+execSync(`${ALICE} -q send ${bank.address()} "20000 sat"`);
+check('bank funded', (await waitBalance(bank, 20000)) >= 20000);
+if (bank.state.vtxos.filter((v) => v.state === 'spendable').length > 1) { await bank.refresh(); for (let i = 0; i < 40 && bank.state.vtxos.filter((v) => v.state === 'spendable').length !== 1; i++) { execSync('docker exec bc bitcoin-cli -rpcwallet=coinos -generate 1'); await bank.sync(); await sleep(2000); } }
+check('...in one coin', bank.state.vtxos.filter((v) => v.state === 'spendable').length === 1);
+for (const [coin, pay, shape] of [[400, 100, 'all dust'], [500, 100, 'change isolated whole'], [1000, 100, 'change pads the dust'], [300, 100, 'dust input']]) {
+ console.log(`\n[${coin} → ${pay}] ${shape}`);
+ const w = await newWallet(), to = await newWallet();
+ await bank.send(w.address(), coin);
+ check(`funded with one ${coin}-sat coin`, (await waitBalance(w, coin)) === coin && w.state.vtxos.filter((v) => v.state === 'spendable').length === 1);
+ let err = null;
+ try { await w.send(to.address(), pay); } catch (e) { err = e.message; }
+ check(`${pay} sent, server cosigned`, !err, err || '');
+ check(`${pay} arrived`, (await waitBalance(to, pay)) === pay);
+ const change = coin - pay;
+ check(`${change} change spendable`, (await waitBalance(w, change)) === change);
+ let err2 = null;
+ try { await w.send(sink.address(), change); sunk += change; } catch (e) { err2 = e.message; }
+ check(`...and spent onward`, !err2, err2 || '');
+}
+check('every onward spend arrived', (await waitBalance(sink, sunk)) === sunk, `${sink.balance().spendableSat}/${sunk}`);
+console.log(ok ? '\n✅ every dust shape goes through ' + ARK : '\n❌ a dust shape failed on ' + ARK);
+process.exit(ok ? 0 : 1);
diff --git a/tools/ark/isolate-dust-test.js b/tools/ark/isolate-dust-test.js
new file mode 100644
index 0000000..1170d68
--- /dev/null
+++ b/tools/ark/isolate-dust-test.js
@@ -0,0 +1,98 @@
+// Dust isolation matches bark's ArkoorBuilder::new_isolate_dust (server-0.9.0)
+// case for case, and every split it makes passes the arkoor amount checks of
+// both server-0.8.0 and server-0.9.0 (lib/src/arkoor/mod.rs validate_amounts,
+// ported below). 0.9.0 (!2822) refuses a checkpoint with a sub-dust output
+// unless the input is dust; the old split "accepted the mix" in two cases.
+// Run: bun tools/ark/isolate-dust-test.js
+import assert from 'node:assert/strict';
+import { isolateDust } from '../../src/ark/send.js';
+import { ArkManager } from '../../src/ark/manager.js';
+
+const D = 330;
+const P = (n) => ({ type: 'pubkey', userPubkey: 'k' + n });
+const outs = (...a) => a.map((amountSat, i) => ({ amountSat, policy: P(i) }));
+const amts = (l) => l.map((o) => o.amountSat);
+const check = (name, ok, detail = '') => { assert(ok, name + (detail ? ' — ' + detail : '')); console.log(' ✓ ' + name); };
+
+// validate_amounts, both versions. Returns null or the error.
+function validate(inputSat, normal, iso, version) {
+ const sum = (l) => l.reduce((n, o) => n + o.amountSat, 0);
+ if (sum(normal) + sum(iso) !== inputSat) return 'Unbalanced';
+ if (version === '0.9' && [...normal, ...iso].some((o) => o.amountSat === 0)) return 'ZeroValueOutput';
+ if (iso.length && sum(iso) < D) return 'Dust';
+ if (iso.some((o) => o.amountSat >= 2 * D)) return 'IsolationNotNeeded';
+ if (iso.length && iso.every((o) => o.amountSat >= D)) return 'IsolationNotNeeded';
+ if (version === '0.9') {
+ if (inputSat >= D && normal.some((o) => o.amountSat < D)) return 'Dust';
+ } else {
+ // seen on regtest 0.8.0: "An error occurred while building arkoor: At least one output is required"
+ if (!normal.length) return 'NoOutputs';
+ if (iso.length && normal.some((o) => o.amountSat < D)) return 'Dust';
+ if (normal.some((o) => o.amountSat < D) && normal.some((o) => o.amountSat >= 2 * D)) return 'Dust';
+ }
+ return null;
+}
+
+// upstream's tests (lib/src/arkoor/mod.rs, isolate_dust_*)
+const cases = [
+ ['all non-dust', 1000, [500, 500], [500, 500], []],
+ ['all dust', 400, [200, 200], [], [200, 200]],
+ ['all dust from a dust input', 300, [200, 100], [200, 100], []],
+ ['sufficient dust', 1000, [600, 200, 200], [600], [200, 200]],
+ ['split successful', 1000, [800, 100, 100], [670], [130, 100, 100]],
+ ['split impossible', 600, [400, 100, 100], [], [400, 100, 100]],
+ ['split impossible isolates the smallest', 950, [450, 400, 100], [450], [400, 100]],
+ ['exactly at the boundary', 1000, [660, 170, 170], [660], [170, 170]],
+];
+for (const [name, input, o, wantOuts, wantIso] of cases) {
+ const r = isolateDust(outs(...o), input);
+ check(`${name}: ${o.join('+')} → [${wantOuts}] + isolated [${wantIso}]`,
+ JSON.stringify(amts(r.outs)) === JSON.stringify(wantOuts) && JSON.stringify(amts(r.isolated)) === JSON.stringify(wantIso),
+ `got [${amts(r.outs)}] + [${amts(r.isolated)}]`);
+ check(`...which 0.9.0 accepts`, !validate(input, r.outs, r.isolated, '0.9'));
+ const l = isolateDust(outs(...o), input, { legacy: true });
+ check(`...and the legacy split for the same payment, 0.8.0`, !validate(input, l.outs, l.isolated, '0.8'), `[${amts(l.outs)}] + [${amts(l.isolated)}]`);
+}
+
+// the two shapes the old split sent that 0.9.0 refuses, as our payments make
+// them (destination first, change last)
+{
+ const r = isolateDust(outs(100, 300), 400);
+ check('100 sent from 400 (all dust): both isolated, none on the checkpoint', !r.outs.length && amts(r.isolated).join() === '100,300');
+ check('...which the old split left on the checkpoint, refused by 0.9.0', validate(400, outs(100, 300), [], '0.9') === 'Dust');
+ const r2 = isolateDust(outs(100, 400), 500);
+ check('100 sent from 500 (change 400 can\'t pad it): the change isolated whole', !r2.outs.length && amts(r2.isolated).join() === '400,100');
+ check('...which the old split also left mixed, refused by 0.9.0', validate(500, outs(100, 400), [], '0.9') === 'Dust');
+}
+// the split keeps each output's policy: the pad piece is paid to the output it came from
+{
+ const o = outs(800, 100, 100);
+ const r = isolateDust(o, 1000);
+ check('the pad piece keeps the policy of the output it came from', r.isolated[0].policy === o[0].policy && r.outs[0].policy === o[0].policy);
+}
+
+// random payments: each rule's split passes its own server's checks
+let n = 0;
+for (let i = 0; i < 200000; i++) {
+ const input = 1 + Math.floor(Math.random() ** 3 * 5000);
+ const k = 1 + Math.floor(Math.random() * 3);
+ const cuts = Array.from({ length: k - 1 }, () => 1 + Math.floor(Math.random() * (input - 1))).sort((a, b) => a - b);
+ const parts = [...cuts, input].map((c, j, a) => c - (j ? a[j - 1] : 0)).filter((x) => x > 0);
+ if (parts.reduce((a, b) => a + b, 0) !== input) continue;
+ for (const [v, legacy] of [['0.9', false], ['0.8', true]]) {
+ const r = isolateDust(outs(...parts), input, { legacy });
+ const err = validate(input, r.outs, r.isolated, v);
+ assert(!err, `${parts.join('+')} from ${input} → [${amts(r.outs)}] + [${amts(r.isolated)}] refused by ${v}: ${err}`);
+ }
+ n++;
+}
+check(`${n.toLocaleString('en-US')} random payments (1–3 outputs, 1–5,000 sat) pass 0.9.0's checks with the new split and 0.8.0's with the legacy one`, n > 100000);
+// which rule a wallet uses: the server's own info decides
+{
+ const m = Object.create(ArkManager.prototype);
+ m.info = { maxVtxoExitDepth: 100 };
+ const before = m._legacyDust();
+ m.info = { maxVtxoExitDepth: 100, maxRoundParticipationOutputs: 4 };
+ check('a server without ArkInfo field 23 (before 0.9.0) gets the legacy split; one with it, the new', before === true && m._legacyDust() === false);
+}
+console.log('\n✅ dust isolation matches server-0.9.0, and 0.8.0 keeps its own');
diff --git a/tools/ark/offboard-split-test.js b/tools/ark/offboard-split-test.js
new file mode 100644
index 0000000..561ee2b
--- /dev/null
+++ b/tools/ark/offboard-split-test.js
@@ -0,0 +1,128 @@
+// A partial on-chain send from Spending moves whole coins: the amount is
+// covered by coins that already add up to it, else split off via a self-send
+// that lands as one coin per input — all of them go, not one of the exact
+// size (Jarryd, 2026-10-23: three splits, no send). Local manager stub.
+// Run: bun tools/ark/offboard-split-test.js
+import assert from 'node:assert/strict';
+import puppeteer from '../puppeteer.js';
+import { generateMnemonic } from '@scure/bip39';
+import { wordlist } from '@scure/bip39/wordlists/english';
+
+const bundle = await Bun.build({ entrypoints: ['src/app.js'], target: 'browser', minify: true,
+ plugins: [{ name: 'offboard-split-test', setup(build) {
+ build.onLoad({ filter: /src\/app\.js$/ }, async ({ path }) => ({ loader: 'js', contents: await Bun.file(path).text() + `
+window.coopApp = { ui, wallet, ctx, render, enterWallet, get ready() { return !_bootDeciding; } };
+` }));
+ build.onLoad({ filter: /src\/features\/ark\.js$/ }, async ({ path }) => ({ loader: 'js', contents:
+ (await Bun.file(path).text()).replace(" return {\n id: 'ark',", `
+ window.coopFeature = { setManager: (mgr) => { ark = mgr; }, offboard: doArkOffboard, exactCoins };
+ return {\n id: 'ark',`) }));
+ build.onLoad({ filter: /src\/video-compress\.js$/ }, () => ({ loader: 'js', contents: 'export async function compressVideo(f) { return f; }' }));
+ } }] });
+assert(bundle.success, bundle.logs.join('\n'));
+const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style>${await Bun.file('src/style.css').text()}</style><div id="app"></div><script type="module">${await bundle.outputs[0].text()}</script>`;
+const server = Bun.serve({ port: 0, fetch: (req) => new URL(req.url).pathname === '/'
+ ? new Response(html, { headers: { 'Content-Type': 'text/html' } }) : new Response(null, { status: 404 }) });
+const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--no-sandbox'] });
+try {
+ const page = await browser.newPage(), errors = [];
+ page.on('pageerror', (e) => errors.push(e.message));
+ await page.setViewport({ width: 390, height: 844 });
+ const cdp = await page.createCDPSession();
+ await cdp.send('Network.enable');
+ await cdp.send('Network.setBlockedURLs', { urls: ['wss://*', 'ws://*'] });
+ await page.setRequestInterception(true);
+ page.on('request', (r) => r.url().startsWith(server.url.origin) || r.url().startsWith('data:') ? r.continue() : r.abort());
+ await page.evaluateOnNewDocument(() => {
+ localStorage.setItem('btc-wallet-network', 'regtest');
+ localStorage.setItem('btc-wallet-ark-provider:regtest', 'off');
+ });
+ await page.goto(server.url.href, { waitUntil: 'domcontentloaded' });
+ await page.waitForFunction(() => window.coopApp?.ready);
+ await page.evaluate(async (mn) => {
+ await coopApp.enterWallet(mn, '', { fresh: true, generated: true });
+ coopApp.ui.onb = null; localStorage.removeItem('btc-wallet-onb-step');
+ coopApp.wallet.scan = async () => {};
+ window.coopCalls = [];
+ window.coopManager = {
+ state: { vtxos: [], actions: [], movements: [], nextKeyIndex: 5 },
+ async offboardQuote() { return { chainSat: 736, serviceSat: 204, totalSat: 940, minSat: 1270 }; },
+ info: { network: 'regtest' }, _tipH: 100,
+ vtxos() { return this.state.vtxos; },
+ refreshFee() { return 0; }, unseenReceives() { return []; }, ackReceives() {},
+ address() { return 'test-ark-address'; },
+ // the real thing: largest inputs first until covered, one destination
+ // coin per input (the last carries the remainder), change on a new key;
+ // the destination coins land on the receive key at the next sync
+ async send(address, amount) {
+ coopCalls.push({ type: 'split', address, amount });
+ const free = this.state.vtxos.filter((v) => v.state === 'spendable').sort((a, b) => b.amountSat - a.amountSat);
+ const inputs = []; let sum = 0;
+ for (const v of free) { inputs.push(v); sum += v.amountSat; if (sum >= amount) break; }
+ let remaining = amount; const landing = [];
+ for (const v of inputs) {
+ const dest = Math.min(remaining, v.amountSat); remaining -= dest;
+ landing.push({ id: `dest-${v.id}`, amountSat: dest, state: 'spendable', keyIndex: 0 });
+ if (v.amountSat > dest) this.state.vtxos.push({ id: `change-${v.id}`, amountSat: v.amountSat - dest, state: 'spendable', keyIndex: this.state.nextKeyIndex++ });
+ v.state = 'spent';
+ }
+ this.pendingLanding = landing;
+ return 'send-1';
+ },
+ async sync() { if (this.pendingLanding) { this.state.vtxos.push(...this.pendingLanding); this.pendingLanding = null; } },
+ async startOffboard(spk, address, ids) {
+ coopCalls.push({ type: 'offboard', address, ids: ids || null });
+ return { txid: 'ab'.repeat(32), netSat: 1, feeSat: 1 };
+ },
+ };
+ coopFeature.setManager(coopManager);
+ coopApp.ui.screen = 'wallet'; coopApp.ui.tab = 'send'; coopApp.render();
+ }, generateMnemonic(wordlist));
+ const run = (coins, amount) => page.evaluate(async (coins, amount) => {
+ coopManager.state.vtxos = coins.map((c) => ({ state: 'spendable', keyIndex: 0, ...c }));
+ coopCalls.length = 0;
+ coopApp.ui.arkError = ''; coopApp.ui.arkOffboarded = null;
+ await coopFeature.offboard(amount, coopApp.wallet.derive(0, 1).address);
+ return { calls: coopCalls, err: coopApp.ui.arkError, done: !!coopApp.ui.arkOffboarded };
+ }, coins, amount);
+
+ // Jarryd's balance after one split: the halves add up, so nothing is split again
+ let r = await run([{ id: 'a', amountSat: 109958 }, { id: 'b', amountSat: 75042 }, { id: 'c', amountSat: 24958, keyIndex: 2 }], 185000);
+ assert.equal(r.err, '');
+ assert(r.done);
+ assert.deepEqual(r.calls.map((c) => c.type), ['offboard']);
+ assert.deepEqual([...r.calls[0].ids].sort(), ['a', 'b']);
+ console.log('✓ coins that already add up to the amount go as they are, no split');
+
+ // one coin of the exact size
+ r = await run([{ id: 'a', amountSat: 109958 }, { id: 'c', amountSat: 24958 }], 24958);
+ assert.deepEqual(r.calls, [{ type: 'offboard', address: r.calls[0].address, ids: ['c'] }]);
+ console.log('✓ a single coin of the exact size is the one that goes');
+
+ // Jarryd's first attempt: 185,000 out of 100,000 + 109,958 — nothing adds
+ // up, so a self-send splits it off and lands as two coins; both go
+ r = await run([{ id: 'a', amountSat: 100000 }, { id: 'b', amountSat: 109958 }], 185000);
+ assert.equal(r.err, '');
+ assert(r.done);
+ assert.deepEqual(r.calls.map((c) => c.type), ['split', 'offboard']);
+ assert.equal(r.calls[0].amount, 185000);
+ assert.deepEqual([...r.calls[1].ids].sort(), ['dest-a', 'dest-b']);
+ const left = await page.evaluate(() => coopManager.state.vtxos.filter((v) => v.state === 'spendable').map((v) => [v.id, v.amountSat, v.keyIndex]));
+ assert.deepEqual(left.filter(([id]) => id.startsWith('change')), [['change-a', 24958, 5]]);
+ console.log('✓ a split that lands as two coins sends both; the change stays behind');
+
+ // everything: no carving at all
+ r = await run([{ id: 'a', amountSat: 100000 }, { id: 'b', amountSat: 109958 }], 0);
+ assert.deepEqual(r.calls, [{ type: 'offboard', address: r.calls[0].address, ids: null }]);
+ console.log('✓ the whole balance goes without a split');
+
+ // the subset search: prefers few large coins, gives up on no fit
+ const sub = await page.evaluate(() => {
+ const coins = (a) => a.map((amountSat, i) => ({ id: 'c' + i, amountSat }));
+ const pick = (a, n) => { const r = coopFeature.exactCoins(coins(a), n); return r && r.map((v) => v.amountSat).sort((x, y) => y - x); };
+ return [pick([5000, 3000, 2000, 1000, 1000], 6000), pick([5000, 3000], 7000), pick([5000, 3000, 2000], 5000), pick([7000, 3000], 3000)];
+ });
+ assert.deepEqual(sub, [[5000, 1000], null, [5000], [3000]]);
+ console.log('✓ exactCoins finds a subset, the single coin, or nothing');
+ assert.deepEqual(errors, []);
+} finally { await browser.close(); server.stop(true); }
diff --git a/tools/ark/refresh-test.js b/tools/ark/refresh-test.js
index 0557659..6938daf 100644
--- a/tools/ark/refresh-test.js
+++ b/tools/ark/refresh-test.js
@@ -29,6 +29,7 @@ import {
import { ALICE, aliceReady } from './alice.js';
const ARK = process.env.ARK_URL || 'http://127.0.0.1:3535';
+const ESPLORA = process.env.ESPLORA_URL || 'http://127.0.0.1:30002';
const BCLI = `docker exec bc bitcoin-cli -rpcwallet=coinos`;
const FUND_SAT = 12345;
const SPEND_SAT = 3000;
@@ -86,7 +87,13 @@ if (!status?.fundingTx) { console.error('round never executed'); process.exit(1)
const fundingTx = parseTx(status.fundingTx);
console.log(`round executed: funding tx ${fundingTx.txid}, ${status.outputVtxos.length} output vtxo(s)`);
execSync(`${BCLI} generatetoaddress 2 $(${BCLI} getnewaddress) >/dev/null`, { shell: '/bin/bash' });
-await sleep(2000);
+// alice's bark checks the round anchor against esplora, which indexes a block
+// ~5 s after it's mined; hand her the coin before then and she drops it
+for (let i = 0; i < 30; i++) {
+ const st = await fetch(`${ESPLORA}/tx/${fundingTx.txid}/status`).then((r) => r.ok && r.json()).catch(() => null);
+ if (st?.confirmed) break;
+ await sleep(1000);
+}
const newVtxo = decodeVtxo(status.outputVtxos[0]);
console.log(`new vtxo: ${newVtxo.id} (${newVtxo.amountSat} sat, expiry ${newVtxo.expiryHeight}, transitions: ${newVtxo.genesis.map((g) => g.transition.type).join(' -> ')})`);
diff --git a/tools/ark/rescue-claimed-test.js b/tools/ark/rescue-claimed-test.js
index 7d3c68b..9e36c61 100644
--- a/tools/ark/rescue-claimed-test.js
+++ b/tools/ark/rescue-claimed-test.js
@@ -12,6 +12,9 @@ mock.module('../../src/ark/refresh.js', () => ({
...refresh,
requestForfeitNonces: async () => { claims++; throw new Error('network'); },
roundParticipationStatus: async () => { statusAsks++; throw new Error('network'); },
+ // the round's coins themselves are checked in round-outputs-check-test;
+ // these fake actions carry none
+ checkRoundOutputs: () => {},
}));
const { ArkManager } = await import('../../src/ark/manager.js');
const mgr = new ArkManager({ storage: { save() {} }, arkUrl: 'http://test.invalid' });
diff --git a/tools/ark/round-outputs-check-test.js b/tools/ark/round-outputs-check-test.js
new file mode 100644
index 0000000..da2dbbb
--- /dev/null
+++ b/tools/ark/round-outputs-check-test.js
@@ -0,0 +1,33 @@
+// A round's new coins are checked before we forfeit for them (bark !2803):
+// locked by our unlock hash, anchored in this round's transaction, paid to
+// our key, worth what we asked for. Any mismatch throws, so nothing is signed.
+// Run: bun tools/ark/round-outputs-check-test.js
+import assert from 'node:assert/strict';
+import { hex } from '@scure/base';
+import { sha256 } from '@noble/hashes/sha256';
+import { checkRoundOutputs } from '../../src/ark/refresh.js';
+
+const check = (name, ok, detail = '') => { assert(ok, name + (detail ? ' — ' + detail : '')); console.log(' ✓ ' + name); };
+const preimage = 'ab'.repeat(32), other = 'cd'.repeat(32);
+const ours = hex.encode(sha256(hex.decode(preimage)));
+const theirs = hex.encode(sha256(hex.decode(other)));
+const me = '02' + '11'.repeat(32), funding = 'f0'.repeat(32);
+const coin = ({ hash = ours, type = 'hashLockedCosigned', txid = funding, owner = me, sat = 50_000, unlock } = {}) => ({
+ id: 'c' + Math.random().toString(16).slice(2, 8) + ':0', amountSat: sat,
+ anchorPoint: { txid, vout: 0 }, policy: { type: 'pubkey', userPubkey: owner },
+ genesis: [{ transition: { type: 'cosigned' } }, { transition: { type, unlock: unlock || { hash } } }],
+});
+const opts = { unlockHash: ours, fundingTxid: funding, ownerPubkey: me, minTotalSat: 50_000 };
+const refuses = (vtxos, o, re) => { try { checkRoundOutputs(vtxos, o); return false; } catch (e) { return re.test(e.message); } };
+
+check('coins locked by our hash, in this round, to our key, as asked: accepted', (() => { checkRoundOutputs([coin()], opts); return true; })());
+check('...v0 leaves too, and two coins that add up', (() => { checkRoundOutputs([coin({ type: 'hashLockedCosigned_v0', sat: 20_000 }), coin({ sat: 30_000 })], opts); return true; })());
+check('...and a coin already carrying our preimage', (() => { checkRoundOutputs([coin({ unlock: { preimage } })], opts); return true; })());
+check('a coin locked by ANOTHER unlock hash: refused (the !2803 attack)', refuses([coin({ hash: theirs })], opts, /locked by unlock hash/));
+check('...even beside a good one', refuses([coin(), coin({ hash: theirs, sat: 1 })], opts, /locked by unlock hash/));
+check('a coin anchored in another transaction: refused', refuses([coin({ txid: 'ee'.repeat(32) })], opts, /anchored in/));
+check('a coin paid to someone else: refused', refuses([coin({ owner: '03' + '22'.repeat(32) })], opts, /not paid to our key/));
+check('less than we asked for: refused', refuses([coin({ sat: 49_999 })], opts, /49999 sat, 50000 were asked/));
+check('not a round leaf: refused', refuses([coin({ type: 'arkoor' })], opts, /not a hash-locked round leaf/));
+check('no coins at all: refused', refuses([], opts, /no coins/));
+console.log('\n✅ a round\'s coins are checked before we forfeit for them');