aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/ark/manager.js30
-rw-r--r--src/ark/proto.js3
-rw-r--r--src/ark/refresh.js26
-rw-r--r--src/ark/send.js52
-rw-r--r--tools/ark/dust-shapes-test.js59
-rw-r--r--tools/ark/isolate-dust-test.js98
-rw-r--r--tools/ark/rescue-claimed-test.js3
-rw-r--r--tools/ark/round-outputs-check-test.js33
8 files changed, 289 insertions, 15 deletions
diff --git a/src/ark/manager.js b/src/ark/manager.js
index 24a2478..8be9d58 100644
--- a/src/ark/manager.js
+++ b/src/ark/manager.js
@@ -41,7 +41,7 @@ import {
} from './board.js';
import {
submitRoundParticipation, roundParticipationStatus, parseTx,
- cosignHarkLeaf, requestForfeitNonces, forfeitBundle, forfeitVtxos,
+ cosignHarkLeaf, requestForfeitNonces, forfeitBundle, forfeitVtxos, checkRoundOutputs,
encodeVtxoFromDecoded,
} from './refresh.js';
import {
@@ -577,6 +577,8 @@ export class ArkManager {
// chain gets there in four days), so such a coin is money only a refresh
// can free — and it refreshes without the base fee at `deepWaiverDepth`.
exitDepth(v) { try { return this._decoded(v).genesis.length; } catch { return 0; } }
+ // a server before 0.9.0 wants the old dust split (see isolateDust)
+ _legacyDust() { return !(this.info && this.info.maxRoundParticipationOutputs); }
_capDepth() { return (this.info && this.info.maxVtxoExitDepth) || 0; }
_waiverDepth() { return (this.info && this.info.refreshFees && this.info.refreshFees.deepWaiverDepth) || 0; }
_capped(v) { const cap = this._capDepth(); return !!cap && this.exitDepth(v) >= cap; }
@@ -1379,7 +1381,7 @@ export class ArkManager {
const decoded = inputRecs.map((r) => this._decoded(r));
const keysList = inputRecs.map((r) => this._keyForVtxo(r));
await registerVtxoTransactions(this.arkUrl, decoded.map((d) => d._raw.bytes));
- const builds = parts.map((p, i) => buildArkoorSend({
+ const builds = parts.map((p, i) => buildArkoorSend({ legacyDust: this._legacyDust(),
input: decoded[i],
outputs: [
{ amountSat: p.destSat, userPubkey: hex.decode(action.destPubkey) },
@@ -1708,7 +1710,7 @@ export class ArkManager {
const htlcKey = this._key(action.htlcKeyIndex);
// every part locks its own HTLC vtxo under the SAME payment hash and
// key — the server sums them into one payment (htlc_vtxo_sum)
- const builds = parts.map((p, i) => buildArkoorSend({
+ const builds = parts.map((p, i) => buildArkoorSend({ legacyDust: this._legacyDust(),
input: decoded[i],
outputs: [
{
@@ -1908,7 +1910,7 @@ export class ArkManager {
const revKey = this._key(action.revKeyIndex);
const inputs = (action.htlcBytesList || [action.htlcBytes])
.map((b) => decodeVtxo(hex.decode(b)));
- const builds = inputs.map((input) => buildArkoorSend({
+ const builds = inputs.map((input) => buildArkoorSend({ legacyDust: this._legacyDust(),
input,
outputs: [{ amountSat: input.amountSat, userPubkey: revKey.pubkey }],
serverPubkey: this.serverPub, vtxoKeys: keys,
@@ -2170,7 +2172,7 @@ export class ArkManager {
return;
}
}
- const builds = decoded.map((input) => buildArkoorSend({
+ const builds = decoded.map((input) => buildArkoorSend({ legacyDust: this._legacyDust(),
input,
outputs: [{ amountSat: input.amountSat, userPubkey: keys.pubkey }],
serverPubkey: this.serverPub, vtxoKeys: keys,
@@ -2240,7 +2242,7 @@ export class ArkManager {
if (changeSat > 0) outputs.push({ amountSat: changeSat, userPubkey: this._key(refundIndex).pubkey });
await registerVtxoTransactions(this.arkUrl, [decoded._raw.bytes]);
- const build = buildArkoorSend({ input: decoded, outputs, serverPubkey: this.serverPub, vtxoKeys: keys });
+ const build = buildArkoorSend({ legacyDust: this._legacyDust(), input: decoded, outputs, serverPubkey: this.serverPub, vtxoKeys: keys });
const sigs = await cosignWithServer(this.arkUrl, build, {
input: decoded, vtxoKeys: keys, serverPubkey: this.serverPub,
});
@@ -2281,7 +2283,7 @@ export class ArkManager {
? (typeof destPubkey === 'string' ? hex.decode(destPubkey) : destPubkey)
: this._key(outIndex).pubkey;
await registerVtxoTransactions(this.arkUrl, [input._raw.bytes]).catch(() => {});
- const build = buildArkoorSend({
+ const build = buildArkoorSend({ legacyDust: this._legacyDust(),
input, outputs: [{ amountSat: input.amountSat, userPubkey: outPub }],
serverPubkey: this.serverPub, vtxoKeys: keys,
});
@@ -2313,7 +2315,7 @@ export class ArkManager {
const keys = this._key(claimKeyIndex);
if (input.policy.claimPubkey !== hex.encode(keys.pubkey)) throw new Error('htlc not held by this key');
await registerVtxoTransactions(this.arkUrl, [input._raw.bytes]).catch(() => {});
- const build = buildArkoorSend({
+ const build = buildArkoorSend({ legacyDust: this._legacyDust(),
input,
outputs: [{ amountSat: input.amountSat, userPubkey: hex.decode(input.policy.refundPubkey) }],
serverPubkey: this.serverPub, vtxoKeys: keys,
@@ -2689,6 +2691,18 @@ export class ArkManager {
const fundingTx = parseTx(hex.decode(action.fundingTxHex));
const unlockHash = hex.decode(action.unlockHash);
const newVtxos = action.outputVtxos.map((b) => decodeVtxo(hex.decode(b)));
+ // nothing is signed for coins we couldn't unlock (bark !2803): the
+ // action stays 'issued' with the reason, and no forfeit goes out
+ try {
+ checkRoundOutputs(newVtxos, {
+ unlockHash: action.unlockHash, fundingTxid: fundingTx.txid,
+ ownerPubkey: outKeys.pubkey ? hex.encode(outKeys.pubkey) : null, minTotalSat: action.outAmountSat || 0,
+ });
+ } catch (e) {
+ if (action.lastError !== e.message) { action.lastError = e.message; this._save(); }
+ console.warn('ark: refusing to forfeit for this round —', e.message);
+ return;
+ }
// leaf cosign + forfeit are both idempotent server-side
const leafSigs = [];
for (const v of newVtxos) {
diff --git a/src/ark/proto.js b/src/ark/proto.js
index 849aaac..69218c6 100644
--- a/src/ark/proto.js
+++ b/src/ark/proto.js
@@ -417,6 +417,9 @@ export async function getArkInfo(ark) {
if (field === 15) info.lnReceiveAntiDosRequired = Number(value) !== 0;
if (field === 16) info.mailboxPubkey = hex.encode(value);
if (field === 19) info.maxVtxoExitDepth = Number(value); // past this depth a coin can't be spent until refreshed
+ // server-0.9.0+ (always ≥ 1 there, so always sent): also the sign that its
+ // stricter arkoor dust rules apply (see isolateDust in send.js)
+ if (field === 23) info.maxRoundParticipationOutputs = Number(value);
if (field === 20) info.maxOffboardInputs = Number(value);
if (field === 18) { // FeeSchedule
for (const f of pbFields(value)) {
diff --git a/src/ark/refresh.js b/src/ark/refresh.js
index 6e4453d..44c8321 100644
--- a/src/ark/refresh.js
+++ b/src/ark/refresh.js
@@ -355,6 +355,32 @@ export async function roundParticipationStatus(ark, unlockHash) {
return out;
}
+// The round's new coins, checked before we cosign their leaves and forfeit
+// our inputs. The forfeits hand the server our inputs in exchange for the
+// preimage of OUR unlock hash, so a new coin locked by any other hash could
+// never be unlocked: forfeiting for it gives the money away. Port of bark
+// !2803 (server-0.9.0's client fix, reported by MrHodl: "Bark didn't check
+// that the unlock hash of its forfeits matched the one locking its new
+// VTXOs"), plus what bark's check_round_matches_participation also asks:
+// every coin a hark leaf anchored in this round's transaction and paid to
+// our key, and together at least what we asked for. Throws on the first
+// mismatch; nothing is signed then.
+export function checkRoundOutputs(vtxos, { unlockHash, fundingTxid, ownerPubkey, minTotalSat = 0 }) {
+ if (!vtxos.length) throw new Error('the round returned no coins for this participation');
+ let total = 0;
+ for (const v of vtxos) {
+ const last = v.genesis[v.genesis.length - 1];
+ const t = last && last.transition;
+ if (!t || !['hashLockedCosigned', 'hashLockedCosigned_v0'].includes(t.type)) throw new Error(`new coin ${v.id} is not a hash-locked round leaf`);
+ const lockedBy = t.unlock && (t.unlock.hash ?? (t.unlock.preimage != null ? sha256Hex(t.unlock.preimage) : null));
+ if (lockedBy !== unlockHash) throw new Error(`new coin ${v.id} is locked by unlock hash ${lockedBy}, expected ${unlockHash}`);
+ if (v.anchorPoint.txid !== fundingTxid) throw new Error(`new coin ${v.id} is anchored in ${v.anchorPoint.txid}, not this round's ${fundingTxid}`);
+ if (v.policy.type !== 'pubkey' || v.policy.userPubkey !== ownerPubkey) throw new Error(`new coin ${v.id} is not paid to our key`);
+ total += v.amountSat;
+ }
+ if (total < minTotalSat) throw new Error(`the round's new coins hold ${total} sat, ${minTotalSat} were asked for`);
+}
+
// MuSig2 script-spend cosign of the hash-locked leaf (NO taptweak)
export async function cosignHarkLeaf(ark, vtxo, fundingTx, vtxoKeys, serverPub) {
const last = vtxo.genesis[vtxo.genesis.length - 1];
diff --git a/src/ark/send.js b/src/ark/send.js
index f0e471a..9cf79b4 100644
--- a/src/ark/send.js
+++ b/src/ark/send.js
@@ -272,11 +272,49 @@ function encodeVtxo({ amountSat, expiryHeight, serverPubkey, exitDelta, anchorPo
const DUST_SAT = 330; // P2TR dust threshold
-// Mirror of bark's ArkoorBuilder::new_isolate_dust: the server rejects an
-// arkoor whose outputs mix dust and non-dust, so dust outputs are routed
-// through a combined isolation output (spent by a fanout tx). When the dust
-// alone can't reach the threshold, a non-dust output is split to pad it.
-function isolateDust(outputs) {
+// Mirror of bark's ArkoorBuilder::new_isolate_dust (server-0.9.0). Dust
+// outputs are routed through one combined isolation output on the checkpoint
+// (spent by a fanout tx), so every checkpoint output is standard. Since
+// server-0.9.0 (!2822) the server refuses a cosign whose checkpoint carries
+// a sub-dust output unless the input itself is dust, so this must match
+// upstream case for case:
+// - no dust, or a dust input: nothing isolated
+// - dust summing to ≥ 330: all of it isolated
+// - otherwise pad the dust from the first non-dust output that stays ≥ 330
+// after giving up the deficit; failing that, isolate the smallest non-dust
+// output whole (each is then under 330 + deficit ≤ 660, which isolation
+// allows). Both used to "accept the mix", which 0.9.0 refuses.
+// - every output dust (from an input ≥ 330): all of it isolated, the
+// checkpoint holding only the isolation output.
+//
+// `legacy`: a server before 0.9.0 (it advertises no ArkInfo field 23) refuses
+// the two new shapes instead — "At least one output is required" for an
+// all-isolated checkpoint, checked on regtest 0.8.0 — and takes the old mix,
+// so it gets the old split (isolateDustLegacy) until it upgrades.
+export function isolateDust(outputs, inputSat, { legacy = false } = {}) {
+ if (legacy) return isolateDustLegacy(outputs);
+ const sum = (l) => l.reduce((n, o) => n + o.amountSat, 0);
+ if (outputs.every((o) => o.amountSat >= DUST_SAT)) return { outs: outputs, isolated: [] };
+ if (inputSat < DUST_SAT) return { outs: outputs, isolated: [] };
+ const dust = outputs.filter((o) => o.amountSat < DUST_SAT);
+ const nonDust = outputs.filter((o) => o.amountSat >= DUST_SAT);
+ if (sum(dust) >= DUST_SAT) return { outs: nonDust, isolated: dust };
+ const deficit = DUST_SAT - sum(dust);
+ const idx = nonDust.findIndex((o) => o.amountSat - deficit >= DUST_SAT);
+ if (idx >= 0) {
+ const outs = nonDust.slice();
+ outs[idx] = { amountSat: outs[idx].amountSat - deficit, policy: outs[idx].policy };
+ return { outs, isolated: [{ amountSat: deficit, policy: nonDust[idx].policy }, ...dust] };
+ }
+ let small = -1;
+ nonDust.forEach((o, i) => { if (small < 0 || o.amountSat < nonDust[small].amountSat) small = i; });
+ if (small < 0) return { outs: [], isolated: dust }; // unreachable: dust alone sums to the input ≥ 330
+ const outs = nonDust.filter((_, i) => i !== small);
+ return { outs, isolated: [nonDust[small], ...dust] };
+}
+
+// bark ≤ 0.8's new_isolate_dust, for servers before 0.9.0
+function isolateDustLegacy(outputs) {
const sum = (l) => l.reduce((n, o) => n + o.amountSat, 0);
const dust = outputs.filter((o) => o.amountSat < DUST_SAT);
const nonDust = outputs.filter((o) => o.amountSat >= DUST_SAT);
@@ -298,7 +336,7 @@ function isolateDust(outputs) {
// — destination first, change last. NB an output may come back SPLIT across
// two result vtxos (dust padding), so callers should consume
// buildAllSignedVtxos() and classify by policy rather than by index.
-export function buildArkoorSend({ input, outputs, serverPubkey, vtxoKeys }) {
+export function buildArkoorSend({ input, outputs, serverPubkey, vtxoKeys, legacyDust = false }) {
const userPub = vtxoKeys.pubkey;
if (hex.encode(userPub) !== policyOwnerPubkey(input.policy)) throw new Error('input not owned by our key');
@@ -307,7 +345,7 @@ export function buildArkoorSend({ input, outputs, serverPubkey, vtxoKeys }) {
amountSat: o.amountSat,
policy: o.policy || { type: 'pubkey', userPubkey: hex.encode(o.userPubkey) },
}));
- const { outs, isolated } = isolateDust(normalized);
+ const { outs, isolated } = isolateDust(normalized, input.amountSat, { legacy: legacyDust });
const isolationSat = isolated.reduce((n, o) => n + o.amountSat, 0);
const inputTaproot = policyTaproot(input.policy, serverPubkey, input.exitDelta);
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/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');