diff --git a/crates/randscan-viewing/README.md b/crates/randscan-viewing/README.md index 9cac082..1267c2e 100644 --- a/crates/randscan-viewing/README.md +++ b/crates/randscan-viewing/README.md @@ -16,7 +16,12 @@ plus a call's sealed input transcript checked against the receipt's `H_IN`, and v0.6.8, `wallet::rebuilt_notes_with`) `rebuild_note`: a chain-computed note — a bridge deposit, a bridge fee note (no envelope), an RPL mint, an RPL-2 payout — rebuilt from its public opening (randscan's `public`) with the key's own `pk` and accepted only when it commits to the leaf -(`tests/rebuild.rs`, chain 20 block 1664's leaves 19 and 20). No sealing, no +(`tests/rebuild.rs`, chain 20 block 1664's leaves 19 and 20). An opening is +not ownership or authorship (audit v14, SCAN-841 / VK-751): `classify` — the wallet's and the +node's `classify` restated — reports a note as received only when its owner `pk` is the key's +own, as sent only when its creator `from` is, as `sent_unverified` when the sender part opens +and `from` is a word the chain fixes (a relayed deposit, a mint, a payout), and otherwise not at +all (`tests/ownership.rs`, which seals its own envelopes). No sealing, no randomness, no ledger. `tests/vectors.json` was produced by the fullnode crate itself; the tests open it. diff --git a/crates/randscan-viewing/src/lib.rs b/crates/randscan-viewing/src/lib.rs index a33d0ea..95aeadc 100644 --- a/crates/randscan-viewing/src/lib.rs +++ b/crates/randscan-viewing/src/lib.rs @@ -447,7 +447,8 @@ pub fn key_info(input: &str, kind: &str) -> Result { #[derive(Serialize)] struct OpenedNote { - /// "received", "sent" or "tx_key": which key path opened the envelope. + /// "received", "sent", "sent_unverified" ([`Role`]: owner and creator are checked against + /// the key's own `pk`, not only that a key path opened the envelope) or "tx_key". role: String, tx_key: String, pk: String, @@ -457,7 +458,7 @@ struct OpenedNote { asset: u32, time: u32, r: String, - /// The nullifier this note publishes when spent, when the receiver's viewing key opened it. + /// The nullifier this note publishes when spent: only for a note the viewing key owns. nullifier: Option, /// True when the opened plaintext recomputes to the on-chain commitment (always, or the /// opening would have failed): stated so the page can say the row is verified. @@ -484,9 +485,71 @@ fn opened(role: &str, key: [u8; 32], note: Note, nullifier: Option, memo: } } +/// What an envelope a viewing key opens is for that key. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Role { + /// The receiver part opens under the key **and** the note's owner `pk` is the key's own. + Received, + /// The sender part opens under the key's `ovk` **and** the note's creator `from` is the + /// key's own `pk`. + Sent, + /// The sender part opens under the key's `ovk` and the note's `from` is one of the words the + /// chain fixes for a note it computes itself ([`CHAIN_FROM_WORDS`]): a bridge deposit this + /// key's holder relayed, a token it minted, a payout of a program it invoked. The note has no + /// creator inside the pool to compare with, and anyone who holds the `ovk` can seal one, so + /// the row is shown under its own label and is never counted as sent. + SentUnverified, +} + +impl Role { + pub fn as_str(self) -> &'static str { + match self { + Role::Received => "received", + Role::Sent => "sent", + Role::SentUnverified => "sent_unverified", + } + } +} + +/// What one envelope is for `vk`: the explorer's restatement of the wallet's and the node's +/// `classify` (fullnode `randprotocol-client/src/wallet.rs`, `randprotocol-node/src/viewing.rs`). +/// +/// An envelope opening is not ownership and not authorship. A shielded address is public, so +/// anyone can seal to its ML-KEM key a note owned by some other `pk` (audit v14, SCAN-841); and +/// anyone who holds a viewing key holds its `ovk`, and can wrap the transaction key of a payment +/// of its own under it (VK-751). The commitment binds `pk` and `from` (it is recomputed from the +/// plaintext by the opening), and the bundle guest forces every input's owner and every output's +/// `from` to the spender's derived `pk`, so both are compared with `vk.pk()`: +/// +/// 1. the receiver part opens and `note.pk == vk.pk()` → [`Role::Received`]; +/// 2. otherwise the sender part opens and `note.from == vk.pk()` → [`Role::Sent`]; +/// 3. otherwise the sender part opens and `note.from` is a chain-fixed word → [`Role::SentUnverified`]; +/// 4. otherwise `None`: the note is neither this key's nor of its making, whatever opened. +/// +/// A note sealed to this key but owned by another still gets the sender path (2–4): the two +/// openings are independent. +pub fn classify(env: &Envelope, cm: &Word8, vk: &ViewingKey) -> Option<(Role, [u8; 32], Note, Option)> { + let pk_self = vk.pk(); + if let Some((k, n, memo)) = env.open_as_receiver_with_memo(cm, vk) { + // A change note is both sent and received; received wins. + if n.pk == pk_self { + return Some((Role::Received, k, n, memo)); + } + } + let (k, n, memo) = env.open_as_sender_with_memo(cm, vk)?; + if n.from == pk_self { + Some((Role::Sent, k, n, memo)) + } else if CHAIN_FROM_WORDS.contains(&n.from) { + Some((Role::SentUnverified, k, n, memo)) + } else { + None + } +} + /// Try to open one envelope with a key. `key_kind` is "viewing" (64-hex `nk`), "spend" /// (64-hex spend key, derived locally), "file" (a key file JSON) or "tx" (32-byte transaction -/// key). Returns the opened note as JSON, or `null` when the key does not open it. +/// key). Returns the opened note as JSON, or `null` when the key does not open it — or, for a +/// viewing key, opens it without the note being the key's own or of its making ([`classify`]). #[wasm_bindgen] pub fn open_note(cm_hex: &str, envelope_json: &str, key_kind: &str, key: &str) -> Result { let cm = word8_from_hex(cm_hex).ok_or("commitment must be 64 hex characters")?; @@ -499,15 +562,10 @@ pub fn open_note(cm_hex: &str, envelope_json: &str, key_kind: &str, key: &str) - } _ => { let vk = viewing_key_from(key_kind, key)?; - if let Some((k, n, memo)) = env.open_as_receiver_with_memo(&cm, &vk) { - let nf = vk.nullifier(&cm); - Some(opened("received", k, n, Some(nf), memo)) - } else if let Some((k, n, memo)) = env.open_as_sender_with_memo(&cm, &vk) { - // A change note is both sent and received; the receiver path above wins. - Some(opened("sent", k, n, None, memo)) - } else { - None - } + classify(&env, &cm, &vk).map(|(role, k, n, memo)| { + let nf = (role == Role::Received).then(|| vk.nullifier(&cm)); + opened(role.as_str(), k, n, nf, memo) + }) } }; match result { @@ -588,6 +646,13 @@ pub const MINT_FROM: Word8 = [u32::from_le_bytes(*b"rpl-"), u32::from_le_bytes(* pub const PROGRAM_FROM: Word8 = [u32::from_le_bytes(*b"rpl2"), u32::from_le_bytes(*b"-pay"), 0, 0, 0, 0, 0, 0]; /// A bridge deposit's and a bridge fee note's `from`: zero (`bridge_notes::DEPOSIT_FROM`). pub const DEPOSIT_FROM: Word8 = [0; 8]; +/// `randprotocol_core::ledger::perps::PERP_FROM`: the `from` word of an RPL-3 perp withdrawal's +/// note, ASCII `rpl3-pay`, zero-padded. +pub const PERP_FROM: Word8 = [u32::from_le_bytes(*b"rpl3"), u32::from_le_bytes(*b"-pay"), 0, 0, 0, 0, 0, 0]; +/// Every `from` word the chain fixes for a note it computes itself (fullnode v0.8.6). None is a +/// key's `pk` (a Poseidon2 digest). Zero is also the `from` of a faucet mint, a genesis alloc and +/// a staking withdrawal, whose envelopes are sealed under throwaway sender keys. +pub const CHAIN_FROM_WORDS: [Word8; 4] = [DEPOSIT_FROM, MINT_FROM, PROGRAM_FROM, PERP_FROM]; /// The public opening of a chain-computed note as randscan serves it beside the leaf /// (`GET /api/v1/envelopes`, `public`): every word but `pk` and `from`. diff --git a/crates/randscan-viewing/tests/ownership.rs b/crates/randscan-viewing/tests/ownership.rs new file mode 100644 index 0000000..15643e2 --- /dev/null +++ b/crates/randscan-viewing/tests/ownership.rs @@ -0,0 +1,153 @@ +//! Audit v14: an envelope that opens is not a row the key owns or made. +//! +//! - SCAN-841: anyone can seal a note it owns itself to a published address. The KEM part then +//! opens under the address holder's key, but the note's `pk` is the sealer's: it is not +//! received, has no nullifier of this key's that will ever reach the chain, and must never +//! count toward a balance. The test needs nothing of the victim's but its public address. +//! - VK-751: whoever holds a wallet's viewing key holds its `ovk`, and can wrap the transaction +//! key of a payment of its own under it. The sender part then opens under the victim's key, but +//! the note's `from` is the planter's `pk`: it is not sent by this key. +//! +//! The crate has no sealing side, so the envelopes are sealed here, the way the fullnode's +//! `viewing::Envelope::seal` does (ML-KEM-768 to the address's key, the transaction key wrapped +//! under the shared secret and under the sender's `ovk`, the note under the transaction key, +//! each ChaCha20-Poly1305 with a 12-byte nonce prepended and `tag ‖ cm` as associated data). + +use randscan_viewing::*; +use serde_json::Value; + +fn vectors() -> Value { + serde_json::from_str(include_str!("vectors.json")).unwrap() +} + +fn s<'a>(v: &'a Value, k: &str) -> &'a str { + v[k].as_str().unwrap() +} + +fn aead_seal(key: &[u8; 32], tag: &[u8], cm: &Word8, pt: &[u8], nonce: u8) -> String { + use chacha20poly1305::aead::{Aead, KeyInit, Payload}; + use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce}; + let nonce = [nonce; 12]; + let aad = [tag, &words_to_bytes(cm)].concat(); + let ct = ChaCha20Poly1305::new(&Key::from(*key)).encrypt(&Nonce::from(nonce), Payload { msg: pt, aad: &aad }).unwrap(); + hex::encode([&nonce[..], &ct].concat()) +} + +/// Seal `note` to the **public** `address` (its ML-KEM key is the bytes after the 32-byte pk), +/// with the transaction key wrapped under `ovk` for the sender. Returns the leaf and its envelope. +fn seal(ovk: &[u8; 32], address: &str, note: &Note) -> (String, String) { + use ml_kem::kem::Encapsulate; + type Ek = ml_kem::ml_kem_768::EncapsulationKey; + let raw = bs58::decode(address.strip_prefix("rand1").unwrap()).into_vec().unwrap(); + let ek = Ek::new(&ml_kem::kem::Key::::try_from(&raw[32..]).expect("1184-byte encapsulation key")).expect("valid key"); + let (kem_ct, ss) = ek.encapsulate_with_rng(&mut rand::rng()); + let ss: [u8; 32] = ss.into(); + let tx_key = [0x5a_u8; 32]; + let cm = note.commitment(); + let env = serde_json::json!({ + "kem_ct": hex::encode(&kem_ct[..]), + "to_receiver": aead_seal(&ss, b"rand-envelope-receiver", &cm, &tx_key, 1), + "to_sender": aead_seal(ovk, b"rand-envelope-sender", &cm, &tx_key, 2), + "body": aead_seal(&tx_key, b"rand-envelope-body", &cm, &words_to_bytes(¬e.words()), 3), + }); + (word8_to_hex(&cm), env.to_string()) +} + +fn open(cm: &str, env: &str, nk: &str) -> Value { + serde_json::from_str(&open_note(cm, env, "viewing", nk).unwrap()).unwrap() +} + +fn key(seed: u32) -> ViewingKey { + ViewingKey::from_spend_key(&[seed; 8]) +} + +const AMOUNT: u64 = 1_000_000 * 100_000_000; + +#[test] +fn a_note_sealed_to_a_published_address_but_owned_by_its_sender_is_not_received() { + // SCAN-841. Everything the attacker uses of the victim's is its published address. + let v = vectors(); + let victim_address = s(&v, "address_b"); + let attacker = key(41); + let phantom = Note { pk: attacker.pk(), from: attacker.pk(), amount: AMOUNT, asset: 0, time: 9, r: [3; 8] }; + let (cm, env) = seal(&attacker.ovk(), victim_address, &phantom); + + // The envelope really does open under the victim's key: that is the whole trap. + let victim = ViewingKey { nk: word8_from_hex(s(&v, "nk_b")).unwrap() }; + let e = Envelope::from_hex(&serde_json::from_str(&env).unwrap()).unwrap(); + assert_eq!(e.open_as_receiver(&word8_from_hex(&cm).unwrap(), &victim).map(|(_, n)| n), Some(phantom)); + + // But the note is not the victim's: no received row, no nullifier, nothing to add to a balance. + let opened = open(&cm, &env, s(&v, "nk_b")); + assert!(opened.is_null(), "a note owned by its sender was reported to the address holder: {opened}"); +} + +#[test] +fn a_note_owned_by_the_key_is_still_received_with_its_nullifier() { + let v = vectors(); + let victim = ViewingKey { nk: word8_from_hex(s(&v, "nk_b")).unwrap() }; + let payer = key(42); + let note = Note { pk: victim.pk(), from: payer.pk(), amount: 7, asset: 0, time: 9, r: [4; 8] }; + let (cm, env) = seal(&payer.ovk(), s(&v, "address_b"), ¬e); + let opened = open(&cm, &env, s(&v, "nk_b")); + assert_eq!(opened["role"], "received"); + assert_eq!(opened["pk"], word8_to_hex(&victim.pk())); + assert_eq!(opened["nullifier"], word8_to_hex(&victim.nullifier(¬e.commitment()))); + // And for the payer, whose `pk` is the note's creator, it is sent. + let opened = open(&cm, &env, &word8_to_hex(&payer.nk)); + assert_eq!(opened["role"], "sent"); + assert!(opened["nullifier"].is_null()); +} + +#[test] +fn a_payment_planted_under_the_keys_ovk_by_another_creator_is_not_sent() { + // VK-751. The planter holds the victim's viewing key (a prover it delegated to, an auditor), + // hence its ovk, and wraps the key of its own payment to `payee` under it. + let v = vectors(); + let victim = ViewingKey { nk: word8_from_hex(s(&v, "nk_b")).unwrap() }; + let planter = key(43); + let payee = key(44); + let planted = Note { pk: payee.pk(), from: planter.pk(), amount: AMOUNT, asset: 0, time: 9, r: [5; 8] }; + let (cm, env) = seal(&victim.ovk(), &payee.address(), &planted); + + let e = Envelope::from_hex(&serde_json::from_str(&env).unwrap()).unwrap(); + assert_eq!(e.open_as_sender(&word8_from_hex(&cm).unwrap(), &victim).map(|(_, n)| n), Some(planted), "the sender part opens"); + + let opened = open(&cm, &env, s(&v, "nk_b")); + assert!(opened.is_null(), "a payment created by another key was reported as this key's: {opened}"); + // The payee still receives it. + assert_eq!(open(&cm, &env, &word8_to_hex(&payee.nk))["role"], "received"); +} + +#[test] +fn a_chain_computed_note_sealed_under_the_keys_ovk_is_shown_but_never_as_sent() { + // A relayed bridge deposit, an RPL mint, an RPL-2 payout and a perp withdrawal are notes + // the chain computes with a fixed `from` word; the submitter seals the envelope under its + // own ovk. The creator field cannot say who that was, and anyone holding the ovk can seal + // one, so the row is "sent_unverified": listed, never Sent. + let v = vectors(); + let relayer = ViewingKey { nk: word8_from_hex(s(&v, "nk_b")).unwrap() }; + let recipient = key(45); + for (i, from) in [DEPOSIT_FROM, MINT_FROM, PROGRAM_FROM, PERP_FROM].into_iter().enumerate() { + let note = Note { pk: recipient.pk(), from, amount: 5, asset: 1, time: 9, r: [10 + i as u32; 8] }; + let (cm, env) = seal(&relayer.ovk(), &recipient.address(), ¬e); + let opened = open(&cm, &env, s(&v, "nk_b")); + assert_eq!(opened["role"], "sent_unverified", "from word {i}"); + assert!(opened["nullifier"].is_null()); + assert_eq!(open(&cm, &env, &word8_to_hex(&recipient.nk))["role"], "received", "from word {i}"); + } +} + +#[test] +fn a_note_the_key_created_stays_sent_even_when_its_envelope_was_sealed_to_the_keys_own_address() { + // The receiver part opening for a note owned by someone else must not hide the sender path: + // the two openings are independent (the wallet's `classify` falls through the same way). + let v = vectors(); + let me = ViewingKey { nk: word8_from_hex(s(&v, "nk_b")).unwrap() }; + let payee = key(46); + let note = Note { pk: payee.pk(), from: me.pk(), amount: 5, asset: 0, time: 9, r: [6; 8] }; + let (cm, env) = seal(&me.ovk(), s(&v, "address_b"), ¬e); + let opened = open(&cm, &env, s(&v, "nk_b")); + assert_eq!(opened["role"], "sent"); + assert!(opened["nullifier"].is_null()); +} diff --git a/frontend/public/viewing/randscan_viewing.d.ts b/frontend/public/viewing/randscan_viewing.d.ts index 78e8e93..d9c6bb5 100644 --- a/frontend/public/viewing/randscan_viewing.d.ts +++ b/frontend/public/viewing/randscan_viewing.d.ts @@ -20,7 +20,8 @@ export function open_call(h_in_hex: string, envelope_json: string, key_kind: str /** * Try to open one envelope with a key. `key_kind` is "viewing" (64-hex `nk`), "spend" * (64-hex spend key, derived locally), "file" (a key file JSON) or "tx" (32-byte transaction - * key). Returns the opened note as JSON, or `null` when the key does not open it. + * key). Returns the opened note as JSON, or `null` when the key does not open it — or, for a + * viewing key, opens it without the note being the key's own or of its making ([`classify`]). */ export function open_note(cm_hex: string, envelope_json: string, key_kind: string, key: string): string; diff --git a/frontend/public/viewing/randscan_viewing.js b/frontend/public/viewing/randscan_viewing.js index 7df8b48..24d44ae 100644 --- a/frontend/public/viewing/randscan_viewing.js +++ b/frontend/public/viewing/randscan_viewing.js @@ -100,7 +100,8 @@ export function open_call(h_in_hex, envelope_json, key_kind, key) { /** * Try to open one envelope with a key. `key_kind` is "viewing" (64-hex `nk`), "spend" * (64-hex spend key, derived locally), "file" (a key file JSON) or "tx" (32-byte transaction - * key). Returns the opened note as JSON, or `null` when the key does not open it. + * key). Returns the opened note as JSON, or `null` when the key does not open it — or, for a + * viewing key, opens it without the note being the key's own or of its making ([`classify`]). * @param {string} cm_hex * @param {string} envelope_json * @param {string} key_kind diff --git a/frontend/public/viewing/randscan_viewing_bg.wasm b/frontend/public/viewing/randscan_viewing_bg.wasm index 756865f..0f586bb 100644 Binary files a/frontend/public/viewing/randscan_viewing_bg.wasm and b/frontend/public/viewing/randscan_viewing_bg.wasm differ diff --git a/frontend/src/app/[lang]/viewing/page.tsx b/frontend/src/app/[lang]/viewing/page.tsx index 0b4cea9..b2b3171 100644 --- a/frontend/src/app/[lang]/viewing/page.tsx +++ b/frontend/src/app/[lang]/viewing/page.tsx @@ -9,6 +9,7 @@ import { StatsCard, StatsRow } from '@/components/StatsCard'; import { PageHeader } from '@/components/States'; import { useTokens } from '@/hooks/useApi'; import * as api from '@/lib/api'; +import { admit, isOwned, spendableNotes } from '@/lib/history'; import { matchSpent } from '@/lib/spent'; import { tokenBalances, type TokenBalance } from '@/lib/utils'; import { L, useFmt, useT, type Fmt } from '@/i18n/client'; @@ -31,6 +32,7 @@ function buildColumns( tokens: TokenInfo[] | undefined, t: (key: string) => string, fmt: Fmt, + ownPk: string | null | undefined, ): Column[] { return [ { @@ -66,12 +68,12 @@ function buildColumns( { key: 'counterparty', header: t('viewing.counterparty'), - render: (r) => , + render: (r) => , }, { key: 'status', header: t('viewing.status'), - render: (r) => (r.note.role === 'received' ? : —), + render: (r) => (isOwned(r.note, ownPk) ? : —), }, ]; } @@ -114,7 +116,7 @@ export default function ViewingPage() { const { data: tokenList } = useTokens(); const { t, tp } = useT(); const fmt = useFmt(); - const columns = buildColumns(tokenList?.tokens, t, fmt); + const columns = buildColumns(tokenList?.tokens, t, fmt, info?.pk); const run = async ({ kind, key }: SubmittedKey) => { setBusy(true); @@ -134,6 +136,9 @@ export default function ViewingPage() { // deposit's may be junk) is rebuilt from its public opening for this key's own pk. let opened = n.envelope ? await openNote(n.cm, n.envelope, kind, key) : null; if (!opened && n.public) opened = await rebuildNote(n.cm, n.public, kind, key); + // Opening is not ownership (audit v14, SCAN-841 / VK-751): a received row must be owned + // by this key's pk and a sent row created by it, or it is dropped / shown as unverified. + if (opened) opened = admit(opened, ki.pk); if (opened) { found.push({ leaf_index: n.leaf_index, cm: n.cm, height: n.height, tx_hash: n.tx_hash, note: opened, spent: { state: 'unknown' } }); } @@ -145,7 +150,7 @@ export default function ViewingPage() { // Spent or not: the public nullifier set is downloaded and matched here. No nullifier of // this key is ever sent to the explorer. A download that fails fails the scan, since a note // of unknown status would silently drop out of the balances. - const owned = found.filter((r) => r.note.role === 'received' && r.note.nullifier); + const owned = found.filter((r) => isOwned(r.note, ki.pk) && r.note.nullifier); const spent = await matchSpent(owned.map((r) => r.note.nullifier!), api.getNullifierPage); for (const r of owned) { const nf = spent.get(r.note.nullifier!); @@ -159,11 +164,9 @@ export default function ViewingPage() { } }; - const received = rows?.filter((r) => r.note.role === 'received') ?? []; - const balances = tokenBalances( - received.filter((r) => r.spent.state === 'unspent').map((r) => r.note), - tokenList?.tokens - ); + // Only notes this key's pk owns are received, and only those, unspent, are a balance. + const received = rows?.filter((r) => isOwned(r.note, info?.pk)) ?? []; + const balances = tokenBalances(spendableNotes(rows ?? [], info?.pk), tokenList?.tokens); const balance = balances[0].units; return ( diff --git a/frontend/src/components/OpenedNotes.tsx b/frontend/src/components/OpenedNotes.tsx index 9ce26a7..576e8dc 100644 --- a/frontend/src/components/OpenedNotes.tsx +++ b/frontend/src/components/OpenedNotes.tsx @@ -26,7 +26,9 @@ export function RoleBadge({ role }: { role: OpenedNote['role'] }) { ? t('components.openedNotes.received') : role === 'sent' ? t('components.openedNotes.sent') - : t('components.openedNotes.openedWithTxKey'); + : role === 'sent_unverified' + ? t('components.openedNotes.sentUnverified') + : t('components.openedNotes.openedWithTxKey'); return {label}; } diff --git a/frontend/src/i18n/messages/ar.json b/frontend/src/i18n/messages/ar.json index fcc5ddc..e7b6c3e 100644 --- a/frontend/src/i18n/messages/ar.json +++ b/frontend/src/i18n/messages/ar.json @@ -288,6 +288,7 @@ "openedNotes": { "received": "مستلَمة", "sent": "مرسَلة", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "فُتحت بمفتاح المعاملة", "unspent": "غير مُنفَقة", "spentIn": "أُنفقت في", diff --git a/frontend/src/i18n/messages/de.json b/frontend/src/i18n/messages/de.json index 567b0e8..09b9c8f 100644 --- a/frontend/src/i18n/messages/de.json +++ b/frontend/src/i18n/messages/de.json @@ -280,6 +280,7 @@ "openedNotes": { "received": "Empfangen", "sent": "Gesendet", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "Mit Tx-Schlüssel geöffnet", "unspent": "unausgegeben", "spentIn": "ausgegeben in", diff --git a/frontend/src/i18n/messages/en.json b/frontend/src/i18n/messages/en.json index 6b052b1..5c6f88f 100644 --- a/frontend/src/i18n/messages/en.json +++ b/frontend/src/i18n/messages/en.json @@ -280,6 +280,7 @@ "openedNotes": { "received": "Received", "sent": "Sent", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "Opened with tx key", "unspent": "unspent", "spentIn": "spent in", diff --git a/frontend/src/i18n/messages/es.json b/frontend/src/i18n/messages/es.json index bd5c735..71a6b33 100644 --- a/frontend/src/i18n/messages/es.json +++ b/frontend/src/i18n/messages/es.json @@ -282,6 +282,7 @@ "openedNotes": { "received": "Recibida", "sent": "Enviada", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "Abierta con la clave de la tx", "unspent": "sin gastar", "spentIn": "gastada en", diff --git a/frontend/src/i18n/messages/fa.json b/frontend/src/i18n/messages/fa.json index 33643e6..031f116 100644 --- a/frontend/src/i18n/messages/fa.json +++ b/frontend/src/i18n/messages/fa.json @@ -280,6 +280,7 @@ "openedNotes": { "received": "دریافت‌شده", "sent": "ارسال‌شده", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "باز شده با کلید تراکنش", "unspent": "خرج‌نشده", "spentIn": "خرج‌شده در", diff --git a/frontend/src/i18n/messages/fr.json b/frontend/src/i18n/messages/fr.json index 6c9a355..0e3c690 100644 --- a/frontend/src/i18n/messages/fr.json +++ b/frontend/src/i18n/messages/fr.json @@ -282,6 +282,7 @@ "openedNotes": { "received": "Reçue", "sent": "Envoyée", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "Ouverte avec la clé de transaction", "unspent": "non dépensée", "spentIn": "dépensée dans", diff --git a/frontend/src/i18n/messages/hi.json b/frontend/src/i18n/messages/hi.json index 3e76d7b..f8b1e85 100644 --- a/frontend/src/i18n/messages/hi.json +++ b/frontend/src/i18n/messages/hi.json @@ -280,6 +280,7 @@ "openedNotes": { "received": "प्राप्त", "sent": "भेजा गया", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "tx कुंजी से खोला गया", "unspent": "अव्ययित", "spentIn": "इसमें खर्च हुआ", diff --git a/frontend/src/i18n/messages/id.json b/frontend/src/i18n/messages/id.json index db661e6..b94c3eb 100644 --- a/frontend/src/i18n/messages/id.json +++ b/frontend/src/i18n/messages/id.json @@ -278,6 +278,7 @@ "openedNotes": { "received": "Diterima", "sent": "Dikirim", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "Dibuka dengan kunci tx", "unspent": "belum dibelanjakan", "spentIn": "dibelanjakan di", diff --git a/frontend/src/i18n/messages/it.json b/frontend/src/i18n/messages/it.json index 99d537c..402b510 100644 --- a/frontend/src/i18n/messages/it.json +++ b/frontend/src/i18n/messages/it.json @@ -282,6 +282,7 @@ "openedNotes": { "received": "Ricevuta", "sent": "Inviata", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "Aperta con la chiave della tx", "unspent": "non spesa", "spentIn": "spesa in", diff --git a/frontend/src/i18n/messages/ja.json b/frontend/src/i18n/messages/ja.json index e1fb1d5..c7da2e0 100644 --- a/frontend/src/i18n/messages/ja.json +++ b/frontend/src/i18n/messages/ja.json @@ -278,6 +278,7 @@ "openedNotes": { "received": "受信", "sent": "送信", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "tx キーで開封", "unspent": "未使用", "spentIn": "使用先", diff --git a/frontend/src/i18n/messages/ko.json b/frontend/src/i18n/messages/ko.json index 15c86ea..a5c9ee2 100644 --- a/frontend/src/i18n/messages/ko.json +++ b/frontend/src/i18n/messages/ko.json @@ -278,6 +278,7 @@ "openedNotes": { "received": "수신", "sent": "발신", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "트랜잭션 키로 열람됨", "unspent": "미사용", "spentIn": "사용된 위치", diff --git a/frontend/src/i18n/messages/ms.json b/frontend/src/i18n/messages/ms.json index 292a318..0bdc832 100644 --- a/frontend/src/i18n/messages/ms.json +++ b/frontend/src/i18n/messages/ms.json @@ -278,6 +278,7 @@ "openedNotes": { "received": "Diterima", "sent": "Dihantar", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "Dibuka dengan kunci tx", "unspent": "belum dibelanjakan", "spentIn": "dibelanjakan dalam", diff --git a/frontend/src/i18n/messages/pl.json b/frontend/src/i18n/messages/pl.json index a5a27e5..f039e20 100644 --- a/frontend/src/i18n/messages/pl.json +++ b/frontend/src/i18n/messages/pl.json @@ -284,6 +284,7 @@ "openedNotes": { "received": "Otrzymane", "sent": "Wysłane", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "Otwarte kluczem tx", "unspent": "niewydane", "spentIn": "wydane w", diff --git a/frontend/src/i18n/messages/ps.json b/frontend/src/i18n/messages/ps.json index e1509f4..f721fc1 100644 --- a/frontend/src/i18n/messages/ps.json +++ b/frontend/src/i18n/messages/ps.json @@ -280,6 +280,7 @@ "openedNotes": { "received": "ترلاسه شوي", "sent": "لېږل شوي", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "د راکړې ورکړې په کیلي پرانیستل شوی", "unspent": "نه دی لګول شوی", "spentIn": "لګول شوی په", diff --git a/frontend/src/i18n/messages/pt.json b/frontend/src/i18n/messages/pt.json index 1948134..3cd4709 100644 --- a/frontend/src/i18n/messages/pt.json +++ b/frontend/src/i18n/messages/pt.json @@ -282,6 +282,7 @@ "openedNotes": { "received": "Recebida", "sent": "Enviada", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "Aberta com a chave da tx", "unspent": "não gasta", "spentIn": "gasta em", diff --git a/frontend/src/i18n/messages/ru.json b/frontend/src/i18n/messages/ru.json index 627df59..080f5fb 100644 --- a/frontend/src/i18n/messages/ru.json +++ b/frontend/src/i18n/messages/ru.json @@ -284,6 +284,7 @@ "openedNotes": { "received": "Получено", "sent": "Отправлено", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "Открыто ключом транзакции", "unspent": "не потрачена", "spentIn": "потрачена в", diff --git a/frontend/src/i18n/messages/ta.json b/frontend/src/i18n/messages/ta.json index 90dd6a8..b2d56d9 100644 --- a/frontend/src/i18n/messages/ta.json +++ b/frontend/src/i18n/messages/ta.json @@ -280,6 +280,7 @@ "openedNotes": { "received": "பெறப்பட்டது", "sent": "அனுப்பப்பட்டது", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "பரிவர்த்தனை விசையால் திறக்கப்பட்டது", "unspent": "செலவிடப்படாதது", "spentIn": "செலவிடப்பட்டது:", diff --git a/frontend/src/i18n/messages/ur.json b/frontend/src/i18n/messages/ur.json index 2e68c86..b2a4522 100644 --- a/frontend/src/i18n/messages/ur.json +++ b/frontend/src/i18n/messages/ur.json @@ -280,6 +280,7 @@ "openedNotes": { "received": "موصول", "sent": "بھیجا گیا", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "tx کی سے کھولا گیا", "unspent": "غیر خرچ شدہ", "spentIn": "خرچ ہوا اس میں", diff --git a/frontend/src/i18n/messages/zh-hk.json b/frontend/src/i18n/messages/zh-hk.json index f4ee958..7f5c255 100644 --- a/frontend/src/i18n/messages/zh-hk.json +++ b/frontend/src/i18n/messages/zh-hk.json @@ -278,6 +278,7 @@ "openedNotes": { "received": "已接收", "sent": "已發送", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "以交易金鑰開啟", "unspent": "未花費", "spentIn": "花費於", diff --git a/frontend/src/i18n/messages/zh.json b/frontend/src/i18n/messages/zh.json index 4b9a568..90a5ab8 100644 --- a/frontend/src/i18n/messages/zh.json +++ b/frontend/src/i18n/messages/zh.json @@ -278,6 +278,7 @@ "openedNotes": { "received": "已接收", "sent": "已发送", + "sentUnverified": "Sealed by this key (sender unverified)", "openedWithTxKey": "已用交易密钥打开", "unspent": "未花费", "spentIn": "花费于", diff --git a/frontend/src/lib/history.ts b/frontend/src/lib/history.ts new file mode 100644 index 0000000..3d616b8 --- /dev/null +++ b/frontend/src/lib/history.ts @@ -0,0 +1,44 @@ +/** + * Which opened rows are a viewing key's own (audit v14, SCAN-841 and VK-751). + * + * An envelope that opens is not ownership and not authorship: anyone can seal a note it owns + * itself to a published address, and anyone who holds a viewing key can wrap a payment of its + * own under that key's ovk. The WebAssembly opener (crates/randscan-viewing, `classify`) already + * compares the note's owner and creator with the key's own pk; this restates the two comparisons + * on the page's side, so the balance never rests on the role string alone. + */ + +/** The fields of an opened note these checks read (`OpenedNote` of `@/lib/viewing`). */ +export interface RoleFields { + role: string; + /** The note's owner. */ + pk: string; + /** The note's creator. */ + from: string; +} + +const same = (a: string, b: string | null | undefined): boolean => !!b && a.toLowerCase() === b.toLowerCase(); + +/** Received and owned: the note's owner is the pasted key's own pk. */ +export function isOwned(note: RoleFields, ownPk: string | null | undefined): boolean { + return note.role === 'received' && same(note.pk, ownPk); +} + +/** + * The row as the history may show it, or `null` to drop it. A received row whose owner is not + * the key's pk is dropped; a sent row whose creator is not the key's pk is shown as + * `sent_unverified`, never as sent. Anything else passes unchanged. + */ +export function admit(note: N, ownPk: string | null | undefined): N | null { + if (note.role === 'received') return same(note.pk, ownPk) ? note : null; + if (note.role === 'sent' && !same(note.from, ownPk)) return { ...note, role: 'sent_unverified' }; + return note; +} + +/** The notes a spendable balance may sum: received, owned by `ownPk`, and known unspent. */ +export function spendableNotes( + rows: { note: N; spent: { state: string } }[], + ownPk: string | null | undefined +): N[] { + return rows.filter((r) => isOwned(r.note, ownPk) && r.spent.state === 'unspent').map((r) => r.note); +} diff --git a/frontend/src/lib/viewing.ts b/frontend/src/lib/viewing.ts index 4e76c0d..012efcf 100644 --- a/frontend/src/lib/viewing.ts +++ b/frontend/src/lib/viewing.ts @@ -17,7 +17,13 @@ export interface KeyInfo { } export interface OpenedNote { - role: 'received' | 'sent' | 'tx_key'; + /** + * `received`: the note's owner is the key's own pk. `sent`: its creator is. `sent_unverified`: + * the sender part opens under the key but the creator is a word the chain fixes (a relayed + * deposit, a mint, a payout), so who sealed it cannot be checked — never counted as sent. + * `tx_key`: opened with a transaction key, which says nothing about either. + */ + role: 'received' | 'sent' | 'sent_unverified' | 'tx_key'; tx_key: string; pk: string; from: string; diff --git a/frontend/tests/history.test.mjs b/frontend/tests/history.test.mjs new file mode 100644 index 0000000..aa93dea --- /dev/null +++ b/frontend/tests/history.test.mjs @@ -0,0 +1,54 @@ +// Audit v14, SCAN-841 / VK-751: the history page's balance sums only notes the pasted key owns, +// and a row is Sent only when the key's own pk created the note. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +const supported = process.features.typescript; +const skip = supported ? false : 'needs Node with TypeScript type stripping'; +const { admit, isOwned, spendableNotes } = supported ? await import('../src/lib/history.ts') : {}; + +const ME = 'a'.repeat(64); +const OTHER = 'b'.repeat(64); +const note = (role, pk, from, amount = '5') => ({ role, pk, from, amount, asset: 0 }); +const row = (n, state = 'unspent') => ({ note: n, spent: { state } }); + +test('a received row owned by another pk never reaches the balance', { skip }, () => { + const phantom = note('received', OTHER, OTHER, '100000000000000'); + const mine = note('received', ME, OTHER, '7'); + assert.equal(isOwned(phantom, ME), false); + assert.equal(isOwned(mine, ME.toUpperCase()), true); + assert.equal(admit(phantom, ME), null, 'the phantom row is dropped from the history'); + assert.deepEqual(spendableNotes([row(phantom), row(mine)], ME), [mine]); + // No pk for the key: nothing is owned. + assert.deepEqual(spendableNotes([row(mine)], null), []); +}); + +test('only unspent received rows are spendable', { skip }, () => { + const a = note('received', ME, OTHER, '1'); + const b = note('received', ME, OTHER, '2'); + const c = note('received', ME, OTHER, '4'); + const sent = note('sent', OTHER, ME, '8'); + const unverified = note('sent_unverified', OTHER, '0'.repeat(64), '16'); + const got = spendableNotes([row(a), row(b, 'spent'), row(c, 'unknown'), row(sent), row(unverified)], ME); + assert.deepEqual(got, [a]); +}); + +test('a sent row is Sent only when the key created the note', { skip }, () => { + const mine = note('sent', OTHER, ME); + const planted = note('sent', OTHER, OTHER); + assert.equal(admit(mine, ME), mine); + assert.equal(admit(planted, ME).role, 'sent_unverified'); + const unverified = note('sent_unverified', OTHER, '0'.repeat(64)); + assert.equal(admit(unverified, ME), unverified); + const byTxKey = note('tx_key', OTHER, OTHER); + assert.equal(admit(byTxKey, ME), byTxKey); +}); + +test('the history page sums its balance through the ownership check', () => { + const page = readFileSync(fileURLToPath(new URL('../src/app/[lang]/viewing/page.tsx', import.meta.url)), 'utf8'); + assert.match(page, /tokenBalances\(\s*spendableNotes\(rows \?\? \[\], info\?\.pk\)/, 'the balance is not summed from spendableNotes'); + assert.match(page, /admit\(/, 'opened rows are not passed through admit'); + assert.ok(!/role === 'received'/.test(page), 'the page decides ownership from the role string alone'); +});