Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion crates/randscan-viewing/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
89 changes: 77 additions & 12 deletions crates/randscan-viewing/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,8 @@ pub fn key_info(input: &str, kind: &str) -> Result<String, String> {

#[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,
Expand All @@ -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<String>,
/// 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.
Expand All @@ -484,9 +485,71 @@ fn opened(role: &str, key: [u8; 32], note: Note, nullifier: Option<Word8>, 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<String>)> {
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<String, String> {
let cm = word8_from_hex(cm_hex).ok_or("commitment must be 64 hex characters")?;
Expand All @@ -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 {
Expand Down Expand Up @@ -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`.
Expand Down
153 changes: 153 additions & 0 deletions crates/randscan-viewing/tests/ownership.rs
Original file line number Diff line number Diff line change
@@ -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::<Ek>::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(&note.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"), &note);
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(&note.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(), &note);
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"), &note);
let opened = open(&cm, &env, s(&v, "nk_b"));
assert_eq!(opened["role"], "sent");
assert!(opened["nullifier"].is_null());
}
3 changes: 2 additions & 1 deletion frontend/public/viewing/randscan_viewing.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
3 changes: 2 additions & 1 deletion frontend/public/viewing/randscan_viewing.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Binary file modified frontend/public/viewing/randscan_viewing_bg.wasm
Binary file not shown.
Loading
Loading