From f455d2b7228d96749ff0734fd0efa063432c85e3 Mon Sep 17 00:00:00 2001 From: Dendi Suhubdy <4477337+dendisuhubdy@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:18:08 +0800 Subject: [PATCH 1/7] =?UTF-8?q?CLI-1002:=20one=20wallet=20per=20create=20?= =?UTF-8?q?=E2=80=94=20single-flight=20backend,=20vault=20check=20repeated?= =?UTF-8?q?=20at=20the=20write,=20in-flight=20guard=20on=20the=20create=20?= =?UTF-8?q?and=20import=20forms?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A second submit while PBKDF2 was still deriving passed both existence checks: two creates succeeded with different keys, the backup screen revealed the first and the vault ended on the second. - backend-shared.js: wallet.create/import are single-flight (the identical call gets the same promise, any other is refused), and the vault is written only after re-reading that none is stored, under an exclusive Web Lock where the platform has one. Never overwrites. - onboarding.js: the create and import forms hold an in-flight guard and disable the submit button until the call settles. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01GFs5h2CVCmdBKerZzH2Xrx --- ui/engine/backend-shared.js | 82 +++++++++++++++++++++++---- ui/screens/onboarding.js | 44 +++++++++++---- ui/test/app.test.mjs | 109 ++++++++++++++++++++++++++++++++++++ ui/test/backend-cases.mjs | 83 +++++++++++++++++++++++++++ 4 files changed, 296 insertions(+), 22 deletions(-) diff --git a/ui/engine/backend-shared.js b/ui/engine/backend-shared.js index 83198f2..26a21f6 100644 --- a/ui/engine/backend-shared.js +++ b/ui/engine/backend-shared.js @@ -997,9 +997,63 @@ export function makeSharedBackend({ } } + // --------------------------------------------------------------- one wallet, made once ------- + // CLI-1002 (audit v14). The vault is written only after PBKDF2 at 600 000 iterations, so for a + // few hundred milliseconds a wallet is being made and `wallet.exists()` still says no. A second + // `create` in that window (a double click, Enter held down) used to pass the check too: both + // succeeded with DIFFERENT keys, the backup screen revealed the first and the vault, the session + // and the stored address ended on the second — a recovery key that does not open the wallet. + // + // Two rules close it, and neither relies on a screen behaving: + // + // 1. **Single flight.** While a create/import is in flight in this backend, the identical + // call is answered with the SAME promise — one keygen, one vault, one answer — and any + // other create/import is refused as if the wallet already existed, which by the time the + // caller could act on it, it does. + // 2. **The existence check is repeated at the write.** `storeNewVault` reads the vault key + // again immediately before writing it — under an exclusive Web Lock where the platform has + // one, so two tabs (or the extension's two windows) cannot both pass — and never writes + // over a vault that is there. The session is started only for a vault this call stored. + const VAULT_LOCK = 'rand-wallet-vault'; + let provisioning = null; // { key, promise } while a create/import is in flight + + function alreadyExists() { + return new Error(t('a wallet already exists on this device')); + } + + function provisionOnce(key, run) { + if (provisioning) { + // Same request, same answer. Anything else would be a second wallet. + return provisioning.key === key ? provisioning.promise : Promise.reject(alreadyExists()); + } + const flight = { key, promise: null }; + flight.promise = (async () => { + try { + return await run(); + } finally { + if (provisioning === flight) provisioning = null; + } + })(); + provisioning = flight; + return flight.promise; + } + + /** Writes `vault` only if no vault is stored — the check and the write as close as storage allows. */ + async function storeNewVault(vault) { + const write = async () => { + if (await storage.get(K.vault)) throw alreadyExists(); + await storage.set(K.vault, vault); + }; + if (locksApi && typeof locksApi.request === 'function') { + await locksApi.request(VAULT_LOCK, { mode: 'exclusive' }, write); + } else { + await write(); + } + } + async function createFrom(info, password) { const vault = await encryptSecret(password, info.spend_key); - await storage.set(K.vault, vault); + await storeNewVault(vault); // throws, having written nothing, if a wallet appeared meanwhile await storage.set(K.wallet, { address: info.address, pk: info.pk, created_ms: Date.now() }); await storage.set(K.notes, emptyNoteStore()); await clearFailures(); @@ -1013,18 +1067,24 @@ export function makeSharedBackend({ return !!(await storage.get(K.vault)); }, - async create(password) { - requirePassword(password); - if (await wallet.exists()) throw new Error(t('a wallet already exists on this device')); - const info = await c.keygen(); - return createFrom(info, password); + create(password) { + // Not `async`: the identical call in flight must get back the very same promise. + try { requirePassword(password); } catch (err) { return Promise.reject(err); } + return provisionOnce(JSON.stringify(['create', password]), async () => { + if (await wallet.exists()) throw alreadyExists(); + const info = await c.keygen(); + return createFrom(info, password); + }); }, - async import(secret, password) { - requirePassword(password); - if (await wallet.exists()) throw new Error(t('a wallet already exists on this device')); - const info = await c.importKey(String(secret || '').trim()); - return createFrom(info, password); + import(secret, password) { + try { requirePassword(password); } catch (err) { return Promise.reject(err); } + const input = String(secret || '').trim(); + return provisionOnce(JSON.stringify(['import', input, password]), async () => { + if (await wallet.exists()) throw alreadyExists(); + const info = await c.importKey(input); + return createFrom(info, password); + }); }, async unlock(password) { diff --git a/ui/screens/onboarding.js b/ui/screens/onboarding.js index b9243e5..b00860c 100644 --- a/ui/screens/onboarding.js +++ b/ui/screens/onboarding.js @@ -118,8 +118,24 @@ function wirePasswordForm(ctx, root, { mode }) { if (input.value.length >= 10) markValid(pwWrap, pwField, 'password-hint'); }); + // CLI-1002 (audit v14): one create/import at a time. The backend derives the vault key for a + // few hundred milliseconds before anything is stored, and a second submit in that window (a + // double click, Enter held down) used to start a second wallet — the backup screen then showed + // a recovery key the vault did not hold. The backend refuses that itself now; this guard is the + // screen's own half, and the disabled button is what tells the user the first click was heard. + const submitBtn = form.querySelector('button[type=submit]'); + let inFlight = false; + function setBusy(busy) { + inFlight = busy; + if (!submitBtn) return; + submitBtn.disabled = busy; + if (busy) submitBtn.setAttribute('aria-busy', 'true'); + else submitBtn.removeAttribute('aria-busy'); + } + async function onSubmit(evt) { evt.preventDefault(); + if (inFlight) return; let ok = true; if (keyField) { if (!keyField.value.trim()) { markInvalid(keyWrap, keyField, 'key-error'); ok = false; } @@ -132,17 +148,20 @@ function wirePasswordForm(ctx, root, { mode }) { } else markValid(confirmWrap, confirmField, 'confirm-hint'); if (!ok) return; - // Defence in depth: resolveRoute already refuses to route here once a wallet exists, so this - // should be unreachable in normal use — but this handler must never call wallet.create/import - // a second time over an existing wallet (that overwrites, i.e. destroys, the current keys), - // so it checks again itself rather than trust routing alone. - if (await ctx.backend.wallet.exists()) { - ctx.toast(t('A wallet already exists on this device.'), { kind: 'negative' }); - ctx.go('#home'); - return; - } - + // Taken synchronously, before the first await: a second submit event dispatched in the same + // turn finds it set. + setBusy(true); try { + // Defence in depth: resolveRoute already refuses to route here once a wallet exists, so this + // should be unreachable in normal use — but this handler must never call wallet.create/import + // a second time over an existing wallet (that overwrites, i.e. destroys, the current keys), + // so it checks again itself rather than trust routing alone. + if (await ctx.backend.wallet.exists()) { + ctx.toast(t('A wallet already exists on this device.'), { kind: 'negative' }); + ctx.go('#home'); + return; + } + // Through the shell, not backend.wallet.create/import directly: a new wallet is a new // session, and ctx.createWallet/importWallet start it *before* this returns, so #backup // below renders inside the new session (and can still read its own spend key). @@ -151,12 +170,15 @@ function wirePasswordForm(ctx, root, { mode }) { pwField.value = ''; confirmField.value = ''; if (keyField) keyField.value = ''; - ctx.go('#backup'); + // Awaited, so the button stays disabled until this form has been replaced by #backup. + await ctx.go('#backup'); } catch (err) { const message = (err && err.message) || t('Could not create the wallet.'); pwWrap.querySelector('.error').textContent = message; markInvalid(pwWrap, pwField, 'password-error'); ctx.toast(message, { kind: 'negative' }); + } finally { + setBusy(false); } } form.addEventListener('submit', onSubmit); diff --git a/ui/test/app.test.mjs b/ui/test/app.test.mjs index b8b6cf7..2f28383 100644 --- a/ui/test/app.test.mjs +++ b/ui/test/app.test.mjs @@ -422,3 +422,112 @@ test('a screen that bypasses the helpers and calls backend.wallet.lock() still e assert.ok(app.session.id > before); assert.equal(ctx.state.sentinel, undefined); }); + +// ------------------------------------------------- CLI-1002 (audit v14): the double submit ---- +// A double click (or Enter twice) on "Create wallet" used to start two creates. With a backend +// that writes its vault only after a slow key derivation — the real one's PBKDF2 at 600 000 +// iterations — both succeeded with different keys: the backup screen revealed the first and the +// vault ended on the second. `racyWalletBackend` is that backend, reduced to the race: nothing in +// it refuses a second create, so only the screen's own in-flight guard can make these pass. +function racyWalletBackend() { + const vault = { key: null, address: null }; + let session = null; + let made = 0; + const provision = async (key) => { + const exists = !!vault.key; // the existence check… + await new Promise((r) => setTimeout(r, 25)); // …the slow derivation… + if (exists) throw new Error('a wallet already exists on this device'); + vault.key = key; // …and only then the write: last writer wins + vault.address = `rand1${key}`; + session = key; + return { address: vault.address, pk: key }; + }; + const b = fakeBackend({ + wallet: { + exists: () => !!vault.key, + isUnlocked: () => session !== null, + create: () => { made += 1; return provision(`key${made}-${'k'.repeat(40)}`); }, + import: (secret) => { made += 1; return provision(`${secret}-${made}`); }, + info: () => ({ address: vault.address, pk: vault.key }), + exportSpendKey: () => session, + }, + }); + return { b, vault }; +} + +const submitOnce = (root) => root.querySelector('form').dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })); +const settle = (ms = 80) => new Promise((r) => setTimeout(r, ms)); + +/** Holds the reveal button for longer than its 650 ms and returns the key the screen wrote. */ +async function revealBackupKey(root) { + root.querySelector('[data-role="hold"]').dispatchEvent(new Event('pointerdown', { bubbles: true, cancelable: true })); + await settle(720); + return root.querySelector('[data-role="key"]').textContent; +} + +test('CLI-1002: a double submit on Create wallet makes one backend call, and the key backed up is the vault\'s', async (t) => { + const { b, vault } = racyWalletBackend(); + const { app, root } = await mountApp(t, b); + await app.go('#create'); + root.querySelector('input[name=password]').value = 'correct horse battery'; + root.querySelector('input[name=confirm]').value = 'correct horse battery'; + const button = root.querySelector('form button[type=submit]'); + + submitOnce(root); + submitOnce(root); // the second click, 0 ms later + await Promise.resolve(); + assert.equal(button.disabled, true, 'the button is disabled while the wallet is being made'); + assert.equal(button.getAttribute('aria-busy'), 'true'); + await settle(); + await app.idle(); + + assert.equal(b.calls.filter((c) => c[0] === 'wallet.create').length, 1, 'one create reached the backend'); + assert.match(location.hash, /^#backup/); + const revealed = await revealBackupKey(root); + assert.ok(revealed && revealed === vault.key, `the key revealed (${revealed}) is the key in the vault (${vault.key})`); + // …and the confirmation the screen accepts is of that same key. + root.querySelector('input[name=check]').value = vault.key.slice(0, 4); + root.querySelector('[data-role="check-form"]').dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })); + await app.idle(); + assert.match(location.hash, /^#home/); +}); + +test('CLI-1002: a double submit on Import wallet makes one backend call', async (t) => { + const { b, vault } = racyWalletBackend(); + const { app, root } = await mountApp(t, b); + await app.go('#import'); + root.querySelector('textarea[name=key]').value = 'imported-recovery-key'; + root.querySelector('input[name=password]').value = 'correct horse battery'; + root.querySelector('input[name=confirm]').value = 'correct horse battery'; + const button = root.querySelector('form button[type=submit]'); + submitOnce(root); + submitOnce(root); + await Promise.resolve(); + assert.equal(button.disabled, true); + await settle(); + await app.idle(); + assert.equal(b.calls.filter((c) => c[0] === 'wallet.import').length, 1, 'one import reached the backend'); + assert.equal(vault.key, 'imported-recovery-key-1'); + assert.match(location.hash, /^#backup/); +}); + +test('CLI-1002: a create the backend refuses re-enables the button, so the user can try again', async (t) => { + let fail = true; + const b = fakeBackend({ + wallet: { create: async () => { if (fail) throw new Error('storage is full'); return { address: 'rand1x', pk: 'x' }; } }, + }); + const { app, root } = await mountApp(t, b); + await app.go('#create'); + root.querySelector('input[name=password]').value = 'correct horse battery'; + root.querySelector('input[name=confirm]').value = 'correct horse battery'; + const button = root.querySelector('form button[type=submit]'); + submitOnce(root); + await settle(20); + assert.equal(button.disabled, false, 'a failed create leaves the form usable'); + assert.equal(button.hasAttribute('aria-busy'), false); + assert.match(location.hash, /^#create/); + fail = false; + submitOnce(root); + await settle(20); + assert.equal(b.calls.filter((c) => c[0] === 'wallet.create').length, 2, 'the retry reaches the backend'); +}); diff --git a/ui/test/backend-cases.mjs b/ui/test/backend-cases.mjs index 40b0e12..9144be5 100644 --- a/ui/test/backend-cases.mjs +++ b/ui/test/backend-cases.mjs @@ -81,6 +81,89 @@ const scoped = (name, fn) => test(`${label}: ${name}`, fn); await assert.rejects(() => backend.wallet.create(PASSWORD), /already exists/); }); + // ---- CLI-1002 (audit v14): a double click on "Create wallet" must not make two wallets ---- + // The vault is written only after PBKDF2 at 600 000 iterations, so a second `create` used to + // pass the existence check while the first was still deriving: both succeeded with different + // keys, the backup screen revealed one and the vault ended on the other. + /** A core whose every `keygen` is a different wallet, as the real one's is. */ + function distinctKeysCore(overrides = {}) { + let n = 0; + const infoOf = (i) => ({ spend_key: `spend-key-${i}-${'ab'.repeat(16)}`, viewing_key: `viewing-key-${i}`, pk: `pk-${i}`, address: `rand1wallet${i}`, key_file: '{"version":2}' }); + const byKey = (spend_key) => infoOf(Number(String(spend_key).split('-')[2])); + return stubCore({ + keygen: () => { n += 1; return infoOf(n); }, + wallet_info: ({ spend_key }) => byKey(spend_key), + import_key: ({ input }) => byKey(input), + ...overrides, + }); + } + const vaultWrites = (storage) => storage.writes.filter(([key]) => key === 'vault'); + + scoped('CLI-1002: two concurrent creates make ONE wallet, and the key revealed opens the vault', async () => { + const core = distinctKeysCore(); + const { backend, storage } = build({ core }); + const results = await Promise.allSettled([backend.wallet.create(PASSWORD), backend.wallet.create(PASSWORD)]); + const made = results.filter((r) => r.status === 'fulfilled').map((r) => r.value); + assert.ok(made.length >= 1, 'the first create succeeds'); + assert.equal(new Set(made.map((m) => m.address)).size, 1, 'every caller that was answered was answered with the same wallet'); + assert.equal(core.calls.filter(([m]) => m === 'keygen').length, 1, 'one key was generated'); + assert.equal(vaultWrites(storage).length, 1, 'one vault was written'); + + // What the backup screen reveals is the key the vault holds, the session holds and the stored + // address names. + const revealed = await backend.wallet.exportSpendKey(); + assert.equal((await backend.wallet.info()).address, made[0].address); + await backend.wallet.lock(); + const reopened = await backend.wallet.unlock(PASSWORD); + assert.equal(reopened.address, made[0].address, 'the vault opens to the wallet that was shown'); + assert.equal(await backend.wallet.exportSpendKey(), revealed, 'the revealed key is the vault\'s key'); + }); + + scoped('CLI-1002: a second create that differs from the one in flight is refused, and changes nothing', async () => { + const core = distinctKeysCore(); + const { backend, storage } = build({ core }); + const first = backend.wallet.create(PASSWORD); + await assert.rejects(() => backend.wallet.create(`${PASSWORD}-another`), /already exists/); + await assert.rejects(() => backend.wallet.import('spend-key-9-zz', PASSWORD), /already exists/); + const made = await first; + assert.equal(vaultWrites(storage).length, 1); + assert.equal(core.calls.filter(([m]) => m === 'keygen' || m === 'import_key').length, 1); + await backend.wallet.lock(); + assert.equal((await backend.wallet.unlock(PASSWORD)).address, made.address); + // …and once it has landed, the guard is released: a later create is refused for the ordinary reason. + await assert.rejects(() => backend.wallet.create(PASSWORD), /already exists/); + }); + + scoped('CLI-1002: two concurrent imports of one key make one wallet', async () => { + const core = distinctKeysCore(); + const { backend, storage } = build({ core }); + const key = 'spend-key-4-imported'; + const results = await Promise.allSettled([backend.wallet.import(key, PASSWORD), backend.wallet.import(key, PASSWORD)]); + assert.ok(results.some((r) => r.status === 'fulfilled')); + assert.equal(vaultWrites(storage).length, 1, 'one vault was written'); + assert.equal(core.calls.filter(([m]) => m === 'import_key').length, 1); + assert.equal((await backend.wallet.info()).address, 'rand1wallet4'); + }); + + scoped('CLI-1002: a vault that appears while the key is being derived is never overwritten', async () => { + // Another context (a second tab, the extension's other window) finished its own create between + // this one's existence check and its write. The check is repeated at the write. + const theirs = { v: 1, kdf: 'pbkdf2-sha256', iter: 600000, salt: 'theirs', iv: 'theirs', ct: 'theirs' }; + let storage; + const core = distinctKeysCore({ + keygen: () => { + storage.local.set('vault', theirs); // after create()'s first check, before its write + return { spend_key: `spend-key-1-${'ab'.repeat(16)}`, viewing_key: 'viewing-key-1', pk: 'pk-1', address: 'rand1wallet1', key_file: '{}' }; + }, + }); + const env = build({ core }); + storage = env.storage; + await assert.rejects(() => env.backend.wallet.create(PASSWORD), /already exists/); + assert.deepEqual(storage.local.get('vault'), theirs, 'the other wallet\'s vault is untouched'); + assert.equal(vaultWrites(storage).length, 0); + assert.equal(await env.backend.wallet.isUnlocked(), false, 'and no session was started for a wallet that was not stored'); + }); + scoped('unlock rejects a wrong password with a constant message, and the delay grows', async (t) => { t.mock.timers.enable({ apis: ['setTimeout'] }); const { backend, storage } = build(); From c5e0662a950d5c99d0766c3359e64a0ce157e7d8 Mon Sep 17 00:00:00 2001 From: Dendi Suhubdy <4477337+dendisuhubdy@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:21:11 +0800 Subject: [PATCH 2/7] CLI-1001: the note-store merge is monotone, and shells without a conditional write merge instead of overwrite - A lost conditional write merged notes by index and kept the winner's copy whole, dropping the loser's spent flags and pending marks while the height cursor was kept: a spent note stayed spendable until a rescan. Notes now merge mark by mark (spent OR, pending kept), submissions only move forward, and the merged scanned_height is the nearer cursor when the further-read side did not hold every note. - The extension and desktop shells have no compareAndSet, so a scan that straddled a send's save wrote its stale copy over the submission record. The engine now keeps the same conditional-write contract itself (write_seq, read-compare-write under an in-process lock) and merges on a lost race. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01GFs5h2CVCmdBKerZzH2Xrx --- ui/engine/wallet.js | 177 ++++++++++++++++++++++++--------- ui/test/engine-wallet.test.mjs | 152 ++++++++++++++++++++++++++++ 2 files changed, 283 insertions(+), 46 deletions(-) diff --git a/ui/engine/wallet.js b/ui/engine/wallet.js index a0efec5..1af2f34 100644 --- a/ui/engine/wallet.js +++ b/ui/engine/wallet.js @@ -303,16 +303,73 @@ export function assetIndexes(store) { return [...new Set((store.notes || []).map((n) => Number(n.asset) || 0))].sort((a, b) => a - b); } +/** + * Merges notes into `store` by leaf index, **monotonically** (CLI-1001, audit v14): a note both + * sides hold keeps the store's copy, but never loses a mark the other side put on it. A spent flag + * is evidence (a nullifier some scan read), and a pending mark is a send that may still land; the + * side that lacks one has simply not seen it yet. Keeping one copy whole dropped the other's mark + * while the height cursor that covered it was kept — a spent note offered as spendable until a + * rescan. A mark kept one scan too long costs nothing: the next scan clears a pending mark through + * `pending_cleared` exactly as it would have. + */ function mergeNotes(store, received) { for (const n of received) { - const i = store.notes.findIndex((x) => x.index === n.index); - if (i < 0) store.notes.push(n); + const mine = store.notes.find((x) => x.index === n.index); + if (!mine) { store.notes.push(n); continue; } + if (n.spent) mine.spent = true; + if (mine.pending == null && n.pending != null) mine.pending = n.pending; } } function mergeSent(store, sent) { for (const s of sent) if (!store.sent.some((x) => x.index === s.index)) store.sent.push(s); } +/** A submission only ever moves forward: pending, then expired or (on evidence) committed. */ +const SUBMISSION_RANK = { pending: 0, expired: 1, committed: 2 }; +function mergeSubmissions(store, submissions) { + for (const sub of submissions) { + const mine = store.submissions.find((x) => x.hash === sub.hash); + if (!mine) { store.submissions.push(sub); continue; } + if ((SUBMISSION_RANK[sub.status] ?? 0) > (SUBMISSION_RANK[mine.status] ?? 0)) mine.status = sub.status; + if (!mine.height && sub.height) mine.height = sub.height; + } +} + +/** + * Folds `st` — a writer's view that lost a race — into `fresh`, the store that won it. Every part + * is a union, so doing it twice is a no-op and nothing either side learned is lost. + * + * The cursors: `scanned_index` and `scanned_attest_height` take the further of the two, because + * the notes each side found below its own cursor are all in the union. `scanned_height` is + * different. It says "every nullifier below here was compared with this store's notes", and that + * is true of the merged notes only if the side that read further HELD them all: a note the other + * side found was never compared with those heights. Then the merged cursor is the nearer of the + * two — a cursor that moves down only costs reading those heights again. + */ +function mergeStores(fresh, st) { + const cur = (v) => (isCursor(v) ? v : 0); + const freshHas = new Set(fresh.notes.map((n) => n.index)); + const stHas = new Set(st.notes.map((n) => n.index)); + const freshLacks = st.notes.some((n) => !freshHas.has(n.index)); + const stLacks = fresh.notes.some((n) => !stHas.has(n.index)); + mergeNotes(fresh, st.notes); + mergeSent(fresh, st.sent); + mergeSubmissions(fresh, st.submissions); + Object.assign(fresh.block_times, st.block_times); + Object.assign(fresh.note_tx, st.note_tx); + for (const key of ['scanned_index', 'scanned_attest_height']) fresh[key] = Math.max(cur(fresh[key]), cur(st[key])); + const fh = cur(fresh.scanned_height); + const sh = cur(st.scanned_height); + const furtherLacks = fh > sh ? freshLacks : (sh > fh ? stLacks : false); + fresh.scanned_height = furtherLacks ? Math.min(fh, sh) : Math.max(fh, sh); + fresh.reset_epoch = Math.max(fresh.reset_epoch || 0, st.reset_epoch || 0); + fresh.head = isCursor(st.head) ? st.head : cur(fresh.head); + fresh.chain_id = st.chain_id ?? fresh.chain_id ?? null; + fresh.genesis = st.genesis ?? fresh.genesis ?? null; + fresh.last_sync_ms = Math.max(Number(fresh.last_sync_ms) || 0, Number(st.last_sync_ms) || 0); + return fresh; +} + /** The shape ui/ recognises as "this was cancelled", not "the node failed" (ui/backend.js). */ export function abortError() { const err = new Error(t('The operation was aborted.')); @@ -333,6 +390,9 @@ export function isStaleStoreError(err) { return !!err && err.name === 'StaleStoreError'; } +/** How many times one save is merged and retried after losing a race before it gives up. */ +const MERGE_RETRIES = 3; + function staleAfterRetry() { const err = new Error(t('another tab changed this wallet while it was syncing; try again')); err.retryable = true; @@ -533,56 +593,81 @@ export function makeWallet({ core, store, rpc, settings, annotate = true, onRese throw new Error(`refusing to save the note store: ${key} moved backwards, ${previous[key]} → ${st[key]}`); } } - const clean = {}; - for (const [key, value] of Object.entries(st)) if (!TRANSIENT.includes(key)) clean[key] = value; - - if (typeof store.compareAndSet !== 'function') { - await store.setNoteStore(clean); - return st; - } - try { - st.rev = await store.compareAndSet(clean, st.rev); - return st; - } catch (err) { - if (!isStaleStoreError(err)) throw err; - // A RESET is never merged. Merging a reset into the winner's store is exactly how a rescan - // silently no-ops: the cursors get re-maxed and the notes re-added. `rescan` catches this, - // re-reads and applies the reset to the new store instead. - if (reset) throw err; - // Another tab wrote while this scan was running. Take its store, re-apply this scan's own - // findings onto it (every merge here is by index, so doing it twice is a no-op) and try - // once more. A second loss means the tabs are fighting; that is the user's to retry. - const fresh = await loadStore(); - if (!reset && (fresh.reset_epoch || 0) > (st.reset_epoch || 0)) { - const stop = new Error(t('this wallet was rescanned while the scan was running; the scan was discarded')); - stop.name = 'StoreResetError'; - stop.retryable = true; - throw stop; - } - mergeNotes(fresh, st.notes); - mergeSent(fresh, st.sent); - for (const sub of st.submissions) if (!fresh.submissions.some((x) => x.hash === sub.hash)) fresh.submissions.push(sub); - Object.assign(fresh.block_times, st.block_times); - Object.assign(fresh.note_tx, st.note_tx); - for (const key of WORK_CURSORS) fresh[key] = Math.max(isCursor(fresh[key]) ? fresh[key] : 0, st[key]); - fresh.reset_epoch = Math.max(fresh.reset_epoch || 0, st.reset_epoch || 0); - fresh.head = isCursor(st.head) ? st.head : (isCursor(fresh.head) ? fresh.head : 0); - fresh.chain_id = st.chain_id ?? fresh.chain_id ?? null; - fresh.genesis = st.genesis ?? fresh.genesis ?? null; - fresh.last_sync_ms = Math.max(Number(fresh.last_sync_ms) || 0, Number(st.last_sync_ms) || 0); - const merged = {}; - for (const [key, value] of Object.entries(fresh)) if (!TRANSIENT.includes(key)) merged[key] = value; + const cleanOf = (value) => { + const clean = {}; + for (const [key, v] of Object.entries(value)) if (!TRANSIENT.includes(key)) clean[key] = v; + return clean; + }; + for (let attempt = 0; ; attempt += 1) { try { - const rev = await store.compareAndSet(merged, fresh.rev); - Object.assign(st, fresh, { rev }); + await conditionalWrite(cleanOf(st), st); return st; - } catch (again) { - if (isStaleStoreError(again)) throw staleAfterRetry(); - throw again; + } catch (err) { + if (!isStaleStoreError(err)) throw err; + // A RESET is never merged. Merging a reset into the winner's store is exactly how a rescan + // silently no-ops: the cursors get re-maxed and the notes re-added. `rescan` catches this, + // re-reads and applies the reset to the new store instead. + if (reset) throw err; + // Losing again and again means the writers are fighting; that is the user's to retry. + if (attempt >= MERGE_RETRIES) throw staleAfterRetry(); + // Somebody else wrote while this one was working — another tab, or (CLI-1001) a send that + // saved its submission while this scan was on the network. Take their store and fold this + // writer's findings into it: every merge is a union (`mergeStores`), so nothing either + // side learned is lost and doing it twice is a no-op. + const fresh = await loadStore(); + if ((fresh.reset_epoch || 0) > (st.reset_epoch || 0)) { + const stop = new Error(t('this wallet was rescanned while the scan was running; the scan was discarded')); + stop.name = 'StoreResetError'; + stop.retryable = true; + throw stop; + } + mergeStores(fresh, st); + // `fresh` carries the revision it was read at, which is what the next attempt is held to. + Object.assign(st, fresh); + // A merge may move `scanned_height` DOWN (see `mergeStores`), on purpose. The caller's + // "before" snapshot is only this function's monotonicity reference, so it follows. + if (previous) for (const key of WORK_CURSORS) if (isCursor(previous[key])) previous[key] = Math.min(previous[key], st[key]); } } } + /** + * One conditional write of the note store: it lands only if nobody wrote since `st` was loaded, + * and otherwise rejects with a `StaleStoreError` for `persist` to merge and retry. + * + * Where the shell's storage has `compareAndSet` (web/wallet/idb.js: one IndexedDB transaction) + * that is the whole of it. Where it has not — the extension and the desktop shell, a plain + * get/set — the same contract is kept HERE (CLI-1001): the store carries a `write_seq`, bumped + * by every write, and the read-compare-write runs under this engine's own lock, so a scan and a + * send of one backend can no longer overwrite each other. It is not a transaction — two + * processes can still interleave between the read and the write — but the window is those two + * storage calls rather than the whole length of a scan. + */ + let writeChain = Promise.resolve(); + function exclusive(fn) { + const run = writeChain.then(fn, fn); + writeChain = run.catch(() => {}); + return run; + } + async function conditionalWrite(clean, st) { + if (typeof store.compareAndSet === 'function') { + st.rev = await store.compareAndSet(clean, st.rev); + return; + } + await exclusive(async () => { + const current = (await store.getNoteStore()) || {}; + const found = isCursor(current.write_seq) ? current.write_seq : 0; + const expected = isCursor(st.write_seq) ? st.write_seq : 0; + if (found !== expected) { + const err = new Error(`the note store changed underneath this write (expected write ${expected}, found ${found})`); + err.name = 'StaleStoreError'; + throw err; + } + await store.setNoteStore({ ...clean, write_seq: found + 1 }); + st.write_seq = found + 1; + }); + } + /** * Bridge deposits this wallet can rebuild from committed blocks it has not read yet. * diff --git a/ui/test/engine-wallet.test.mjs b/ui/test/engine-wallet.test.mjs index e1289f4..4425cea 100644 --- a/ui/test/engine-wallet.test.mjs +++ b/ui/test/engine-wallet.test.mjs @@ -1175,3 +1175,155 @@ test('on a chain with bridge fees the recipient rebuilds its fee notes, a burn\' assert.equal(placed.index, 0); assert.equal(placed.amount, '22000'); }); + +// ====================================================== CLI-1001 (audit v14): monotone merges === +// A note's spent flag and its pending mark, and a submission record, are things one writer KNOWS +// and another may not have seen yet. A merge that keeps one side's copy of a note by index drops +// what the other side learned about it — a spent note shown as spendable until a rescan, because +// the height cursor that covered its nullifier was kept all the same. + +/** A note store with the optional conditional write, as web/wallet/idb.js provides it. */ +function casStore(initial = emptyNoteStore()) { + const backing = memoryStore(initial); + let rev = 0; + const hooks = { beforeWrite: null }; + return { + backing, hooks, + get rev() { return rev; }, + /** Another tab's write: applies `change` to what is stored and moves the revision. */ + async otherTabWrites(change) { + const current = await backing.getNoteStore(); + await backing.setNoteStore(change(current) || current); + rev += 1; + }, + async getNoteStore() { return { ...(await backing.getNoteStore()), rev }; }, + async setNoteStore(s) { await backing.setNoteStore(s); }, + async compareAndSet(value, expectedRev) { + if (hooks.beforeWrite) { const fn = hooks.beforeWrite; hooks.beforeWrite = null; await fn(); } + if (expectedRev !== rev) { const err = new Error('stale'); err.name = 'StaleStoreError'; throw err; } + rev += 1; + await backing.setNoteStore(value); + return rev; + }, + }; +} + +const ownedNote = (index, extra = {}) => ({ + index, note: '00'.repeat(112), cm: HEX64(`c${index}`), nf: HEX64(`f${index}`), + amount: '5000', asset: 0, time: 4, from: '00'.repeat(32), height: 4, spent: false, pending: null, ...extra, +}); + +test('CLI-1001: a lost conditional write keeps the spent flag the losing scan found', async () => { + const store = casStore({ ...emptyNoteStore(), notes: [ownedNote(0)], chain_id: 13, genesis: GENESIS_A }); + const client = stubClient({ nullifiers: (from) => (from <= 5 ? [{ height: 5, nullifier: HEX64('f0') }] : []) }); + const wallet = makeWallet({ core: stubCore(), store, rpc: () => client, settings: async () => ({}), annotate: false }); + // Another tab saves (anything at all) between this scan's load and its one save. + store.hooks.beforeWrite = () => store.otherTabWrites((s) => { s.last_sync_ms = 1; }); + + const st = await wallet.scan(SPEND_KEY, {}); + assert.equal(store.backing.current.notes[0].spent, true, 'the spent flag was dropped by the merge while the cursor was kept'); + assert.equal(st.notes[0].spent, true); + assert.equal(store.backing.current.scanned_height, 21, 'and the cursor covers the height the flag came from'); +}); + +test('CLI-1001: a lost conditional write keeps a send\'s pending marks and its submission record', async () => { + const store = casStore({ ...emptyNoteStore(), notes: [ownedNote(0), ownedNote(1)], chain_id: 13, genesis: GENESIS_A }); + const wallet = makeWallet({ core: stubCore(), store, rpc: () => stubClient(), settings: async () => ({}), annotate: false }); + // The send's own save: load, mark the inputs pending, record the submission… + const fresh = await wallet.loadStore(); + fresh.notes[0].pending = 7; + fresh.submissions.unshift({ hash: HEX64('ab'), status: 'pending', spent_indices: [0], time: 7, amount: '1' }); + // …and a scan in another tab lands first, with neither. + await store.otherTabWrites((s) => { s.scanned_height = 9; }); + await wallet.persist(fresh); + + const saved = store.backing.current; + assert.equal(saved.notes[0].pending, 7, 'the pending mark was dropped: the note is offered to the next send again'); + assert.equal(saved.notes[1].pending, null); + assert.equal(saved.submissions.length, 1); + assert.equal(saved.scanned_height, 9); +}); + +test('CLI-1001: the merge never un-spends, never un-pends and never moves a submission back to pending', async () => { + const store = casStore({ + ...emptyNoteStore(), chain_id: 13, genesis: GENESIS_A, + notes: [ownedNote(0), ownedNote(1)], + submissions: [{ hash: HEX64('ab'), status: 'pending', spent_indices: [0], time: 7 }], + }); + const wallet = makeWallet({ core: stubCore(), store, rpc: () => stubClient(), settings: async () => ({}), annotate: false }); + const mine = await wallet.loadStore(); + // The winner learned: note 0 is spent, note 1 is pending, the submission committed at 12. + await store.otherTabWrites((s) => { + s.notes[0].spent = true; + s.notes[1].pending = 9; + s.submissions[0].status = 'committed'; + s.submissions[0].height = 12; + }); + // The loser knows none of it and saves its own, older view. + await wallet.persist(mine); + const saved = store.backing.current; + assert.equal(saved.notes[0].spent, true); + assert.equal(saved.notes[1].pending, 9); + assert.deepEqual([saved.submissions[0].status, saved.submissions[0].height], ['committed', 12]); +}); + +test('CLI-1001: a merged height cursor does not cover a note the further-read side never had', async () => { + // This scan read nullifiers through height 20 and knows note 0 only. Another tab, at height 3, + // found note 1. Nobody has compared note 1 with the nullifiers of heights 3..20, so the merged + // cursor must not claim they were read. + const store = casStore({ ...emptyNoteStore(), notes: [ownedNote(0)], chain_id: 13, genesis: GENESIS_A, scanned_height: 3 }); + const wallet = makeWallet({ core: stubCore(), store, rpc: () => stubClient(), settings: async () => ({}), annotate: false }); + store.hooks.beforeWrite = () => store.otherTabWrites((s) => { s.notes.push(ownedNote(1)); }); + await wallet.scan(SPEND_KEY, {}); + assert.equal(store.backing.current.notes.length, 2); + assert.equal(store.backing.current.scanned_height, 3, 'the cursor passed heights whose nullifiers were never compared with note 1'); + // The next scan reads them again and catches up; a regressed cursor is not an error. + const next = await wallet.scan(SPEND_KEY, {}); + assert.equal(next.scanned_height, 21); +}); + +test('CLI-1001: without a conditional write, a scan that straddles a send\'s save keeps the submission record', async () => { + // The extension and the desktop shell: storage is a plain get/set. The scan loads the store, + // spends a long time on the network, and used to write its own copy back over whatever a send + // had saved meanwhile — the submission record and the pending marks with it. + const store = memoryStore({ ...emptyNoteStore(), notes: [ownedNote(0)], chain_id: 13, genesis: GENESIS_A }); + let release; + const gate = new Promise((r) => { release = r; }); + let reached; + const atNullifiers = new Promise((r) => { reached = r; }); + const client = stubClient({ + nullifiers: async () => { reached(); await gate; return []; }, + sendTransaction: () => HEX64('dd'), + }); + const core = stubCore({ parse_address: () => ({ valid: true, pk: HEX64('99') }) }); + const wallet = makeWallet({ core, store, rpc: () => client, settings: async () => ({}), annotate: false }); + + const scanning = wallet.scan(SPEND_KEY, {}); + await atNullifiers; // the scan has loaded the store and is waiting on the node + const submission = await wallet.completeSend(SPEND_KEY, PROVED, { to: 'rand1payee', wait: false, client }); + assert.equal(store.current.submissions.length, 1, 'the send saved its record'); + release(); + await scanning; + + assert.equal(store.current.submissions.length, 1, 'the scan\'s save erased the submission record'); + assert.equal(store.current.submissions[0].hash, submission.hash); + assert.equal(store.current.notes[0].pending, PROVED.time, 'and the pending mark on the note it spends'); + assert.equal(store.current.scanned_height, 21, 'while the scan\'s own work is kept too'); +}); + +test('CLI-1001: without a conditional write, two saves of one loaded store do not overwrite each other', async () => { + const store = memoryStore({ ...emptyNoteStore(), notes: [ownedNote(0), ownedNote(1)], chain_id: 13, genesis: GENESIS_A }); + const wallet = makeWallet({ core: stubCore(), store, rpc: () => stubClient(), settings: async () => ({}), annotate: false }); + const a = await wallet.loadStore(); + const b = await wallet.loadStore(); + a.notes[0].spent = true; + b.notes[1].pending = 4; + await Promise.all([wallet.persist(a), wallet.persist(b)]); + assert.equal(store.current.notes[0].spent, true); + assert.equal(store.current.notes[1].pending, 4); + // A lone writer still clears what it means to clear: nothing else wrote, so nothing is merged back. + const c = await wallet.loadStore(); + c.notes[1].pending = null; + await wallet.persist(c); + assert.equal(store.current.notes[1].pending, null); +}); From e3216c5d401299e7178237cea14d26ad01a465f1 Mon Sep 17 00:00:00 2001 From: Dendi Suhubdy <4477337+dendisuhubdy@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:26:45 +0800 Subject: [PATCH 3/7] VK-751: a note is Sent only when its creator is this wallet; a chain-fixed creator is "sent, sender unverified"; anything else is dropped The sender part of an envelope opens under the viewing key, which is handed out (delegated prover, auditor), so its holder could plant sent payments in the wallet's history. The bundle guest commits every output with from = the spender's pk, which the holder cannot choose. - ui/engine/wallet.js: the scan judges every row whose sender part opened by its creator (sentRole): own pk -> Sent; zero / rpl-mint / rpl2-pay / rpl3-pay -> kept with unverified: true, its own activity kind, never matched to a submission; anything else, a row with no creator included, is dropped. A page replaces what was stored for its leaves, so a rescan removes rows an older build kept. - backend-shared.js, lib/rows.js, backend.js, locales: the new 'out-unverified' activity kind and its title in all 20 languages. - core/crates/wallet-core: classify applies the same rule; scan_page reports `from` on every sent row and the unverified ones in their own list (sent_unverified), so the mobile apps, which read `sent` alone, never count one. Two tests added. NOT compiled or run here: the vendored node is not checked out in this worktree. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01GFs5h2CVCmdBKerZzH2Xrx --- core/crates/wallet-core/src/lib.rs | 141 +++++++++++++++++++++--- ui/backend.js | 4 +- ui/engine/backend-shared.js | 8 ++ ui/engine/wallet.js | 80 +++++++++++++- ui/lib/rows.js | 5 + ui/locales/ar.js | 1 + ui/locales/de.js | 1 + ui/locales/en.js | 3 +- ui/locales/es.js | 1 + ui/locales/fa.js | 1 + ui/locales/fr.js | 1 + ui/locales/hi.js | 1 + ui/locales/id.js | 1 + ui/locales/it.js | 1 + ui/locales/ja.js | 1 + ui/locales/ko.js | 1 + ui/locales/ms.js | 1 + ui/locales/pl.js | 1 + ui/locales/ps.js | 1 + ui/locales/pt.js | 1 + ui/locales/ru.js | 1 + ui/locales/ta.js | 1 + ui/locales/ur.js | 1 + ui/locales/zh-hk.js | 1 + ui/locales/zh.js | 1 + ui/test/backend-cases.mjs | 33 +++++- ui/test/engine-wallet.test.mjs | 171 +++++++++++++++++++++++++++++ ui/test/rows-banner.test.mjs | 7 ++ 28 files changed, 453 insertions(+), 18 deletions(-) diff --git a/core/crates/wallet-core/src/lib.rs b/core/crates/wallet-core/src/lib.rs index fb044a5..30146af 100644 --- a/core/crates/wallet-core/src/lib.rs +++ b/core/crates/wallet-core/src/lib.rs @@ -482,6 +482,12 @@ pub struct SentRow { /// [`OwnedNote::memo`]. #[serde(default)] pub memo: Option, + /// The note's creator (`Note::from`), 64 hex — VK-751. In [`ScanResult::sent`] it is always + /// this wallet's own `pk`; in [`ScanResult::sent_unverified`] one of [`FIXED_CREATORS`]. A + /// client checks it again before it stores the row. `#[serde(default)]` so a row a client + /// stored before the field existed still loads (as the empty string, which matches nothing). + #[serde(default)] + pub from: String, } fn owned_note(w: &Wallet, index: u64, height: u64, cm: Word8, note: Note) -> OwnedNote { @@ -532,28 +538,61 @@ impl EnvelopeHex { } } +/// The creators the chain itself writes into a note (VK-751): a `from` that is one of these names +/// no sender inside the pool. Zero is a bridge deposit or its fee note, a faucet mint, a genesis +/// allocation and a staking withdrawal; then an RPL mint (`rpl-mint`), a program payout +/// (`rpl2-pay`) and a perp payout (`rpl3-pay`). +pub const FIXED_CREATORS: [Word8; 4] = [ + [0; 8], + randprotocol_core::ledger::tokens::MINT_FROM, + PROGRAM_FROM, + randprotocol_core::ledger::perps::PERP_FROM, +]; + /// What one leaf turned out to be for this wallet. Mirrors `randprotocol_client::wallet::classify`: /// an envelope that opens is not proof of ownership (anyone can seal to a public address), so a /// received note is only kept when its `pk` is this wallet's. +/// +/// **Nor is the sender part opening proof of having sent it (VK-751, audit v14).** It opens under +/// the *viewing* key, which is handed out — to the prover of every delegated proof, to an auditor, +/// to a node it is imported into — and whoever holds it can seal a note of their own under it. +/// What they cannot choose is the note's creator: the bundle guest commits every output with +/// `from = pk_self`, the spender's own `pk`. So, with `pk_self` this wallet's: +/// +/// * `note.from == pk_self` — [`Found::Sent`]; +/// * `note.from` one of [`FIXED_CREATORS`] — [`Found::SentUnverified`]: a relayed deposit, a mint +/// or a payout is sealed under the *submitter's* key with a constant creator, so the row may be +/// this key's own doing, and an ovk holder can mint its own token and seal it the same way. It +/// is reported apart and never as Sent; +/// * anything else that opens — [`Found::Skipped`]. pub enum Found { /// A note this wallet owns, with the memo its sender sealed, if any. Received(Note, Option), - /// A note this wallet sent, with the memo it sealed, if any. + /// A note this wallet sent — its creator is this wallet — with the memo it sealed, if any. Sent(Note, Option), + /// A note sealed under this wallet's key whose creator is a chain constant: not known to be + /// this wallet's doing. + SentUnverified(Note, Option), Skipped, } pub fn classify(w: &Wallet, cm: Word8, envelope: &Envelope) -> Found { let env = envelope_from_core(envelope); + let pk_self = w.vk.pk(); // The memo opens under the same transaction key the note did; a legacy body, an empty field // or a malformed one is `None` (a malformed memo never costs the payee the note). if let Some((key, note)) = env.open_as_receiver(cm, &w.vk) { - if note.pk == w.vk.pk() { + if note.pk == pk_self { return Found::Received(note, env.memo(cm, &key)); } } if let Some((key, note)) = env.open_as_sender(cm, &w.vk) { - return Found::Sent(note, env.memo(cm, &key)); + if note.from == pk_self { + return Found::Sent(note, env.memo(cm, &key)); + } + if FIXED_CREATORS.contains(¬e.from) { + return Found::SentUnverified(note, env.memo(cm, &key)); + } } Found::Skipped } @@ -561,7 +600,11 @@ pub fn classify(w: &Wallet, cm: Word8, envelope: &Envelope) -> Found { #[derive(Serialize, Default)] pub struct ScanResult { pub received: Vec, + /// Notes this wallet sent: each one's `from` is this wallet's `pk`. pub sent: Vec, + /// Notes sealed under this wallet's key whose creator is a chain constant (VK-751) — "sent, + /// sender unverified". A separate list, so a client that reads only `sent` never counts one. + pub sent_unverified: Vec, /// One past the highest leaf index in the page, for the client's cursor. pub next_index: u64, pub rows: usize, @@ -574,19 +617,22 @@ pub fn scan_page(w: &Wallet, rows: &[CommitmentRow]) -> Result { for r in rows { let cm = word8_from_hex(&r.cm).ok_or("cm is not 64 hex characters")?; let env = r.envelope.decode()?; + let sent_row = |note: &Note, memo: Option| SentRow { + index: r.index, + to_pk: word8_to_hex(¬e.pk), + amount: note.amount.to_string(), + asset: note.asset, + time: note.time, + height: r.height, + memo, + from: word8_to_hex(¬e.from), + }; match classify(w, cm, &env) { Found::Received(note, memo) => { out.received.push(OwnedNote { memo, ..owned_note(w, r.index, r.height, cm, note) }) } - Found::Sent(note, memo) => out.sent.push(SentRow { - index: r.index, - to_pk: word8_to_hex(¬e.pk), - amount: note.amount.to_string(), - asset: note.asset, - time: note.time, - height: r.height, - memo, - }), + Found::Sent(note, memo) => out.sent.push(sent_row(¬e, memo)), + Found::SentUnverified(note, memo) => out.sent_unverified.push(sent_row(¬e, memo)), Found::Skipped => {} } out.next_index = out.next_index.max(r.index + 1); @@ -4077,8 +4123,10 @@ fn asset_param(p: &Value) -> Result { /// - `uri_parse` `{uri}` → `{address, amount, asset, memo, fingerprint}`; absent parameters are /// `null`, `amount` is the display decimal as written, `fingerprint` is recomputed /// - `uri_format` `{address, amount?, asset?, memo?}` → `{uri}`; all strings, empty = absent -/// - `scan_page` `{spend_key, rows: [getCommitments rows]}` → `{received, sent, next_index, rows}`; -/// every received note and sent row carries `memo` (a string, or `null` for none) +/// - `scan_page` `{spend_key, rows: [getCommitments rows]}` → `{received, sent, sent_unverified, +/// next_index, rows}`; every received note and sent row carries `memo` (a string, or `null` for +/// none), and every sent row `from`, the note's creator: this wallet's `pk` in `sent`, a chain +/// constant in `sent_unverified` (VK-751 — see [`classify`]) /// - `rebuilt_deposit` `{spend_key, action}` → owned note or null /// - `rebuilt_notes` `{spend_key, action}` → owned notes (an array): a `bridge_attest`'s deposit, /// or every note an RPL-2 `invoke` paid out to this wallet, from the action's public fields @@ -4594,6 +4642,70 @@ mod tests { assert!(open_with_tx_key(&rows[1].cm, &rows[1].envelope, &hex::encode(key1.0)).unwrap().is_none()); } + /// [`sealed_row`] for a note whose creator (`from`) is chosen by the caller: `sealer`'s + /// viewing key seals it, which is all the sender part opening says. + fn sealed_row_from(sealer: &Wallet, to: &Wallet, from: Word8, amount: u64, index: u64, memo: &str) -> CommitmentRow { + let note = Note::new(to.vk.pk(), from, amount, 0, 3); + let env = seal_note_as(EnvelopeFormat::Memo, &sealer.vk, &to.address, ¬e, &TxKey::random(), memo).unwrap(); + CommitmentRow { + index, + cm: word8_to_hex(¬e.commitment()), + height: 9, + envelope: EnvelopeHex { + kem_ct: hex::encode(&env.kem_ct), + to_receiver: hex::encode(&env.to_receiver), + to_sender: hex::encode(&env.to_sender), + body: hex::encode(&env.body), + }, + } + } + + /// VK-751: a holder of the victim's viewing key seals a note of its own under it. The note's + /// creator is the planter (the guest commits `from = pk_self` for whoever spends), so the + /// victim's scan must not file the planter's payee, amount and memo as a payment it sent. + #[test] + fn scan_page_does_not_file_a_note_planted_under_the_viewing_key_as_sent() { + let victim = wallet(1); + let planter = wallet(2); + let payee = wallet(3); + // Everything the planter needs of the victim is the viewing key: a wallet with the + // victim's `vk` seals exactly as the victim's own would. + let planted = sealed_row_from(&victim, &payee, planter.vk.pk(), 123_456_789, 10, "invoice 42"); + let real = sealed_row_from(&victim, &payee, victim.vk.pk(), 5, 11, "rent"); + let scan = scan_page(&victim, &[planted, real]).unwrap(); + assert_eq!(scan.sent.len(), 1, "exactly the victim's own payment is sent"); + assert_eq!((scan.sent[0].index, scan.sent[0].amount.as_str(), scan.sent[0].memo.as_deref()), (11, "5", Some("rent"))); + assert_eq!(scan.sent[0].from, word8_to_hex(&victim.vk.pk())); + assert!(scan.sent_unverified.is_empty()); + assert_eq!(scan.next_index, 12, "the cursor still passes the planted leaf"); + // The payee is unaffected: both notes are its own, whoever created them. + assert_eq!(scan_page(&payee, &[sealed_row_from(&victim, &payee, planter.vk.pk(), 1, 10, "")]).unwrap().received.len(), 1); + } + + /// VK-751: a chain-fixed creator (a relayed deposit, a mint, a program or perp payout) under + /// this wallet's key is reported apart — never in `sent` — and any other creator is dropped. + #[test] + fn scan_page_reports_a_chain_fixed_creator_apart_and_never_as_sent() { + let relayer = wallet(1); + let payee = wallet(2); + let rows: Vec = FIXED_CREATORS + .iter() + .enumerate() + .map(|(i, from)| sealed_row_from(&relayer, &payee, *from, 7 + i as u64, 20 + i as u64, "")) + .chain(std::iter::once(sealed_row_from(&relayer, &payee, [9; 8], 1, 30, ""))) + .collect(); + let scan = scan_page(&relayer, &rows).unwrap(); + assert!(scan.sent.is_empty(), "none is a payment this wallet is known to have sent"); + assert_eq!(scan.sent_unverified.iter().map(|s| s.index).collect::>(), vec![20, 21, 22, 23]); + for (row, from) in scan.sent_unverified.iter().zip(FIXED_CREATORS.iter()) { + assert_eq!(row.from, word8_to_hex(from)); + } + // The tags are the chain's, readable in a hex dump. + assert_eq!(&word8_to_hex(&FIXED_CREATORS[1])[..16], hex::encode(b"rpl-mint")); + assert_eq!(&word8_to_hex(&FIXED_CREATORS[2])[..16], hex::encode(b"rpl2-pay")); + assert_eq!(&word8_to_hex(&FIXED_CREATORS[3])[..16], hex::encode(b"rpl3-pay")); + } + #[test] fn selection_is_largest_first_and_at_most_two() { let w = wallet(4); @@ -5705,6 +5817,7 @@ mod tests { // A note this wallet *sent*: the payment, addressed to somebody else. Found::Sent(n, _) if n.pk == to.pk => "pay", Found::Sent(..) => "sent-elsewhere", + Found::SentUnverified(..) => "sent-unverified", Found::Skipped => "nobody", } }) diff --git a/ui/backend.js b/ui/backend.js index d40763f..00508e8 100644 --- a/ui/backend.js +++ b/ui/backend.js @@ -76,7 +76,9 @@ * `'AbortError'`); the UI treats that as "no longer wanted", never as a node failure. A backend * that ignores it is still correct — the UI discards the result either way. * An **activity item** is `{kind, asset, amount, time, hash?, index?}` where `kind` is one of - * `'in' | 'out' | 'faucet' | 'pending'`, `asset` is an asset index, `amount` is a units string and + * `'in' | 'out' | 'faucet' | 'pending' | 'out-unverified'` (the last: a note sealed under this + * wallet's key whose creator is a chain constant — VK-751; a screen must not present it as money + * this wallet sent), `asset` is an asset index, `amount` is a units string and * `time` is a unix timestamp in **seconds** (`lastSyncMs` and every other `*Ms` field is * milliseconds, as named). These further fields are **OPTIONAL** — a backend may supply none of * them, and every screen renders each one only when it is present: diff --git a/ui/engine/backend-shared.js b/ui/engine/backend-shared.js index 26a21f6..3be52d5 100644 --- a/ui/engine/backend-shared.js +++ b/ui/engine/backend-shared.js @@ -338,6 +338,14 @@ function uiActivity(row, st) { if (row.height) item.block = Number(row.height); return item; } + if (row.kind === 'sent_unverified') { + // VK-751: the sender part opened under this wallet's key, but the note's creator is a chain + // constant (a relayed deposit, a mint, a payout), so it is not known to be this wallet's + // doing. Its own kind — a screen titles it as such and never counts it as money sent. + const item = { kind: 'out-unverified', asset: Number(row.asset) || 0, amount: String(row.amount), time: at(row.height), ...memoField(row.memo) }; + if (row.height) item.block = Number(row.height); + return item; + } // A submission this wallet made: the faucet, a burn withdrawal, or (on a shell that can prove) // a transfer. const sub = row.sub || {}; diff --git a/ui/engine/wallet.js b/ui/engine/wallet.js index 1af2f34..cf3a3e7 100644 --- a/ui/engine/wallet.js +++ b/ui/engine/wallet.js @@ -266,6 +266,54 @@ const MAX_ATTEST_REQUESTS_PER_SCAN = 96; */ export const DEPOSIT_ACTIONS = Object.freeze({ kinds: Object.freeze(['bridge_attest', 'bridge_burn']), maxActionChars: 65536 }); +/** + * VK-751 (audit v14) — WHO CREATED A "SENT" NOTE. + * + * An envelope's sender part opens under the wallet's *viewing* key, and that key is handed out: to + * the prover of every delegated proof, to an auditor, to a node it is imported into. Whoever holds + * it can seal a note of their own under it, so "the sender part opens" is not "this wallet sent + * it" — it used to be read as exactly that, and a planted payment (the planter's payee, amount and + * memo) landed in the victim's history. What a holder of the viewing key cannot choose is the + * note's **creator**: the bundle guest commits every output with `from` = the spender's own `pk` + * (`hidden.rs`, `HiddenOutput::note`), a private multisig account's bundle included (its `pk`). + * + * The rule, the same one the node's viewing rows and the explorer apply. With `pk_self` the pk of + * the key being scanned, a row whose sender part opened is: + * + * `from == pk_self` → **Sent**. + * `from` a chain-fixed constant → **sent, sender unverified** (`unverified: true`): a relayed + * bridge deposit or fee / faucet mint / staking withdrawal + * (zero), an RPL mint (`rpl-mint`), a program payout + * (`rpl2-pay`), a perp payout (`rpl3-pay`). These are sealed + * under the SUBMITTER's key with a constant creator, so the row + * may be this key's own doing — and an ovk holder can mint its + * own token and seal it the same way. Kept apart; never counted + * as Sent, never matched to a submission. + * anything else → dropped. A row with no `from` at all (a core from before + * this rule) is evidence of nothing and is dropped too. + * + * The core applies the same rule (`wallet-core`'s `classify`) and reports `from` on every row; it + * is applied again here because this is the last thing between a row and the store. + */ +const fixedCreator = (tag) => (Array.from(tag, (ch) => ch.charCodeAt(0).toString(16).padStart(2, '0')).join('') + '0'.repeat(64)).slice(0, 64); +export const FIXED_CREATORS = Object.freeze({ + zero: '0'.repeat(64), // bridge deposit and fee, faucet mint, genesis, staking withdrawal + mint: fixedCreator('rpl-mint'), // `tokens::MINT_FROM` + program: fixedCreator('rpl2-pay'), // `program_state::PROGRAM_FROM` + perp: fixedCreator('rpl3-pay'), // `perps::PERP_FROM` +}); +const FIXED_CREATOR_SET = new Set(Object.values(FIXED_CREATORS)); +const HEX64_RE = /^[0-9a-f]{64}$/; + +/** `'sent' | 'unverified' | null` for one row whose sender part opened, against this wallet's pk. */ +export function sentRole(row, ownPk) { + const from = row && typeof row.from === 'string' ? row.from.trim().toLowerCase().replace(/^0x/, '') : ''; + const own = typeof ownPk === 'string' ? ownPk.trim().toLowerCase().replace(/^0x/, '') : ''; + if (!HEX64_RE.test(from) || !HEX64_RE.test(own)) return null; + if (from === own) return 'sent'; + return FIXED_CREATOR_SET.has(from) ? 'unverified' : null; +} + export function emptyNoteStore() { return { scanned_index: 0, scanned_height: 0, scanned_attest_height: 0, @@ -1054,6 +1102,14 @@ export function makeWallet({ core, store, rpc, settings, annotate = true, onRese leafCount = total; } catch { /* a node without it: the continuity checks still apply, this one is skipped */ } + // This wallet's own pk, from the core and from the key being scanned — asked for once, and + // only by a scan that found a row to judge with it. + let ownPkHex; + const ownPk = async () => { + if (ownPkHex === undefined) ownPkHex = String((await c.walletInfo(spendKey)).pk || ''); + return ownPkHex; + }; + const placePage = async (rows) => { const res = await c.scanPage(spendKey, rows); // A rebuilt deposit takes precedence over whatever its envelope says. @@ -1062,7 +1118,23 @@ export function makeWallet({ core, store, rpc, settings, annotate = true, onRese if (dep) { deposits.delete(r.cm); mergeNotes(st, [{ ...dep, index: r.index, height: r.height }]); } } mergeNotes(st, res.received); - mergeSent(st, res.sent); + // VK-751: a row is Sent only when the note's creator is this wallet (see `sentRole`). What + // this page says about its own leaves REPLACES what was stored for them, so a rescan also + // removes a planted row a build from before the rule had kept. + const opened = [...(Array.isArray(res.sent) ? res.sent : []), ...(Array.isArray(res.sent_unverified) ? res.sent_unverified : [])]; + const kept = []; + if (opened.length) { + const pk = await ownPk(); + for (const row of opened) { + const role = sentRole(row, pk); + if (role === 'sent') { const { unverified: _drop, ...clean } = row; kept.push(clean); } + else if (role === 'unverified') kept.push({ ...row, unverified: true }); + } + } + const first = rows[0].index; + const last = rows[rows.length - 1].index; + st.sent = st.sent.filter((x) => !(x.index >= first && x.index <= last)); + mergeSent(st, kept); const next = intField('scan_page', 'next_index', res.next_index); // Our own trust boundary, so it costs nothing to close: the core cannot have seen a leaf // past the page it was handed, and one before `from` would move the cursor backwards. @@ -1705,6 +1777,12 @@ export function activity(store) { } const subs = store.submissions || []; for (const s of store.sent) { + // VK-751: a row whose creator is a chain constant is not known to be this wallet's doing. It + // is its own kind, and it neither stands in for a submission nor dates one. + if (s.unverified) { + rows.push({ kind: 'sent_unverified', index: s.index, amount: s.amount, asset: s.asset, height: s.height, to_pk: s.to_pk, memo: s.memo ?? null, sort: s.height }); + continue; + } const sub = subs.find((x) => x.to_pk === s.to_pk && x.amount === s.amount && x.time === s.time); if (sub) { if (!sub.height) sub.height = s.height; continue; } rows.push({ kind: 'sent', index: s.index, amount: s.amount, asset: s.asset, height: s.height, to_pk: s.to_pk, memo: s.memo ?? null, sort: s.height }); diff --git a/ui/lib/rows.js b/ui/lib/rows.js index 5b8d760..feb2309 100644 --- a/ui/lib/rows.js +++ b/ui/lib/rows.js @@ -84,6 +84,11 @@ export function kindOf(item) { if (kind === 'in' || kind === 'out' || kind === 'faucet') { return { kind, icon: KIND_ICON[kind], title: KIND_TITLE[kind](), sign: KIND_SIGN[kind], tint: kind }; } + if (kind === 'out-unverified') { + // VK-751: a note sealed under this wallet's key whose creator is a chain constant. Shown as + // what it is — no sign and no Sent tint, because it is not known to be money this wallet sent. + return { kind, icon: 'arrowUpRight', title: t('Sent (sender unverified)'), sign: '', tint: '' }; + } if (kind === 'pending') { const titled = PENDING_TITLE[String(item.status || '').toLowerCase()]; const title = titled ? titled() : t('Pending'); diff --git a/ui/locales/ar.js b/ui/locales/ar.js index d2d77c8..fc339da 100644 --- a/ui/locales/ar.js +++ b/ui/locales/ar.js @@ -655,6 +655,7 @@ export default { "Sending twice would pay twice.": "الإرسال مرتين يعني الدفع مرتين.", "Sending…": "جارٍ الإرسال…", "Sent": "أُرسل", + "Sent (sender unverified)": "أُرسل (المُرسِل غير مُتحقَّق منه)", "Sent — view": "أُرسل — عرض", "Sent.": "أُرسل.", "Set on this device when this wallet was created.": "عُيّنت على هذا الجهاز عند إنشاء هذه المحفظة.", diff --git a/ui/locales/de.js b/ui/locales/de.js index d8c3614..267b542 100644 --- a/ui/locales/de.js +++ b/ui/locales/de.js @@ -655,6 +655,7 @@ export default { "Sending twice would pay twice.": "Zweimal senden heißt zweimal zahlen.", "Sending…": "Sende …", "Sent": "Gesendet", + "Sent (sender unverified)": "Gesendet (Absender unbestätigt)", "Sent — view": "Gesendet – ansehen", "Sent.": "Gesendet.", "Set on this device when this wallet was created.": "Auf diesem Gerät festgelegt, als diese Wallet erstellt wurde.", diff --git a/ui/locales/en.js b/ui/locales/en.js index 73ddb76..7b44831 100644 --- a/ui/locales/en.js +++ b/ui/locales/en.js @@ -4,7 +4,7 @@ // value, or an object of CLDR plural categories ({one, few, many, other}) for a key with an // {n} hole whose translation inflects by number. `{name}` holes and the words in the glossary // at the top of each dictionary are kept as they are. -// 1120 strings. +// 1121 strings. export default { "{amount} {symbol}": "{amount} {symbol}", "{blocks} blocks left to prove it.": "{blocks} blocks left to prove it.", @@ -658,6 +658,7 @@ export default { "Sending…": "Sending…", "Sent": "Sent", "Sent — view": "Sent — view", + "Sent (sender unverified)": "Sent (sender unverified)", "Sent.": "Sent.", "Set on this device when this wallet was created.": "Set on this device when this wallet was created.", "Settings": "Settings", diff --git a/ui/locales/es.js b/ui/locales/es.js index 15fdbac..13162f2 100644 --- a/ui/locales/es.js +++ b/ui/locales/es.js @@ -655,6 +655,7 @@ export default { "Sending twice would pay twice.": "Enviar dos veces pagaría dos veces.", "Sending…": "Enviando…", "Sent": "Enviado", + "Sent (sender unverified)": "Enviado (remitente sin verificar)", "Sent — view": "Enviado: ver", "Sent.": "Enviado.", "Set on this device when this wallet was created.": "Se configuró en este dispositivo cuando se creó esta billetera.", diff --git a/ui/locales/fa.js b/ui/locales/fa.js index bb31325..b22bfac 100644 --- a/ui/locales/fa.js +++ b/ui/locales/fa.js @@ -656,6 +656,7 @@ export default { "Sending twice would pay twice.": "ارسال دوباره یعنی دو بار پرداخت.", "Sending…": "در حال ارسال…", "Sent": "ارسال‌شده", + "Sent (sender unverified)": "ارسال‌شده (فرستنده تأییدنشده)", "Sent — view": "ارسال شد — مشاهده", "Sent.": "ارسال شد.", "Set on this device when this wallet was created.": "هنگام ساختن این کیف پول روی این دستگاه تعیین شد.", diff --git a/ui/locales/fr.js b/ui/locales/fr.js index e2bbaf0..c24b5e7 100644 --- a/ui/locales/fr.js +++ b/ui/locales/fr.js @@ -657,6 +657,7 @@ export default { "Sending twice would pay twice.": "Envoyer deux fois paierait deux fois.", "Sending…": "Envoi…", "Sent": "Envoyé", + "Sent (sender unverified)": "Envoyé (expéditeur non vérifié)", "Sent — view": "Envoyé : afficher", "Sent.": "Envoyé.", "Set on this device when this wallet was created.": "Défini sur cet appareil lors de la création de ce portefeuille.", diff --git a/ui/locales/hi.js b/ui/locales/hi.js index acde9f5..bd27609 100644 --- a/ui/locales/hi.js +++ b/ui/locales/hi.js @@ -655,6 +655,7 @@ export default { "Sending twice would pay twice.": "दो बार भेजने पर दो बार भुगतान होगा।", "Sending…": "भेजा जा रहा है…", "Sent": "भेजा गया", + "Sent (sender unverified)": "भेजा गया (प्रेषक असत्यापित)", "Sent — view": "भेजा गया — देखें", "Sent.": "भेजा गया।", "Set on this device when this wallet was created.": "यह वॉलेट बनाते समय इसी डिवाइस पर सेट किया गया।", diff --git a/ui/locales/id.js b/ui/locales/id.js index 969b55c..ab311cf 100644 --- a/ui/locales/id.js +++ b/ui/locales/id.js @@ -648,6 +648,7 @@ export default { "Sending twice would pay twice.": "Mengirim dua kali berarti membayar dua kali.", "Sending…": "Mengirim…", "Sent": "Terkirim", + "Sent (sender unverified)": "Terkirim (pengirim belum terverifikasi)", "Sent — view": "Terkirim — lihat", "Sent.": "Terkirim.", "Set on this device when this wallet was created.": "Ditetapkan di perangkat ini saat dompet ini dibuat.", diff --git a/ui/locales/it.js b/ui/locales/it.js index f1db4af..49c5362 100644 --- a/ui/locales/it.js +++ b/ui/locales/it.js @@ -655,6 +655,7 @@ export default { "Sending twice would pay twice.": "Inviando due volte pagheresti due volte.", "Sending…": "Invio…", "Sent": "Inviato", + "Sent (sender unverified)": "Inviato (mittente non verificato)", "Sent — view": "Inviato — vedi", "Sent.": "Inviato.", "Set on this device when this wallet was created.": "Impostata su questo dispositivo quando è stato creato questo portafoglio.", diff --git a/ui/locales/ja.js b/ui/locales/ja.js index e5cd65a..cb13e49 100644 --- a/ui/locales/ja.js +++ b/ui/locales/ja.js @@ -648,6 +648,7 @@ export default { "Sending twice would pay twice.": "二重に送信すると二重に支払うことになります。", "Sending…": "送信中…", "Sent": "送信済み", + "Sent (sender unverified)": "送信済み(送信者未確認)", "Sent — view": "送信済み — 表示", "Sent.": "送信しました。", "Set on this device when this wallet was created.": "このウォレットの作成時にこの端末で設定されました。", diff --git a/ui/locales/ko.js b/ui/locales/ko.js index 9fcccc7..4e89bb1 100644 --- a/ui/locales/ko.js +++ b/ui/locales/ko.js @@ -648,6 +648,7 @@ export default { "Sending twice would pay twice.": "두 번 보내면 두 번 지불됩니다.", "Sending…": "보내는 중…", "Sent": "보냄", + "Sent (sender unverified)": "보냄 (보낸 사람 미확인)", "Sent — view": "보냄 — 보기", "Sent.": "보냈습니다.", "Set on this device when this wallet was created.": "이 지갑을 만들 때 이 기기에서 설정했습니다.", diff --git a/ui/locales/ms.js b/ui/locales/ms.js index 79db424..cf45e25 100644 --- a/ui/locales/ms.js +++ b/ui/locales/ms.js @@ -650,6 +650,7 @@ export default { "Sending twice would pay twice.": "Menghantar dua kali akan membayar dua kali.", "Sending…": "Menghantar…", "Sent": "Dihantar", + "Sent (sender unverified)": "Dihantar (penghantar belum disahkan)", "Sent — view": "Dihantar — lihat", "Sent.": "Dihantar.", "Set on this device when this wallet was created.": "Ditetapkan pada peranti ini semasa dompet ini dicipta.", diff --git a/ui/locales/pl.js b/ui/locales/pl.js index b4c4fe5..cdcf3aa 100644 --- a/ui/locales/pl.js +++ b/ui/locales/pl.js @@ -651,6 +651,7 @@ export default { "Sending twice would pay twice.": "Dwukrotne wysłanie oznacza dwukrotną płatność.", "Sending…": "Wysyłanie…", "Sent": "Wysłano", + "Sent (sender unverified)": "Wysłano (nadawca niezweryfikowany)", "Sent — view": "Wysłano — zobacz", "Sent.": "Wysłano.", "Set on this device when this wallet was created.": "Ustawione na tym urządzeniu przy tworzeniu portfela.", diff --git a/ui/locales/ps.js b/ui/locales/ps.js index 8ea262a..c43640b 100644 --- a/ui/locales/ps.js +++ b/ui/locales/ps.js @@ -655,6 +655,7 @@ export default { "Sending twice would pay twice.": "دوه ځله لېږل به دوه ځله ورکړه وي.", "Sending…": "لېږل کېږي…", "Sent": "ولېږل شو", + "Sent (sender unverified)": "ولېږل شو (لېږونکی نه دی تایید شوی)", "Sent — view": "ولېږل شو — وګورئ", "Sent.": "ولېږل شو.", "Set on this device when this wallet was created.": "په دې وسیله کې هغه وخت ټاکل شوی کله چې دا والټ جوړ شو.", diff --git a/ui/locales/pt.js b/ui/locales/pt.js index 9f4f8bb..2f7e958 100644 --- a/ui/locales/pt.js +++ b/ui/locales/pt.js @@ -655,6 +655,7 @@ export default { "Sending twice would pay twice.": "Enviar duas vezes pagaria duas vezes.", "Sending…": "Enviando…", "Sent": "Enviado", + "Sent (sender unverified)": "Enviado (remetente não verificado)", "Sent — view": "Enviado — ver", "Sent.": "Enviado.", "Set on this device when this wallet was created.": "Definida neste dispositivo quando esta carteira foi criada.", diff --git a/ui/locales/ru.js b/ui/locales/ru.js index b6ca8ae..225645a 100644 --- a/ui/locales/ru.js +++ b/ui/locales/ru.js @@ -653,6 +653,7 @@ export default { "Sending twice would pay twice.": "Повторная отправка заплатит дважды.", "Sending…": "Отправка…", "Sent": "Отправлено", + "Sent (sender unverified)": "Отправлено (отправитель не подтверждён)", "Sent — view": "Отправлено — открыть", "Sent.": "Отправлено.", "Set on this device when this wallet was created.": "Задан на этом устройстве при создании кошелька.", diff --git a/ui/locales/ta.js b/ui/locales/ta.js index aaac901..3c92d6a 100644 --- a/ui/locales/ta.js +++ b/ui/locales/ta.js @@ -655,6 +655,7 @@ export default { "Sending twice would pay twice.": "இருமுறை அனுப்பினால் இருமுறை பணம் செலுத்தப்படும்.", "Sending…": "அனுப்புகிறது…", "Sent": "அனுப்பப்பட்டது", + "Sent (sender unverified)": "அனுப்பப்பட்டது (அனுப்புநர் சரிபார்க்கப்படவில்லை)", "Sent — view": "அனுப்பப்பட்டது — பார்", "Sent.": "அனுப்பப்பட்டது.", "Set on this device when this wallet was created.": "இந்த வாலட் உருவாக்கப்பட்டபோது இந்தச் சாதனத்தில் அமைக்கப்பட்டது.", diff --git a/ui/locales/ur.js b/ui/locales/ur.js index fefe116..10ccf93 100644 --- a/ui/locales/ur.js +++ b/ui/locales/ur.js @@ -656,6 +656,7 @@ export default { "Sending twice would pay twice.": "دو بار بھیجنے سے دو بار ادائیگی ہو گی۔", "Sending…": "بھیجا جا رہا ہے…", "Sent": "بھیج دیا گیا", + "Sent (sender unverified)": "بھیج دیا گیا (بھیجنے والا غیر تصدیق شدہ)", "Sent — view": "بھیج دیا گیا — دیکھیں", "Sent.": "بھیج دیا گیا۔", "Set on this device when this wallet was created.": "یہ والیٹ بنتے وقت اسی ڈیوائس پر مقرر کیا گیا۔", diff --git a/ui/locales/zh-hk.js b/ui/locales/zh-hk.js index e39a6d0..5fc8345 100644 --- a/ui/locales/zh-hk.js +++ b/ui/locales/zh-hk.js @@ -648,6 +648,7 @@ export default { "Sending twice would pay twice.": "重複傳送會付款兩次。", "Sending…": "正在傳送…", "Sent": "已傳送", + "Sent (sender unverified)": "已傳送(寄件人未驗證)", "Sent — view": "已傳送,查看", "Sent.": "已傳送。", "Set on this device when this wallet was created.": "於此錢包建立時在此裝置上設定。", diff --git a/ui/locales/zh.js b/ui/locales/zh.js index 0f2e956..049c555 100644 --- a/ui/locales/zh.js +++ b/ui/locales/zh.js @@ -648,6 +648,7 @@ export default { "Sending twice would pay twice.": "发送两次就会付款两次。", "Sending…": "正在发送…", "Sent": "已发送", + "Sent (sender unverified)": "已发送(发送方未验证)", "Sent — view": "已发送——查看", "Sent.": "已发送。", "Set on this device when this wallet was created.": "在此设备上创建此钱包时设置。", diff --git a/ui/test/backend-cases.mjs b/ui/test/backend-cases.mjs index 9144be5..ee4486f 100644 --- a/ui/test/backend-cases.mjs +++ b/ui/test/backend-cases.mjs @@ -2366,7 +2366,8 @@ const scoped = (name, fn) => test(`${label}: ${name}`, fn); amount: '2500000000', asset: 0, time: 7, from: '00'.repeat(32), height: 7, spent: false, pending: null, memo: 'rent', }; const without = { ...withMemo, index: 0, cm: '0a'.repeat(32), nf: '0d'.repeat(32), height: 5, memo: null }; - const sent = { index: 9, amount: '100', asset: 0, height: 7, to_pk: 'ee'.repeat(32), time: 3, memo: 'thanks' }; + // `from: PK` — the note's creator is this wallet, which is what makes the row Sent (VK-751). + const sent = { index: 1, amount: '100', asset: 0, height: 7, to_pk: 'ee'.repeat(32), time: 3, memo: 'thanks', from: PK }; const core = stubCore({ scan_page: ({ rows: page }) => ({ received: page.length ? [without, withMemo] : [], sent: page.length ? [sent] : [], @@ -2388,4 +2389,34 @@ const scoped = (name, fn) => test(`${label}: ${name}`, fn); const out = result.activity.find((a) => a.kind === 'out'); assert.equal(out.memo, 'thanks'); }); + + scoped('VK-751: a planted sent row reaches neither the store nor sync; a constant-creator row is `out-unverified`, never `out`', async () => { + const rows = [0, 1, 2].map((index) => ({ index, cm: `0${index}`.repeat(32), height: 5, envelope: { kem_ct: '', to_receiver: '', to_sender: '', body: '' } })); + let served = false; + const row = (index, from, memo) => ({ index, amount: '4200', asset: 0, height: 5, to_pk: 'ee'.repeat(32), time: 3, memo, from }); + const core = stubCore({ + scan_page: ({ rows: page }) => ({ + received: [], + // Leaf 0: sealed by a holder of the viewing key (its own pk as creator). Leaf 1: a mint + // sealed under this wallet's key. Leaf 2: a payment this wallet made. + sent: page.length ? [row(0, '66'.repeat(32), 'planted'), row(2, PK, 'mine')] : [], + sent_unverified: page.length ? [row(1, `${Buffer.from('rpl-mint').toString('hex')}${'00'.repeat(24)}`, 'minted')] : [], + next_index: page.length ? page[page.length - 1].index + 1 : 0, rows: page.length, + }), + }); + const fetch = stubFetch({ + rand_getCommitments: ([from]) => { if (from === 0 && !served) { served = true; return rows; } return []; }, + rand_getBlockByHeight: ([h]) => ({ height: h, timestamp_ms: 1788000000000 }), + rand_getTreeInfo: () => ({ next_index: 3, root: '00'.repeat(32), nullifiers: 0 }), + }); + const { backend, storage } = build({ core, fetch }); + await backend.wallet.create(PASSWORD); + const result = await backend.sync.scan(() => {}); + assert.equal(JSON.stringify(storage.local.get('notes')).includes('planted'), false, 'the planted row is in the store'); + assert.equal(JSON.stringify(result).includes('planted'), false, 'the planted row reached the screens'); + assert.deepEqual(result.activity.filter((a) => a.kind === 'out').map((a) => a.memo), ['mine'], 'exactly the wallet\'s own payment is Sent'); + const unverified = result.activity.filter((a) => a.kind === 'out-unverified'); + assert.deepEqual(unverified.map((a) => [a.memo, a.amount, a.block]), [['minted', '4200', 5]]); + assert.equal(result.activity.some((a) => a.kind === 'pending'), false, 'and it is not mistaken for a submission'); + }); } diff --git a/ui/test/engine-wallet.test.mjs b/ui/test/engine-wallet.test.mjs index 4425cea..a4b1757 100644 --- a/ui/test/engine-wallet.test.mjs +++ b/ui/test/engine-wallet.test.mjs @@ -1327,3 +1327,174 @@ test('CLI-1001: without a conditional write, two saves of one loaded store do no await wallet.persist(c); assert.equal(store.current.notes[1].pending, null); }); + +// ============================================ VK-751 (audit v14): who created a "sent" note ===== +// An envelope's sender part opens under the wallet's VIEWING key, and a viewing key is handed out: +// to the prover of every delegated proof, to an auditor. Whoever holds it can seal a note of their +// own under it, and the scan used to file that note as a payment this wallet SENT — the planter's +// payee, amount and memo in the victim's history. What a holder of the viewing key cannot choose +// is the note's creator: the bundle guest commits every output with `from` = the spender's own pk. +// So: Sent only when `from` is this wallet's pk; a chain-fixed creator (a relayed deposit, a mint, +// a program or perp payout — sealed under the submitter's key with a constant `from`, which an ovk +// holder can also arrange) is kept apart as "sent, sender unverified"; anything else is dropped. +const OWN_PK = HEX64('a7'); +const PLANTER_PK = HEX64('66'); +const PAYEE_PK = HEX64('9e'); +const FROM_ZERO = '00'.repeat(32); +const tagFrom = (tag) => (Buffer.from(tag, 'ascii').toString('hex') + '00'.repeat(32)).slice(0, 64); +const FROM_MINT = tagFrom('rpl-mint'); +const FROM_PROGRAM = tagFrom('rpl2-pay'); +const FROM_PERP = tagFrom('rpl3-pay'); + +const sentRow = (index, from, extra = {}) => ({ + index, to_pk: PAYEE_PK, amount: '777', asset: 0, time: 5, height: 5, memo: null, ...(from === undefined ? {} : { from }), ...extra, +}); + +/** A wallet whose core "opens" the given rows on the leaf page: `{received, sent, sent_unverified}`. */ +function scanningWallet({ received = [], sent = [], sentUnverified, store = memoryStore(), deposits = null } = {}) { + const leaves = [...received, ...sent, ...(sentUnverified || [])].map((r) => r.index); + const top = Math.max(0, ...leaves) + 1; + const client = stubClient({ + treeInfo: () => ({ next_index: top, root: HEX64('00'), nullifiers: 0 }), + commitments: (from) => (from === 0 + ? Array.from({ length: top }, (_, i) => ({ index: i, cm: HEX64(`c${i % 10}`), height: 5, envelope: envelope() })) + : []), + sendTransaction: () => HEX64('dd'), + ...(deposits ? deposits.client : {}), + }); + const calls = []; + const core = stubCore({ + wallet_info: (p) => { calls.push(['wallet_info', p]); return { pk: OWN_PK, address: 'rand1own' }; }, + scan_page: ({ rows }) => ({ + received: rows.length ? received : [], + sent: rows.length ? sent : [], + ...(sentUnverified ? { sent_unverified: rows.length ? sentUnverified : [] } : {}), + next_index: rows.length ? rows[rows.length - 1].index + 1 : 0, rows: rows.length, + }), + parse_address: () => ({ valid: true, pk: PAYEE_PK }), + ...(deposits ? deposits.core : {}), + }); + const wallet = makeWallet({ core, store, rpc: () => client, settings: async () => ({}), annotate: false }); + return { wallet, store, client, calls }; +} + +test('VK-751: a sent row planted under the viewing key never lands in the store', async () => { + // The verifier's end-to-end test: the planter seals its own note (creator = the planter) under + // the victim's ovk. Payee, amount and memo are all the planter's choice. + const planted = sentRow(1, PLANTER_PK, { amount: '123456789', memo: 'invoice 42 — paid in full' }); + const { wallet, store } = scanningWallet({ sent: [planted] }); + const st = await wallet.scan(SPEND_KEY, {}); + assert.deepEqual(store.current.sent, [], 'the planted payment is in the victim\'s store'); + const rows = wallet.activity(st); + assert.equal(rows.some((r) => r.memo === planted.memo || r.amount === planted.amount || r.to_pk === PAYEE_PK), false, 'and in its history'); +}); + +test('VK-751: a payment this wallet made is Sent — its creator is the wallet\'s own pk', async () => { + const mine = sentRow(2, OWN_PK.toUpperCase(), { memo: 'rent' }); // hex case is not identity + const { wallet, store, calls } = scanningWallet({ sent: [mine] }); + const st = await wallet.scan(SPEND_KEY, {}); + assert.equal(store.current.sent.length, 1); + assert.equal(store.current.sent[0].unverified, undefined); + const rows = wallet.activity(st).filter((r) => r.kind === 'sent'); + assert.deepEqual(rows.map((r) => [r.index, r.amount, r.to_pk, r.memo]), [[2, '777', PAYEE_PK, 'rent']]); + assert.deepEqual(calls[0], ['wallet_info', { spend_key: SPEND_KEY }], 'the wallet\'s own pk comes from the core, from the key being scanned'); +}); + +test('VK-751: a chain-fixed creator is "sent, sender unverified" — kept apart, never counted as Sent', async () => { + // Relayed deposits, mints and payouts are sealed under the SUBMITTER's key with a constant + // `from`, so the row may be this wallet's own doing — and an ovk holder can mint its own token + // and seal it the same way. The row is shown as what it is. + const rowsIn = [sentRow(1, FROM_ZERO), sentRow(2, FROM_MINT), sentRow(3, FROM_PROGRAM), sentRow(4, FROM_PERP)]; + for (const shape of ['in sent', 'in sent_unverified']) { + const { wallet, store } = shape === 'in sent' ? scanningWallet({ sent: rowsIn }) : scanningWallet({ sentUnverified: rowsIn }); + const st = await wallet.scan(SPEND_KEY, {}); + assert.deepEqual(store.current.sent.map((s) => [s.index, s.unverified]), [[1, true], [2, true], [3, true], [4, true]], shape); + const rows = wallet.activity(st); + assert.equal(rows.filter((r) => r.kind === 'sent').length, 0, `${shape}: none is counted as Sent`); + assert.equal(rows.filter((r) => r.kind === 'sent_unverified').length, 4, shape); + } +}); + +test('VK-751: the core cannot promote a row — a foreign creator under `sent`, or an own-looking one under `sent_unverified`', async () => { + const { wallet, store } = scanningWallet({ + sent: [sentRow(1, PLANTER_PK), sentRow(2, undefined), sentRow(3, 'not hex'), sentRow(4, null)], + sentUnverified: [sentRow(5, PLANTER_PK), sentRow(6, OWN_PK)], + }); + await wallet.scan(SPEND_KEY, {}); + // Row 6 names this wallet as creator, so it is Sent whichever list it arrived in; a row with no + // creator at all (a core from before this rule) is not evidence of anything. + assert.deepEqual(store.current.sent.map((s) => [s.index, s.unverified === true]), [[6, false]]); +}); + +test('VK-751: an unverified row cannot stand in for, or annotate, a submission this wallet made', async () => { + const store = memoryStore({ + ...emptyNoteStore(), chain_id: 13, genesis: GENESIS_A, + submissions: [{ hash: HEX64('ab'), to_pk: PAYEE_PK, amount: '777', time: 5, status: 'committed', created_ms: 1 }], + }); + const { wallet } = scanningWallet({ sent: [sentRow(1, FROM_MINT, { height: 99 })], store }); + const st = await wallet.scan(SPEND_KEY, {}); + const rows = wallet.activity(st); + assert.equal(rows.filter((r) => r.kind === 'sent_unverified').length, 1, 'it is its own row'); + assert.equal(rows.find((r) => r.kind === 'submission').sub.height, undefined, 'and it did not date the real payment'); +}); + +test('VK-751: a rescan removes a planted row an older build stored, and keeps the real ones', async () => { + // Stored before this rule: no `from` on either row. The rescan re-reads the leaves, and what the + // page says now replaces what was stored for those leaves. + const store = memoryStore({ + ...emptyNoteStore(), chain_id: 13, genesis: GENESIS_A, scanned_index: 3, + sent: [sentRow(1, undefined, { memo: 'planted' }), sentRow(2, undefined, { memo: 'real' })], + }); + const { wallet } = scanningWallet({ sent: [sentRow(1, PLANTER_PK, { memo: 'planted' }), sentRow(2, OWN_PK, { memo: 'real' })], store }); + await wallet.rescan(SPEND_KEY, {}); + assert.deepEqual(store.current.sent.map((s) => [s.index, s.memo]), [[2, 'real']]); +}); + +// The reviewer's caution: a creator comparison must not cost a wallet its legitimate history. +// Each kind of row a wallet really has, through the same scan. +test('VK-751: legitimate rows survive — a bridge deposit, a faucet mint, a received payment', async () => { + // None of these is a "sent" row at all: they are notes this wallet OWNS (pk = own), whatever + // their creator — zero for a relayed deposit and a faucet mint, the payer's pk for a payment. + const deposit = ownedNote(0, { from: FROM_ZERO, amount: '4000000000', cm: HEX64('c0') }); + const faucet = ownedNote(1, { from: FROM_ZERO, amount: '100000000000', cm: HEX64('c1') }); + const payment = ownedNote(2, { from: PLANTER_PK, amount: '5', cm: HEX64('c2'), memo: 'thanks' }); + const { wallet, store } = scanningWallet({ + received: [faucet, payment], + deposits: { + client: { + bridgeState: () => ({ enabled: true }), + blockByHeight: (h) => ({ height: h, timestamp_ms: 1788000000000, transactions: h === 5 ? [{ action: { kind: 'bridge_attest' } }] : [] }), + }, + core: { rebuilt_deposit: () => ({ ...deposit, index: 18446744073709551615, height: 0 }) }, + }, + }); + const st = await wallet.scan(SPEND_KEY, {}); + assert.deepEqual(store.current.notes.map((n) => [n.index, n.amount]).sort(), [[0, '4000000000'], [1, '100000000000'], [2, '5']]); + const received = wallet.activity(st).filter((r) => r.kind === 'received'); + assert.equal(received.length, 3); + assert.equal(received.find((r) => r.index === 2).memo, 'thanks'); +}); + +test('VK-751: legitimate rows survive — a withdrawal, a faucet request, and a send proved by a paired prover', async () => { + // A withdrawal (burn) addresses no note to anybody: it is its submission record. A relayed or + // delegated send is a bundle THIS wallet's key spends, whoever proved it, so the guest commits + // its payment with this wallet's pk as creator — and the chain's copy folds into the record. + const store = memoryStore({ + ...emptyNoteStore(), chain_id: 13, genesis: GENESIS_A, notes: [ownedNote(0)], + submissions: [ + { hash: HEX64('b1'), kind: 'burn', asset: 1, amount: '250', to_chain: 1, status: 'committed', created_ms: 3 }, + { hash: HEX64('fa'), kind: 'faucet', amount: '100000000000', status: 'committed', created_ms: 2 }, + ], + }); + const paid = sentRow(1, OWN_PK, { amount: PROVED.amount, time: PROVED.time, height: 8 }); + const { wallet, client } = scanningWallet({ sent: [paid], store }); + // The proof came back from a prover (`completeSend` is what `send.resume` runs for one). + const submission = await wallet.completeSend(SPEND_KEY, PROVED, { to: 'rand1payee', wait: false, client }); + const st = await wallet.scan(SPEND_KEY, {}); + const rows = wallet.activity(st); + assert.deepEqual(rows.filter((r) => r.kind === 'submission').map((r) => r.hash).sort(), [HEX64('b1'), submission.hash].sort(), 'the withdrawal and the send are both listed'); + assert.equal(rows.filter((r) => r.kind === 'faucet').length, 1); + assert.equal(rows.filter((r) => r.kind === 'sent').length, 0, 'the chain\'s copy of the send folded into its record, not a second row'); + assert.equal(rows.find((r) => r.hash === submission.hash).sub.height, 8, 'and dated it'); + assert.equal(st.sent.length, 1); +}); diff --git a/ui/test/rows-banner.test.mjs b/ui/test/rows-banner.test.mjs index 3b2f73a..b714eff 100644 --- a/ui/test/rows-banner.test.mjs +++ b/ui/test/rows-banner.test.mjs @@ -9,6 +9,13 @@ test('kindOf: in, out and faucet carry a sign and their own tint', () => { assert.deepEqual(kindOf({ kind: 'faucet' }), { kind: 'faucet', icon: 'droplet', title: 'Faucet', sign: '+', tint: 'faucet' }); }); +test('kindOf: VK-751 — a sent row whose sender is unverified says so, and carries no sign and no Sent tint', () => { + assert.deepEqual(kindOf({ kind: 'out-unverified' }), { kind: 'out-unverified', icon: 'arrowUpRight', title: 'Sent (sender unverified)', sign: '', tint: '' }); + const html = String(activityRowMarkup({ kind: 'out-unverified', asset: 0, amount: '4200', time: 1 }, new Map())); + assert.match(html, /Sent \(sender unverified\)/); + assert.doesNotMatch(html, /−/, 'no minus sign: it is not counted as money this wallet sent'); +}); + test('kindOf: a pending item is titled by its known status, else "Pending"; no sign', () => { assert.equal(kindOf({ kind: 'pending', status: 'Proving' }).title, 'Proving'); assert.equal(kindOf({ kind: 'pending', status: 'confirming' }).title, 'Confirming'); From 69febcf10006fefdab6169220d7917499e8a6933 Mon Sep 17 00:00:00 2001 From: Dendi Suhubdy <4477337+dendisuhubdy@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:29:04 +0800 Subject: [PATCH 4/7] =?UTF-8?q?CLI-1006:=20a=20transfer's=20outcome=20is?= =?UTF-8?q?=20decided=20by=20its=20phase=20first=20=E2=80=94=20nothing=20a?= =?UTF-8?q?fter=20the=20broadcast=20reads=20as=20cancelled?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit outcomeOf (send and withdraw) tested the abort before the phase, safe only because the engine's last abort checkpoint sits immediately before the broadcast. And isAbortError took code 20 for an abort, so a node answering the confirmation read with JSON-RPC code 20 made a broadcast transfer read as cancelled while Activity listed it pending. - From 'submitting' on the outcome is 'unknown' (or 'not-sent' when the node refused the broadcast), whatever the error or the cancel flag. - RpcError is named, and a node's own error is never an abort. - Tests pin the engine invariant for completeSend/Burn/Invoke: an abort signalled at the broadcast still records and resolves. Adding a checkpoint after the broadcast turns them red (checked by mutation). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01GFs5h2CVCmdBKerZzH2Xrx --- ui/engine/rpc.js | 4 +++ ui/screens/send/state.js | 19 ++++++++-- ui/screens/withdraw.js | 10 +++--- ui/test/engine-wallet.test.mjs | 42 +++++++++++++++++++++++ ui/test/send.test.mjs | 63 +++++++++++++++++++++++++++++++++- 5 files changed, 130 insertions(+), 8 deletions(-) diff --git a/ui/engine/rpc.js b/ui/engine/rpc.js index c96aaa2..ad71eb9 100644 --- a/ui/engine/rpc.js +++ b/ui/engine/rpc.js @@ -67,6 +67,10 @@ export class RpcError extends Error { */ constructor(message, code, failure) { super(message); + // Named, so a screen can tell a node's own error from anything else by `name` alone — the + // node chooses `code`, and must not be able to choose one that reads as something it is not + // (CLI-1006: code 20 used to read as a cancelled transfer). + this.name = 'RpcError'; this.code = code; if (failure) this.failure = failure; } diff --git a/ui/screens/send/state.js b/ui/screens/send/state.js index 188a37d..63c59c1 100644 --- a/ui/screens/send/state.js +++ b/ui/screens/send/state.js @@ -193,12 +193,20 @@ export function proveCost(proofs, via) { * - `'not-sent'` — it failed before anything was broadcast, or the backend says it *knows* the * transfer did not happen (`err.definite`). Safe to try again. * - `'unknown'` — it failed at or after `'submitting'`. It may be on chain. Not safe to retry. + * + * **The phase is read first (CLI-1006, audit v14).** From `'submitting'` on the transaction is + * with the node, and nothing that happens afterwards can make it "cancelled": not an abort (the + * user's, a lock's, or a checkpoint somebody adds to the engine one day), not `store.cancelling`, + * and not a node answering the confirmation read with an error that happens to look like one. The + * only thing still knowable there is `err.definite` — the node answered the broadcast and refused. + * Testing the abort first was safe only because the engine's last abort checkpoint comes + * immediately before the broadcast; this order does not depend on that. */ export function outcomeOf(store) { if (!store || !store.error) return 'ok'; + if (AFTER_BROADCAST.includes(store.phase)) return store.error.definite === true ? 'not-sent' : 'unknown'; if (store.cancelling || isAbortError(store.error)) return 'cancelled'; - if (store.error.definite === true) return 'not-sent'; - return AFTER_BROADCAST.includes(store.phase) ? 'unknown' : 'not-sent'; + return 'not-sent'; } /** @@ -234,7 +242,12 @@ export function explainProvingError(msg) { /** An error that means "this was cancelled", not "it failed" — see ui/backend.js. */ export function isAbortError(err) { - return !!err && (err.name === 'AbortError' || err.code === 'ABORT_ERR' || err.code === 20); + if (!err) return false; + if (err.name === 'AbortError') return true; + // A node's own JSON-RPC error carries the node's own `code`, and a node may answer 20 or + // "ABORT_ERR" like any other value (CLI-1006): that is a refusal, never a cancellation. + if (err.name === 'RpcError') return false; + return err.code === 'ABORT_ERR' || err.code === 20; } // ------------------------------------------------------------------- the transaction key ------ diff --git a/ui/screens/withdraw.js b/ui/screens/withdraw.js index f3adf67..aa799d0 100644 --- a/ui/screens/withdraw.js +++ b/ui/screens/withdraw.js @@ -33,7 +33,7 @@ import { parseUnits, formatUnits, shortHex, elapsed } from '../lib/format.js'; import { markInvalid, markValid } from '../lib/forms.js'; import { explorerLink, TX_HASH_RE } from '../lib/explorer.js'; import { unlistedText, isUnlisted, backingsOf, feeDecimals, feeSymbol } from '../lib/assets.js'; -import { plainUnits, proveCost, provingLabel, phaseLabel, recordPhase, provingBanner } from './send/state.js'; +import { plainUnits, proveCost, provingLabel, phaseLabel, recordPhase, provingBanner, isAbortError } from './send/state.js'; import { proverNoticeMarkup, proverUnreachableMarkup, proverDeclinedMarkup } from './send/markup.js'; // ============================================================================ the vocabulary === @@ -122,9 +122,11 @@ export function currentWithdrawal(ctx) { export function outcomeOf(store) { if (!store || !store.error) return 'ok'; const err = store.error; - if (store.cancelling || err.name === 'AbortError' || err.code === 'ABORT_ERR') return 'cancelled'; - if (err.definite === true) return 'not-sent'; - return AFTER_BROADCAST.includes(store.phase) ? 'unknown' : 'not-sent'; + // The phase first (CLI-1006): once the burn is with the node, no abort and no error a node + // answers with can make it "cancelled" — see `outcomeOf` in screens/send/state.js. + if (AFTER_BROADCAST.includes(store.phase)) return err.definite === true ? 'not-sent' : 'unknown'; + if (store.cancelling || isAbortError(err)) return 'cancelled'; + return 'not-sent'; } function safeHash(hash) { diff --git a/ui/test/engine-wallet.test.mjs b/ui/test/engine-wallet.test.mjs index a4b1757..0178ab2 100644 --- a/ui/test/engine-wallet.test.mjs +++ b/ui/test/engine-wallet.test.mjs @@ -1498,3 +1498,45 @@ test('VK-751: legitimate rows survive — a withdrawal, a faucet request, and a assert.equal(rows.find((r) => r.hash === submission.hash).sub.height, 8, 'and dated it'); assert.equal(st.sent.length, 1); }); + + +// ===================================== CLI-1006 (audit v14): no abort after the broadcast ====== +// The invariant the screens' "cancelled" rests on: the engine's LAST abort checkpoint is the one +// immediately before `rand_sendTransaction`. Once the node has the transaction, an abort changes +// nothing — the submission is recorded and the call resolves. A checkpoint added anywhere after +// the broadcast turns these red. +for (const [name, run, extraCore] of [ + ['completeSend', (w, opts) => w.completeSend(SPEND_KEY, PROVED, { to: 'rand1payee', ...opts }), { parse_address: () => ({ valid: true, pk: HEX64('99') }) }], + ['completeBurn', (w, opts) => w.completeBurn(SPEND_KEY, { ...PROVED, to_chain: 1, token: 'ee'.repeat(32), to: 'ff'.repeat(32), relayer_fee: '0' }, opts), {}], + ['completeInvoke', (w, opts) => w.completeInvoke(SPEND_KEY, { ...PROVED, program: HEX64('70'), payouts: [] }, opts), {}], +]) { + test(`CLI-1006: ${name} — an abort signalled once the transaction is broadcast is not a cancellation`, async () => { + const store = memoryStore({ ...emptyNoteStore(), notes: [ownedNote(0)], chain_id: 13, genesis: GENESIS_A }); + const controller = new AbortController(); + const phases = []; + const client = stubClient({ + // The abort lands while the node is taking the transaction: the latest it can and still + // be "during" the call, and every step after it runs with the signal already aborted. + sendTransaction: () => { controller.abort(); return HEX64('dd'); }, + getTransaction: () => ({ hash: HEX64('dd'), height: 9 }), + }); + const wallet = makeWallet({ core: stubCore(extraCore), store, rpc: () => client, settings: async () => ({}), annotate: false }); + const submission = await run(wallet, { wait: true, signal: controller.signal, client, onPhase: (p) => phases.push(p) }); + assert.equal(submission.hash, HEX64('dd'), 'the call resolves with the submission; it does not reject with an AbortError'); + assert.deepEqual(phases, ['submit', 'wait']); + assert.equal(store.current.submissions.length, 1, 'and the record of it is on disk'); + assert.equal(store.current.submissions[0].status, 'committed'); + }); + + test(`CLI-1006: ${name} — an abort before the broadcast sends nothing`, async () => { + const store = memoryStore({ ...emptyNoteStore(), notes: [ownedNote(0)], chain_id: 13, genesis: GENESIS_A }); + const controller = new AbortController(); + controller.abort(); + const client = stubClient({ sendTransaction: () => HEX64('dd') }); + const wallet = makeWallet({ core: stubCore(extraCore), store, rpc: () => client, settings: async () => ({}), annotate: false }); + const phases = []; + await assert.rejects(() => run(wallet, { wait: false, signal: controller.signal, client, onPhase: (p) => phases.push(p) }), (err) => err.name === 'AbortError'); + assert.equal(client.calls.some(([m]) => m === 'sendTransaction'), false); + assert.deepEqual(phases, [], 'and \'submit\' was never reported, which is what lets a screen read the phase'); + }); +} diff --git a/ui/test/send.test.mjs b/ui/test/send.test.mjs index ef075f1..3162cb7 100644 --- a/ui/test/send.test.mjs +++ b/ui/test/send.test.mjs @@ -18,7 +18,9 @@ import { registerScreen } from '../app.js'; import { unlockedBackend, NO_SPENDABLE_RAND_TEXT, fakeFingerprint } from './fake-backend.mjs'; import { mountApp } from './helpers.mjs'; import { explainProvingError } from '../screens/send.js'; -import { markUnknownOutcome, unknownOutcome } from '../screens/send/state.js'; +import { markUnknownOutcome, unknownOutcome, outcomeOf, isAbortError, AFTER_BROADCAST, CANCELLABLE } from '../screens/send/state.js'; +import { outcomeOf as withdrawOutcomeOf } from '../screens/withdraw.js'; +import { RpcError } from '../engine/rpc.js'; import { UNLISTED_TEXT } from '../lib/assets.js'; const TO = `rand1${'p'.repeat(40)}`; @@ -1770,3 +1772,62 @@ test('Cancel on a resumed proof whose prover has no name still cancels the pendi await turns(6); assert.equal(ctl.cancelled, 1); }); + + +// ================================================= CLI-1006 (audit v14): the phase decides ===== +// `outcomeOf` used to test the abort BEFORE the phase. That was safe only because the engine's +// last abort checkpoint sits immediately before the broadcast — one more checkpoint anywhere after +// it and a broadcast transfer would read "cancelled", with every test still green. And it had one +// real hole: `isAbortError` took `code === 20` (a DOMException's legacy ABORT_ERR) for an abort, +// so a node answering the confirmation read with JSON-RPC error code 20 made a transfer that HAD +// been broadcast read as cancelled while Activity listed it pending. +const abortErr = () => Object.assign(new Error('The operation was aborted.'), { name: 'AbortError' }); + +test('CLI-1006: once the phase is submitting or confirming, nothing reads as cancelled', () => { + for (const outcome of [outcomeOf, withdrawOutcomeOf]) { + for (const phase of AFTER_BROADCAST) { + // An abort signalled after the broadcast — by Cancel, by a lock, by a checkpoint somebody + // adds to the engine one day — is "submitted, confirmation unknown". + assert.equal(outcome({ phase, error: abortErr() }), 'unknown', `${phase}: an AbortError`); + assert.equal(outcome({ phase, error: abortErr(), cancelling: true }), 'unknown', `${phase}: while cancelling`); + assert.equal(outcome({ phase, error: new Error('socket dropped'), cancelling: true }), 'unknown'); + assert.equal(outcome({ phase, error: Object.assign(new Error('x'), { code: 'ABORT_ERR' }) }), 'unknown'); + assert.equal(outcome({ phase, error: Object.assign(new Error('x'), { code: 20 }) }), 'unknown'); + // The one thing that is still known after 'submitting': the node answered and refused. + assert.equal(outcome({ phase, error: Object.assign(new Error('refused'), { definite: true }) }), 'not-sent'); + } + for (const phase of CANCELLABLE) { + assert.equal(outcome({ phase, error: abortErr() }), 'cancelled', `${phase}: nothing had left this device`); + assert.equal(outcome({ phase, error: new Error('x'), cancelling: true }), 'cancelled'); + assert.equal(outcome({ phase, error: new Error('the prover gave up') }), 'not-sent'); + } + assert.equal(outcome({ phase: 'confirming' }), 'ok'); + } +}); + +test('CLI-1006: a node\'s own JSON-RPC error code is never an abort, whatever the number', () => { + assert.equal(isAbortError(new RpcError('the node says no', 20)), false); + assert.equal(isAbortError(new RpcError('the node says no', 'ABORT_ERR')), false); + assert.equal(isAbortError(abortErr()), true); + assert.equal(isAbortError(Object.assign(new Error('legacy DOMException shape'), { code: 20 })), true); + // …so before the broadcast it is an ordinary failure, not a cancellation nobody asked for. + assert.equal(outcomeOf({ phase: 'witness', error: new RpcError('the node says no', 20) }), 'not-sent'); +}); + +test('CLI-1006: the confirmation read answered with JSON-RPC code 20 says "outcome unknown", not "cancelled"', async (t) => { + const { b, ctl } = controlledSend(); + const { root } = await review(t, b); + root.querySelector('[data-action="prove"]').click(); + await turns(); + ctl.emit('submitting'); + ctl.emit('confirming'); // the transaction is with the node; the wallet is reading for it + await turns(); + ctl.fail(new RpcError('rand_getTransaction: try later', 20)); + await turns(); + + assert.match(root.textContent, /We couldn.t confirm this transfer/i); + assert.match(root.textContent, /may already have been sent/i); + assert.ok(root.querySelector('[data-role="check-activity"]'), 'the way out is Activity'); + assertGone(root.querySelector('[data-action="prove"]'), 'no way to prove it again'); + assertGone(root.querySelector('[data-role="retry"]'), 'and no retry'); +}); From b9ea76299bfc05266017aa8eeb37bdcc28a0d4e9 Mon Sep 17 00:00:00 2001 From: Dendi Suhubdy <4477337+dendisuhubdy@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:33:52 +0800 Subject: [PATCH 5/7] =?UTF-8?q?CLI-1009:=20a=20block=20whose=20header=20an?= =?UTF-8?q?nounced=20transactions=20and=20whose=20body=20is=20null=20or=20?= =?UTF-8?q?short=20is=20not=20read=20as=20empty=20=E2=80=94=20the=20deposi?= =?UTF-8?q?t=20cursor=20stays=20under=20it?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The shared JS engine, the Android walk and the iOS walk all advanced the bridge-deposit cursor past a block whose header said tx_count > 0 and whose body came back null or with no transactions: a deposit in it was never looked for again. - ui/engine: checkBlockActions takes the header's tx_count and refuses a null or short body; depositsByHeader passes it, so the walk stops under the block, reports it (bridgeUnknown) and the next scan asks again. The one-block-at-a-time path stops at a null block under the node's own tip. Tests added; two fixtures that served an empty body under a header announcing one now serve what the header says. - android DepositWalk.java: the same rule (served()), with unit tests. NOT compiled or run: no JDK on this machine. - ios DepositWalk.swift / RpcClient.swift / WalletService.swift: the walk hands tx_count to the block read, and RpcClient.actions(ofBlock:) refuses a null or short body, with unit tests. Type-checked with swiftc only (RpcClient, DepositWalk, the walk tests); not built or run, and the WalletService call site was not type-checked. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01GFs5h2CVCmdBKerZzH2Xrx --- .../wallet/wallet/DepositWalk.java | 21 +++++ .../wallet/wallet/DepositWalkTest.java | 74 ++++++++++++++++ ios/RandWallet/Network/RpcClient.swift | 26 +++++- ios/RandWallet/Services/DepositWalk.swift | 17 ++-- ios/RandWallet/Services/WalletService.swift | 2 +- ios/RandWalletTests/DepositWalkTests.swift | 67 ++++++++++++-- ui/engine/validate.js | 17 +++- ui/engine/wallet.js | 16 +++- ui/locales/ar.js | 1 + ui/locales/de.js | 1 + ui/locales/en.js | 3 +- ui/locales/es.js | 1 + ui/locales/fa.js | 1 + ui/locales/fr.js | 1 + ui/locales/hi.js | 1 + ui/locales/id.js | 1 + ui/locales/it.js | 1 + ui/locales/ja.js | 1 + ui/locales/ko.js | 1 + ui/locales/ms.js | 1 + ui/locales/pl.js | 1 + ui/locales/ps.js | 1 + ui/locales/pt.js | 1 + ui/locales/ru.js | 1 + ui/locales/ta.js | 1 + ui/locales/ur.js | 1 + ui/locales/zh-hk.js | 1 + ui/locales/zh.js | 1 + ui/test/engine-wallet.test.mjs | 87 ++++++++++++++++++- ui/test/validate.test.mjs | 16 ++++ 30 files changed, 342 insertions(+), 23 deletions(-) diff --git a/android/app/src/main/java/org/randprotocol/wallet/wallet/DepositWalk.java b/android/app/src/main/java/org/randprotocol/wallet/wallet/DepositWalk.java index 3fc3bc5..c6d610e 100644 --- a/android/app/src/main/java/org/randprotocol/wallet/wallet/DepositWalk.java +++ b/android/app/src/main/java/org/randprotocol/wallet/wallet/DepositWalk.java @@ -30,6 +30,9 @@ * blocks together; a longer gap is closed over several scans. *
  • A node with no {@code rand_getBlocks} is read one block at a time, at most * {@link #MAX_HEIGHTS_WITHOUT_HEADERS} a scan.
  • + *
  • A block whose header announced transactions and whose body is null, or carries fewer, was + * not served (CLI-1009): the walk stops under it, {@link Result#unknown}. So does a null + * block under the node's own tip on the one-at-a-time path.
  • * * The core refusing an action it was handed is this wallet's own failure and is thrown, not * reported as unknown. @@ -98,6 +101,10 @@ static Result run(Node node, long start, long head, Sink sink) throws CoreExcept } catch (RpcException e) { return new Result(examined, true); } + // CLI-1009: the header announced `counts[i]` transactions. A body that is + // null, or carries fewer, is a block the node did not serve — not one with + // no actions. The cursor stays under it and the next scan asks again. + if (!served(block, counts[i])) return new Result(examined, true); offerAttests(block, sink); } examined = height; @@ -118,6 +125,9 @@ private static Result oneByOne(Node node, long start, long head, Sink sink) thro } catch (RpcException e) { return new Result(examined, true); } + // CLI-1009: `h` is at or under the tip this node named, so null is a block it did not + // serve (an honest node answers a pruned height with an error), not an empty one. + if (block == null) return new Result(examined, true); offerAttests(block, sink); examined = h; } @@ -158,6 +168,17 @@ private static long wholeNumber(JSONObject row, String name, int i) throws RpcEx throw new RpcException(0, "rand_getBlocks: header " + i + " " + name + " is not a non-negative integer"); } + /** + * Whether {@code block} is the body its header announced: there at all, and with at least + * {@code announced} transactions (CLI-1009, audit v14). More than announced withholds nothing. + */ + static boolean served(JSONObject block, long announced) { + if (block == null) return false; + JSONArray txs = block.optJSONArray("transactions"); + long got = txs == null ? 0 : txs.length(); + return got >= announced; + } + private static void offerAttests(JSONObject block, Sink sink) throws CoreException, JSONException { if (block == null) return; JSONArray txs = block.optJSONArray("transactions"); diff --git a/android/app/src/test/java/org/randprotocol/wallet/wallet/DepositWalkTest.java b/android/app/src/test/java/org/randprotocol/wallet/wallet/DepositWalkTest.java index fdb659c..0b39834 100644 --- a/android/app/src/test/java/org/randprotocol/wallet/wallet/DepositWalkTest.java +++ b/android/app/src/test/java/org/randprotocol/wallet/wallet/DepositWalkTest.java @@ -191,6 +191,80 @@ public JSONObject block(long height) throws RpcException { assertTrue(r[0].unknown); } + /** {@code honest}'s headers, with the body of block {@code at} replaced by {@code body}. */ + private static DepositWalk.Node withBody(Node honest, long at, JSONObject body) { + return new DepositWalk.Node() { + @Override + public JSONArray headers(long from, long to) throws RpcException { + return honest.headers(from, to); + } + + @Override + public JSONObject block(long height) throws RpcException { + JSONObject real = honest.block(height); + return height == at ? body : real; + } + }; + } + + /** + * CLI-1009 (audit v14): the header said the block carries a transaction and the body came back + * null, or with none. That is a block the node did not serve; the cursor stays under it. + */ + @Test + public void aBlockWhoseHeaderAnnouncedTransactionsAndWhoseBodyIsNullOrShortDoesNotMoveTheCursor() throws Exception { + JSONObject[] bodies = { + null, + new JSONObject().put("height", 2000), + new JSONObject().put("height", 2000).put("transactions", new JSONArray()), + }; + for (int i = 0; i < bodies.length; i++) { + Node honest = new Node(3000, 7L, 2000L); + DepositWalk.Result[] r = new DepositWalk.Result[1]; + List seen = offered(withBody(honest, 2000, bodies[i]), 0, 3000, r); + assertEquals("body " + i, Arrays.asList(7L), seen); + assertEquals("body " + i + " moved the cursor past a block that was not read", 1999, r[0].through); + assertTrue("body " + i + " was not reported", r[0].unknown); + assertEquals("body " + i + ": the block was asked for", Arrays.asList(7L, 2000L), honest.opened); + } + // The same node answering honestly on the next scan is read from where the walk stopped. + Node honest = new Node(3000, 7L, 2000L); + DepositWalk.Result[] r = new DepositWalk.Result[1]; + assertEquals(Arrays.asList(2000L), offered(honest, 2000, 3000, r)); + assertEquals(3000, r[0].through); + assertFalse(r[0].unknown); + } + + @Test + public void servedHoldsABodyToItsHeader() throws Exception { + JSONObject two = new JSONObject().put("transactions", new JSONArray().put(new JSONObject()).put(new JSONObject())); + assertFalse(DepositWalk.served(null, 1)); + assertFalse(DepositWalk.served(new JSONObject(), 1)); + assertFalse(DepositWalk.served(two, 3)); + assertTrue(DepositWalk.served(two, 2)); + assertTrue("more than announced withholds nothing", DepositWalk.served(two, 1)); + } + + /** CLI-1009, the one-at-a-time path: a null block under the node's own tip stops the walk. */ + @Test + public void withoutGetBlocksANullBlockUnderTheTipStopsTheWalkThere() throws Exception { + Node honest = new Node(5000); + DepositWalk.Node node = new DepositWalk.Node() { + @Override + public JSONArray headers(long from, long to) throws RpcException { + throw new RpcException(-32601, "unknown method rand_getBlocks"); + } + + @Override + public JSONObject block(long height) throws RpcException { + return height == 40 ? null : honest.block(height); + } + }; + DepositWalk.Result r = DepositWalk.run(node, 0, 5000, action -> { }); + assertEquals(39, r.through); + assertTrue(r.unknown); + } + @Test public void aNodeWithNoGetBlocksIsReadOneBlockAtATimeAndCapped() throws Exception { Node honest = new Node(5000); diff --git a/ios/RandWallet/Network/RpcClient.swift b/ios/RandWallet/Network/RpcClient.swift index fecdb5a..d94658d 100644 --- a/ios/RandWallet/Network/RpcClient.swift +++ b/ios/RandWallet/Network/RpcClient.swift @@ -301,10 +301,28 @@ final class RpcClient { try await call("rand_getBlocks", [from, to]) } - func blockActions(height: UInt64) async throws -> [Any] { - let b = try await call("rand_getBlockByHeight", [height]) as? [String: Any] - let txs = b?["transactions"] as? [[String: Any]] ?? [] - return txs.compactMap { $0["action"] } + /// The actions of the block at `height`, held to what its header said (CLI-1009, audit v14). + /// `announced` is the header's `tx_count` when `DepositWalk` read one, `nil` when it is + /// reading block by block. + func blockActions(height: UInt64, announced: UInt64? = nil) async throws -> [Any] { + try Self.actions(ofBlock: try await call("rand_getBlockByHeight", [height]), height: height, announced: announced) + } + + /// The actions in a `rand_getBlockByHeight` reply — or an error when the reply is not the + /// block that was asked for: `null` (or anything that is not an object) for a height at or + /// under the tip the node named, or fewer transactions than its header announced. Read as "no + /// actions", either moved the deposit cursor past a block that was never served, and a bridge + /// deposit in it was never looked for again. An honest node answers a pruned height with an + /// error, never with `null`. More transactions than announced withholds nothing. + static func actions(ofBlock reply: Any?, height: UInt64, announced: UInt64?) throws -> [Any] { + guard let block = reply as? [String: Any] else { + throw RpcError(code: 0, message: "rand_getBlockByHeight: the node has no block \(height) under the tip it named") + } + let txs = block["transactions"] as? [Any] ?? [] + if let n = announced, UInt64(txs.count) < n { + throw RpcError(code: 0, message: "rand_getBlockByHeight: block \(height) has \(txs.count) of the \(n) transactions its header announced") + } + return txs.compactMap { ($0 as? [String: Any])?["action"] } } // MARK: RPL-2 program state (fullnode v0.6.8, `docs/rpc.md`) diff --git a/ios/RandWallet/Services/DepositWalk.swift b/ios/RandWallet/Services/DepositWalk.swift index 6ea669a..4a35d6d 100644 --- a/ios/RandWallet/Services/DepositWalk.swift +++ b/ios/RandWallet/Services/DepositWalk.swift @@ -23,6 +23,9 @@ import Foundation /// together; a longer gap is closed over several scans. /// * A node with no `rand_getBlocks` is read one block at a time, at most /// `maxHeightsWithoutHeaders` a scan. +/// * A block whose header announced transactions and whose body is `null`, or carries fewer, was +/// not served (CLI-1009): the walk stops under it, `unknown`. So does a `null` block under the +/// node's own tip on the one-at-a-time path. /// /// The core refusing an action it was handed is this wallet's own failure and is thrown, not /// reported as unknown. @@ -48,13 +51,17 @@ enum DepositWalk { /// - Parameters: /// - headers: `rand_getBlocks(from, to)`, raw. - /// - actions: the actions of the block at a height (`rand_getBlockByHeight`). + /// - actions: the actions of the block at a height (`rand_getBlockByHeight`). Its second + /// argument is the `tx_count` the block's header announced, `nil` when no header was read + /// (a node without `rand_getBlocks`). It throws for a block that was not served — `null`, + /// or fewer transactions than announced (CLI-1009; `RpcClient.actions(ofBlock:…)`) — and + /// the walk then stops under that block, as for any other read the node refused. /// - offer: where each `bridge_attest` action found goes; what it throws is thrown. static func run( start: UInt64, head: UInt64, headers: (UInt64, UInt64) async throws -> Any, - actions: (UInt64) async throws -> [Any], + actions: (UInt64, UInt64?) async throws -> [Any], offer: (Any) throws -> Void ) async throws -> Result { var next = start @@ -83,7 +90,7 @@ enum DepositWalk { budget -= 1 let found: [Any] do { - found = try await actions(height) + found = try await actions(height, count) } catch is CancellationError { throw CancellationError() } catch { @@ -102,7 +109,7 @@ enum DepositWalk { private static func oneByOne( start: UInt64, head: UInt64, - actions: (UInt64) async throws -> [Any], + actions: (UInt64, UInt64?) async throws -> [Any], offer: (Any) throws -> Void ) async throws -> Result { var next = start @@ -111,7 +118,7 @@ enum DepositWalk { for h in start...last { let found: [Any] do { - found = try await actions(h) + found = try await actions(h, nil) } catch is CancellationError { throw CancellationError() } catch { diff --git a/ios/RandWallet/Services/WalletService.swift b/ios/RandWallet/Services/WalletService.swift index 65ef750..842c8c8 100644 --- a/ios/RandWallet/Services/WalletService.swift +++ b/ios/RandWallet/Services/WalletService.swift @@ -171,7 +171,7 @@ final class WalletService: ObservableObject { start: s.scannedAttestHeight, head: head0, headers: { try await rpc.blockHeaders(from: $0, to: $1) }, - actions: { try await rpc.blockActions(height: $0) }, + actions: { try await rpc.blockActions(height: $0, announced: $1) }, offer: { action in let kind = (action as? [String: Any])?["kind"] as? String if let fr = feeRecipient { diff --git a/ios/RandWalletTests/DepositWalkTests.swift b/ios/RandWalletTests/DepositWalkTests.swift index a65c4d9..154e492 100644 --- a/ios/RandWalletTests/DepositWalkTests.swift +++ b/ios/RandWalletTests/DepositWalkTests.swift @@ -33,7 +33,7 @@ final class DepositWalkTests: XCTestCase { let r = try await DepositWalk.run( start: start, head: node.head, headers: { node.headers($0, $1) }, - actions: { node.actions($0) }, + actions: { h, _ in node.actions(h) }, offer: { found.append(($0 as? [String: Any])?["at"] as? UInt64 ?? 0) }) seen = found return r @@ -99,7 +99,7 @@ final class DepositWalkTests: XCTestCase { let r = try await DepositWalk.run( start: 0, head: 50, headers: { forge(honest.headers($0, $1) as! [[String: Any]]) }, - actions: { _ in XCTFail("a page that \(why) led to a block being opened"); return [] }, + actions: { _, _ in XCTFail("a page that \(why) led to a block being opened"); return [] }, offer: { _ in }) XCTAssertEqual(r, DepositWalk.Result(next: 0, unknown: true), "a page that \(why)") } @@ -111,7 +111,7 @@ final class DepositWalkTests: XCTestCase { let r = try await DepositWalk.run( start: 0, head: 3000, headers: { node.headers($0, $1) }, - actions: { h in + actions: { h, _ in if h == 2000 { throw RpcClient.RpcError(code: 429, message: "node answered HTTP 429", isHTTP: true) } return node.actions(h) }, @@ -125,7 +125,7 @@ final class DepositWalkTests: XCTestCase { let r = try await DepositWalk.run( start: 0, head: 5000, headers: { _, _ in throw RpcClient.RpcError(code: -32601, message: "unknown method rand_getBlocks") }, - actions: { node.actions($0) }, + actions: { h, _ in node.actions(h) }, offer: { _ in }) XCTAssertEqual(UInt64(node.opened.count), DepositWalk.maxHeightsWithoutHeaders) XCTAssertEqual(r, DepositWalk.Result(next: DepositWalk.maxHeightsWithoutHeaders, unknown: false)) @@ -137,7 +137,7 @@ final class DepositWalkTests: XCTestCase { let r = try await DepositWalk.run( start: 0, head: 3, headers: { node.headers($0, $1) }, - actions: { _ in [["kind": "bundle"], "not an action", ["kind": "bridge_attest", "at": UInt64(2)], ["kind": "bridge_burn", "at": UInt64(3)]] }, + actions: { _, _ in [["kind": "bundle"], "not an action", ["kind": "bridge_attest", "at": UInt64(2)], ["kind": "bridge_burn", "at": UInt64(3)]] }, offer: { seen.append(($0 as? [String: Any])?["at"] as? UInt64 ?? 0) }) XCTAssertEqual(seen, [2, 3], "a burn is offered too: its fee note is the fee recipient's (v0.6.8)") XCTAssertEqual(r.next, 4) @@ -150,12 +150,67 @@ final class DepositWalkTests: XCTestCase { _ = try await DepositWalk.run( start: 0, head: 10, headers: { node.headers($0, $1) }, - actions: { node.actions($0) }, + actions: { h, _ in node.actions(h) }, offer: { _ in throw CoreSaidNo() }) XCTFail("the core's refusal was swallowed") } catch is CoreSaidNo {} } + // MARK: CLI-1009 — a header that announced transactions, and no body + + /// A `rand_getBlockByHeight` reply is held to the header that announced it: `null`, or fewer + /// transactions than `tx_count`, is a block the node did not serve. + func testABlockReplyIsHeldToItsHeader() throws { + let tx: [String: Any] = ["action": ["kind": "bridge_attest"]] + let short: [Any?] = [nil, NSNull(), "block", [String: Any](), ["transactions": [Any]()], ["transactions": [tx]]] + for reply in short { + XCTAssertThrowsError(try RpcClient.actions(ofBlock: reply as Any?, height: 77, announced: 2), "\(String(describing: reply))") { + XCTAssertTrue(($0 as? RpcClient.RpcError)?.message.contains("77") ?? false) + } + } + XCTAssertEqual(try RpcClient.actions(ofBlock: ["transactions": [tx, tx]], height: 77, announced: 2).count, 2) + XCTAssertEqual(try RpcClient.actions(ofBlock: ["transactions": [tx, tx, tx]], height: 77, announced: 2).count, 3, "more than announced withholds nothing") + // No header read (a node without rand_getBlocks): the block must still be there. + XCTAssertEqual(try RpcClient.actions(ofBlock: ["transactions": [Any]()], height: 77, announced: nil).count, 0) + XCTAssertThrowsError(try RpcClient.actions(ofBlock: NSNull(), height: 77, announced: nil)) + } + + /// The walk hands the header's `tx_count` to the block read, and a block that read refuses + /// (as `RpcClient.actions(ofBlock:…)` does for a null or short body) stops the cursor under it. + func testABlockWhoseHeaderAnnouncedTransactionsAndWhoseBodyIsNullDoesNotMoveTheCursor() async throws { + let node = Node(head: 3000, busy: [7, 2000]) + var seen: [UInt64] = [] + var announced: [UInt64?] = [] + let r = try await DepositWalk.run( + start: 0, head: 3000, + headers: { node.headers($0, $1) }, + actions: { h, count in + announced.append(count) + _ = node.actions(h) + // Block 2000 comes back `null`; every other block carries what its header said. + let reply: Any = h == 2000 ? NSNull() : ["transactions": [["action": ["kind": "bridge_attest", "at": h] as [String: Any]]]] + return try RpcClient.actions(ofBlock: reply, height: h, announced: count) + }, + offer: { seen.append(($0 as? [String: Any])?["at"] as? UInt64 ?? 0) }) + XCTAssertEqual(seen, [7]) + XCTAssertEqual(announced, [1, 1], "the header's tx_count reaches the block read") + XCTAssertEqual(node.opened, [7, 2000], "the block was asked for") + XCTAssertEqual(r, DepositWalk.Result(next: 2000, unknown: true), "the cursor moved past a block that was never read") + } + + func testWithoutGetBlocksANullBlockUnderTheTipStopsTheWalkThere() async throws { + let r = try await DepositWalk.run( + start: 0, head: 5000, + headers: { _, _ in throw RpcClient.RpcError(code: -32601, message: "unknown method rand_getBlocks") }, + actions: { h, count in + XCTAssertNil(count, "no header was read, so nothing was announced") + let reply: Any = h == 40 ? NSNull() : ["transactions": [Any]()] + return try RpcClient.actions(ofBlock: reply, height: h, announced: count) + }, + offer: { _ in }) + XCTAssertEqual(r, DepositWalk.Result(next: 40, unknown: true)) + } + // MARK: HTTP 429 in the RPC client /// A client over `StubProver` whose waits are recorded, not slept. diff --git a/ui/engine/validate.js b/ui/engine/validate.js index 07292fd..07c6243 100644 --- a/ui/engine/validate.js +++ b/ui/engine/validate.js @@ -464,12 +464,25 @@ export function checkGenesisHash(reply) { * the cursor under the block, and asked for the same block on every scan after. Only an oversize * action of a kind that IS read still refuses, and that cap is the caller's to size for what the * core can take. + * + * `announced` and `height`, when given, hold the body to its header — see the first lines below. */ -export function checkBlockActions(reply, { maxTransactions = 4096, maxActionChars = 8192, kinds = null } = {}) { +export function checkBlockActions(reply, { maxTransactions = 4096, maxActionChars = 8192, kinds = null, announced = 0, height = null } = {}) { const m = 'rand_getBlockByHeight'; - if (reply === null || reply === undefined) return []; + // CLI-1009 (audit v14). `announced` is the `tx_count` the block's HEADER gave, when the caller + // read one: a body that is `null`, or carries fewer transactions than that, is not a block with + // no actions — it is a block that was not served, and reading it as empty moved the deposit + // cursor past it for good. An honest node answers a pruned height with an error, never with + // `null`. More transactions than announced withholds nothing and is left alone. + const want = Number.isSafeInteger(announced) && announced > 0 ? announced : 0; + const short = (got) => fail(m, t('block {height} has {got} of the {n} transactions its header announced', { height: height ?? '?', got, n: want })); + if (reply === null || reply === undefined) { + if (want) short(0); + return []; + } if (typeof reply !== 'object' || Array.isArray(reply)) fail(m, t('the reply is not an object'), reply); const list = Array.isArray(reply.transactions) ? reply.transactions : []; + if (list.length < want) short(list.length); if (list.length > maxTransactions) fail(m, t('the block has {n} transactions', { n: list.length })); const wanted = Array.isArray(kinds) ? new Set(kinds) : null; const actions = []; diff --git a/ui/engine/wallet.js b/ui/engine/wallet.js index cf3a3e7..23b16ac 100644 --- a/ui/engine/wallet.js +++ b/ui/engine/wallet.js @@ -778,8 +778,13 @@ export function makeWallet({ core, store, rpc, settings, annotate = true, onRese let examined = start - 1; for (let h = start; h <= last; h++) { throwIfAborted(signal); + const raw = await client.blockByHeight(h, { signal }); + // No header here to say what the block holds, but `h` is at or under the tip this node just + // named: `null` for it is a block the node did not serve, not an empty one (CLI-1009). The + // walk stops under it and the next scan asks again. + if (raw === null || raw === undefined) return { deposits: out, through: examined, unknown: true }; // Every action is re-parsed into a plain, size-bounded object before it reaches the core. - for (const action of checkBlockActions(await client.blockByHeight(h, { signal }), DEPOSIT_ACTIONS)) { + for (const action of checkBlockActions(raw, DEPOSIT_ACTIONS)) { for (const note of await notesOf(spendKey, action, feeRecipient)) out.set(note.cm, note); } examined = h; @@ -841,7 +846,14 @@ export function makeWallet({ core, store, rpc, settings, annotate = true, onRese throwIfAborted(signal); budget -= 1; // Every action is re-parsed into a plain, size-bounded object before it reaches the core. - const block = await ask(async () => checkBlockActions(await client.blockByHeight(header.height, { signal }), DEPOSIT_ACTIONS)); + // …and held to the header that announced it (CLI-1009): a body that is `null` or short + // of `tx_count` is a block that was not served. It is refused like any other reply the + // node did not give — the cursor stays under it, the caller is told (`unknown`), and the + // next scan asks for the same block again. + const block = await ask(async () => checkBlockActions( + await client.blockByHeight(header.height, { signal }), + { ...DEPOSIT_ACTIONS, announced: header.tx_count, height: header.height }, + )); if (block.failed) return { deposits: out, through: examined, unknown: true }; for (const action of block.value) { for (const note of await notesOf(spendKey, action, feeRecipient)) out.set(note.cm, note); diff --git a/ui/locales/ar.js b/ui/locales/ar.js index fc339da..01f4341 100644 --- a/ui/locales/ar.js +++ b/ui/locales/ar.js @@ -1128,4 +1128,5 @@ export default { "the record is damaged": "السجل تالف", "the record was saved by a newer version of Rand Wallet": "حُفظ السجل بإصدار أحدث من Rand Wallet", "the record does not open with this password": "لا يُفتح السجل بكلمة المرور هذه", + "block {height} has {got} of the {n} transactions its header announced": "الكتلة {height} تحتوي على {got} من أصل {n} معاملة أعلنت عنها ترويستها", }; diff --git a/ui/locales/de.js b/ui/locales/de.js index 267b542..f89f528 100644 --- a/ui/locales/de.js +++ b/ui/locales/de.js @@ -1128,4 +1128,5 @@ export default { "the record is damaged": "der Datensatz ist beschädigt", "the record was saved by a newer version of Rand Wallet": "der Datensatz wurde von einer neueren Version von Rand Wallet gespeichert", "the record does not open with this password": "der Datensatz lässt sich mit diesem Passwort nicht öffnen", + "block {height} has {got} of the {n} transactions its header announced": "Block {height} enthält {got} der {n} Transaktionen, die sein Header angekündigt hat", }; diff --git a/ui/locales/en.js b/ui/locales/en.js index 7b44831..7c29305 100644 --- a/ui/locales/en.js +++ b/ui/locales/en.js @@ -4,7 +4,7 @@ // value, or an object of CLDR plural categories ({one, few, many, other}) for a key with an // {n} hole whose translation inflects by number. `{name}` holes and the words in the glossary // at the top of each dictionary are kept as they are. -// 1121 strings. +// 1122 strings. export default { "{amount} {symbol}": "{amount} {symbol}", "{blocks} blocks left to prove it.": "{blocks} blocks left to prove it.", @@ -181,6 +181,7 @@ export default { "Balance": "Balance", "Before the first send through the RandProtocol provers, read what they can see: the one that proves it gets this wallet's viewing key. Continue on the send screen, or pair your own prover in Settings.": "Before the first send through the RandProtocol provers, read what they can see: the one that proves it gets this wallet's viewing key. Continue on the send screen, or pair your own prover in Settings.", "Block": "Block", + "block {height} has {got} of the {n} transactions its header announced": "block {height} has {got} of the {n} transactions its header announced", "block {height} has {n} or more nullifiers; this wallet cannot page inside one block": "block {height} has {n} or more nullifiers; this wallet cannot page inside one block", "Bridge": "Bridge", "Bridge fee": "Bridge fee", diff --git a/ui/locales/es.js b/ui/locales/es.js index 13162f2..e634cf5 100644 --- a/ui/locales/es.js +++ b/ui/locales/es.js @@ -1128,4 +1128,5 @@ export default { "the record is damaged": "el registro está dañado", "the record was saved by a newer version of Rand Wallet": "el registro se guardó con una versión más reciente de Rand Wallet", "the record does not open with this password": "el registro no se abre con esta contraseña", + "block {height} has {got} of the {n} transactions its header announced": "el bloque {height} tiene {got} de las {n} transacciones que anunció su cabecera", }; diff --git a/ui/locales/fa.js b/ui/locales/fa.js index b22bfac..fb95ade 100644 --- a/ui/locales/fa.js +++ b/ui/locales/fa.js @@ -1129,4 +1129,5 @@ export default { "the record is damaged": "رکورد آسیب دیده است", "the record was saved by a newer version of Rand Wallet": "رکورد با نسخه‌ی جدیدتری از Rand Wallet ذخیره شده است", "the record does not open with this password": "رکورد با این گذرواژه باز نمی‌شود", + "block {height} has {got} of the {n} transactions its header announced": "بلوک {height} تنها {got} تراکنش از {n} تراکنشی را دارد که سرآیندش اعلام کرده بود", }; diff --git a/ui/locales/fr.js b/ui/locales/fr.js index c24b5e7..7b64d87 100644 --- a/ui/locales/fr.js +++ b/ui/locales/fr.js @@ -1130,4 +1130,5 @@ export default { "the record is damaged": "l'enregistrement est endommagé", "the record was saved by a newer version of Rand Wallet": "l'enregistrement a été sauvegardé par une version plus récente de Rand Wallet", "the record does not open with this password": "l'enregistrement ne s'ouvre pas avec ce mot de passe", + "block {height} has {got} of the {n} transactions its header announced": "le bloc {height} contient {got} des {n} transactions annoncées par son en-tête", }; diff --git a/ui/locales/hi.js b/ui/locales/hi.js index bd27609..fcbeab5 100644 --- a/ui/locales/hi.js +++ b/ui/locales/hi.js @@ -1128,4 +1128,5 @@ export default { "the record is damaged": "रिकॉर्ड खराब है", "the record was saved by a newer version of Rand Wallet": "रिकॉर्ड Rand Wallet के नए संस्करण से सहेजा गया था", "the record does not open with this password": "रिकॉर्ड इस पासवर्ड से नहीं खुलता", + "block {height} has {got} of the {n} transactions its header announced": "ब्लॉक {height} में उसके हेडर द्वारा घोषित {n} लेनदेन में से {got} हैं", }; diff --git a/ui/locales/id.js b/ui/locales/id.js index ab311cf..cde6a61 100644 --- a/ui/locales/id.js +++ b/ui/locales/id.js @@ -1121,4 +1121,5 @@ export default { "the record is damaged": "rekaman rusak", "the record was saved by a newer version of Rand Wallet": "rekaman disimpan oleh versi Rand Wallet yang lebih baru", "the record does not open with this password": "rekaman tidak terbuka dengan kata sandi ini", + "block {height} has {got} of the {n} transactions its header announced": "blok {height} berisi {got} dari {n} transaksi yang diumumkan header-nya", }; diff --git a/ui/locales/it.js b/ui/locales/it.js index 49c5362..931e998 100644 --- a/ui/locales/it.js +++ b/ui/locales/it.js @@ -1128,4 +1128,5 @@ export default { "the record is damaged": "il record è danneggiato", "the record was saved by a newer version of Rand Wallet": "il record è stato salvato da una versione più recente di Rand Wallet", "the record does not open with this password": "il record non si apre con questa password", + "block {height} has {got} of the {n} transactions its header announced": "il blocco {height} contiene {got} delle {n} transazioni annunciate dalla sua intestazione", }; diff --git a/ui/locales/ja.js b/ui/locales/ja.js index cb13e49..c3dffb4 100644 --- a/ui/locales/ja.js +++ b/ui/locales/ja.js @@ -1121,4 +1121,5 @@ export default { "the record is damaged": "レコードが破損しています", "the record was saved by a newer version of Rand Wallet": "レコードは新しいバージョンの Rand Wallet で保存されています", "the record does not open with this password": "このパスワードではレコードを開けません", + "block {height} has {got} of the {n} transactions its header announced": "ブロック {height} には、ヘッダーが示した {n} 件のトランザクションのうち {got} 件しかありません", }; diff --git a/ui/locales/ko.js b/ui/locales/ko.js index 4e89bb1..bce5ea3 100644 --- a/ui/locales/ko.js +++ b/ui/locales/ko.js @@ -1121,4 +1121,5 @@ export default { "the record is damaged": "레코드가 손상되었습니다", "the record was saved by a newer version of Rand Wallet": "레코드가 더 새로운 버전의 Rand Wallet에서 저장되었습니다", "the record does not open with this password": "이 비밀번호로는 레코드가 열리지 않습니다", + "block {height} has {got} of the {n} transactions its header announced": "블록 {height}에는 헤더가 알린 트랜잭션 {n}개 중 {got}개만 있습니다", }; diff --git a/ui/locales/ms.js b/ui/locales/ms.js index cf45e25..7a81c7b 100644 --- a/ui/locales/ms.js +++ b/ui/locales/ms.js @@ -1123,4 +1123,5 @@ export default { "the record is damaged": "rekod rosak", "the record was saved by a newer version of Rand Wallet": "rekod disimpan oleh versi Rand Wallet yang lebih baharu", "the record does not open with this password": "rekod tidak terbuka dengan kata laluan ini", + "block {height} has {got} of the {n} transactions its header announced": "blok {height} mengandungi {got} daripada {n} transaksi yang diumumkan oleh pengepalanya", }; diff --git a/ui/locales/pl.js b/ui/locales/pl.js index cdcf3aa..d145681 100644 --- a/ui/locales/pl.js +++ b/ui/locales/pl.js @@ -1124,4 +1124,5 @@ export default { "the record is damaged": "rekord jest uszkodzony", "the record was saved by a newer version of Rand Wallet": "rekord został zapisany przez nowszą wersję Rand Wallet", "the record does not open with this password": "rekord nie otwiera się tym hasłem", + "block {height} has {got} of the {n} transactions its header announced": "blok {height} zawiera {got} z {n} transakcji zapowiedzianych w nagłówku", }; diff --git a/ui/locales/ps.js b/ui/locales/ps.js index c43640b..21f213e 100644 --- a/ui/locales/ps.js +++ b/ui/locales/ps.js @@ -1128,4 +1128,5 @@ export default { "the record is damaged": "ریکارډ خراب شوی", "the record was saved by a newer version of Rand Wallet": "ریکارډ د Rand Wallet د نوې نسخې لخوا خوندي شوی", "the record does not open with this password": "ریکارډ د دې پاسورډ سره نه خلاصېږي", + "block {height} has {got} of the {n} transactions its header announced": "بلاک {height} د هغو {n} راکړو ورکړو څخه {got} لري چې سرلیک یې اعلان کړې وې", }; diff --git a/ui/locales/pt.js b/ui/locales/pt.js index 2f7e958..19b5597 100644 --- a/ui/locales/pt.js +++ b/ui/locales/pt.js @@ -1128,4 +1128,5 @@ export default { "the record is damaged": "o registro está danificado", "the record was saved by a newer version of Rand Wallet": "o registro foi salvo por uma versão mais nova da Rand Wallet", "the record does not open with this password": "o registro não abre com esta senha", + "block {height} has {got} of the {n} transactions its header announced": "o bloco {height} tem {got} das {n} transações que seu cabeçalho anunciou", }; diff --git a/ui/locales/ru.js b/ui/locales/ru.js index 225645a..cdffd00 100644 --- a/ui/locales/ru.js +++ b/ui/locales/ru.js @@ -1126,4 +1126,5 @@ export default { "the record is damaged": "запись повреждена", "the record was saved by a newer version of Rand Wallet": "запись сохранена более новой версией Rand Wallet", "the record does not open with this password": "запись не открывается этим паролем", + "block {height} has {got} of the {n} transactions its header announced": "блок {height} содержит {got} из {n} транзакций, объявленных в его заголовке", }; diff --git a/ui/locales/ta.js b/ui/locales/ta.js index 3c92d6a..ea51546 100644 --- a/ui/locales/ta.js +++ b/ui/locales/ta.js @@ -1128,4 +1128,5 @@ export default { "the record is damaged": "பதிவு சேதமடைந்துள்ளது", "the record was saved by a newer version of Rand Wallet": "பதிவு Rand Wallet இன் புதிய பதிப்பால் சேமிக்கப்பட்டது", "the record does not open with this password": "இந்தக் கடவுச்சொல்லால் பதிவு திறக்கவில்லை", + "block {height} has {got} of the {n} transactions its header announced": "தொகுதி {height} அதன் தலைப்பு அறிவித்த {n} பரிவர்த்தனைகளில் {got} மட்டுமே கொண்டுள்ளது", }; diff --git a/ui/locales/ur.js b/ui/locales/ur.js index 10ccf93..512b3d8 100644 --- a/ui/locales/ur.js +++ b/ui/locales/ur.js @@ -1129,4 +1129,5 @@ export default { "the record is damaged": "ریکارڈ خراب ہے", "the record was saved by a newer version of Rand Wallet": "ریکارڈ Rand Wallet کے نئے ورژن نے محفوظ کیا تھا", "the record does not open with this password": "ریکارڈ اس پاس ورڈ سے نہیں کھلتا", + "block {height} has {got} of the {n} transactions its header announced": "بلاک {height} میں اس کے ہیڈر کے اعلان کردہ {n} لین دین میں سے {got} ہیں", }; diff --git a/ui/locales/zh-hk.js b/ui/locales/zh-hk.js index 5fc8345..d6d98e3 100644 --- a/ui/locales/zh-hk.js +++ b/ui/locales/zh-hk.js @@ -1121,4 +1121,5 @@ export default { "the record is damaged": "記錄已損壞", "the record was saved by a newer version of Rand Wallet": "記錄由較新版本的 Rand Wallet 儲存", "the record does not open with this password": "此密碼無法開啟該記錄", + "block {height} has {got} of the {n} transactions its header announced": "區塊 {height} 只有 {got} 筆交易,而其區塊頭宣告了 {n} 筆", }; diff --git a/ui/locales/zh.js b/ui/locales/zh.js index 049c555..2ba4a18 100644 --- a/ui/locales/zh.js +++ b/ui/locales/zh.js @@ -1121,4 +1121,5 @@ export default { "the record is damaged": "记录已损坏", "the record was saved by a newer version of Rand Wallet": "记录由更新版本的 Rand Wallet 保存", "the record does not open with this password": "此密码无法打开该记录", + "block {height} has {got} of the {n} transactions its header announced": "区块 {height} 只有 {got} 笔交易,而其区块头声明了 {n} 笔", }; diff --git a/ui/test/engine-wallet.test.mjs b/ui/test/engine-wallet.test.mjs index 0178ab2..71982e1 100644 --- a/ui/test/engine-wallet.test.mjs +++ b/ui/test/engine-wallet.test.mjs @@ -1036,7 +1036,8 @@ test('the walk is budgeted per scan, in requests, and the next scan carries on f head: () => ({ height: head, hash: HEX64('ab') }), bridgeState: () => ({ enabled: true }), getBlocks: headerNode(head, new Set([5, 6]), pages), - blockByHeight: (h) => { opened.push(h); return { height: h, transactions: [] }; }, + // One transaction, as its header announced (`headerNode`): a short body is a refusal (CLI-1009). + blockByHeight: (h) => { opened.push(h); return { height: h, transactions: [{ action: { kind: 'transfer' } }] }; }, // The spend pass is budgeted by its own rule; keep it out of the way of this count. nullifiers: () => [], }); @@ -1065,7 +1066,8 @@ test('a budget spent in the middle of a page stops the cursor at the last block head: () => ({ height: 3000, hash: HEX64('ab') }), bridgeState: () => ({ enabled: true }), getBlocks: headerNode(3000, busy, pages), - blockByHeight: (h) => { opened.push(h); return { height: h, transactions: [] }; }, + // One transaction, as its header announced (`headerNode`): a short body is a refusal (CLI-1009). + blockByHeight: (h) => { opened.push(h); return { height: h, transactions: [{ action: { kind: 'transfer' } }] }; }, }); const wallet = makeWallet({ core: stubCore(), store, rpc: () => client, settings: async () => ({}), annotate: false }); await wallet.scan(SPEND_KEY, {}); @@ -1540,3 +1542,84 @@ for (const [name, run, extraCore] of [ assert.deepEqual(phases, [], 'and \'submit\' was never reported, which is what lets a screen read the phase'); }); } + +// ================== CLI-1009 (audit v14): a header that announced transactions, and no body ==== +// The header said `tx_count > 0`; the block came back `null`, or with fewer transactions than +// announced. That was read as "no actions" and the deposit cursor moved past the block — a bridge +// deposit in it is then never looked for again. An honest node answers a pruned height with an +// error, so this takes a hostile node or replicas that disagree; either way the block was not +// read, and a cursor moves only over what was. +for (const [what, body] of [ + ['null', () => null], + ['an empty transaction list', (h) => ({ height: h, transactions: [] })], + ['fewer transactions than announced', (h) => ({ height: h, transactions: [{ action: { kind: 'transfer' } }] })], + ['no transaction list at all', (h) => ({ height: h })], +]) { + test(`CLI-1009: a block whose header announced 2 transactions and whose body is ${what} does not move the cursor`, async () => { + const store = memoryStore(); + const deposit = ownedNote(0, { cm: HEX64('de'), from: '00'.repeat(32) }); + let honest = false; + const opened = []; + const client = stubClient({ + head: () => ({ height: 3000, hash: HEX64('ab') }), + bridgeState: () => ({ enabled: true }), + getBlocks: (from, to) => { + const rows = []; + for (let h = from; h <= Math.min(to, 3000); h += 1) rows.push({ height: h, hash: HEX64('ab'), tx_count: h === 2000 ? 2 : 0 }); + return rows; + }, + blockByHeight: (h) => { + opened.push(h); + if (!honest) return body(h); + return { height: h, transactions: [{ action: { kind: 'bridge_attest' } }, { action: { kind: 'transfer' } }] }; + }, + treeInfo: () => ({ next_index: 1, root: HEX64('00'), nullifiers: 0 }), + commitments: (from) => (from === 0 ? [{ index: 0, cm: HEX64('de'), height: 2000, envelope: envelope() }] : []), + }); + const core = stubCore({ rebuilt_deposit: () => ({ ...deposit, index: 18446744073709551615, height: 0 }) }); + const wallet = makeWallet({ core, store, rpc: () => client, settings: async () => ({}), annotate: false }); + + const st = await wallet.scan(SPEND_KEY, {}); + assert.equal(store.current.scanned_attest_height, 2000, 'the cursor moved past a block that was never read'); + assert.equal(st.bridgeUnknown, true, 'and the caller is told the deposits could not all be read'); + assert.equal(store.current.notes.length, 0); + assert.ok(store.current.last_sync_ms > 0, 'the rest of the scan still ran'); + + // The next scan asks for the same block again; an honest answer is read and the walk goes on. + honest = true; + const again = await wallet.scan(SPEND_KEY, {}); + assert.deepEqual(opened, [2000, 2000], 'the block is retried, not skipped'); + assert.equal(store.current.notes.length, 1, 'the deposit in it is found'); + assert.equal(store.current.scanned_attest_height, 3001); + assert.equal(again.bridgeUnknown, undefined); + }); +} + +test('CLI-1009: a block with exactly the transactions its header announced is read as before', async () => { + const store = memoryStore(); + const client = stubClient({ + head: () => ({ height: 100, hash: HEX64('ab') }), + bridgeState: () => ({ enabled: true }), + getBlocks: (from, to) => Array.from({ length: Math.min(to, 100) - from + 1 }, (_, i) => ({ height: from + i, hash: HEX64('ab'), tx_count: from + i === 9 ? 3 : 0 })), + // More than announced is not this rule's business either: nothing was withheld. + blockByHeight: (h) => ({ height: h, transactions: [{ action: { kind: 'transfer' } }, { action: { kind: 'transfer' } }, { action: { kind: 'transfer' } }] }), + }); + const wallet = makeWallet({ core: stubCore(), store, rpc: () => client, settings: async () => ({}), annotate: false }); + const st = await wallet.scan(SPEND_KEY, {}); + assert.equal(store.current.scanned_attest_height, 101); + assert.equal(st.bridgeUnknown, undefined); +}); + +test('CLI-1009: without rand_getBlocks, a height under the node\'s own tip that comes back null stops the walk there', async () => { + const store = memoryStore(); + const client = stubClient({ + head: () => ({ height: 5000, hash: HEX64('ab') }), + bridgeState: () => ({ enabled: true }), + getBlocks: () => { const e = new Error('unknown method rand_getBlocks'); e.code = -32601; throw e; }, + blockByHeight: (h) => (h === 40 ? null : { height: h, transactions: [] }), + }); + const wallet = makeWallet({ core: stubCore(), store, rpc: () => client, settings: async () => ({}), annotate: false }); + const st = await wallet.scan(SPEND_KEY, {}); + assert.equal(store.current.scanned_attest_height, 40, 'the cursor passed a block the node did not serve'); + assert.equal(st.bridgeUnknown, true); +}); diff --git a/ui/test/validate.test.mjs b/ui/test/validate.test.mjs index 97bff06..3c95aea 100644 --- a/ui/test/validate.test.mjs +++ b/ui/test/validate.test.mjs @@ -514,3 +514,19 @@ test('bridge state: v0.6.8 fees are read when the chain has them, and held to th rejects(() => checkBridgeState({ enabled: true, fees: { mint_bps: 10, burn_bps: 10, recipient: '