From f39513ec0a1bc178d8569116286f2b5b90ef3822 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Sun, 22 Nov 2026 09:31:49 -0700 Subject: A payment's refund the wallet lost can come back through its mailbox. Handoff from the coinos-server agent on desk, 2026-11-22 ("V3 wallet lost a Lightning refund", user json534543): on 2026-11-20 a 14,770-sat Lightning payment failed six times in two minutes; after the last failure the server cosigned the revocation at 12:41:05 UTC and holds the refund as two spendable coins (14,786 and 2 sats) paid to the payment's refund key, but the page was reloaded in that second and the wallet never wrote them down, so it shows a balance of 0. The wallet builds the refund coin itself and nothing gave it back afterwards: the mailbox was the only way in, and it took coins paid to key 0 only. A coin from the mailbox is now accepted when it is paid to any key this wallet has handed out, and is kept under that key. When that key is a payment's refund key the payment is closed as failed with "payment failed, funds returned" and its HTLC coins marked spent, instead of a "Received" row. A coin to a key that is not ours is refused as before. A build from before this change refuses such a coin and moves the mailbox cursor past it, so once a session, while such a refusal is on record, the mailbox is read again from the start and what the server still holds for one of our keys is adopted. New ark-refund-mailbox test (3 cases); ark-htlc-orphan, ark-htlc-held, ark-reconcile-race and features-smoke pass. Both stored coins pass the wallet's own validation against the chain. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01VMan6Upic5L6MMJzkTn8zg --- src/ark/manager.js | 72 +++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 69 insertions(+), 3 deletions(-) (limited to 'src/ark/manager.js') 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 -- cgit v1.2.3