diff --git a/CLAUDE.md b/CLAUDE.md index 0a5d6da..97a3f2f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,7 +5,7 @@ bridge until Zcash's Tachyon upgrade changes how wallets find payments. Read `README.md` first for the user-facing description. **Status (2026-11-01): pre-alpha, phase 1 of 4: spec and prototype.** The -draft protocol spec is `spec/v0.md` (rev 3.21); `crates/lz-proto` holds the +draft protocol spec is `spec/v0.md` (rev 3.22); `crates/lz-proto` holds the shared protocol types; `server/` is a prototype (OHTTP gateway, devices, 30-minute pings, chain follower, and the scanner with in-memory leases, events, hints, and long-poll); `gateway/`, `client/core`, and the diff --git a/client/uniffi/README.md b/client/uniffi/README.md index 9c1a401..85e8104 100644 --- a/client/uniffi/README.md +++ b/client/uniffi/README.md @@ -47,7 +47,10 @@ the binding layer can't enforce: - **Never log requests or responses.** Over Tor the headers carry the token and bodies may carry viewing keys. - **One `wake` per scheduled ping, nothing after a payment push**, to any - service (spec §3.3). Show the alert from the ping itself. + service (spec §3.3). Show the alert from the ping itself. A ping + event's `amount` is the transaction's total in zatoshis (`null` or + `nil` when unknown, never 0), unconfirmed like the event. Show it only + if the user chose to, since it can appear on a locked screen. - **Alerts are claims** (spec §6.3). An app that is not a wallet can never confirm a payment: show every event as unconfirmed. - **Persist `state()` after every call.** diff --git a/client/uniffi/src/lib.rs b/client/uniffi/src/lib.rs index 6a0b1eb..1c0aed5 100644 --- a/client/uniffi/src/lib.rs +++ b/client/uniffi/src/lib.rs @@ -352,6 +352,11 @@ pub struct Event { /// `CompactTx` protobuf bytes, base64url, to trial-decrypt on the /// device. Absent in pings. pub compact_tx: Option, + /// Only in pings (spec §5.2): the total in zatoshis the transaction + /// pays the lease's keys. `None` means unknown, never zero. A claim + /// like the event: show it as unconfirmed until the wallet's own sync + /// finds the transaction. + pub amount: Option, } impl std::fmt::Debug for Event { @@ -382,6 +387,7 @@ impl From for Event { height: e.height, confirmations: e.confirmations, compact_tx: e.compact_tx, + amount: e.amount, } } } @@ -869,6 +875,7 @@ impl Client { height: event.height, confirmations: event.confirmations, compact_tx: None, + amount: None, }; lock(&self.0).ack(&e) } diff --git a/client/uniffi/tests/bindings.rs b/client/uniffi/tests/bindings.rs index 05e5c05..f1a63bc 100644 --- a/client/uniffi/tests/bindings.rs +++ b/client/uniffi/tests/bindings.rs @@ -294,3 +294,21 @@ fn helpers() { Err(LzError::PushDecrypt) )); } + +/// Spec §5.2: a ping event's `amount` reaches Swift and Kotlin, and its +/// absence stays unknown rather than zero. +#[test] +fn ping_events_carry_their_amount() { + let ping: lz_proto::api::Ping = serde_json::from_str( + r#"{"v":0,"t":"payment","events":[ + {"id":"a","rev":1,"kind":"received","status":"mempool","height":null,"confirmations":0,"amount":1200000}, + {"id":"b","rev":1,"kind":"received","status":"mempool","height":null,"confirmations":0} + ]}"#, + ) + .unwrap(); + let ping = lz_client_uniffi::Ping::from(ping); + assert_eq!(ping.ping_type, lz_client_uniffi::PingType::Payment); + assert_eq!(ping.events[0].amount, Some(1_200_000)); + assert_eq!(ping.events[1].amount, None); + assert!(!format!("{:?}", ping.events[0]).contains("1200000")); +} diff --git a/crates/lz-proto/src/api.rs b/crates/lz-proto/src/api.rs index 83c80ee..80efff7 100644 --- a/crates/lz-proto/src/api.rs +++ b/crates/lz-proto/src/api.rs @@ -176,6 +176,12 @@ pub struct Event { /// `CompactTx` protobuf bytes, base64url. Omitted in push payloads. #[serde(default, skip_serializing_if = "Option::is_none")] pub compact_tx: Option, + /// In push payloads only (spec §5.2): the total in zatoshis that the + /// transaction pays the lease's keys. `None` means unknown, never + /// zero. A claim, like the event: unconfirmed until the wallet's own + /// sync finds the transaction. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub amount: Option, } impl std::fmt::Debug for Event { @@ -191,6 +197,7 @@ impl std::fmt::Debug for Event { "compact_tx", &self.compact_tx.as_ref().map(|_| ""), ) + .field("amount", &self.amount.map(|_| "")) .finish() } } @@ -199,10 +206,14 @@ impl std::fmt::Debug for Event { /// Derived from a key, so `Debug` hides the payment details. #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct WebhookDelivery { + /// The event without `compact_tx`, and with its `amount` left `None`: + /// the delivery's own `amount` below takes that key. #[serde(flatten)] pub event: Event, pub txid: String, pub pool: Pool, + /// This output's value in zatoshis (a push's `amount` is the whole + /// transaction's). pub amount: u64, /// The whole 512-byte memo field, unpadded base64url; read it as ZIP /// 302 says. `None` when the server had no full ciphertext for it. @@ -328,6 +339,7 @@ mod tests { height: None, confirmations: 0, compact_tx: None, + amount: None, } } @@ -340,6 +352,54 @@ mod tests { assert!(dbg.contains("redacted")); } + #[test] + fn event_debug_redacts_amount() { + let mut e = event(); + e.amount = Some(1_234_567); + let dbg = format!("{e:?}"); + assert!(!dbg.contains("1234567"), "{dbg}"); + assert!(dbg.contains("redacted")); + } + + /// Spec §5.2: `amount` is optional both ways. Absent, it parses as + /// unknown (older servers), and it is left out when unknown, so older + /// wallets see the same bytes as before. + #[test] + fn amount_is_optional_on_the_wire() { + let old = r#"{"id":"x","rev":1,"kind":"received","status":"mempool","height":null,"confirmations":0}"#; + let e: Event = serde_json::from_str(old).unwrap(); + assert_eq!(e.amount, None); + assert_eq!(serde_json::to_string(&e).unwrap(), old); + let with: Event = serde_json::from_str( + r#"{"id":"x","rev":1,"kind":"received","status":"mempool","height":null,"confirmations":0,"amount":1200000}"#, + ) + .unwrap(); + assert_eq!(with.amount, Some(1_200_000)); + assert!( + serde_json::to_string(&with) + .unwrap() + .ends_with(r#","amount":1200000}"#) + ); + let p: Ping = serde_json::from_str(&format!( + r#"{{"v":0,"t":"payment","events":[{}]}}"#, + serde_json::to_string(&with).unwrap() + )) + .unwrap(); + assert_eq!(p.events[0].amount, Some(1_200_000)); + } + + /// A field added after `amount` doesn't stop it parsing: `Event` + /// ignores fields it doesn't know, which is also how wallets built + /// before `amount` skip it. + #[test] + fn amount_parses_next_to_unknown_fields() { + let e: Event = serde_json::from_str( + r#"{"id":"x","rev":1,"kind":"received","status":"mined","height":3,"confirmations":1,"amount":5,"later":true}"#, + ) + .unwrap(); + assert_eq!(e.amount, Some(5)); + } + #[test] fn default_wake_matches_spec_shape() { let w = WakeRequest { @@ -376,6 +436,7 @@ mod tests { height: Some(5), confirmations: 1, compact_tx: None, + amount: None, }, txid: "aabbccdd".into(), pool: Pool::Orchard, @@ -392,6 +453,20 @@ mod tests { assert!(!format!("{s:?}").contains("c2VjcmV0")); } + /// A webhook delivery's `amount` is its own field and lands there, not + /// in the flattened event. + #[test] + fn webhook_amount_is_the_delivery_field() { + let d: WebhookDelivery = serde_json::from_str( + r#"{"id":"e","rev":1,"kind":"received","status":"mined","height":5,"confirmations":1,"txid":"ab","pool":"ironwood","amount":7,"memo":null}"#, + ) + .unwrap(); + assert_eq!(d.amount, 7); + assert_eq!(d.event.amount, None); + let json = serde_json::to_string(&d).unwrap(); + assert_eq!(json.matches("\"amount\"").count(), 1, "{json}"); + } + #[test] fn ignores_unknown_fields() { let r: EventsResponse = @@ -422,8 +497,9 @@ mod tests { assert!(len + 1024 <= REQUEST_SIZE, "wake body is {len} bytes"); } - /// Spec §5.1: a scheduled ping with the most `private` events still fits - /// the fixed ping size. + /// Spec §5.1, §5.2: a scheduled ping with the most `private` events, + /// each with the longest values (`amount` included), still fits the + /// fixed ping size. #[test] fn fullest_ping_fits_ping_size() { let mut e = event(); @@ -431,6 +507,7 @@ mod tests { e.height = Some(u64::MAX); e.confirmations = u32::MAX; e.rev = u32::MAX; + e.amount = Some(u64::MAX); let p = Ping { v: 0, t: PingType::Wake, diff --git a/crates/lz-proto/src/webhook.rs b/crates/lz-proto/src/webhook.rs index 7322501..01c775e 100644 --- a/crates/lz-proto/src/webhook.rs +++ b/crates/lz-proto/src/webhook.rs @@ -296,6 +296,7 @@ mod tests { height: Some(1), confirmations: 1, compact_tx: None, + amount: None, }, txid: "ab".into(), pool: crate::event_id::Pool::Sapling, diff --git a/crates/lz-proto/tests/properties.rs b/crates/lz-proto/tests/properties.rs index 653b507..4d1b311 100644 --- a/crates/lz-proto/tests/properties.rs +++ b/crates/lz-proto/tests/properties.rs @@ -4,6 +4,7 @@ use std::collections::BTreeSet; +use lz_proto::api::{Event, EventKind, EventStatus, MAX_PING_EVENTS, Ping, PingType}; use lz_proto::hex; use lz_proto::padding::{PING_SIZE, REQUEST_SIZE, pad_bhttp, pad_ping_json}; use lz_proto::replay::{SeqWindow, WINDOW, next_seq}; @@ -179,6 +180,36 @@ proptest! { prop_assert_eq!(back, fields); } + /// Spec §5.2: a ping with up to the most `private` events, any + /// heights, confirmations, and amounts (or none), fits the pad and + /// parses back to the same events. + #[test] + fn a_ping_with_amounts_fits_and_parses_back( + fields in proptest::collection::vec( + (any::(), any::>(), any::(), any::>(), any::()), + 0..=MAX_PING_EVENTS, + ), + ) { + let events: Vec = fields + .into_iter() + .map(|(rev, height, confirmations, amount, mined)| Event { + id: "A".repeat(22), + rev, + kind: EventKind::Received, + status: if mined { EventStatus::Mined } else { EventStatus::Mempool }, + height, + confirmations, + compact_tx: None, + amount, + }) + .collect(); + let ping = Ping { v: 0, t: PingType::Wake, events }; + let padded = pad_ping_json(&serde_json::to_string(&ping).unwrap()).unwrap(); + prop_assert_eq!(padded.len(), PING_SIZE); + let back: Ping = serde_json::from_slice(&padded).unwrap(); + prop_assert_eq!(back, ping); + } + // --- Replay window (spec §3.4) --- /// The window against a plain model: a `seq` is accepted exactly when diff --git a/server/README.md b/server/README.md index 5f3670e..2828d74 100644 --- a/server/README.md +++ b/server/README.md @@ -22,7 +22,7 @@ scanning also against real Zebra and Zaino on regtest | `POST /v0/events` | §4.3 | Long-poll held until the server-wide release (new block, match, or reorg; at most one every 5 s) plus 0–2 s jitter, or 25–30 s; never early, even with events pending; `wait: 0` for `next` pages | | Scanner | §4.4, §6.1 | Trial decryption of Sapling outputs and Orchard and Ironwood actions in compact blocks, for every active lease; deterministic event ids; `mined` → `reorged` → re-mined; confirmations up to the finality depth; events deleted on ack or after 7 days; expired leases swept every minute; catches up after falling behind | | Mempool | §4.3, §6.1 | `GetMempoolStream`, reopened after each block; full transactions (v5 and v6) cut to `CompactTx` and trial-decrypted like blocks; matches are `mempool` events that become `mined` with the same id; a new lease is checked against the pending mempool, kept in compact form up to 64 MiB; an unknown branch id is logged, not fatal | -| Payment alerts | §5.2 | `instant`: an extra `Urgency: high` push when a payment is first seen (usually in the mempool, seconds after it was sent), one per transaction, at most 2 a minute per account; `private`: up to 4 events inside the scheduled ping, same 1024-byte size. Backfilled payments don't push | +| Payment alerts | §5.2 | `instant`: an extra `Urgency: high` push when a payment is first seen (usually in the mempool, seconds after it was sent), one per transaction, at most 2 a minute per account; `private`: up to 4 events (one per transaction) inside the scheduled ping, same 1024-byte size. Both carry the transaction's `amount`. Backfilled payments don't push | | Webhooks | §4.5 | `PUT`/`DELETE /v0/webhook` on a scanning server; URL (https, at most 1024 bytes, no user info, SSRF rules) and `whsec_` secret kept in `state.json`. Every event delivered on each change, Standard Webhooks signed (`webhook-id` from the event's state), retried with backoff and jitter for 24 h; a final delivered event is deleted; `410` deletes the webhook; undelivered events are exempt from the event cap. Deliveries go out on each release and every 5 s | | Replay protection | §3.4 | `Date` within 60 s, and a `Date` on every response so wallets can correct their clocks; `seq` windows per device, or per account for registration, rotation, and deletion; `409 stale-seq` with `min_seq` | | Rate limits | §3.5 | Per account and per device, per minute; `429` with `Retry-After`, delivered inside OHTTP | diff --git a/server/src/scanner/events.rs b/server/src/scanner/events.rs index 7ff3275..622b1ad 100644 --- a/server/src/scanner/events.rs +++ b/server/src/scanner/events.rs @@ -30,6 +30,7 @@ impl Scanner { tip: u64, now: SystemTime, ) -> Vec<(AccountId, Event)> { + let totals = tx_totals(matches.iter().map(|m| ((m.account, m.tx), m.value))); let mut new = Vec::new(); let mut inner = self.lock(); for m in matches { @@ -40,6 +41,7 @@ impl Scanner { { continue; } + let tx_amount = totals.get(&(m.account, m.tx)).copied().flatten(); let Some(tx) = block.vtx.get(m.tx) else { continue; }; @@ -61,6 +63,7 @@ impl Scanner { e.confirmations = confirmations; // The block's copy has the transaction's real index. e.compact_tx = Some(compact_tx.clone()); + s.tx_amount = tx_amount; e.rev += 1; acct.last_seq += 1; s.seq = acct.last_seq; @@ -77,10 +80,11 @@ impl Scanner { height: Some(block.height), confirmations, compact_tx: Some(compact_tx), + amount: None, }; let json_len = json_len(&event); acct.last_seq += 1; - new.push((m.account, event.clone())); + new.push((m.account, with_amount(&event, tx_amount))); acct.by_id.insert( id.clone(), Stored { @@ -94,6 +98,7 @@ impl Scanner { value: m.value, memo: None, }, + tx_amount, delivery: webhooks::Delivery::default(), }, ); @@ -119,9 +124,11 @@ impl Scanner { let Ok(txid) = <[u8; 32]>::try_from(&tx.txid[..]) else { return vec![]; }; + let totals = tx_totals(matches.iter().map(|(m, _)| (m.account, m.value))); let mut new = Vec::new(); let mut inner = self.lock(); for (m, memo) in matches { + let tx_amount = totals.get(&m.account).copied().flatten(); if inner .leases .get(&m.account) @@ -155,10 +162,11 @@ impl Scanner { height: None, confirmations: 0, compact_tx: Some(URL_SAFE_NO_PAD.encode(tx.encode_to_vec())), + amount: None, }; let json_len = json_len(&event); acct.last_seq += 1; - new.push((m.account, event.clone())); + new.push((m.account, with_amount(&event, tx_amount))); acct.by_id.insert( id, Stored { @@ -172,6 +180,7 @@ impl Scanner { value: m.value, memo, }, + tx_amount, delivery: webhooks::Delivery::default(), }, ); @@ -330,8 +339,10 @@ impl Scanner { } /// Events for the next scheduled ping of a `private`-mode lease (spec - /// §5.2): up to [`MAX_PING_EVENTS`] unacknowledged ones, oldest first, - /// without `compact_tx`. Empty for other accounts. + /// §5.2): one per transaction, as a payment push would carry it, for up + /// to [`MAX_PING_EVENTS`] unacknowledged transactions, oldest first, + /// without `compact_tx` and with the transaction's `amount`. Empty for + /// other accounts. pub fn ping_events(&self, account: AccountId, now: SystemTime) -> Vec { let inner = self.lock(); let private = inner @@ -347,13 +358,42 @@ impl Scanner { .map(|a| a.by_id.values().collect()) .unwrap_or_default(); stored.sort_unstable_by_key(|s| (s.created, s.seq)); + let mut txids = std::collections::HashSet::new(); stored .into_iter() + .filter(|s| txids.insert(s.payment.txid)) .take(MAX_PING_EVENTS) .map(|s| Event { compact_tx: None, - ..s.event.clone() + ..with_amount(&s.event, s.tx_amount) }) .collect() } } + +/// The total value per transaction key, `None` where it would overflow +/// (it can't for real notes; unknown is never sent as a wrong number). +fn tx_totals( + values: impl Iterator, +) -> HashMap> { + let mut totals = HashMap::new(); + for (k, v) in values { + let t: &mut Option = totals.entry(k).or_insert(Some(0)); + *t = t.and_then(|t| t.checked_add(v)); + } + totals +} + +/// `event` as push payloads carry it (spec §5.2): with the transaction's +/// `amount` on `received` events. Stored events never carry it, so +/// `events` responses and webhook deliveries don't either. +fn with_amount(event: &Event, tx_amount: Option) -> Event { + Event { + amount: if event.kind == EventKind::Received { + tx_amount + } else { + None + }, + ..event.clone() + } +} diff --git a/server/src/scanner/mod.rs b/server/src/scanner/mod.rs index dcc35f5..2507203 100644 --- a/server/src/scanner/mod.rs +++ b/server/src/scanner/mod.rs @@ -104,6 +104,10 @@ struct Stored { json_len: usize, /// What a webhook delivery reports beyond the event (spec §4.5). payment: webhooks::Payment, + /// The total the transaction pays the account's keys, for push + /// payloads (spec §5.2); `None` if it overflowed. Derived from a key: + /// memory only, never logged (invariant 3). + tx_amount: Option, /// Webhook delivery of the event's current state, on accounts with a /// webhook (spec §4.5). delivery: webhooks::Delivery, diff --git a/server/src/scanner/webhooks.rs b/server/src/scanner/webhooks.rs index 0000081..866321d 100644 --- a/server/src/scanner/webhooks.rs +++ b/server/src/scanner/webhooks.rs @@ -129,8 +129,11 @@ impl Scanner { body: WebhookDelivery { // Without `compact_tx`, as in push payloads: it can be // large, and the merchant fields say what it would. + // `amount` stays `None` on the event: the delivery's + // own per-output `amount` takes that key. event: Event { compact_tx: None, + amount: None, ..e.clone() }, txid: txid_hex(&s.payment.txid), diff --git a/server/tests/end_to_end/client.rs b/server/tests/end_to_end/client.rs index c8d9976..0a779a7 100644 --- a/server/tests/end_to_end/client.rs +++ b/server/tests/end_to_end/client.rs @@ -213,6 +213,9 @@ async fn a_wallet_session_through_the_client_core() { let ping = device.open_ping(&body).unwrap(); assert_eq!(ping.t, PingType::Payment); assert_eq!(ping.events[0].id, event.id); + // The push carries the transaction's total; the poll's event doesn't. + assert_eq!(ping.events[0].amount, Some(5_000)); + assert_eq!(event.amount, None); // The next wake repeats the event (not reported again) with its hint; // the acknowledgement rides on the one after and clears both. diff --git a/server/tests/end_to_end/scanning.rs b/server/tests/end_to_end/scanning.rs index 9a613ba..48746f1 100644 --- a/server/tests/end_to_end/scanning.rs +++ b/server/tests/end_to_end/scanning.rs @@ -206,6 +206,10 @@ async fn lease_live_match_long_poll_instant_push_and_ack() { assert_eq!(ping["t"], "payment"); assert_eq!(ping["events"][0]["id"], id.as_str()); assert!(ping["events"][0].get("compact_tx").is_none()); + // The transaction paid Alice one 5,000-zatoshi Orchard note (§5.2); + // the `events` response above left `amount` out. + assert_eq!(ping["events"][0]["amount"], 5_000); + assert!(events[0].get("amount").is_none()); // The next wake carries the event and a hint; an ack clears both. let r = s.wake(&[], lease_json(&alice, 101, "instant")).await; @@ -319,6 +323,7 @@ async fn private_mode_events_ride_in_the_scheduled_ping() { let ping: Value = serde_json::from_slice(&plain).unwrap(); assert_eq!(ping["t"], "wake"); assert_eq!(ping["events"].as_array().unwrap().len(), 1); + assert_eq!(ping["events"][0]["amount"], 5_000); } #[tokio::test] @@ -600,6 +605,11 @@ async fn one_push_per_transaction_and_at_most_two_a_minute() { assert_eq!(s.page_len(), 2); s.h.state.settle().await; assert_eq!(s.pushes.0.lock().unwrap().len(), 1); + // The one push carries both outputs' total (spec §5.2). + let (_, body) = s.pushes.0.lock().unwrap()[0].clone(); + let ping: Value = serde_json::from_slice(&open_push(&body, &s.push_keys)).unwrap(); + assert_eq!(ping["events"].as_array().unwrap().len(), 1); + assert_eq!(ping["events"][0]["amount"], 14_000); // Three more payments in the same minute: only one more push, but all // of them reach the wallet. diff --git a/server/tests/scanner.rs b/server/tests/scanner.rs index caee982..1153897 100644 --- a/server/tests/scanner.rs +++ b/server/tests/scanner.rs @@ -440,6 +440,90 @@ fn private_mode_pings_carry_up_to_four_events() { assert!(events.iter().all(|e| e.compact_tx.is_none())); } +/// Spec §5.2: push events carry the total the transaction pays the +/// lease's keys; stored events (and so `events` pages) don't carry it. +#[test] +fn push_events_carry_the_transaction_total() { + let w = Wallet::new(1); + let s = scanner(); + let now = t0(); + s.set_lease( + A, + keys(&w), + &lease_req(&w, 1, AlertMode::Private), + WEEK, + 10, + now, + ); + // One transaction paying a Sapling output (7,000) and an Orchard + // action (5,000), and another paying one Ironwood action (5,000). + let b = block( + 10, + vec![ + tx( + 0xA1, + vec![sapling_output(&w.sapling, 1)], + vec![action(&w.orchard, 1, false)], + vec![], + ), + tx(0xA2, vec![], vec![], vec![action(&w.orchard, 2, true)]), + ], + ); + let matches = trial_decrypt(&b, &s.active_keys(now)); + let new = s.record(&b, &matches, 10, now); + let mut amounts: Vec> = new.iter().map(|(_, e)| e.amount).collect(); + amounts.sort(); + assert_eq!(amounts, [Some(5_000), Some(12_000), Some(12_000)]); + + let page = s.page(A, None, 3500); + assert_eq!(page.events.len(), 3); + assert!(page.events.iter().all(|e| e.amount.is_none())); + + // A private ping holds one event per transaction, with its total. + let ping = s.ping_events(A, now); + let mut amounts: Vec> = ping.iter().map(|e| e.amount).collect(); + amounts.sort(); + assert_eq!(amounts, [Some(5_000), Some(12_000)]); + assert!(ping.iter().all(|e| e.compact_tx.is_none())); + + // The amounts never show in debug output. + for e in &ping { + let dbg = format!("{e:?}"); + assert!(!dbg.contains("12000") && !dbg.contains("5000"), "{dbg}"); + } +} + +/// A mempool transaction's push event carries its total too. +#[test] +fn mempool_push_events_carry_the_transaction_total() { + use zcash_protocol::consensus::BranchId; + let w = Wallet::new(1); + let s = scanner(); + let now = t0(); + s.set_lease( + A, + keys(&w), + &lease_req(&w, 1, AlertMode::Instant), + WEEK, + 10, + now, + ); + let raw = common::wallet::full_tx(&w, true, true); + let tx = lz_server::mempool::to_compact(&raw, BranchId::Nu6_3).unwrap(); + let found = + lz_server::scanner::trial_decrypt_txs(std::slice::from_ref(&tx), &s.active_keys(now)); + assert_eq!(found.len(), 2); + let new = s.record_mempool(&tx, found.into_iter().map(|m| (m, None)).collect(), now); + assert_eq!(new.len(), 2); + assert!(new.iter().all(|(_, e)| e.amount == Some(12_000))); + assert!( + s.page(A, None, 3500) + .events + .iter() + .all(|e| e.amount.is_none()) + ); +} + #[test] fn caps_stored_events_per_account() { let w = Wallet::new(1); diff --git a/spec/v0.md b/spec/v0.md index 85d5df5..7438641 100644 --- a/spec/v0.md +++ b/spec/v0.md @@ -869,10 +869,39 @@ The lease's `alert_mode` picks one of two behaviors: SHOULD cap payment pushes per account (the reference server allows 2 a minute), so a burst of payments can't use up the device's push budget. Every event still arrives through `wake` and the long-poll. The event is the one from 4.3 - without `compact_tx`. The plaintext is padded to 1024 bytes and - RFC 8291-encrypted (invariant 5). + without `compact_tx`, plus `amount` (below). The plaintext is padded to + 1024 bytes and RFC 8291-encrypted (invariant 5). - **`private`** places up to 4 such events in the next scheduled ping's - `events`. + `events`, one per transaction, like the payment push. +- **`amount`** (optional, zatoshis, an unsigned 64-bit integer) is the + total the transaction pays the lease's keys, across all of its outputs + that match, since the push carries one event per transaction: + + ```json + {"v":0,"t":"payment","events":[{"id":"","rev":1,"kind":"received", + "status":"mempool","height":null,"confirmations":0,"amount":1200000}]} + ``` + + - It lets the wallet show the amount in the alert itself, since it can't + make a request because of the push (3.3). + - Servers SHOULD include it on `received` events in payment pushes and + `private` pings. Other events don't carry it: `spent` events, and + those in `wake` and `events` responses, which carry `compact_tx` for + the wallet to decrypt itself. A webhook's `amount` (4.5) is a + different field: one output's value. + - It never exceeds the 21 million ZEC supply (2.1 × 10^15 zatoshis), so + JSON parsers that read numbers as doubles, such as JavaScript's, read + it exactly. + - A missing `amount` means unknown, never zero. Wallets MUST accept + events without it, and servers that don't send it remain conformant. + - It is a claim, like the event (6.3): wallets MUST keep it unconfirmed + until their own sync finds the transaction. + - It exposes nothing new. The server already knows it from + trial-decrypting the payment with the leased key, and already sends + it to merchants in webhooks (4.5). The ping keeps its fixed size and + its encryption, so the gateway and Apple or Google learn nothing + more (invariants 4 and 5). Four events with the longest values, + `amount` included, still fit in 1024 bytes. - In both modes, the wallet decrypts on the device and shows a local alert. It MUST NOT make an off-schedule request, to any service, because of the push (3.3). Full details arrive on the next scheduled `wake`, or on @@ -1047,7 +1076,11 @@ below. - **Alerts are claims.** The server, or the chain source it reads, can report a payment that never happened. Wallets MUST present payment alerts and events as incoming and unconfirmed, and MUST NOT count them - as funds, until their own sync finds the transaction in a block. + as funds, until their own sync finds the transaction in a block. The + same goes for a push's `amount` (5.2), which can also be wrong. +- **Amounts in notifications.** A local alert that shows `amount` can be + read on a locked screen. Wallets SHOULD show it only if the user chose + to. - **Viewing-key clients: confirmation.** A client with no sync of its own can never confirm a payment. It MUST show every alert and event as the server's claim, never as funds, including events the server reports as @@ -1109,6 +1142,11 @@ below. ## Changelog +- **2026-11-14, rev 3.22:** an optional `amount` on events in payment + pushes and `private` pings: the total the transaction pays the lease's + keys, unknown when missing, a claim like the event. `private` pings + carry one event per transaction. Sizes and encryption are unchanged + (5.2, 6.3). - **2026-11-06, rev 3.21:** Oblivious Network added to `spec/relays.md`, now that it no longer adds region or connection headers (tested 2026-11-06). Open question 3 (relay-added headers) is closed, and open