aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/ark/manager.js72
-rw-r--r--tools/ark-refund-mailbox.test.js47
2 files changed, 116 insertions, 3 deletions
diff --git a/src/ark/manager.js b/src/ark/manager.js
index 8aa8707..24a2478 100644
--- a/src/ark/manager.js
+++ b/src/ark/manager.js
@@ -290,6 +290,14 @@ export class ArkManager {
return (this._mbKey = { privkey: node.privateKey, pubkey: secp256k1.getPublicKey(node.privateKey, true) });
}
_keyForVtxo(v) { return this._key(v.keyIndex); }
+ // Which of this wallet's keys a coin is paid to: 0 is the receive key,
+ // the rest were handed out one per payment, change or refund. -1: not ours.
+ _ownKeyIndex(pubkeyHex) {
+ if (pubkeyHex === hex.encode(this._key(0).pubkey)) return 0;
+ const n = (this.state.nextKeyIndex || 1) + 64;
+ for (let i = 1; i < n; i++) if (hex.encode(this._key(i).pubkey) === pubkeyHex) return i;
+ return -1;
+ }
// ---- lifecycle ----
async init() {
@@ -636,6 +644,7 @@ export class ArkManager {
if (!this._expiredRescanned) {
this._expiredRescanned = true;
try { if (await this.rescanRejectedExpired()) this._save(); } catch (e) { this._expiredRescanned = false; }
+ try { if (await this.rescanOwnKeyRejects()) this._save(); } catch (e) { this._ownKeyRescanned = false; }
}
const baselining = !!this.state.baselinePending;
// keep the cached tip fresh: balance() and input selection judge coin
@@ -709,6 +718,44 @@ export class ArkManager {
// Once per wallet: re-read the mailbox from the start and adopt what the
// server still reports spendable; clear the old verdicts the same way. The
// cursor is left where it is. Returns whether anything changed.
+ // A coin to one of our own keys other than the receive key, refused at
+ // pickup by a build that took only key 0 ("vtxo not paid to one of our
+ // keys") and left behind the mailbox cursor. Re-read the mailbox from the
+ // start, once a session while such a refusal is on record, and adopt what
+ // the server still holds for us.
+ async rescanOwnKeyRejects() {
+ const rejected = (this.state.movements || []).filter((m) => m.type === 'receive' && m.status === 'rejected' && /not paid to one of our keys/i.test(m.detail || ''));
+ if (!rejected.length || this._ownKeyRescanned) return false;
+ this._ownKeyRescanned = true;
+ let changed = false;
+ const adopted = [];
+ let checkpoint = 0;
+ for (let page = 0; page < 50; page++) {
+ const { messages, haveMore } = await readMailbox(this.arkUrl, this._mailboxKey(), checkpoint);
+ for (const m of messages) {
+ checkpoint = Math.max(checkpoint, m.checkpoint || 0);
+ if (m.kind !== 'arkoor') continue;
+ const fresh = [];
+ for (const v of m.vtxos) {
+ if (this._vtxo(v.id)) continue;
+ const idx = this._ownKeyIndex(v.policy.userPubkey);
+ if (idx < 1) continue;
+ let status = 0;
+ try { status = await getVtxoStatus(this.arkUrl, v.point.raw, this._key(idx).privkey); } catch { status = 0; }
+ if (status === VTXO_STATE_SPENDABLE) fresh.push(v);
+ }
+ if (fresh.length && await this._handleMailboxMessage({ ...m, vtxos: fresh })) { changed = true; adopted.push(...fresh.filter((v) => this._vtxo(v.id)).map((v) => v.amountSat)); }
+ }
+ if (!haveMore || !messages.length) break;
+ }
+ // the refusals those coins left in the history
+ for (const amt of adopted) {
+ const i = this.state.movements.findIndex((m) => rejected.includes(m) && m.amountSat === amt);
+ if (i >= 0) this.state.movements.splice(i, 1);
+ }
+ return changed;
+ }
+
async rescanRejectedExpired() {
if (!this.honorsExpired || this.state.expiredRescanDone) return false;
let changed = false;
@@ -798,7 +845,7 @@ export class ArkManager {
return changed;
}
if (m.kind !== 'arkoor') return changed;
- const ourKeys = [hex.encode(this._key(0).pubkey)];
+ const key0 = hex.encode(this._key(0).pubkey);
const tip = await this._tipMemo();
// The mailbox checkpoint IS the delivery timestamp (ms << 20, verified
// to the millisecond against the server's rows) — the one honest date
@@ -821,8 +868,13 @@ export class ArkManager {
}
continue;
}
+ // Receives are paid to key 0, but every key this wallet has handed
+ // out is its own: a failed payment's refund, cosigned by the server
+ // and lost here before it was written down (a reload in that second),
+ // comes back through the mailbox to the key it was made for.
+ const keyIndex = this._ownKeyIndex(v.policy.userPubkey);
try {
- await validateVtxo(v, { serverPubkey: this.serverPub, chain: this.chain, expectPubkeys: ourKeys, acceptExpired: this.honorsExpired });
+ await validateVtxo(v, { serverPubkey: this.serverPub, chain: this.chain, expectPubkeys: keyIndex > 0 ? [v.policy.userPubkey] : [key0], acceptExpired: this.honorsExpired });
} catch (e) {
if (e instanceof VtxoValidationError) {
this._movement({ type: 'receive', amountSat: v.amountSat, status: 'rejected', detail: e.message });
@@ -834,7 +886,21 @@ export class ArkManager {
// _addVtxo dedupes by id — the poll and the live stream can process the
// same message concurrently (validation awaits in between), and only the
// copy that actually added the vtxo may record the receive movement.
- if (!this._addVtxo(v, v._raw.bytes, 0)) continue;
+ if (!this._addVtxo(v, v._raw.bytes, keyIndex)) continue;
+ if (keyIndex >= (this.state.nextKeyIndex || 1)) this.state.nextKeyIndex = keyIndex + 1;
+ // the refund of a payment of ours: that payment failed and its money
+ // is back, which is what the history says, not "received"
+ const pay = keyIndex > 0 && this.state.actions.find((a) => a.type === 'ln-pay' && a.revKeyIndex === keyIndex);
+ if (pay) {
+ if (!['done', 'failed'].includes(pay.step)) {
+ for (const id of pay.htlcVtxoIds || [pay.htlcVtxoId]) { const htlc = this._vtxo(id); if (htlc) htlc.state = 'spent'; }
+ pay.step = 'failed';
+ pay.error = pay.error || 'payment failed';
+ this._movement({ type: 'ln-send', amountSat: pay.amountSat, status: 'failed', detail: 'payment failed, funds returned', invoice: pay.invoice });
+ }
+ changed = true;
+ continue;
+ }
// `batch` names the mailbox message: one payment can arrive as several
// coins (a sweep of a gift held in two, a dust-padded split), and the
// history folds a message's coins back into one row
diff --git a/tools/ark-refund-mailbox.test.js b/tools/ark-refund-mailbox.test.js
new file mode 100644
index 0000000..03a76da
--- /dev/null
+++ b/tools/ark-refund-mailbox.test.js
@@ -0,0 +1,47 @@
+// bun test tools/ark-refund-mailbox.test.js — a failed Lightning payment's
+// refund that the wallet lost (the server cosigned the revocation, the page
+// was reloaded before the coin was written down: json534543, 2026-11-20,
+// 14,786 sats) comes back through the mailbox to the refund key. The wallet
+// takes a coin paid to any key it has handed out, closes the payment it
+// refunds as failed, and still refuses a coin to a key that is not its own.
+import { test, expect, mock } from 'bun:test';
+import { hex } from '@scure/base';
+import * as validate from '../src/ark/validate.js';
+const seen = [];
+mock.module('../src/ark/validate.js', () => ({ ...validate, validateVtxo: async (v, o) => { seen.push(o.expectPubkeys); if (!o.expectPubkeys.includes(v.policy.userPubkey)) throw new validate.VtxoValidationError('vtxo not paid to one of our keys'); } }));
+const { ArkManager } = await import('../src/ark/manager.js');
+const pk = (i) => hex.encode(Uint8Array.from({ length: 33 }, () => i + 2));
+const mgr = () => {
+ const m = Object.create(ArkManager.prototype);
+ m.state = { vtxos: [{ id: 'htlc', state: 'pending', amountSat: 14786, policy: 'serverHtlcSend' }], movements: [], nextKeyIndex: 9, mailboxCheckpoint: 0,
+ actions: [{ type: 'ln-pay', step: 'revoking', amountSat: 14770, invoice: 'lnbc1', paymentHash: 'aa', htlcVtxoIds: ['htlc'], htlcKeyIndex: 6, revKeyIndex: 7 }] };
+ m._key = (i) => ({ pubkey: hex.decode(pk(i)), privkey: new Uint8Array(32) });
+ m._tipMemo = async () => 900000; m._save = () => {}; m._estimateReceiveTs = () => 1;
+ m._movement = (x) => m.state.movements.push(x);
+ return m;
+};
+const coin = (id, amountSat, key) => ({ id, amountSat, expiryHeight: 985313, policy: { type: 'pubkey', userPubkey: pk(key) }, _raw: { bytes: Uint8Array.of(1, 2, 3) } });
+test('a refund delivered to the refund key is taken and closes the payment', async () => {
+ const m = mgr();
+ const changed = await m._handleMailboxMessage({ kind: 'arkoor', checkpoint: 0, vtxos: [coin('refund', 14786, 7), coin('dust', 2, 7)] });
+ expect(changed).toBe(true);
+ const held = Object.fromEntries(m.state.vtxos.map((v) => [v.id, v]));
+ expect(held.refund.state).toBe('spendable'); expect(held.refund.keyIndex).toBe(7);
+ expect(held.dust.keyIndex).toBe(7);
+ expect(held.htlc.state).toBe('spent');
+ expect(m.state.actions[0].step).toBe('failed');
+ expect(m.state.movements).toEqual([{ type: 'ln-send', amountSat: 14770, status: 'failed', detail: 'payment failed, funds returned', invoice: 'lnbc1' }]);
+});
+test('an ordinary receive to key 0 is a receive, as before', async () => {
+ const m = mgr();
+ await m._handleMailboxMessage({ kind: 'arkoor', checkpoint: 0, vtxos: [coin('gift', 500, 0)] });
+ expect(m.state.vtxos.find((v) => v.id === 'gift').keyIndex).toBe(0);
+ expect(m.state.movements[0].type).toBe('receive'); expect(m.state.movements[0].status).toBe('complete');
+ expect(m.state.actions[0].step).toBe('revoking');
+});
+test('a coin to a key that is not ours is refused', async () => {
+ const m = mgr();
+ await m._handleMailboxMessage({ kind: 'arkoor', checkpoint: 0, vtxos: [coin('theirs', 500, 200)] });
+ expect(m.state.vtxos.some((v) => v.id === 'theirs')).toBe(false);
+ expect(m.state.movements[0].status).toBe('rejected');
+});