diff --git a/pkgs/id/crates/id-sync/src/federation/slices/b22_loop_inform.rs b/pkgs/id/crates/id-sync/src/federation/slices/b22_loop_inform.rs new file mode 100644 index 0000000000..b7a55b2c86 --- /dev/null +++ b/pkgs/id/crates/id-sync/src/federation/slices/b22_loop_inform.rs @@ -0,0 +1,366 @@ +//! B22: tell the parties to a request about duplicates, and report a +//! loop only with the signed path that proves it (#10230, statements +//! S1.65, S1.66 and S1.69; design "Duplicate/replay/cycle state"). +//! +//! A peer that receives a federated query runs it through a +//! [`LoopInformer`], which checks the B17 origin query and grant chain +//! first and then decides one of four things: +//! +//! - **Run** it: the first valid arrival at this peer. +//! - **Duplicate**: a valid repeat of a request this peer already has, +//! in flight or answered, such as the same query arriving directly +//! and through a relay (S1.64, normal and not an error). It is not +//! run again (B20, B21), and the peer issues a signed duplicate +//! [`Notice`] so the requester and the peer that sent it learn that +//! it was not silently swallowed (S1.66). A completed duplicate's +//! notice names the cached outcome. +//! - **Loop**: the verified grant chain shows that this peer already +//! signed a grant for this request, so the query came back round. +//! The loop notice carries that whole chain as evidence (S1.69). +//! Repeating a request id, arriving twice, or a path where some +//! other peer appears twice is never a loop at this peer; only its +//! own signature earlier in the path is. +//! - **Refused**: the query or chain does not verify, the chain was not +//! granted to this peer, the last grant is this peer granting itself, +//! or B20 refuses the identity (replay, binding conflict, expiry, a +//! full ledger). A refused arrival issues no notice, so an unverified +//! path can never produce a loop report. +//! +//! Notices go to the origin and to the peer that delivered the request +//! (the last grant's relay; the origin itself for a direct arrival). +//! Each is signed by the reporting peer. [`verify_notice`] lets any +//! recipient check one: the signature, and for a loop, that the +//! evidence chain verified when it was observed, that it was granted +//! to the reporter by someone else, and that the reporter appears in +//! its path. A duplicate notice is the reporter's signed statement and +//! carries no evidence, since a repeat leaves no third-party proof. +//! +//! Rollback: [`LoopInformer::set_inform_duplicates`] turns duplicate +//! notices off. Duplicates are still recognized and never rerun, and +//! loops are still detected and reported. +//! +//! Notice preimage, with integers big-endian: +//! +//! ```text +//! "id-sync/b22-notice/v1" request_id origin reporter +//! sender (0x00, or 0x01 and a 32-byte peer) +//! kind (0x01 duplicate in flight; 0x02 duplicate completed and a +//! 32-byte outcome; 0x03 loop) +//! observed_at:u64 evidence_len:u32 grant digests[] +//! ``` +//! +//! This module is deliberately self-contained: the federation roots +//! record slice paths without declaring them (slice 9110-02), so the +//! slice's integration test includes this file directly and no shared +//! root names it yet; #9110-09 wires versioned public exports after +//! module outputs land. + +use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; + +use super::b17_query_grants::{ChainError, OriginQuery, RelayGrant, verify_chain}; +use super::b20_request_identity::{ + Classification, DedupError, DedupLedger, OriginKey, OutcomeId, PeerKey, RequestId, + RequestIdentity, +}; + +/// Domain prefix of a notice preimage. +pub const NOTICE_DOMAIN: &[u8] = b"id-sync/b22-notice/v1"; + +/// What a notice reports. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NoticeKind { + /// A repeat of a request this peer is still working on. + DuplicateInFlight, + /// A repeat of a request this peer already answered. + DuplicateCompleted { + /// The cached outcome the repeat is answered with. + outcome: OutcomeId, + }, + /// The request came back to a peer already on its signed path. + Loop, +} + +/// A reporting peer's signed statement about one arrival. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Notice { + /// The request. + pub request_id: RequestId, + /// The origin, always a recipient. + pub origin: OriginKey, + /// The peer that observed the arrival and signs the notice. + pub reporter: PeerKey, + /// The peer that delivered it, if a relay did. + pub sender: Option, + /// What happened. + pub kind: NoticeKind, + /// When the reporter observed it, in its own clock. + pub observed_at: u64, + /// For a loop, the signed chain that arrived; empty otherwise. + pub evidence: Vec, + /// The reporter's signature. + pub signature: [u8; 64], +} + +impl Notice { + /// The signed preimage. + pub fn preimage(&self) -> Vec { + let mut out = NOTICE_DOMAIN.to_vec(); + out.extend_from_slice(&self.request_id.0); + out.extend_from_slice(&self.origin); + out.extend_from_slice(&self.reporter); + match self.sender { + None => out.push(0), + Some(sender) => { + out.push(1); + out.extend_from_slice(&sender); + } + } + match self.kind { + NoticeKind::DuplicateInFlight => out.push(1), + NoticeKind::DuplicateCompleted { outcome } => { + out.push(2); + out.extend_from_slice(&outcome); + } + NoticeKind::Loop => out.push(3), + } + out.extend_from_slice(&self.observed_at.to_be_bytes()); + out.extend_from_slice( + &u32::try_from(self.evidence.len()) + .unwrap_or(u32::MAX) + .to_be_bytes(), + ); + for grant in &self.evidence { + out.extend_from_slice(&grant.digest()); + } + out + } + + /// Sign (or re-sign) the notice's current fields. + pub fn sign(&mut self, key: &SigningKey) { + self.signature = key.sign(&self.preimage()).to_bytes(); + } + + /// Who the notice goes to: the origin, then the sender if it is + /// another peer. + pub fn recipients(&self) -> Vec { + let mut out = vec![self.origin]; + if let Some(sender) = self.sender + && sender != self.origin + { + out.push(sender); + } + out + } +} + +/// Why an arrival was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Refusal { + /// The origin query or the grant chain did not verify. + Chain(ChainError), + /// The chain was granted to another peer, or a direct arrival + /// reached a peer the origin did not address. + NotAddressed, + /// The last grant is this peer granting itself. + SelfGrant, + /// B20: the origin nonce already minted another request. + Replay, + /// B20: the binding differs from the one registered under this id. + BindingConflict, + /// B20: the request has expired. + Expired, + /// B20: the ledger is full of live requests. + LedgerFull, +} + +/// What this peer does with one arrival. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Arrival { + /// First valid arrival: run it. + Run, + /// A repeat: do not run it again. `notice` is `None` only while + /// duplicate notices are turned off. + Duplicate { + /// The cached outcome, when the request was already answered. + completed: Option, + /// The notice for the origin and the sender. + notice: Option, + }, + /// The request came back round: do not run or forward it. + Loop { + /// The notice, with the chain that proves it. + notice: Notice, + }, + /// Not accepted, and nothing is reported. + Refused(Refusal), +} + +/// One peer's arrival handling for federated queries. +#[derive(Debug)] +pub struct LoopInformer { + key: SigningKey, + ledger: DedupLedger, + inform_duplicates: bool, +} + +impl LoopInformer { + /// A peer signing with `key`, keeping at most `capacity` requests + /// in its B20 ledger, each for `cleanup_grace_secs` past expiry. + pub fn new(key: SigningKey, capacity: usize, cleanup_grace_secs: u64) -> Self { + Self { + key, + ledger: DedupLedger::new(capacity, cleanup_grace_secs), + inform_duplicates: true, + } + } + + /// This peer's id. + pub fn peer(&self) -> PeerKey { + self.key.verifying_key().to_bytes() + } + + /// Turn duplicate notices on or off (the rollback switch). + pub const fn set_inform_duplicates(&mut self, on: bool) { + self.inform_duplicates = on; + } + + /// Handle `query` arriving with `grants` at `now`. With no grants, + /// the origin sent it directly, and `addressed` says whether the + /// origin meant this peer. + pub fn arrive( + &mut self, + query: &OriginQuery, + grants: &[RelayGrant], + addressed: bool, + now: u64, + ) -> Arrival { + let path = match verify_chain(query, grants, now) { + Ok(path) => path, + Err(error) => return Arrival::Refused(Refusal::Chain(error)), + }; + let local = self.peer(); + match path.holder { + Some(holder) if holder != local => return Arrival::Refused(Refusal::NotAddressed), + None if !addressed => return Arrival::Refused(Refusal::NotAddressed), + _ => {} + } + let sender = grants.last().map(|g| g.relay_id); + if sender == Some(local) { + return Arrival::Refused(Refusal::SelfGrant); + } + let identity = RequestIdentity::new(query.origin, query.nonce, query.binding.clone()); + if path.visits(&local) { + let notice = self.notice(query, sender, NoticeKind::Loop, now, grants.to_vec()); + return Arrival::Loop { notice }; + } + let kind = match self.ledger.observe(&identity, now) { + Classification::New => return Arrival::Run, + Classification::DuplicateInFlight => NoticeKind::DuplicateInFlight, + Classification::DuplicateCompleted => match self.ledger.cached_outcome(&identity.id) { + Some(outcome) => NoticeKind::DuplicateCompleted { outcome }, + None => NoticeKind::DuplicateInFlight, + }, + Classification::Replay => return Arrival::Refused(Refusal::Replay), + Classification::BindingConflict => { + return Arrival::Refused(Refusal::BindingConflict); + } + Classification::Expired | Classification::Cycle => { + return Arrival::Refused(Refusal::Expired); + } + Classification::LedgerFull => return Arrival::Refused(Refusal::LedgerFull), + }; + let completed = match kind { + NoticeKind::DuplicateCompleted { outcome } => Some(outcome), + NoticeKind::DuplicateInFlight | NoticeKind::Loop => None, + }; + let notice = self + .inform_duplicates + .then(|| self.notice(query, sender, kind, now, Vec::new())); + Arrival::Duplicate { completed, notice } + } + + /// Record the outcome of a request this peer ran (B20). + pub fn complete(&mut self, query: &OriginQuery, outcome: OutcomeId) -> Result<(), DedupError> { + let identity = RequestIdentity::new(query.origin, query.nonce, query.binding.clone()); + self.ledger.complete(&identity, outcome) + } + + fn notice( + &self, + query: &OriginQuery, + sender: Option, + kind: NoticeKind, + now: u64, + evidence: Vec, + ) -> Notice { + let mut notice = Notice { + request_id: query.request_id, + origin: query.origin, + reporter: self.peer(), + sender, + kind, + observed_at: now, + evidence, + signature: [0; 64], + }; + notice.sign(&self.key); + notice + } +} + +/// Why a notice was refused by a recipient. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NoticeError { + /// The notice is about another request or origin. + WrongRequest, + /// The reporter's signature does not verify. + BadSignature, + /// A duplicate notice carries evidence, or a loop notice has none. + EvidenceShape, + /// The loop evidence did not verify when it was observed. + Evidence(ChainError), + /// The loop evidence was granted to someone else, or the sender + /// named is not the last grant's relay. + NotTheReporter, + /// The last grant of the evidence is the reporter granting itself. + SelfGrant, + /// The evidence path does not show the reporter already visited. + NoSelfVisit, +} + +/// Check a notice about `query` as a recipient would. +pub fn verify_notice(query: &OriginQuery, notice: &Notice) -> Result<(), NoticeError> { + if notice.request_id != query.request_id || notice.origin != query.origin { + return Err(NoticeError::WrongRequest); + } + let verified = VerifyingKey::from_bytes(¬ice.reporter).is_ok_and(|key| { + key.verify_strict( + ¬ice.preimage(), + &Signature::from_bytes(¬ice.signature), + ) + .is_ok() + }); + if !verified { + return Err(NoticeError::BadSignature); + } + let is_loop = notice.kind == NoticeKind::Loop; + if is_loop == notice.evidence.is_empty() { + return Err(NoticeError::EvidenceShape); + } + if !is_loop { + return Ok(()); + } + let path = + verify_chain(query, ¬ice.evidence, notice.observed_at).map_err(NoticeError::Evidence)?; + let last = notice.evidence.last().map(|g| g.relay_id); + if path.holder != Some(notice.reporter) || notice.sender != last { + return Err(NoticeError::NotTheReporter); + } + if last == Some(notice.reporter) { + return Err(NoticeError::SelfGrant); + } + if !path.visits(¬ice.reporter) { + return Err(NoticeError::NoSelfVisit); + } + Ok(()) +} diff --git a/pkgs/id/crates/id-sync/tests/federation_b22.rs b/pkgs/id/crates/id-sync/tests/federation_b22.rs new file mode 100644 index 0000000000..5484902554 --- /dev/null +++ b/pkgs/id/crates/id-sync/tests/federation_b22.rs @@ -0,0 +1,638 @@ +//! B22 invariant test: duplicate notices and loop reports (#10230, +//! statements S1.65, S1.66 and S1.69). +//! +//! Oracle: **invariant** — the requester and the delivering peer are +//! informed of a duplicate, and a loop is reported only with a retained +//! signed path showing the reporting peer already visited. The +//! reference is a state machine in this file: for each peer it tracks +//! which requests it has run and with what outcome, and it predicts +//! every arrival from how the test built the delivery (route of relays, +//! intended and actual destination, tampering, hop bound), never from +//! the slice. Random streams sign queries, deliver them directly and +//! through random relay routes that may revisit peers, misdirect or +//! tamper with chains, complete requests and toggle duplicate notices. +//! Every notice must verify for its recipients, and a hand-built +//! encoder checks the notice preimage layout. +//! +//! The slice modules are loaded by path: the federation roots record +//! them without declaring them (slice 9110-02), and B22 reaches B17 and +//! B20 through `super::`. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +#[path = "../src/federation/slices/b20_request_identity.rs"] +#[allow(dead_code)] +mod b20_request_identity; + +#[path = "../src/federation/slices/b17_query_grants.rs"] +#[allow(dead_code)] +mod b17_query_grants; + +#[path = "../src/federation/slices/b22_loop_inform.rs"] +mod b22_loop_inform; + +use std::collections::BTreeMap; + +use b17_query_grants::{ChainError, OriginQuery, QueryError, RelayGrant}; +use b20_request_identity::{DedupError, OutcomeId, PeerKey, QueryBinding}; +use b22_loop_inform::{ + Arrival, LoopInformer, Notice, NoticeError, NoticeKind, Refusal, verify_notice, +}; +use ed25519_dalek::{Signature, SigningKey, VerifyingKey}; +use proptest::prelude::*; + +const NOW: u64 = 500; +const PEERS: std::ops::RangeInclusive = 2..=7; + +fn key(seed: u8) -> SigningKey { + SigningKey::from_bytes(&[seed; 32]) +} + +fn id(seed: u8) -> PeerKey { + key(seed).verifying_key().to_bytes() +} + +fn query(nonce: u8, hops: u32) -> OriginQuery { + OriginQuery::sign( + &key(1), + [nonce; 32], + QueryBinding { + query_digest: [9; 32], + scope: b"public".to_vec(), + issued_at: 100, + expires_at: 1000, + initial_max_hops: hops, + }, + ) +} + +/// Grants by each relay in `route` in turn, the last one granting `child`. +fn chain(query: &OriginQuery, route: &[u8], child: u8) -> Vec { + let mut grants: Vec = Vec::new(); + for (i, relay) in route.iter().enumerate() { + let next = route.get(i + 1).copied().unwrap_or(child); + let grant = RelayGrant::issue(&key(*relay), query, grants.last(), id(next), 900); + grants.push(grant); + } + grants +} + +fn informer(seed: u8) -> LoopInformer { + LoopInformer::new(key(seed), 64, 60) +} + +// ----- notice layout -------------------------------------------------- + +fn expected_preimage(n: &Notice) -> Vec { + let mut out = b"id-sync/b22-notice/v1".to_vec(); + out.extend_from_slice(&n.request_id.0); + out.extend_from_slice(&n.origin); + out.extend_from_slice(&n.reporter); + if let Some(sender) = n.sender { + out.push(1); + out.extend_from_slice(&sender); + } else { + out.push(0); + } + match n.kind { + NoticeKind::DuplicateInFlight => out.push(1), + NoticeKind::DuplicateCompleted { outcome } => { + out.push(2); + out.extend_from_slice(&outcome); + } + NoticeKind::Loop => out.push(3), + } + out.extend_from_slice(&n.observed_at.to_be_bytes()); + out.extend_from_slice(&u32::try_from(n.evidence.len()).unwrap().to_be_bytes()); + for grant in &n.evidence { + out.extend_from_slice(&grant.digest()); + } + out +} + +fn check_layout(n: &Notice) { + let pre = expected_preimage(n); + assert_eq!(n.preimage(), pre); + assert!( + VerifyingKey::from_bytes(&n.reporter) + .unwrap() + .verify_strict(&pre, &Signature::from_bytes(&n.signature)) + .is_ok() + ); +} + +// ----- explicit cases ------------------------------------------------- + +#[test] +fn the_same_request_direct_and_relayed_is_a_duplicate_not_a_loop() { + let q = query(1, 4); + let mut peer = informer(5); + assert_eq!(peer.arrive(&q, &[], true, NOW), Arrival::Run); + let relayed = chain(&q, &[2, 3], 5); + let Arrival::Duplicate { + completed: None, + notice: Some(notice), + } = peer.arrive(&q, &relayed, false, NOW) + else { + panic!("expected an in-flight duplicate notice"); + }; + assert_eq!(notice.kind, NoticeKind::DuplicateInFlight); + assert_eq!(notice.sender, Some(id(3))); + assert_eq!(notice.recipients(), vec![q.origin, id(3)]); + assert!(notice.evidence.is_empty()); + check_layout(¬ice); + assert_eq!(verify_notice(&q, ¬ice), Ok(())); +} + +#[test] +fn an_answered_duplicate_names_its_cached_outcome() { + let q = query(1, 4); + let mut peer = informer(5); + assert_eq!( + peer.arrive(&q, &chain(&q, &[2], 5), false, NOW), + Arrival::Run + ); + assert_eq!(peer.complete(&q, [8; 32]), Ok(())); + assert_eq!(peer.complete(&q, [9; 32]), Err(DedupError::OutcomeConflict)); + let Arrival::Duplicate { + completed: Some(outcome), + notice: Some(notice), + } = peer.arrive(&q, &[], true, NOW) + else { + panic!("expected a completed duplicate notice"); + }; + assert_eq!(outcome, [8; 32]); + assert_eq!(notice.kind, NoticeKind::DuplicateCompleted { outcome }); + // A direct duplicate goes to the origin only. + assert_eq!(notice.sender, None); + assert_eq!(notice.recipients(), vec![q.origin]); + check_layout(¬ice); + assert_eq!(verify_notice(&q, ¬ice), Ok(())); + assert_eq!( + informer(6).complete(&q, [8; 32]), + Err(DedupError::UnknownRequest) + ); +} + +#[test] +fn a_loop_is_reported_with_the_chain_that_proves_it() { + let q = query(1, 6); + let mut peer = informer(2); + // 2 relays to 3, 3 to 4, and 4 hands it back to 2. + let grants = chain(&q, &[2, 3, 4], 2); + let Arrival::Loop { notice } = peer.arrive(&q, &grants, false, NOW) else { + panic!("expected a loop"); + }; + assert_eq!(notice.kind, NoticeKind::Loop); + assert_eq!(notice.evidence, grants); + assert_eq!(notice.sender, Some(id(4))); + assert_eq!(notice.recipients(), vec![q.origin, id(4)]); + check_layout(¬ice); + assert_eq!(verify_notice(&q, ¬ice), Ok(())); + // A loop is not registered as work: the first real arrival still runs. + assert_eq!(peer.arrive(&q, &[], true, NOW), Arrival::Run); +} + +#[test] +fn the_origin_relaying_itself_is_told_once() { + let q = query(1, 4); + let mut peer = informer(5); + assert_eq!(peer.arrive(&q, &[], true, NOW), Arrival::Run); + // The origin's key also signs as the first relay. + let Arrival::Duplicate { + notice: Some(notice), + .. + } = peer.arrive(&q, &chain(&q, &[1], 5), false, NOW) + else { + panic!("expected a duplicate notice"); + }; + assert_eq!(notice.sender, Some(q.origin)); + assert_eq!(notice.recipients(), vec![q.origin]); +} + +#[test] +fn a_path_where_another_peer_repeats_is_not_a_loop_here() { + let q = query(1, 6); + let mut peer = informer(5); + let grants = chain(&q, &[2, 3, 2], 5); + assert_eq!(peer.arrive(&q, &grants, false, NOW), Arrival::Run); +} + +#[test] +fn a_loop_notice_outlives_the_grants_it_carries() { + let q = query(1, 6); + let mut peer = informer(2); + let Arrival::Loop { notice } = peer.arrive(&q, &chain(&q, &[2, 3], 2), false, NOW) else { + panic!("expected a loop"); + }; + // The grants expire at 900 and the query at 1000; the notice is + // checked as of when it was observed. + assert_eq!(verify_notice(&q, ¬ice), Ok(())); + assert!(notice.observed_at < 900); +} + +#[test] +fn unverified_or_misdirected_arrivals_report_nothing() { + let q = query(1, 4); + let mut peer = informer(5); + + let mut forged = chain(&q, &[2, 5, 3], 5); + forged[1].signature[0] ^= 1; + assert_eq!( + peer.arrive(&q, &forged, false, NOW), + Arrival::Refused(Refusal::Chain(ChainError::BadSignature { index: 1 })) + ); + assert_eq!( + peer.arrive(&q, &chain(&q, &[2, 3], 6), false, NOW), + Arrival::Refused(Refusal::NotAddressed) + ); + assert_eq!( + peer.arrive(&q, &[], false, NOW), + Arrival::Refused(Refusal::NotAddressed) + ); + // A peer that grants itself does not get to call that a loop. + assert_eq!( + peer.arrive(&q, &chain(&q, &[5], 5), false, NOW), + Arrival::Refused(Refusal::SelfGrant) + ); + assert_eq!( + peer.arrive(&q, &chain(&q, &[2, 3, 4, 6], 5), false, NOW), + Arrival::Refused(Refusal::Chain(ChainError::HopBoundExceeded { index: 3 })) + ); + assert_eq!( + peer.arrive(&q, &[], true, 1000), + Arrival::Refused(Refusal::Chain(ChainError::Query(QueryError::Expired))) + ); + // None of that registered the request. + assert_eq!(peer.arrive(&q, &[], true, NOW), Arrival::Run); +} + +#[test] +fn b20_refusals_pass_through_without_a_notice() { + let mut peer = informer(5); + let first = query(1, 4); + assert_eq!(peer.arrive(&first, &[], true, NOW), Arrival::Run); + // The same origin nonce under another binding is a replay. + let replay = query(1, 5); + assert_eq!( + peer.arrive(&replay, &[], true, NOW), + Arrival::Refused(Refusal::Replay) + ); + + let mut small = LoopInformer::new(key(5), 1, 0); + assert_eq!(small.arrive(&query(2, 4), &[], true, NOW), Arrival::Run); + assert_eq!( + small.arrive(&query(3, 4), &[], true, NOW), + Arrival::Refused(Refusal::LedgerFull) + ); +} + +#[test] +fn turning_duplicate_notices_off_keeps_loops_and_dedup() { + let q = query(1, 6); + let mut peer = informer(3); + peer.set_inform_duplicates(false); + assert_eq!(peer.arrive(&q, &[], true, NOW), Arrival::Run); + assert_eq!( + peer.arrive(&q, &chain(&q, &[2], 3), false, NOW), + Arrival::Duplicate { + completed: None, + notice: None + } + ); + assert!(matches!( + peer.arrive(&q, &chain(&q, &[3, 4], 3), false, NOW), + Arrival::Loop { .. } + )); + peer.set_inform_duplicates(true); + assert!(matches!( + peer.arrive(&q, &[], true, NOW), + Arrival::Duplicate { + notice: Some(_), + .. + } + )); +} + +#[test] +fn forged_loop_reports_are_refused() { + let q = query(1, 6); + let reporter = key(5); + let honest_loop = { + let mut peer = LoopInformer::new(reporter.clone(), 8, 0); + let Arrival::Loop { notice } = peer.arrive(&q, &chain(&q, &[5, 3], 5), false, NOW) else { + panic!("expected a loop"); + }; + notice + }; + assert_eq!(verify_notice(&q, &honest_loop), Ok(())); + let resign = |mut n: Notice| { + n.sign(&reporter); + n + }; + + // A path that never visited the reporter. + let mut no_visit = honest_loop.clone(); + no_visit.evidence = chain(&q, &[2, 3], 5); + assert_eq!( + verify_notice(&q, &resign(no_visit)), + Err(NoticeError::NoSelfVisit) + ); + + // Someone else's loop, claimed by the reporter. + let mut theirs = honest_loop.clone(); + theirs.evidence = chain(&q, &[4, 3], 4); + assert_eq!( + verify_notice(&q, &resign(theirs)), + Err(NoticeError::NotTheReporter) + ); + + // The reporter's own self-grant as "evidence". + let mut own = honest_loop.clone(); + own.evidence = chain(&q, &[5], 5); + own.sender = Some(id(5)); + assert_eq!(verify_notice(&q, &resign(own)), Err(NoticeError::SelfGrant)); + + // A sender other than the relay that delivered it. + let mut wrong_sender = honest_loop.clone(); + wrong_sender.sender = Some(id(4)); + assert_eq!( + verify_notice(&q, &resign(wrong_sender)), + Err(NoticeError::NotTheReporter) + ); + + // An evidence grant changed after signing. + let mut tampered = honest_loop.clone(); + tampered.evidence[0].expires_at = 899; + assert!(matches!( + verify_notice(&q, &resign(tampered)), + Err(NoticeError::Evidence(ChainError::BadSignature { index: 0 })) + )); + + // Observed after the grants expired. + let mut late = honest_loop.clone(); + late.observed_at = 950; + assert!(matches!( + verify_notice(&q, &resign(late)), + Err(NoticeError::Evidence(ChainError::Expired { .. })) + )); + + // A loop with no evidence, and a duplicate with some. + let mut bare = honest_loop.clone(); + bare.evidence.clear(); + assert_eq!( + verify_notice(&q, &resign(bare)), + Err(NoticeError::EvidenceShape) + ); + let mut padded = honest_loop.clone(); + padded.kind = NoticeKind::DuplicateInFlight; + assert_eq!( + verify_notice(&q, &resign(padded)), + Err(NoticeError::EvidenceShape) + ); + + // Signed by another peer in the reporter's name. + let mut impostor = honest_loop.clone(); + impostor.sign(&key(6)); + assert_eq!(verify_notice(&q, &impostor), Err(NoticeError::BadSignature)); + + // Naming another origin under the same request id. + let mut other_origin = honest_loop.clone(); + other_origin.origin = id(6); + assert_eq!( + verify_notice(&q, &resign(other_origin)), + Err(NoticeError::WrongRequest) + ); + + // About another request. + assert_eq!( + verify_notice(&query(2, 6), &honest_loop), + Err(NoticeError::WrongRequest) + ); +} + +// ----- reference model ------------------------------------------------- + +#[derive(Debug, Clone)] +enum Action { + Sign { + hops: u32, + }, + Deliver { + query: usize, + route: Vec, + intended: u8, + actual: u8, + addressed: bool, + tamper: bool, + }, + Complete { + query: usize, + peer: u8, + outcome: u8, + }, + Inform { + peer: u8, + on: bool, + }, +} + +fn peer_seed() -> impl Strategy { + PEERS +} + +fn action() -> impl Strategy { + prop_oneof![ + 1 => (1u32..=8).prop_map(|hops| Action::Sign { hops }), + 6 => ( + any::(), + prop::collection::vec(peer_seed(), 0..6), + peer_seed(), + prop::option::weighted(0.15, peer_seed()), + prop::bool::weighted(0.85), + prop::bool::weighted(0.1), + ) + .prop_map(|(query, route, intended, misdirect, addressed, tamper)| { + Action::Deliver { + query, + route, + intended, + actual: misdirect.unwrap_or(intended), + addressed, + tamper, + } + }), + 2 => (any::(), peer_seed(), 0u8..3).prop_map(|(query, peer, outcome)| { + Action::Complete { query, peer, outcome } + }), + 1 => (peer_seed(), any::()).prop_map(|(peer, on)| Action::Inform { peer, on }), + ] +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Seen { + Running, + Answered(OutcomeId), +} + +#[derive(Debug, PartialEq, Eq)] +enum Expect { + Run, + Duplicate(Option), + Loop, + ChainRefused, + NotAddressed, + SelfGrant, +} + +struct Model { + queries: Vec, + peers: BTreeMap, + seen: BTreeMap<(usize, u8), Seen>, + inform: BTreeMap, +} + +impl Model { + fn new() -> Self { + Self { + queries: vec![query(0, 4)], + peers: PEERS.map(|p| (p, informer(p))).collect(), + seen: BTreeMap::new(), + inform: PEERS.map(|p| (p, true)).collect(), + } + } + + fn expect( + &self, + q: usize, + route: &[u8], + intended: u8, + actual: u8, + addressed: bool, + tamper: bool, + ) -> Expect { + let hops = self.queries[q].binding.initial_max_hops as usize; + if route.len() >= hops || (tamper && !route.is_empty()) { + return Expect::ChainRefused; + } + if (route.is_empty() && !addressed) || (!route.is_empty() && intended != actual) { + return Expect::NotAddressed; + } + if route.last() == Some(&actual) { + return Expect::SelfGrant; + } + if route.contains(&actual) { + return Expect::Loop; + } + match self.seen.get(&(q, actual)) { + None => Expect::Run, + Some(Seen::Running) => Expect::Duplicate(None), + Some(Seen::Answered(outcome)) => Expect::Duplicate(Some(*outcome)), + } + } + + fn step(&mut self, action: &Action) { + match action { + Action::Sign { hops } => { + let nonce = u8::try_from(self.queries.len()).unwrap(); + self.queries.push(query(nonce, *hops)); + } + Action::Inform { peer, on } => { + self.peers.get_mut(peer).unwrap().set_inform_duplicates(*on); + self.inform.insert(*peer, *on); + } + Action::Complete { + query, + peer, + outcome, + } => { + let q = query % self.queries.len(); + let outcome = [*outcome; 32]; + let got = self + .peers + .get_mut(peer) + .unwrap() + .complete(&self.queries[q], outcome); + let want = match self.seen.get(&(q, *peer)) { + None => Err(DedupError::UnknownRequest), + Some(Seen::Running) => Ok(()), + Some(Seen::Answered(o)) if *o == outcome => Ok(()), + Some(Seen::Answered(_)) => Err(DedupError::OutcomeConflict), + }; + assert_eq!(got, want, "{action:?}"); + if want.is_ok() { + self.seen.insert((q, *peer), Seen::Answered(outcome)); + } + } + Action::Deliver { + query, + route, + intended, + actual, + addressed, + tamper, + } => { + let q = query % self.queries.len(); + let origin_query = self.queries[q].clone(); + let mut grants = chain(&origin_query, route, *intended); + if *tamper && let Some(g) = grants.last_mut() { + g.signature[5] ^= 1; + } + let want = self.expect(q, route, *intended, *actual, *addressed, *tamper); + let got = self.peers.get_mut(actual).unwrap().arrive( + &origin_query, + &grants, + *addressed, + NOW, + ); + let sender = route.last().map(|r| id(*r)); + let check = |notice: &Notice, kind: NoticeKind, evidence: &[RelayGrant]| { + assert_eq!(notice.kind, kind, "{action:?}"); + assert_eq!(notice.reporter, id(*actual)); + assert_eq!(notice.sender, sender); + assert_eq!(notice.evidence, evidence); + let mut recipients = vec![origin_query.origin]; + recipients.extend(sender); + assert_eq!(notice.recipients(), recipients); + check_layout(notice); + assert_eq!(verify_notice(&origin_query, notice), Ok(()), "{action:?}"); + }; + match (&want, got) { + (Expect::Run, Arrival::Run) => { + self.seen.insert((q, *actual), Seen::Running); + } + (Expect::Duplicate(cached), Arrival::Duplicate { completed, notice }) => { + assert_eq!(completed, *cached, "{action:?}"); + assert_eq!(notice.is_some(), self.inform[actual], "{action:?}"); + if let Some(notice) = notice { + let kind = cached.map_or(NoticeKind::DuplicateInFlight, |outcome| { + NoticeKind::DuplicateCompleted { outcome } + }); + check(¬ice, kind, &[]); + } + } + (Expect::Loop, Arrival::Loop { notice }) => { + assert!(notice.evidence.iter().any(|g| g.relay_id == id(*actual))); + check(¬ice, NoticeKind::Loop, &grants); + } + (Expect::ChainRefused, Arrival::Refused(Refusal::Chain(_))) + | (Expect::NotAddressed, Arrival::Refused(Refusal::NotAddressed)) + | (Expect::SelfGrant, Arrival::Refused(Refusal::SelfGrant)) => {} + (want, got) => panic!("{action:?}: expected {want:?}, got {got:?}"), + } + } + } + } +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 64, ..ProptestConfig::default() })] + + #[test] + fn arrivals_match_the_reference(actions in prop::collection::vec(action(), 1..40)) { + let mut model = Model::new(); + for action in &actions { + model.step(action); + } + } +}