diff options
| author | Adam Soltys <[email protected]> | 2026-10-16 12:32:28 -0700 |
|---|---|---|
| committer | Adam Soltys <[email protected]> | 2026-10-16 12:32:28 -0700 |
| commit | 294a49598e43e3e6f9e34f0246bbea41837359f9 (patch) | |
| tree | 0fe376316626a9b27330ecbba15740d14ec4c825 /tools | |
| parent | 38ce0b441505d0bdd048d38c82ac95afe4d3b407 (diff) | |
| download | coinosv3-294a49598e43e3e6f9e34f0246bbea41837359f9.tar.gz coinosv3-294a49598e43e3e6f9e34f0246bbea41837359f9.zip | |
NWC: budgets reset by the day, week or month; a revoked connection says so; a closed wallet keeps its coins renewed. Three asks from a subscription service builder (PullCap, by DM, 2026-10-16) testing a 1-sat-an-hour pull against a locked phone. (1) "For a monthly subscription a monthly cap would be tighter": a connection's budget now resets every day, week (Monday) or month, in UTC (nwc-budget.js: the window key stamps the spent counter; both the app and the worker count by it), chosen on the form, read on the card ("21,000 a month · 0 spent this month"); the worker now also counts what the APP spent this window (the counter rides the mirror) — it only ever counted its own log before, so a daily budget could be exceeded across the two; get_budget answers used/total/renews_at/renewal_period (NIP-47), in get_info's method list and the 13194 event. (2) "Does V3 reply with an NWC error when a connection is revoked, or just stop answering?" — it stopped: the open app dropped the request, the mirror forgot the key, the device even de-registered it from the push notifier, so a revocation looked exactly like a phone that is off. Now a revoked connection is kept for 30 days (revokedAt; the earlier date wins in a merge): still subscribed, still registered for pushes, still in the mirror flagged, and every request on it — from the app or the worker, in the asker's scheme — is answered UNAUTHORIZED "this connection was revoked"; no capability event for it; after the grace it is forgotten. (3) "If a user is only woken once a month by an NWC request, will V3 renew the coins on its own?" — only for one cycle: the app registers a standing order per coin, but a coin the worker SPENDS voids its order and the change had none until the app next opened, and a renewed coin sat unclaimed until then too. Now every NWC wake, after the answer and inside what is left of the push budget (tendRenewals, sw-nwc.js): claim orders whose round has run — and drive a claim left in flight on, since one takes several round trips and confirmations — then register an order for every coin without one (backstopMargin shared with the app; limited to the output keys the mirror carries; the mirror now also carries the output key a standing order or a claim in flight burned, which was below the window). Standing orders merge by unlock hash when the app returns (mergeScheduled, in mergeArkStates), so it adopts the worker's. tools/ark/bg-renewal-test.js on regtest, end to end: the worker registers from the mirror alone, a worker spend kills the order and the next wake covers the change, the round runs with nobody online and the next wake claims the renewed coin — and covers it in the same wake — then the app merges it all (fresh coin, right balance, the order adopted, not busy, one history row). tools/nwc-budget-test.js (windows, renews_at, counting with the worker's unabsorbed spends); nwc-sw-test.js (monthly budget over app+worker spends, last month's not counted, get_budget, UNAUTHORIZED in both schemes, the mirror's keys and flags, tending: claim/drive/register and their limits); nwc-test.js (monthly refusal naming the period, get_budget, a counter from last month reads as nothing, the revoked connection answered UNAUTHORIZED, no 13194, revokedAt in the snapshot, forgotten after 31 days, the earlier date wins); nwc-settings-ui-test.js (the form's period choice, the card's wording, Revoke dates it); ark-renewal-sync, sync-blob, sync-outbox and spending-restore tests pass.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01J1Kon8bxJoHRpJdSzshCkp
Diffstat (limited to 'tools')
| -rw-r--r-- | tools/ark/bg-renewal-test.js | 135 | ||||
| -rw-r--r-- | tools/nwc-budget-test.js | 52 | ||||
| -rw-r--r-- | tools/nwc-settings-ui-test.js | 80 | ||||
| -rw-r--r-- | tools/nwc-sw-test.js | 131 | ||||
| -rw-r--r-- | tools/nwc-test.js | 66 |
5 files changed, 463 insertions, 1 deletions
diff --git a/tools/ark/bg-renewal-test.js b/tools/ark/bg-renewal-test.js new file mode 100644 index 0000000..0a85816 --- /dev/null +++ b/tools/ark/bg-renewal-test.js @@ -0,0 +1,135 @@ +// The service worker tends a closed wallet's renewals, on regtest, end to end: +// +// the app receives a coin and writes the background mirror -> "closes" -> +// the worker (tendRenewals over the mirror, keys from the mirror alone) +// registers a standing order for the coin -> the worker SPENDS from the +// mirror (an NWC pay) which voids that order; the next wake covers the +// change coin -> the scheduled height passes, the server runs the round +// with nobody online -> the next wake claims the renewed coin into the +// mirror -> the app returns and merges the worker's state: fresh coin, +// old one spent, the order gone. +// +// Usage: bun tools/ark/bg-renewal-test.js +// Needs the ark-regtest stack (bc, ark-electrs, captaind on :3535). + +import { execSync } from 'node:child_process'; +import { hex } from '@scure/base'; +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'; +import { buildBg } from '../../src/nwc-bg.js'; +import { tendRenewals, bgManager } from '../../src/nwc-respond.js'; +import { mergeArkStates } from '../../src/features/ark.js'; +import { ALICE, aliceReady } from './alice.js'; + +const ARK = process.env.ARK_URL || 'http://127.0.0.1:3535'; +const ESPLORA = process.env.ESPLORA_URL || 'http://127.0.0.1:30002'; +const BCLI = `docker exec bc bitcoin-cli -rpcwallet=coinos`; + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const sh = (cmd) => execSync(cmd, { shell: '/bin/bash' }).toString().trim(); +const mine = (n = 1) => sh(`${BCLI} generatetoaddress ${n} $(${BCLI} getnewaddress) >/dev/null`); +const tipHeight = () => Number(sh(`${BCLI} getblockcount`)); + +let ok = true; +const check = (name, cond, detail = '') => { + console.log(` ${cond ? '✓' : '✗'} ${name}${detail ? ' — ' + detail : ''}`); + if (!cond) ok = false; +}; + +// --- the app's wallet --- +const store = { raw: null }; +const storage = { load: () => (store.raw ? JSON.parse(store.raw) : null), save: (s) => { store.raw = JSON.stringify(s); } }; +const mnemonic = generateMnemonic(wordlist); +const account = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic)).derive("m/86'/0'/9'"); +const app = await new ArkManager({ account, storage, arkUrl: ARK, esploraUrl: ESPLORA }).init(); +await aliceReady(); + +const receive = async (sat) => { + const before = app.balance().spendableSat; + sh(`${ALICE} -q send ${app.address()} "${sat} sat"`); + for (let i = 0; i < 15 && app.balance().spendableSat < before + sat; i++) { await app.sync(); await sleep(1000); } + return app.balance().spendableSat - before; +}; + +// --- the mirror the worker answers from (what writeBgMirror writes) --- +let rec = null; +const writeMirror = () => { + rec = buildBg({ + ark: { arkUrl: ARK, esploraUrl: ESPLORA, network: 'regtest', serverPubkey: app.info.serverPubkey }, + mgrState: JSON.parse(JSON.stringify(app.state)), + keyFor: (chain, i) => hex.encode(account.deriveChild(chain).deriveChild(i).privateKey), + connections: [], + }); +}; +const recs = async () => [{ walletKey: 'w1', rec }]; +const saveFn = async (k, r) => { rec = r; }; +const log = (m) => console.log(' [sw-renew] ' + m); +const tend = (margin) => tendRenewals({ recordsFn: recs, saveFn, log, deadline: Date.now() + 60_000, margin }); +const mirrorCoins = () => (rec.mgr.vtxos || []).filter((v) => v.state === 'spendable'); + +console.log('\n[1] the app receives a coin, mirrors it, and closes'); +check('received 20000 sat', (await receive(20000)) === 20000, JSON.stringify(app.balance())); +writeMirror(); +const coin = mirrorCoins()[0]; +check('the mirror holds the coin and its key', !!coin && !!rec.keys[String(coin.keyIndex)] && !!rec.key4); +check('no standing order yet, on either side', !(app.state.scheduled || []).length && !(rec.mgr.scheduled || []).length); + +console.log('\n[2] a wake: the worker registers a standing order from the mirror alone'); +// aim the order a few blocks out so the test needn't mine a month +const n1 = await tend(coin.expiryHeight - (tipHeight() + 3)); +const order1 = (rec.mgr.scheduled || [])[0]; +check('one order registered', n1 === 1 && (rec.mgr.scheduled || []).length === 1); +check('with the server\'s unlock hash', !!order1?.unlockHash, order1?.unlockHash?.slice(0, 16)); +check('the coin stays spendable in the mirror', mirrorCoins().some((v) => v.id === coin.id)); +check('the output key it burned is in the mirror', !!rec.keys[String(order1?.outKeyIndex)]); +check('the app knows nothing of it yet', !(app.state.scheduled || []).length); +check('a second wake registers nothing more', (await tend(coin.expiryHeight - (tipHeight() + 3))) === 0 && rec.mgr.scheduled.length === 1); + +console.log('\n[3] the worker spends from the mirror (an NWC pay): the order dies, the change gets its own'); +const worker = await bgManager(rec, 'w1', saveFn); +await worker.send(sh(`${ALICE} -q address`), 5000); +await worker.sync(); +const change = mirrorCoins().find((v) => v.id !== coin.id); +check('change coin in the mirror', !!change, change && `${change.amountSat} sat`); +check('the spent coin\'s order is gone', !(rec.mgr.scheduled || []).some((s) => s.inputIds.includes(coin.id))); +const n2 = await tend(change.expiryHeight - (tipHeight() + 3)); +const order2 = (rec.mgr.scheduled || []).find((s) => s.inputIds.includes(change.id)); +check('the next wake covers the change coin', n2 === 1 && !!order2, JSON.stringify((rec.mgr.scheduled || []).map((s) => s.inputIds))); +check('scheduled a few blocks out', order2?.scheduledHeight === tipHeight() + 3, `${order2?.scheduledHeight} vs ${tipHeight() + 3}`); + +console.log('\n[4] the round runs with nobody online; the next wake claims it into the mirror'); +mine(3 + 2); +await sleep(15_000); +const claimed = () => (rec.mgr.actions || []).some((a) => a.type === 'refresh' && a.step === 'done'); +for (let i = 0; i < 25 && !claimed(); i++) { await tend(change.expiryHeight - (tipHeight() + 3)); mine(1); await sleep(1500); } +if (!claimed()) console.log(' actions:', JSON.stringify((rec.mgr.actions || []).map((a) => [a.type, a.step, a.lastError]))); +const renewed = mirrorCoins().find((v) => v.id !== change.id && v.id !== coin.id); +const renewedId = mirrorCoins().find((v) => v.id !== change.id && v.id !== coin.id)?.id; +check('the consumed order is replaced by one for the fresh coin, in the same wake', (rec.mgr.scheduled || []).length === 1 && !!renewedId && rec.mgr.scheduled[0].inputIds.includes(renewedId), JSON.stringify((rec.mgr.scheduled || []).map((s) => s.inputIds))); +check('the change coin is spent', rec.mgr.vtxos.find((v) => v.id === change.id)?.state === 'spent'); +check('a fresh coin sits in the mirror', !!renewed, renewed && `${renewed.amountSat} sat`); +check('worth the change minus the scheduled fee', !!renewed && renewed.amountSat === change.amountSat - order2.feeSat, `${renewed?.amountSat} vs ${change?.amountSat} - ${order2?.feeSat}`); +check('with its expiry clock restarted', !!renewed && renewed.expiryHeight > change.expiryHeight, renewed && `${change.expiryHeight} -> ${renewed.expiryHeight}`); +check('the renewal is in the mirror\'s history', (rec.mgr.movements || []).some((m) => m.type === 'refresh' && m.status === 'complete')); + +console.log('\n[5] the app returns and merges the worker\'s state'); +// what mergeBgWorkerState does on connect: additive merge, the worker's spent flips win, reconcile +const merged = mergeArkStates(app.state, rec.mgr); +const workerState = new Map(rec.mgr.vtxos.map((v) => [v.id, v.state])); +for (const v of merged.vtxos) if (workerState.get(v.id) === 'spent') v.state = 'spent'; +merged.nextKeyIndex = Math.max(merged.nextKeyIndex || 1, rec.mgr.nextKeyIndex || 1); +app.state = merged; app._save(); +await app.reconcile().catch((e) => console.log(' reconcile:', e.message)); +await app.sync(); +const appCoins = app.vtxos().filter((v) => v.state === 'spendable'); +check('the app holds the fresh coin and nothing stale', appCoins.length === 1 && appCoins[0].id === renewed?.id, JSON.stringify(appCoins.map((v) => [v.id.slice(0, 8), v.amountSat, v.state]))); +check('balance is the change minus the renewal fee', app.balance().spendableSat === change.amountSat - order2.feeSat, JSON.stringify(app.balance())); +check('the app adopts the worker\'s order for the fresh coin', (app.state.scheduled || []).length === 1 && app.state.scheduled[0].inputIds.includes(renewed?.id) && app.state.scheduled[0].unlockHash === rec.mgr.scheduled[0].unlockHash, JSON.stringify((app.state.scheduled || []).map((s) => s.inputIds))); +check('the app is not busy', app.pendingActions().length === 0, JSON.stringify(app.pendingActions().map((a) => [a.type, a.step]))); +check('the renewal shows in the app\'s history once', app.movements().filter((m) => m.type === 'refresh' && m.status === 'complete').length === 1); + +console.log(ok ? '\nALL GREEN\n' : '\nFAILURES\n'); +process.exit(ok ? 0 : 1); diff --git a/tools/nwc-budget-test.js b/tools/nwc-budget-test.js new file mode 100644 index 0000000..780f5ea --- /dev/null +++ b/tools/nwc-budget-test.js @@ -0,0 +1,52 @@ +// The NWC budget window: a UTC day, week (Monday) or month; what a +// connection spent in the window on now, counting the app's counter and the +// worker's unabsorbed spends; when it renews. Run: bun tools/nwc-budget-test.js +import { budgetWindow, budgetRenewsAt, renewalPeriod, spentInWindow } from '../src/nwc-budget.js'; + +let fails = 0; +const check = (name, ok, detail = '') => { console.log(` ${ok ? '✓' : '✗'} ${name}${detail ? ' — ' + detail : ''}`); if (!ok) fails++; }; + +// Wednesday 2026-10-14 23:30 UTC +const T = Date.UTC(2026, 9, 14, 23, 30); +check('day window is the UTC date', budgetWindow('day', T) === '2026-10-14', budgetWindow('day', T)); +check('day: half an hour later is the next day', budgetWindow('day', T + 3600_000) === '2026-10-15'); +check('week window is keyed by its Monday', budgetWindow('week', T) === 'W2026-10-12', budgetWindow('week', T)); +check('week: Sunday night is still that week', budgetWindow('week', Date.UTC(2026, 9, 18, 23, 59)) === 'W2026-10-12'); +check('week: Monday 00:00 starts the next', budgetWindow('week', Date.UTC(2026, 9, 19, 0, 0)) === 'W2026-10-19'); +check('month window is the UTC month', budgetWindow('month', T) === '2026-10'); +check('month: Nov 1 00:00 is the next', budgetWindow('month', Date.UTC(2026, 10, 1)) === '2026-11'); +check('unknown period counts as a day', budgetWindow(undefined, T) === '2026-10-14'); + +check('day renews at next midnight', budgetRenewsAt('day', T) === Date.UTC(2026, 9, 15) / 1000); +check('week renews next Monday', budgetRenewsAt('week', T) === Date.UTC(2026, 9, 19) / 1000); +check('month renews on the 1st', budgetRenewsAt('month', T) === Date.UTC(2026, 10, 1) / 1000); +check('December rolls into January', budgetRenewsAt('month', Date.UTC(2026, 11, 20)) === Date.UTC(2027, 0, 1) / 1000); +check('NIP-47 period words', renewalPeriod('day') === 'daily' && renewalPeriod('week') === 'weekly' && renewalPeriod('month') === 'monthly' && renewalPeriod(undefined) === 'daily'); + +console.log('\n[spent in the window]'); +const conn = { id: 'c1', dailySat: 10000, period: 'month', spentDate: '2026-10', spentToday: 3000 }; +{ + const r = spentInWindow(conn, [], T); + check('the app counter counts when stamped with this window', r.spent === 3000 && r.left === 7000, JSON.stringify(r)); +} +{ + const r = spentInWindow({ ...conn, spentDate: '2026-09' }, [], T); + check('a counter from last month does not', r.spent === 0 && r.left === 10000); +} +{ + const spends = [ + { connId: 'c1', amountSat: 500, feeSat: 2, ts: Date.UTC(2026, 9, 2) }, // this month, unabsorbed + { connId: 'c1', amountSat: 400, feeSat: 0, ts: Date.UTC(2026, 9, 3), absorbed: true }, // already in the counter + { connId: 'c1', amountSat: 900, feeSat: 0, ts: Date.UTC(2026, 8, 30) }, // last month + { connId: 'c2', amountSat: 800, feeSat: 0, ts: Date.UTC(2026, 9, 5) }, // another connection + ]; + const r = spentInWindow(conn, spends, T); + check('the worker adds only its own, unabsorbed spends from this window', r.spent === 3502, String(r.spent)); +} +{ + const r = spentInWindow({ id: 'c1', dailySat: 100, spentDate: '2026-10-14', spentToday: 80 }, [{ connId: 'c1', amountSat: 30, ts: T - 60_000 }], T); + check('a day budget, over: left is 0 not negative', r.spent === 110 && r.left === 0); +} + +console.log(fails ? `\n❌ ${fails} failure(s)` : '\n✅ budget windows behave'); +process.exit(fails ? 1 : 0); diff --git a/tools/nwc-settings-ui-test.js b/tools/nwc-settings-ui-test.js new file mode 100644 index 0000000..b88f9f7 --- /dev/null +++ b/tools/nwc-settings-ui-test.js @@ -0,0 +1,80 @@ +// Settings → Nostr → Nostr Wallet Connect: a connection is made with a +// budget that resets every day, week or month; the card says so, and +// Revoke keeps it (greyed out of the list) answering for a while. +// Run: bun tools/nwc-settings-ui-test.js (needs the regtest ark stack on :3535 for the card to show) +import puppeteer from './puppeteer.js'; +import { buildHtml } from '../build.js'; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let ok = true; +const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; +const html = await buildHtml({ minify: true, pwa: false }); +const server = Bun.serve({ port: 0, fetch: (req) => { + const path = new URL(req.url).pathname; + if (path.startsWith('/punks')) return new Response(Bun.file('dist' + path)); + return new Response(html, { headers: { 'content-type': 'text/html' } }); +} }); +const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); +await browser.defaultBrowserContext().overridePermissions(server.url.origin, ['notifications']); +const page = await browser.newPage(); +// a headless Chrome has no push service: make notifications look allowed so +// the connection is created (the app creates it anyway when permission is +// granted and the plumbing fails), without the real notifier in the picture +await page.evaluateOnNewDocument(() => { + try { Object.defineProperty(Notification, 'permission', { get: () => 'granted' }); Notification.requestPermission = async () => 'granted'; } catch {} + // no service worker in this build: 'ready' would never resolve and the + // Create button would hang on it. Stand in one whose push subscribe fails + // the way a browser without a push service does. + try { + Object.defineProperty(navigator.serviceWorker, 'ready', { get: () => Promise.resolve({ + pushManager: { subscribe: async () => { throw new Error('Registration failed - push service error'); }, getSubscription: async () => null }, + showNotification: async () => {}, + }) }); + } catch {} + const f = window.fetch; + window.fetch = (u, o) => (String(u).includes('nwcpush') ? Promise.reject(new Error('no notifier in the test')) : f(u, o)); +}); +const errs = []; +page.on('pageerror', (e) => errs.push(String(e))); +const logs = []; +page.on('console', (m) => logs.push(m.text())); +const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t); +const waitText = async (x, ms = 25000) => { for (let i = 0; i < ms / 250; i++) { if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; }; +const text = () => page.evaluate(() => document.body.innerText); +try { + await page.setViewport({ width: 390, height: 844, hasTouch: true }); + await page.goto(server.url.href, { waitUntil: 'domcontentloaded' }); + await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); + await page.reload({ waitUntil: 'domcontentloaded' }); + await sleep(400); + await click('create a new wallet'); await sleep(600); + await page.waitForSelector('.words .w .t'); + await click('skip verification'); + await waitText('receive', 20000); + await page.evaluate(() => { const b = [...document.querySelectorAll('button')].find((e) => e.getAttribute('aria-label') === 'Settings'); b.click(); }); await sleep(600); + await page.evaluate(() => { const b = [...document.querySelectorAll('.settings-tile')].find((e) => [...e.querySelectorAll('span')].some((x) => x.textContent.trim() === 'Nostr')); if (b) b.click(); }); await sleep(800); + check('the Wallet Connect card is there', await waitText('nostr wallet connect', 15000)); + await click('add a connection'); await sleep(400); + check('the form offers a budget period', await page.evaluate(() => { const s = document.querySelector('select.nwc-period'); return !!s && [...s.options].map((o) => o.value).join() === 'day,week,month' && s.value === 'day'; })); + check('…and says when it resets', (await text()).includes('midnight UTC')); + await page.type('input[placeholder*="App name"]', 'PullCap'); + await page.evaluate(() => { const s = document.querySelector('select.nwc-period'); s.value = 'month'; s.dispatchEvent(new Event('change', { bubbles: true })); }); + await page.evaluate(() => { const i = [...document.querySelectorAll('label.field')].find((l) => l.textContent.includes('Budget (sats)')).querySelector('input'); i.value = ''; i.dispatchEvent(new Event('input', { bubbles: true })); }); + await page.evaluate(() => { const i = [...document.querySelectorAll('label.field')].find((l) => l.textContent.includes('Budget (sats)')).querySelector('input'); i.value = '21000'; i.dispatchEvent(new Event('input', { bubbles: true })); }); + await click('create connection'); + const created = await waitText('pullcap', 10000); + if (!created) console.log('DEBUG env:', await page.evaluate(() => ({ push: 'PushManager' in window, sw: 'serviceWorker' in navigator, perm: Notification.permission, toast: document.querySelector('.toast, [class*=toast]')?.textContent })), '\nDEBUG logs:', logs.slice(-10).join('\n')); + check('the connection is created', created); + const line = (await text()).split('\n').find((l) => /\/payment/.test(l)) || ''; + check('the card reads the budget as monthly', /21,000 a month · 0 spent this month/.test(line), line); + const st = await page.evaluate(() => { const k = Object.keys(localStorage).find((x) => x.endsWith(':nwc') || x.includes('nwc')); return k; }); + const conn = await page.evaluate(() => { for (const k of Object.keys(localStorage)) { try { const v = JSON.parse(localStorage.getItem(k)); const c = v && v.conns && v.conns[0]; if (c && c.name === 'PullCap') return c; } catch {} } return null; }); + check('stored with period month and the budget', conn && conn.period === 'month' && conn.dailySat === 21000, JSON.stringify(conn && { period: conn.period, dailySat: conn.dailySat })); + await page.evaluate(() => { const e = [...document.querySelectorAll('.linklike')].find((n) => n.textContent.trim() === 'Revoke'); e.click(); }); await sleep(600); + const after = await page.evaluate(() => { for (const k of Object.keys(localStorage)) { try { const v = JSON.parse(localStorage.getItem(k)); const c = v && v.conns && v.conns[0]; if (c && c.name === 'PullCap') return c; } catch {} } return null; }); + check('Revoke dates the revocation', after && after.revoked === true && typeof after.revokedAt === 'number' && Date.now() - after.revokedAt < 60_000, JSON.stringify(after && { revoked: after.revoked, revokedAt: after.revokedAt })); + check('…and the connection leaves the list', await page.evaluate(() => ![...document.querySelectorAll('.linklike')].some((n) => n.textContent.trim() === 'Revoke') && ![...document.querySelectorAll('button')].some((b) => b.textContent.includes('Show connection string')))); + await page.screenshot({ path: process.env.SHOT || '/tmp/claude-1000/-home-adam-coinosv3/a8722639-d1b4-4c63-af48-8537d47913b1/scratchpad/nwc-settings.png' }); + check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); +} catch (e) { console.error(e); ok = false; } finally { await browser.close(); server.stop(true); } +console.log(ok ? '\n✅ budget periods in the settings card' : '\n❌ failed'); +process.exit(ok ? 0 : 1); diff --git a/tools/nwc-sw-test.js b/tools/nwc-sw-test.js index 62248a4..e3bdb7b 100644 --- a/tools/nwc-sw-test.js +++ b/tools/nwc-sw-test.js @@ -239,5 +239,136 @@ console.log('\n[sibling record hygiene]'); check('stale record keeps its coin state', saved.wStale.mgr.vtxos.length === 1); } + +console.log('\n[period budgets + get_budget]'); +{ + const { budgetWindow } = await import('../src/nwc-budget.js'); + // a monthly budget: the app's counter (mirrored, stamped with this month) plus the worker's own spends count + const rec = baseRec(); + rec.connections = [{ ...conn, period: 'month', dailySat: 2000, spentDate: budgetWindow('month'), spentToday: 1500 }]; + rec.spends = [{ connId: 'c1', amountSat: 490, feeSat: 0, ts: Date.now() }]; + const { deps, published, decryptReply } = harness({ rec }); + const handled = await respondFromBg({ type: 'nwc', event: ev(makeReq('pay_invoice', { invoice: INV21 })) }, deps); + const r = decryptReply(published[0]); + check('app counter + worker spends over the monthly budget → refused, naming the period', handled && r.error?.code === 'QUOTA_EXCEEDED' && /monthly budget \(10 sat\)/.test(r.error.message), JSON.stringify(r.error)); +} +{ + const { budgetWindow } = await import('../src/nwc-budget.js'); + const rec = baseRec(); + // a counter from LAST month and a worker spend from last month: neither counts this month + const lastMonth = new Date(); lastMonth.setUTCMonth(lastMonth.getUTCMonth() - 1); + rec.connections = [{ ...conn, period: 'month', dailySat: 2000, spentDate: budgetWindow('month', lastMonth.getTime()), spentToday: 1999 }]; + rec.spends = [{ connId: 'c1', amountSat: 1999, feeSat: 0, ts: lastMonth.getTime() }]; + rec.mgr.vtxos = []; // so the pay stops at "empty mirror" right after the budget check + const { deps, published } = harness({ rec }); + const handled = await respondFromBg({ type: 'nwc', event: ev(makeReq('pay_invoice', { invoice: INV21 })) }, deps); + check('last month\'s spending does not count this month (budget passed, mirror empty → wake)', handled === false && published.length === 0); +} +{ + const { budgetWindow, budgetRenewsAt } = await import('../src/nwc-budget.js'); + const rec = baseRec(); + rec.connections = [{ ...conn, period: 'week', dailySat: 7000, spentDate: budgetWindow('week'), spentToday: 1000 }]; + rec.spends = [{ connId: 'c1', amountSat: 200, feeSat: 1, ts: Date.now() }]; + const { deps, published, decryptReply } = harness({ rec }); + const handled = await respondFromBg({ type: 'nwc', event: ev(makeReq('get_budget')) }, deps); + const r = decryptReply(published[0]); + check('get_budget: used, total, renews_at and the period, in msat', handled && r.result?.used_budget === 1201000 && r.result?.total_budget === 7000000 && r.result?.renewal_period === 'weekly' && r.result?.renews_at === budgetRenewsAt('week'), JSON.stringify(r)); + const { deps: d2, published: p2, decryptReply: dr2 } = harness(); + await respondFromBg({ type: 'nwc', event: ev(makeReq('get_info')) }, d2); + check('get_info lists get_budget', dr2(p2[0]).result.methods.includes('get_budget')); +} + +console.log('\n[revoked connection]'); +{ + const rec = baseRec(); + rec.connections = [{ ...conn, revoked: true }]; + const { deps, published, decryptReply } = harness({ rec }); + const handled = await respondFromBg({ type: 'nwc', event: ev(makeReq('pay_invoice', { invoice: INV21 })) }, deps); + const r = decryptReply(published[0]); + check('a pay on a revoked connection is refused UNAUTHORIZED, not ignored', handled === true && r.error?.code === 'UNAUTHORIZED' && r.result_type === 'pay_invoice', JSON.stringify(r)); + const { deps: d2, published: p2, decryptReply: dr2 } = harness({ rec }); + await respondFromBg({ type: 'nwc', event: ev(makeReq('get_balance', {}, 'nip04')) }, d2); + check('…so is a balance ask, in the asker\'s scheme', dr2(p2[0]).error?.code === 'UNAUTHORIZED' && p2[0].tags.find((t) => t[0] === 'encryption')[1] === 'nip04'); +} + +console.log('\n[the mirror carries what the worker needs]'); +{ + const { buildBg } = await import('../src/nwc-bg.js'); + const keyFor = (chain, i) => `${chain}:${i}`.padEnd(8, '0'); + const mgrState = { + nextKeyIndex: 40, nextLnRecvIndex: 0, + vtxos: [{ id: 'v1', keyIndex: 7, state: 'spendable' }, { id: 'v0', keyIndex: 3, state: 'spent' }], + scheduled: [{ unlockHash: 'u1', inputIds: ['v1'], outKeyIndex: 12 }], + actions: [{ type: 'refresh', step: 'submitted', outKeyIndex: 15 }, { type: 'refresh', step: 'done', outKeyIndex: 16 }], + }; + const rec = buildBg({ ark: {}, mgrState, keyFor, connections: [{ ...conn, period: 'month', spentDate: '2026-10', spentToday: 77, revoked: true }] }); + check('a standing order\'s output key travels', rec.keys['12'] === keyFor(3, 12)); + check('a renewal in flight\'s output key travels', rec.keys['15'] === keyFor(3, 15)); + check('a finished renewal\'s does not', !rec.keys['16']); + check('the spent coin\'s key does not, the live one\'s does', !rec.keys['3'] && !!rec.keys['7']); + const c = rec.connections[0]; + check('period, the spent counter and the revocation ride along', c.period === 'month' && c.spentDate === '2026-10' && c.spentToday === 77 && c.revoked === true); + check('…and the budget period defaults to a day', buildBg({ ark: {}, mgrState, keyFor, connections: [conn] }).connections[0].period === 'day'); +} +{ + const { ArkManager } = await import('../src/ark/manager.js'); + const m = ArkManager.mergeScheduled([{ unlockHash: 'a' }, { unlockHash: 'b' }], [{ unlockHash: 'b' }, { unlockHash: 'c' }, { inputIds: [] }]); + check('standing orders merge by unlock hash', m.map((s) => s.unlockHash).join() === 'a,b,c', JSON.stringify(m)); +} + +console.log('\n[tending renewals while closed]'); +{ + const { tendRenewals } = await import('../src/nwc-respond.js'); + const { ArkManager } = await import('../src/ark/manager.js'); + const calls = []; + const orig = { init: ArkManager.prototype.init, tip: ArkManager.prototype._tipMemo, drive: ArkManager.prototype._driveScheduled, ensure: ArkManager.prototype.ensureScheduledRefreshes, refresh: ArkManager.prototype._driveRefresh }; + ArkManager.prototype.init = async function () { this.state = this.storage.load(); calls.push(['init', this.network]); return this; }; + ArkManager.prototype._tipMemo = async function () { calls.push(['tip']); return 100; }; + ArkManager.prototype._driveScheduled = async function () { + calls.push(['drive', (this.state.scheduled || []).length]); + // the round for one order ran: it is promoted — out of scheduled, into a refresh action in flight + const ran = (this.state.scheduled || []).find((s) => s.unlockHash === 'ran'); + this.state.scheduled = (this.state.scheduled || []).filter((s) => s !== ran); + if (ran) (this.state.actions ||= []).push({ id: 'r1', type: 'refresh', step: 'submitted', unlockHash: ran.unlockHash }); + }; + ArkManager.prototype._driveRefresh = async function (a) { calls.push(['claim', a.id, a.step]); a.step = 'done'; }; + ArkManager.prototype.ensureScheduledRefreshes = async function (margin, max) { calls.push(['ensure', margin, max]); return 1; }; + try { + const rec = baseRec(); + rec.key4 = 'ff'.repeat(32); + rec.mgr.nextKeyIndex = 5; + rec.keys = { 1: 'aa', 5: 'bb', 6: 'cc' }; // two upcoming indices in the window + rec.mgr.scheduled = [{ unlockHash: 'ran', inputIds: ['v1'], outKeyIndex: 2 }, { unlockHash: 'waiting', inputIds: ['v1'], outKeyIndex: 3 }]; + const saved = []; + const n = await tendRenewals({ recordsFn: async () => [{ walletKey: 'w1', rec }], saveFn: async (k, r) => saved.push(k), log: () => {} }); + check('claims what ran, then covers what is bare: orders limited to the key window', JSON.stringify(calls) === JSON.stringify([['init', 'mainnet'], ['tip'], ['drive', 2], ['claim', 'r1', 'submitted'], ['ensure', 36, 2]]), JSON.stringify(calls)); + check('one claim and one order counted, the record saved', n === 2 && saved.includes('w1')); + check('the claimed order is gone from the mirror, its claim done', rec.mgr.scheduled.length === 1 && rec.mgr.scheduled[0].unlockHash === 'waiting' && rec.mgr.actions[0].step === 'done'); + // a claim left in flight by an earlier wake (out of time, unconfirmed) is driven on by the next + calls.length = 0; + const rec5 = baseRec(); rec5.key4 = 'ff'.repeat(32); rec5.keys = { 1: 'aa' }; + rec5.mgr.actions = [{ id: 'r2', type: 'refresh', step: 'issued' }, { id: 'r3', type: 'refresh', step: 'done' }, { id: 's1', type: 'send', step: 'created' }]; + const n5 = await tendRenewals({ recordsFn: async () => [{ walletKey: 'w5', rec: rec5 }], saveFn: async () => {} }); + check('a renewal claim in flight is driven on; finished ones and other actions are not', JSON.stringify(calls) === JSON.stringify([['init', 'mainnet'], ['tip'], ['drive', 0], ['claim', 'r2', 'issued']]) && n5 === 1, JSON.stringify(calls)); + + calls.length = 0; + const rec2 = baseRec(); rec2.key4 = 'ff'.repeat(32); rec2.ark.network = 'regtest'; rec2.mgr.nextKeyIndex = 9; rec2.keys = { 1: 'aa' }; // no upcoming key + await tendRenewals({ recordsFn: async () => [{ walletKey: 'w2', rec: rec2 }], saveFn: async () => {} }); + check('no key for an order\'s output → claims still, registers nothing (regtest margin would be 6)', JSON.stringify(calls) === JSON.stringify([['init', 'regtest'], ['tip'], ['drive', 0]]), JSON.stringify(calls)); + + calls.length = 0; + const old = baseRec(); // no key4: a mirror from before invoices — can't sign for the mailbox + await tendRenewals({ recordsFn: async () => [{ walletKey: 'w3', rec: old }], saveFn: async () => {} }); + check('an old mirror is left alone', calls.length === 0); + + calls.length = 0; + const rec4 = baseRec(); rec4.key4 = 'ff'.repeat(32); + await tendRenewals({ recordsFn: async () => [{ walletKey: 'w4', rec: rec4 }], saveFn: async () => {}, deadline: Date.now() - 1 }); + check('out of push budget → nothing started', calls.length === 0); + } finally { + Object.assign(ArkManager.prototype, { init: orig.init, _tipMemo: orig.tip, _driveScheduled: orig.drive, ensureScheduledRefreshes: orig.ensure, _driveRefresh: orig.refresh }); + } +} + console.log(fails ? `\n❌ ${fails} failure(s)` : '\n✅ background responder behaves'); process.exit(fails ? 1 : 0); diff --git a/tools/nwc-test.js b/tools/nwc-test.js index 848b2c6..5b0dd10 100644 --- a/tools/nwc-test.js +++ b/tools/nwc-test.js @@ -13,12 +13,13 @@ const store = {}; globalThis.localStorage = { getItem:k=>k in store?store[k]:null, setItem:(k,v)=>{store[k]=v;}, removeItem:k=>{delete store[k];} }; let subHandler = null; +const subFilters = []; // every filter subscribed, in order let priorReplies = []; let claimOk = true; const published = []; // fake relay transport: capture the subscription handler and any replies const nwcTransport = { - subscribe: (relays, filter, on) => { subHandler = on; return () => { subHandler = null; }; }, + subscribe: (relays, filter, on) => { subFilters.push(filter); subHandler = on; return () => { subHandler = null; }; }, publish: async (relays, evt) => { published.push(evt); return true; }, query: async () => priorReplies, // what other devices have answered (none, unless a test says so) errGraceMs: 20, // the sibling-first hold, shortened for the harness @@ -222,5 +223,68 @@ console.log('\n[device sync of connections]'); check('what we publish carries the connections', Array.isArray(ext.save().nwcConns)); } + +// --------------------------------------------------------------------------- +console.log('\n[period budgets + get_budget]'); +{ + const { budgetWindow, budgetRenewsAt } = await import('../src/nwc-budget.js'); + const st = JSON.parse(store['fs:nwc']); + const c = st.conns.find((x) => x.id === 'test1'); + Object.assign(c, { period: 'month', dailySat: 2000, spentDate: budgetWindow('month'), spentToday: 1990 }); + store['fs:nwc'] = JSON.stringify(st); + f.stop(); f.init(); priorReplies = []; claimOk = true; + const wasPaid = paid.length; + r = await request('pay_invoice', { invoice: 'lnbc210n1p4xuk2wpp506wkjr0xk3677nu7je9c55vq4lzlkyd0ztcq2mlvumap0zpe3alqhp5ppg7g8qwpdv34hgpymhw446y37duzwcn388yp3pw05n7tlulyn2scqzysxqrrssrzjqv3dpepm8kfdxrk3sl6wzqdf49s9c0h9ljtjrek6c08r6aejlwcnur0dwyqqvusqqqqqqqlgqqqq86qqjqsp5dc0jrq94ke2f4dzx8c2dwqsc6a65eu56dt2j599l7kxp7q2hs6zq9qxpqysgqdjeft8gkl0uga24e502pvcp5vgsfap3dxuutcpgfaj33fffuqs9psmnrklshp3fg3py7vlnzsea90vj9ahqq5t9xuy67u3pk0sfnheqpn95f2g' }); + check('21 sat over a monthly budget with 10 left → refused, naming the month', r?.error?.code === 'QUOTA_EXCEEDED' && /monthly budget \(10 sat\)/.test(r?.error?.message || ''), JSON.stringify(r?.error)); + check('nothing was paid', paid.length === wasPaid); + r = await request('get_budget', {}); + check('get_budget reports the month', r?.result?.used_budget === 1990000 && r?.result?.total_budget === 2000000 && r?.result?.renewal_period === 'monthly' && r?.result?.renews_at === budgetRenewsAt('month'), JSON.stringify(r)); + r = await request('get_info', {}); + check('get_info lists get_budget', r?.result?.methods?.includes('get_budget')); + // last month's counter is not this month's + const st2 = JSON.parse(store['fs:nwc']); + const lm = new Date(); lm.setUTCMonth(lm.getUTCMonth() - 1); + Object.assign(st2.conns.find((x) => x.id === 'test1'), { spentDate: budgetWindow('month', lm.getTime()), spentToday: 1990 }); + store['fs:nwc'] = JSON.stringify(st2); + f.stop(); f.init(); + r = await request('get_budget', {}); + check('a counter from last month reads as nothing spent', r?.result?.used_budget === 0, JSON.stringify(r?.result)); + r = await request('pay_invoice', { invoice: INV21 }); // the mock seam pays 25 + 1 fee + check('…and a payment goes through, stamped with this month', !!r?.result?.preimage && JSON.parse(store['fs:nwc']).conns.find((x) => x.id === 'test1').spentDate === budgetWindow('month') && JSON.parse(store['fs:nwc']).conns.find((x) => x.id === 'test1').spentToday === 26, JSON.stringify(r?.error || r)); +} + +console.log('\n[revoked: refused out loud, for a while]'); +{ + const st = JSON.parse(store['fs:nwc']); + const c = st.conns.find((x) => x.id === 'test1'); + c.revoked = true; c.revokedAt = Date.now(); + store['fs:nwc'] = JSON.stringify(st); + subFilters.length = 0; + f.stop(); f.init(); + check('a lately revoked connection is still listened for', subFilters.some((x) => x.kinds?.[0] === 23194 && x['#p']?.[0] === conn.servicePk)); + const wasPaid = paid.length; + r = await request('pay_invoice', { invoice: INV21 }); + check('a pay is answered UNAUTHORIZED', r?.error?.code === 'UNAUTHORIZED' && r?.result_type === 'pay_invoice', JSON.stringify(r)); + check('nothing was paid', paid.length === wasPaid); + r = await request('get_balance', {}, 'nip04'); + check('a balance ask too, in nip04', r?.error?.code === 'UNAUTHORIZED' && r?.result_type === 'get_balance', JSON.stringify(r)); + const n = published.filter((e) => e.kind === 13194 && e.pubkey === conn.servicePk).length; + f.stop(); f.init(); await new Promise((r) => setTimeout(r, 100)); + check('no capability event is published for it', published.filter((e) => e.kind === 13194 && e.pubkey === conn.servicePk).length === n); + check('the revocation date travels in the snapshot', wallet.__ext.save().nwcConns.find((x) => x.id === 'test1').revokedAt === c.revokedAt); + // 31 days on: forgotten + const st2 = JSON.parse(store['fs:nwc']); + st2.conns.find((x) => x.id === 'test1').revokedAt = Date.now() - 31 * 86_400_000; + store['fs:nwc'] = JSON.stringify(st2); + subFilters.length = 0; + f.stop(); f.init(); + check('after the grace period it is no longer listened for', !subFilters.some((x) => x.kinds?.[0] === 23194 && x['#p']?.[0] === conn.servicePk)); + // a revocation dated on two devices keeps the earlier date + const ext = wallet.__ext; + const stale = { ...JSON.parse(store['fs:nwc']).conns.find((x) => x.id === 'test1'), revokedAt: Date.now() - 40 * 86_400_000 }; + ext.load({ nwcConns: [stale] }); + check('merge keeps the earlier revocation date', JSON.parse(store['fs:nwc']).conns.find((x) => x.id === 'test1').revokedAt === stale.revokedAt); +} + console.log(ok ? '\n✅ NWC service behaves' : '\n❌ failed'); process.exit(ok?0:1); |
