diff options
Diffstat (limited to 'src/ark')
| -rw-r--r-- | src/ark/manager.js | 551 | ||||
| -rw-r--r-- | src/ark/proto.js | 7 | ||||
| -rw-r--r-- | src/ark/refresh.js | 26 | ||||
| -rw-r--r-- | src/ark/send.js | 52 | ||||
| -rw-r--r-- | src/ark/store.js | 20 | ||||
| -rw-r--r-- | src/ark/validate.js | 8 |
6 files changed, 581 insertions, 83 deletions
diff --git a/src/ark/manager.js b/src/ark/manager.js index d5ae2b0..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 { @@ -92,6 +92,16 @@ const actionTs = (a) => Number(String(a.id || '').split('-').pop()) || 0; // claim recorded before it stamped them — the same amount within minutes). // Derived at read time, never deleted: a synced copy from another device // can't bring a twin back. +// Two receive rows that are one payment delivered as several coins (a gift +// held in two swept at once, a dust-padded split): the same mailbox message +// (`batch`), or for rows recorded before the stamp, the same delivery instant. +// A receive the registrar's receipts tagged ⚡ is its own payment. +export function sameDelivery(a, b) { + return !!a && !!b && a.type === 'receive' && b.type === 'receive' + && a.status === 'complete' && b.status === 'complete' && !a.viaLn && !b.viaLn + && (a.batch || b.batch ? a.batch === b.batch : !!a.ts && a.ts === b.ts); +} + export function lnFoldedIds(movements) { const out = new Set(); const recs = (movements || []).filter((m) => m.type === 'receive' && m.status === 'complete' && m.vtxoId); @@ -119,6 +129,24 @@ export function lnFoldedIds(movements) { } if (best) out.add(best.id); } + // A Lightning payment the closed app's worker made is told twice once the + // app opens: the worker's own ln-send row (merged in from the mirror) and + // the "while closed" note the app adds from the worker's spend log. Per + // preimage (or payment hash), keep the row that names its inputs — the + // manager's — else the earliest. + const sends = (movements || []).filter((m) => m.type === 'ln-send' && m.status === 'complete' && (m.preimage || m.paymentHash)); + const keyOf = new Map(); // payment hash → the preimage key, where a row knows both + for (const s of sends) if (s.preimage && s.paymentHash) keyOf.set(s.paymentHash, 'p:' + s.preimage); + const byPay = new Map(); + for (const s of sends) { + const k = s.preimage ? 'p:' + s.preimage : (keyOf.get(s.paymentHash) || 'h:' + s.paymentHash); + (byPay.get(k) || byPay.set(k, []).get(k)).push(s); + } + for (const rows of byPay.values()) { + if (rows.length < 2) continue; + const keep = rows.find((r) => r.inputIds && r.inputIds.length) || rows.reduce((a, b) => ((a.ts || 0) <= (b.ts || 0) ? a : b)); + for (const r of rows) if (r !== keep) out.add(r.id); + } return out; } @@ -177,9 +205,46 @@ export function pruneArkState(state, now = Date.now()) { // Shared by the app (features/ark.js) and the worker tending a closed wallet. export const backstopMargin = (network) => (network === 'regtest' ? 6 : 36); +// Custody tiers — what a coin's timelock means to this wallet: +// custodial nothing renews. The coinos server keeps honoring a coin past +// its timelock (it has swept the tree; the coin is its IOU), so +// the balance works like a v2 one, and no renewal is ever paid. +// self renew in the last hours before expiry — the free ppm bracket, +// one base fee per round — so a unilateral exit is always there. +// exit the same, plus: renew a coin as soon as its history runs +// `maxDepth` hops deep. A unilateral exit publishes one on-chain +// transaction per hop, so depth — not age — is what makes an +// exit expensive; a renewal flattens it to one hop. Early, so +// the top ppm bracket + base; only for a coin worth it (the fee +// under a tenth of its value — see maybeAutoRefresh). +// A policy is { window, margin, grid } in blocks: the app renews a coin with +// under `window` blocks left; the server-side backstop is registered `margin` +// blocks before expiry, snapped DOWN to a multiple of `grid` so everyone's +// orders land in the same round (one round's mining fee shared, not one per +// coin). The snapped height stays inside the free bracket: 36–83 blocks out. +export const CUSTODY_TIERS = ['custodial', 'self', 'exit']; +export const MAX_SEND_INPUTS = 48; +export function renewPolicy(tier, network) { + const rt = network === 'regtest'; + const self = { window: rt ? 24 : 96, margin: backstopMargin(network), grid: rt ? 1 : 48 }; + // 'early' was the third tier for a day (2026-10-22): a week-ahead renewal, + // which flattens the same history a last-hours one does — mirrors may + // still carry the name + if (tier === 'exit' || tier === 'early') return { ...self, maxDepth: 4 }; + if (tier === 'self') return self; + return null; +} + export class ArkManager { - constructor({ account, storage, arkUrl, esploraUrl, network = 'regtest', onUpdate, lnQuoteUrl, statusHint }) { + constructor({ account, storage, arkUrl, esploraUrl, network = 'regtest', onUpdate, lnQuoteUrl, statusHint, honorsExpired = false, infoHint = null, lnOldestFirst }) { this.account = account; // HDKey node; ark keys derived beneath it + // The server's last published info, kept by the app: lets the wallet open + // when the server can't be reached (see init) + this.infoHint = infoHint || null; + this.offline = false; + // the server cosigns spends of a coin past its timelock (coinos): such a + // coin stays money here — spendable, receivable — just not exitable + this.honorsExpired = !!honorsExpired; this.storage = storage; // { load(): obj|null, save(obj): void } this.arkUrl = arkUrl; this.esploraUrl = esploraUrl; @@ -193,6 +258,9 @@ export class ArkManager { : network === 'mutinynet' ? 'https://names.halwallet.app/lnquote?network=mutinynet' : null; this.onUpdate = onUpdate || (() => {}); + // () => true when this wallet renews its own coins (custody tier self or + // exit): a Lightning send then spends the coins nearest expiry first + this.lnOldestFirst = lnOldestFirst || (() => false); this.state = null; this.info = null; this._lnDriving = new Set(); // re-entrancy guard: sync poll vs UI fast-poll vs mailbox push @@ -222,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() { @@ -242,8 +318,23 @@ export class ArkManager { seen.add(m.vtxoId); return true; }); - this.info = await getArkInfo(this.arkUrl); - const hs = await handshake(this.arkUrl).catch(() => null); + // (the handshake goes out beside the info call, not after it: a wake of + // the phone's worker pays for every round trip in the zap it answers) + const hsP = handshake(this.arkUrl).catch(() => null); + try { + this.info = await getArkInfo(this.arkUrl); + this.offline = false; + } catch (e) { + // The server is unreachable. With its last published info in hand the + // wallet still opens on its own records: coins read, a unilateral exit + // can start (that needs the chain, not the server), and anything that + // does need the server fails when it asks. Without that info there is + // no server key to check anything against — then it really is closed. + if (!this.infoHint) throw e; + this.info = this.infoHint; + this.offline = true; + } + const hs = await hsP; this.psa = hs?.psa; this.serverPub = hex.decode(this.info.serverPubkey); @@ -307,6 +398,20 @@ export class ArkManager { return Date.now() - age * 600_000; } + // The tip for a payment about to be built: one asked for moments ago (a + // worker warms it while the manager starts) is as good as asking again. + warmTip() { + const p = this.chain.tipHeight().then((h) => { this._tipH = h; this._tipAt = Date.now(); this._tipNow = Date.now(); return h; }); + this._tipWarm = p; + p.catch(() => {}).finally(() => { if (this._tipWarm === p) this._tipWarm = null; }); + return p; + } + async _tipFresh() { + if (this._tipNow && Date.now() - this._tipNow < 5000 && this._tipH) return this._tipH; + if (this._tipWarm) { try { return await this._tipWarm; } catch { /* ask again */ } } + return this.chain.tipHeight(); + } + async _tipMemo() { if (this._tipAt && Date.now() - this._tipAt < 60_000) return this._tipH; try { @@ -417,7 +522,9 @@ export class ArkManager { // the exception — they have no unilateral exit to protect and the coinos ASP // keeps honoring them off-chain (mirrors validateVtxo's carve-out). _expired(v, tip) { - return !!v.expiryRejected || (!!tip && !!v.expiryHeight && v.amountSat >= 330 && v.expiryHeight <= tip); + if (v.expiryRejected) return true; // the server said no to this one + if (this.honorsExpired) return false; + return !!tip && !!v.expiryHeight && v.amountSat >= 330 && v.expiryHeight <= tip; } // The dust exemption is not a promise that every old coin will be @@ -462,6 +569,34 @@ export class ArkManager { // free to spend, renew or exit from THIS device _free(v, busy = this._remoteBusy()) { return !!v && v.state === 'spendable' && !busy.has(v.id) && this._policyType(v) === 'pubkey'; } + // A coin's exit depth: one transaction per hop of its history (the round + // tree's branch, then every arkoor transfer). Each off-chain payment adds + // one to the change and one to what the recipient gets; only a round + // flattens it. The server refuses to cosign a spend of a coin at its + // `maxVtxoExitDepth` (100 on coinos: a wallet paying hourly from one change + // 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; } + // The free coins a refresh should flatten now: at the server's waiver depth + // (no base fee, so always worth it), or within a few hops of the cap on a + // server without one (stuck otherwise). Expired coins too: a round is the + // one thing an expired coin can always do, and the server honors it. + deepCoins() { + const waiver = this._waiverDepth(), cap = this._capDepth(); + if (!waiver && !cap) return []; + const busy = this._remoteBusy(); + return this.state.vtxos.filter((v) => { + if (!this._free(v, busy)) return false; + const d = this.exitDepth(v); + return (waiver && d >= waiver) || (cap && d >= cap - 8); + }); + } + balance() { const tip = this._tipH || 0; const busy = this._remoteBusy(); @@ -508,6 +643,11 @@ export class ArkManager { this._lnRescanned = true; try { if (await this.rescanLnReceives()) await this._save(); } catch (e) { this._lnRescanned = false; } } + 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 // expiry against it synchronously, and a stale tip hides dead coins @@ -570,6 +710,97 @@ export class ArkManager { } } + // On a server that honors coins past their timelock, the ones this wallet + // wrote off before it knew that are still its money: + // - receives an older build refused at pickup ("vtxo expired at …"), + // recorded as rejected and left behind the mailbox cursor — the + // forwards stranded that way before 2026-08-24 among them; + // - coins the server once refused to spend (expiryRejected, from before + // allow_expired_arkoor), and expired dust the user gave up (Forget). + // 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; + const alive = async (v) => { + try { + return (await getVtxoStatus(this.arkUrl, this._decoded(v).point.raw, this._keyForVtxo(v).privkey)) === VTXO_STATE_SPENDABLE; + } catch { return false; } + }; + for (const v of this.state.vtxos) { + if (!(v.expiryRejected || (v.forgotten && v.state === 'spent'))) continue; + if (!(await alive(v))) continue; + delete v.expiryRejected; delete v.forgotten; v.state = 'spendable'; + changed = true; + } + const rejected = (this.state.movements || []).filter((m) => m.type === 'receive' && m.status === 'rejected' && /expired at/i.test(m.detail || '')); + if (rejected.length) { + const mailbox = this._mailboxKey(); + let checkpoint = 0; + for (let page = 0; page < 50; page++) { + const { messages, haveMore } = await readMailbox(this.arkUrl, mailbox, 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; + // a coin another device of this wallet adopted and spent since + // is not money here; only what the server still holds for us is + let status = 0; + try { status = await getVtxoStatus(this.arkUrl, v.point.raw, this._key(0).privkey); } catch { status = 0; } + if (status === VTXO_STATE_SPENDABLE) fresh.push(v); + } + if (fresh.length && await this._handleMailboxMessage({ ...m, vtxos: fresh })) changed = true; + } + if (!haveMore || !messages.length) break; + } + this.state.movements = this.state.movements.filter((m) => !rejected.includes(m)); + changed = true; + } + this.state.expiredRescanDone = true; + return true; + } + async _handleMailboxMessage(m) { let changed = false; if (m.kind === 'lnSendFinished') { @@ -616,7 +847,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 @@ -639,8 +870,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 }); + 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 }); @@ -652,10 +888,28 @@ 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 this._movement({ type: 'receive', amountSat: v.amountSat, status: 'complete', vtxoId: v.id, ts: ckTs ?? (live ? Date.now() : this._estimateReceiveTs(v, tip)), + ...(m.checkpoint ? { batch: String(m.checkpoint) } : {}), }); changed = true; } @@ -733,8 +987,13 @@ export class ArkManager { v.state = owner.step === 'done' || owner.step === 'failed' ? 'spent' : 'pending'; changed = true; } + // An HTLC coin whose payment no action names any more (done ln-pays are + // pruned after a while) is an orphan too: five 22-sat ones sat 'pending' + // in a wallet for days, counted as money on its way. The server's answer + // settles it — spent is spent; one still open stays pending, since an + // HTLC coin is never this wallet's to spend (see below). const candidates = this.state.vtxos.filter((v) => v.state === 'spendable' - || (v.state === 'pending' && !held.has(v.id) && v.bytes && this._policyType(v) === 'pubkey')); + || (v.state === 'pending' && !held.has(v.id) && v.bytes)); const was = candidates.map((v) => v.state); // what each was when this pass began // Each status query signs a challenge (schnorr) and may decode the vtxo — // real secp256k1 work. Building them all in one synchronous map was a @@ -759,8 +1018,8 @@ export class ArkManager { // an orphan the server still counts is simply spendable again; one it // holds as spent is gone, and the pay that took it was recorded (or // will merge in) elsewhere — no row of its own - if (states[i] === VTXO_STATE_SPENDABLE) { v.state = 'spendable'; changed = true; } - else if (states[i] === VTXO_STATE_SPENT) { v.state = 'spent'; changed = true; } + if (states[i] === VTXO_STATE_SPENT) { v.state = 'spent'; changed = true; } + else if (states[i] === VTXO_STATE_SPENDABLE && this._policyType(v) === 'pubkey') { v.state = 'spendable'; changed = true; } return; } if (states[i] !== VTXO_STATE_SPENT) return; @@ -962,30 +1221,91 @@ export class ArkManager { // that covers it, else largest-first until the sum does. A balance scattered // by many small receives stays spendable — the package cosign spends all // the inputs atomically and the recipient just receives several vtxos. + // A coin past its timelock spends LAST. The server honors it, and so does + // this build at pickup — but a receiver on an older build still refuses + // one as expired and strands it. Reaching for such a coin only when + // nothing else covers the amount narrows that to almost no payment. + _pastExpiry(v, tip) { return !!tip && !!v.expiryHeight && v.expiryHeight <= tip; } + _spendOrder(list, tip, cmp) { + const live = list.filter((v) => !this._pastExpiry(v, tip)).sort(cmp); + const past = list.filter((v) => this._pastExpiry(v, tip)).sort(cmp); + return [...live, ...past]; + } + // largest-first (or in `order`) until `need` is covered; the coins inside their + // timelock alone if they can carry it, else everything + _accumulate(spendable, tip, need, order) { + const desc = order || ((a, b) => b.amountSat - a.amountSat); + const live = spendable.filter((v) => !this._pastExpiry(v, tip)).sort(desc); + for (const pool of [live, [...spendable].sort(desc)]) { + const picked = []; + let sum = 0; + for (const v of pool) { + picked.push(v); sum += v.amountSat; + if (need(picked, sum)) return picked; + } + } + return null; + } + _selectInputs(amountSat, tip = this._tipH || 0) { const busy = this._remoteBusy(); + // a coin at the server's depth cap can't be an input: the cosign is refused const spendable = this.state.vtxos - .filter((v) => this._free(v, busy) && !this._expired(v, tip)); - const single = spendable - .filter((v) => v.amountSat >= amountSat) - .sort((a, b) => a.amountSat - b.amountSat)[0]; + .filter((v) => this._free(v, busy) && !this._expired(v, tip) && !this._capped(v)); + const single = this._spendOrder(spendable.filter((v) => v.amountSat >= amountSat), tip, (a, b) => a.amountSat - b.amountSat)[0]; if (single) return [single]; - const picked = []; - let sum = 0; - for (const v of [...spendable].sort((a, b) => b.amountSat - a.amountSat)) { - picked.push(v); sum += v.amountSat; - if (sum >= amountSat) break; - } - if (sum < amountSat) throw new Error(this._insufficientMsg(tip)); - if (picked.length > 24) throw new Error('balance is spread over too many coins for one send'); + const picked = this._accumulate(spendable, tip, (set, sum) => sum >= amountSat); + if (!picked) throw new Error(this._insufficientMsg(tip)); + // The cap is this wallet's, not the server's (which caps offboard and + // board inputs only). It used to be 24, with an automatic consolidation + // round at 20 coins to stay under it — a round that cost 0.2% + base on + // every coin and was 84% of what users paid in fees. Wider, no round. + if (picked.length > MAX_SEND_INPUTS) throw new Error('balance is spread over too many coins for one send'); return picked; } + // Inputs for a Lightning send of `amountSat` plus `routing`, and the fee + // they come to: { inputs, feeSat }. Throws when the coins can't cover it. + _selectLnInputs(spendable, tip, amountSat, routing) { + let inputs = null, feeSat = 0; + // A wallet that renews its own coins pays for every renewal, so it + // spends the coins nearest expiry first (Stacker News, 2026-10-29): the + // ASP takes them, so nobody downstream inherits the short timelock, as + // an Ark-to-Ark send's recipient would. Otherwise (and on a tie) the + // smallest coin that covers it, keeping the balance in few coins. + const oldest = !!this.lnOldestFirst(); + const exp = (v) => v.expiryHeight || Infinity; + const bySize = (a, b) => a.amountSat - b.amountSat; + const byAge = (a, b) => (exp(a) - exp(b)) || bySize(a, b); + for (const v of this._spendOrder(spendable, tip, oldest ? byAge : bySize)) { + const fee = lnSendFee(amountSat, this.info.lnSendFees, [v], tip) + routing; + if (v.amountSat >= amountSat + fee) { inputs = [v]; feeSat = fee; break; } + } + if (!inputs) { + const need = (set, sum) => { + feeSat = lnSendFee(amountSat, this.info.lnSendFees, set, tip) + routing; + return sum >= amountSat + feeSat; + }; + let picked = oldest ? this._accumulate(spendable, tip, need, byAge) : null; + // too many old crumbs for one payment: fall back to largest-first + if (!picked || picked.length > MAX_SEND_INPUTS) picked = this._accumulate(spendable, tip, need); + if (picked) inputs = picked; + if (!inputs) throw new Error(this._insufficientMsg(tip)); + if (inputs.length > MAX_SEND_INPUTS) throw new Error('balance is spread over too many coins for one payment'); + } + return { inputs, feeSat }; + } + _insufficientMsg(tip) { const expiredSat = this.state.vtxos .filter((v) => v.state === 'spendable' && this._expired(v, tip)) .reduce((n, v) => n + v.amountSat, 0); if (expiredSat) return `insufficient ark balance (${expiredSat} sat expired and unusable)`; + const cappedSat = this.state.vtxos.filter((v) => this._free(v) && this._capped(v)).reduce((n, v) => n + v.amountSat, 0); + // under dust a round won't take it either: only new money pays from here + if (cappedSat) return cappedSat < 330 + ? `insufficient ark balance (${cappedSat} sat have a history too long to spend and are too few to renew; receive more to keep paying)` + : `insufficient ark balance (${cappedSat} sat have a history too long to spend and are waiting to be renewed)`; // coins a renewal took stay unspendable until its round confirms on-chain const renewing = lnShortfall(this.state.vtxos, this.state.actions, Infinity).renewingSat; return renewing @@ -1061,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) }, @@ -1186,10 +1506,17 @@ export class ArkManager { async awaitLnPay(id, timeoutMs = 90_000) { const a = this.lnAction(id); if (!a || a.step !== 'initiated') return this.driveLn(id); - await Promise.race([ + const res = await Promise.race([ checkLightningPayment(this.arkUrl, hex.decode(a.paymentHash), true).catch(() => null), new Promise((r) => setTimeout(r, timeoutMs)), ]); + // the held call's own answer settles it: asking once more for the same + // preimage was a round trip between the payment and its reply + if (res && res.status === 'success' && res.preimage && a.step === 'initiated' + && hex.encode(sha256(hex.decode(res.preimage))) === a.paymentHash) { + this._settleLnPay(a, res.preimage); + return a; + } return this.driveLn(id); } @@ -1313,34 +1640,30 @@ export class ArkManager { if (expectNet && dec.network && dec.network !== expectNet) throw new Error(`invoice is for ${dec.network}, wallet is on ${expectNet}`); const amountSat = dec.amountSat ?? userAmountSat; if (!amountSat || amountSat <= 0) throw new Error('invoice has no amount'); - if (this.state.actions.some((a) => - a.type === 'ln-pay' && a.paymentHash === dec.paymentHash && a.step !== 'failed')) { - throw new Error('this invoice was already paid or is being paid'); + const prior = this.state.actions.find((a) => + a.type === 'ln-pay' && a.paymentHash === dec.paymentHash && a.step !== 'failed'); + if (prior) { + // two messages, so a caller can tell a settled payment from one still + // on its way (an NWC client once read "already paid or is being paid" + // as paid, hours before the money moved) + throw new Error(prior.step === 'done' ? 'this invoice was already paid' : 'a payment for this invoice is already in progress'); } - const tip = await this.chain.tipHeight(); - const routing = routingFeeSat != null ? routingFeeSat : await this.lnRouteFee(invoice, amountSat); + const [tip, routing] = await Promise.all([ + this._tipFresh(), + routingFeeSat != null ? routingFeeSat : this.lnRouteFee(invoice, amountSat), + ]); + // the two awaits above let a second call for the same invoice in + const twin = this.state.actions.find((a) => + a.type === 'ln-pay' && a.paymentHash === dec.paymentHash && a.step !== 'failed'); + if (twin) throw new Error(twin.step === 'done' ? 'this invoice was already paid' : 'a payment for this invoice is already in progress'); // smallest single vtxo that covers amount + routing + its expiry-dependent // fee — else gather largest-first: each input funds its own HTLC vtxo with // the same payment hash, and the server sums them into one payment. const busy = this._remoteBusy(); + // a coin at the depth cap can't be an input: the ASP refuses the cosign const spendable = this.state.vtxos - .filter((v) => this._free(v, busy) && !this._expired(v, tip)); - let inputs = null, feeSat = 0; - for (const v of [...spendable].sort((a, b) => a.amountSat - b.amountSat)) { - const fee = lnSendFee(amountSat, this.info.lnSendFees, [v], tip) + routing; - if (v.amountSat >= amountSat + fee) { inputs = [v]; feeSat = fee; break; } - } - if (!inputs) { - const picked = []; - let sum = 0; - for (const v of [...spendable].sort((a, b) => b.amountSat - a.amountSat)) { - picked.push(v); sum += v.amountSat; - feeSat = lnSendFee(amountSat, this.info.lnSendFees, picked, tip) + routing; - if (sum >= amountSat + feeSat) { inputs = picked; break; } - } - if (!inputs) throw new Error(this._insufficientMsg(tip)); - if (inputs.length > 24) throw new Error('balance is spread over too many coins for one payment'); - } + .filter((v) => this._free(v, busy) && !this._expired(v, tip) && !this._capped(v)); + const { inputs, feeSat } = this._selectLnInputs(spendable, tip, amountSat, routing); // per-input HTLC share: first n-1 consumed whole, the last carries change let remainingLock = amountSat + feeSat; const parts = inputs.map((v) => { @@ -1387,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: [ { @@ -1496,10 +1819,22 @@ export class ArkManager { }); action.step = 'initiated'; this._save(); + // Just handed to the server: nothing to learn from asking this + // instant (it answered "pending", and the chain tip was fetched to + // go with it — two round trips before the caller's held call could + // even start). The caller waits on it (awaitLnPay) or polls. + return; } catch (e) { + // the HTLC already went to this payment: another context (a second + // wake of the phone's worker, seconds apart, over its own copy of the + // state) initiated it first. That payment is this one — follow it. + // (PullCap 2026-10-24 23:21: a paid send was marked 'revoking' here.) + if (e instanceof GrpcError && /state: ln-spent/i.test(e.message)) { + action.step = 'initiated'; + this._save(); // INVALID_ARGUMENT: the server itself deems the invoice unpayable — // retrying can never succeed, revoke the HTLC instead - if (e instanceof GrpcError && e.grpcStatus === 3) { + } else if (e instanceof GrpcError && e.grpcStatus === 3) { action.error = e.message; action.step = 'revoking'; this._save(); @@ -1526,7 +1861,22 @@ export class ArkManager { this._save(); } } - if (action.step === 'revoking') await this._revokeLnPay(action); + if (action.step === 'revoking') { + // Ask first: a send can land in 'revoking' over a stale copy of the + // state while the payment went through (or is still going) — a + // settled payment is settled here too, and one in flight waits. + const res = await checkLightningPayment(this.arkUrl, hex.decode(action.paymentHash), false).catch(() => null); + if (res && res.status === 'success' && res.preimage + && hex.encode(sha256(hex.decode(res.preimage))) === action.paymentHash) { + this._settleLnPay(action, res.preimage); + return; + } + if (res && res.status === 'pending' && action.htlcExpiry) { + const tip = await this.chain.tipHeight().catch(() => 0); + if (tip && tip <= action.htlcExpiry) { action.step = 'initiated'; delete action.error; this._save(); return; } + } + await this._revokeLnPay(action); + } } _settleLnPay(action, preimageHex) { @@ -1560,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, @@ -1623,9 +1973,11 @@ export class ArkManager { }); } catch (e) { // "already been paid" for a settled one; "UNIQUE constraint failed: - // invoices.payment_hash" for one merely issued before — both mean - // this index is spoken for - const used = /already been paid|already exists|already in use|duplicate|UNIQUE constraint|payment_hash/i.test(e?.message || ''); + // invoices.payment_hash" for one merely issued before; "the invoice + // for payment hash … was canceled" for one a cancel retired (a + // withdraw-link claim died on that, 2026-11-08) — all mean this + // index is spoken for + const used = /already been paid|already exists|already in use|duplicate|UNIQUE constraint|payment_hash|payment hash [0-9a-f]+ was cancel+ed/i.test(e?.message || ''); if (!used || tries >= 200) throw e; this._save(); // remember the skipped index even if the next try fails continue; @@ -1771,7 +2123,7 @@ export class ArkManager { if (v.policy.userPubkey !== hex.encode(keys.pubkey)) throw new Error('HTLC vtxo pubkey mismatch'); if (v.policy.htlcExpiry < htlcRecvExpiry) throw new Error('HTLC vtxo expiry lower than requested'); try { - await validateVtxo(v, { serverPubkey: this.serverPub, chain: this.chain, allowPolicies: ['serverHtlcRecv'] }); + await validateVtxo(v, { serverPubkey: this.serverPub, chain: this.chain, allowPolicies: ['serverHtlcRecv'], acceptExpired: this.honorsExpired }); } catch (e) { // a granted vtxo can anchor to a round the chain hasn't confirmed // yet — park (no preimage revealed, nothing at risk) and retry on @@ -1820,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, @@ -1890,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, }); @@ -1931,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, }); @@ -1963,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, @@ -1987,7 +2339,7 @@ export class ArkManager { if (v.policy.type !== 'pubkey' || v.policy.userPubkey !== expect) { throw new Error('refund vtxo is not paid to our refund key'); } - await validateVtxo(v, { serverPubkey: this.serverPub, chain: this.chain, expectPubkeys: [expect] }); + await validateVtxo(v, { serverPubkey: this.serverPub, chain: this.chain, expectPubkeys: [expect], acceptExpired: this.honorsExpired }); if (this._addVtxo(v, bytes, refundIndex)) total += v.amountSat; } if (total) { @@ -2110,7 +2462,10 @@ export class ArkManager { const entry = table.filter((e) => e.thresholdBlocks <= blocks).pop(); ppmUnits += v.amountSat * (entry?.ppm ?? 0); } - return this.info.refreshFees.baseFeeSat + Math.ceil(ppmUnits / 1_000_000); + // the server waives the base fee when every input is at its waiver depth + const waiver = this._waiverDepth(); + const base = waiver && inputs.length && inputs.every((v) => this.exitDepth(v) >= waiver) ? 0 : this.info.refreshFees.baseFeeSat; + return base + Math.ceil(ppmUnits / 1_000_000); } // manual: the user asked for this one (the coins page) — it earns a @@ -2250,19 +2605,20 @@ export class ArkManager { if (action.step === 'created') { // A set the round would refuse anyway is retired here, not resubmitted - // every sync: an input past its expiry (only the server's backstop can - // renew it now), or an output the fee leaves under the 330-sat dust - // floor (a 21-sat coin with a 150-sat fee sat "in progress" for days). - // Nothing was spent, so the inputs go back to spendable. - const tip = this._tipH || (await this.chain.tipHeight().catch(() => 0)); + // every sync: an output the fee leaves under the 330-sat dust floor (a + // 21-sat coin with a 150-sat fee sat "in progress" for days), or an + // input no longer held. Nothing was spent, so the inputs go back to + // spendable. An input PAST ITS EXPIRY is not a reason: the server's + // round-input check has no expiry clause (a coin 3,127 blocks past its + // height was renewed on mainnet, 2026-10-14) — renewal is the one + // thing an expired coin can always do, and this gate used to retire + // the Manage page's own "Renew" of exactly those coins, silently. const inSat = inputRecs.reduce((n, v) => n + (v ? v.amountSat : 0), 0); - const expired = inputRecs.some((v) => v && v.expiryHeight && tip && v.expiryHeight <= tip); - if (expired || inSat - (action.feeSat || 0) < 330 || inputRecs.some((v) => !v)) { + if (inSat - (action.feeSat || 0) < 330 || inputRecs.some((v) => !v)) { for (const v of inputRecs) if (v && v.state === 'pending') v.state = 'spendable'; action.step = 'failed'; action.superseded = true; // no row: the renewal never began - action.lastError = expired ? 'an input has expired: only the server can renew it now' - : inputRecs.some((v) => !v) ? 'an input is no longer held' : 'the fee leaves less than the 330-sat minimum'; + action.lastError = inputRecs.some((v) => !v) ? 'an input is no longer held' : 'the fee leaves less than the 330-sat minimum'; this._save(); return; } @@ -2335,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) { @@ -2437,24 +2805,32 @@ export class ArkManager { // expiry. Coins arrive, get spent, get renewed — each new one needs its own // backstop while it still has the lifetime to register one. Caller owns the // policy (how much margin, how often to ask); this owns the bookkeeping. - async ensureScheduledRefreshes(marginBlocks, maxCoins = 8) { + // grid: the order's height is snapped DOWN to a multiple of it, so orders + // from every wallet fall into the same round instead of one round (one + // on-chain fee) per coin. The snap only ever moves EARLIER, by under one + // grid step — the caller picks a margin+grid that stays in one fee bracket. + async ensureScheduledRefreshes(marginBlocks, maxCoins = 8, grid = 1) { const tip = await this._tipMemo(); if (!tip) return 0; const covered = new Set((this.state.scheduled || []).flatMap((s) => s.inputIds)); + const runAt = (v) => { + const h = v.expiryHeight - marginBlocks; + return grid > 1 ? h - (h % grid) : h; + }; // A round output over the server's cap is refused when the round runs — // long after registration, with nobody there to hear it. Don't register // an order that is going to die that quietly. const cap = this.info.maxVtxoAmountSat || Infinity; const coins = this.state.vtxos .filter((v) => this._free(v) && v.expiryHeight && !covered.has(v.id) - && !this._expired(v, tip) && v.expiryHeight - marginBlocks > tip && v.amountSat <= cap) + && !this._expired(v, tip) && v.expiryHeight > tip && runAt(v) > tip && v.amountSat <= cap) .sort((a, b) => b.amountSat - a.amountSat) .slice(0, maxCoins); let n = 0; for (const v of coins) { // One participation per coin. A shared one dies whole the moment any // single input is spent, taking the untouched coins' cover with it. - try { await this.scheduleRefresh([v.id], v.expiryHeight - marginBlocks); n++; } + try { await this.scheduleRefresh([v.id], runAt(v)); n++; } catch (e) { // priced from a stale schedule: re-read it so the next pass registers if (/insufficient refresh fee/i.test(e.message || '')) this.info = await getArkInfo(this.arkUrl).catch(() => this.info); @@ -2464,6 +2840,35 @@ export class ArkManager { return n; } + // The worker's version of flattening deep coins: it can't sit through a + // live round, so each deep coin gets a standing order for two blocks out, + // one per coin (an order dies whole when any input is spent — and a coin + // that is spent hourly will void it; the next wake registers again, and + // the one time the coin rests through the height, the round runs). Only + // coins still inside their timelock can be scheduled; an expired deep coin + // waits for the app, whose live refresh the server honors. + async ensureDeepRefreshes(maxCoins = 2) { + const deep = this.deepCoins(); + if (!deep.length || !maxCoins) return 0; + const tip = await this._tipMemo(); + if (!tip) return 0; + const covered = new Set((this.state.scheduled || []).flatMap((s) => s.inputIds)); + const cap = this.info.maxVtxoAmountSat || Infinity; + // a round output under dust (330 sat) is refused, so a coin that small + // can't be renewed on its own — asking only spends the wake's budget + const coins = deep + .filter((v) => !covered.has(v.id) && v.expiryHeight > tip + 2 && v.amountSat <= cap + && v.amountSat - this.refreshFee([v], tip + 2) >= 330) + .sort((a, b) => this.exitDepth(b) - this.exitDepth(a)) + .slice(0, maxCoins); + let n = 0; + for (const v of coins) { + try { await this.scheduleRefresh([v.id], tip + 2); n++; } + catch (e) { console.warn('ark: no deep refresh order for', v.id, '—', e.message); } + } + return n; + } + _dropScheduled(entry) { this.state.scheduled = (this.state.scheduled || []).filter((s) => s !== entry); this._save(); diff --git a/src/ark/proto.js b/src/ark/proto.js index eb89d5e..69218c6 100644 --- a/src/ark/proto.js +++ b/src/ark/proto.js @@ -416,6 +416,10 @@ export async function getArkInfo(ark) { if (field === 13) info.minBoardAmountSat = Number(value); 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)) { @@ -445,9 +449,10 @@ export async function getArkInfo(ark) { info.offboardFees = ob; } if (f.field === 3) { // refresh - const rf = { baseFeeSat: 0, ppmExpiryTable: [] }; + const rf = { baseFeeSat: 0, ppmExpiryTable: [], deepWaiverDepth: 0 }; for (const g of pbFields(f.value)) { if (g.field === 1) rf.baseFeeSat = Number(g.value); + if (g.field === 3) rf.deepWaiverDepth = Number(g.value); // base fee waived when every input is this deep if (g.field === 2) { const e = { thresholdBlocks: 0, ppm: 0 }; for (const h of pbFields(g.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/src/ark/store.js b/src/ark/store.js index b1caa94..24d8f55 100644 --- a/src/ark/store.js +++ b/src/ark/store.js @@ -139,6 +139,7 @@ export class ArkStore { } } this.ready = true; + this._parsed = null; // peeks now read the opened store if (migrated.length) { this.flush().then(() => { for (const k of migrated) { try { ls.removeItem(k); } catch {} } }).catch(() => {}); } @@ -153,13 +154,32 @@ export class ArkStore { const v = this.mem.get(key); return v ? clone(v) : null; } + // The stored object itself, not a copy — for readers that only look (the + // render path). get() deep-copies, and a big wallet's state is ~1 MB: on a + // Pixel 9 each copy took ~220 ms and the first render asked five to seven + // times before the manager connected, 1.4 s of every launch. Never mutate + // what this returns. Before the store opens (or on localStorage) the parse + // is kept until the key is next written. + peek(key) { + if (!this.ready || this.lsMode) { + const hit = this._parsed && this._parsed.get(key); + if (hit !== undefined) return hit; + let v = null; + try { const raw = this.ls().getItem(key); v = raw ? JSON.parse(raw) : null; } catch { v = null; } + (this._parsed ||= new Map()).set(key, v); + return v; + } + return this.mem.get(key) || null; + } set(key, obj) { + if (this._parsed) this._parsed.delete(key); if (!this.ready || this.lsMode) { try { this.ls().setItem(key, JSON.stringify(obj)); } catch {} return; } this.mem.set(key, obj); this.dirty.add(key); this._schedule(); } remove(key) { + if (this._parsed) this._parsed.delete(key); if (!this.ready || this.lsMode) { try { this.ls().removeItem(key); } catch {} return; } this.mem.delete(key); this.dirty.add(key); diff --git a/src/ark/validate.js b/src/ark/validate.js index fae3465..9cb1751 100644 --- a/src/ark/validate.js +++ b/src/ark/validate.js @@ -24,7 +24,11 @@ const fail = (msg) => { throw new VtxoValidationError(msg); }; // plus getTxStatus(txid) -> {confirmed, block_height} (esplora semantics) // allowPolicies: acceptable policy types (default plain pubkey only; lightning // flows pass ['serverHtlcSend'] / ['serverHtlcRecv'] for their HTLC vtxos) -export async function validateVtxo(vtxo, { serverPubkey, chain, expectPubkeys, allowPolicies = ['pubkey'] }) { +// acceptExpired: the server keeps honoring coins past their timelock (coinos: +// captaind allow_expired_arkoor) — the coin is then an IOU the server has +// already swept the tree of, which is exactly what the holder chose when they +// left custody to coinos; refuse only on servers that would refuse to spend it +export async function validateVtxo(vtxo, { serverPubkey, chain, expectPubkeys, allowPolicies = ['pubkey'], acceptExpired = false }) { const serverHex = hex.encode(serverPubkey); // -- structural -- @@ -41,7 +45,7 @@ export async function validateVtxo(vtxo, { serverPubkey, chain, expectPubkeys, a // and the coinos ASP keeps honoring them off-chain after sweeping their // round — an explicit IOU where the trustless path never existed anyway. const tip = await chain.tipHeight(); - if (vtxo.expiryHeight <= tip && vtxo.amountSat >= 330) { + if (!acceptExpired && vtxo.expiryHeight <= tip && vtxo.amountSat >= 330) { fail(`vtxo expired at ${vtxo.expiryHeight}, tip ${tip}`); } |
