Skip to main content

cbcl_core/
equivocation.rs

1//! Equivocation accountability (SPEC-015 REQ-705/REQ-706/REQ-707,
2//! ADR-703, CON-702).
3//!
4//! The paper proves per-message *exclusion* of equivocation is non-monotone
5//! (outside the CALM coordination-free envelope) while *detection* is
6//! monotone and the offending signed pair is a transferable proof. This
7//! module makes that literal, in three pieces:
8//!
9//! 1. [`equivocation`] (REQ-705) — a monotone predicate over a
10//!    thread-scoped store: does `key` have two distinct messages in
11//!    `thread` that are (a) messages of two distinct alternatives of one
12//!    `(any …)` choice point of the dialect's protocol (*choice*
13//!    equivocation), or (b) two distinct discharges of the same protocol
14//!    obligation — same performative, different content hash (*obligation*
15//!    equivocation)? Detection is read-only and verdict-neutral: both
16//!    members of the pair keep whatever verdict they individually earned
17//!    (detection, not exclusion — ADR-703).
18//! 2. [`EquivocationProof`] / [`verify_equivocation_proof`] (REQ-706,
19//!    CON-702) — the offending pair as a transferable proof object
20//!    `(equivocation key thread dialect-hash member member)`, verifiable
21//!    by any third party from the pair and the *pinned* dialect alone (the
22//!    proof names the governing dialect's content hash and verification is
23//!    against a dialect matching it, never a same-named substitute): no
24//!    store, no testimony. Anything short of a fully-verifying pair is a
25//!    typed rejection.
26//! 3. [`choice_transparency_lint`] (REQ-707) — an opt-in, advisory R6-area
27//!    lint: when a choice point's alternatives share no common recipient
28//!    role other than the chooser, no single honest endpoint is guaranteed
29//!    to witness a choice equivocation locally, and detection relies on
30//!    proof gossip. A warning, never a violation — the corpus shows
31//!    disjoint-branch addressing is legitimate.
32//!
33//! Key identity is canonical throughout ([`KeyId`], REQ-708): `@alice` and
34//! `@ed25519:alice` are one identity, so spelling aliases can neither evade
35//! the predicate nor split a proof.
36//!
37//! Choice-membership is read from the dialect as the `(any …)` node-refs of
38//! its causal protocol: every [`NodeRef::Any`] set appearing in any step's
39//! predecessor or successor position is one choice point, its members the
40//! alternatives (`begin` excluded).
41// SIMPLIFY: multi-entry predecessor lists ([Single(a), Single(b)]) are read
42// as a ∨ b by the deployed verifier and by R6 chooser coherence (r6.rs),
43// but are not yet treated as choice points here — REQ-705 names the
44// `(any …)` form. Fold them in if the spec is amended to say so.
45
46#![forbid(unsafe_code)]
47
48use crate::attest::{verify_attestation_v2, AttestError, AttestationHeader};
49use crate::dialect::Dialect;
50use crate::envelope::{verify_opened, OpenedError};
51use crate::keyid::{KeyId, KeyIdError};
52use crate::message::Message;
53use crate::protocol::{CausalProtocol, NodeRef, BEGIN_KEYWORD};
54use crate::r4::Signer;
55use crate::role::RoleAnnotation;
56use crate::store::{ContentHash, MessageStore, ThreadId};
57use alloc::collections::{BTreeMap, BTreeSet};
58use alloc::string::String;
59use alloc::vec::Vec;
60use core::fmt;
61
62// ---------------------------------------------------------------------------
63// Shared: content hashing and choice-point extraction
64// ---------------------------------------------------------------------------
65
66/// Canonical content hash of a message: `f1220<lowercase-hex64>`, the
67/// single content-address hub for every content-addressed message (attestation
68/// headers, envelope redaction, equivocation, `:caused-by` references, and the
69/// wasm binding's message hashing, SPEC-003 REQ-314).
70///
71/// SPEC-017 Stage 1 (hub flip): this is the canonical **typed Merkle root**
72/// over the message's fields ([`crate::typed_addr::typed_root`]), not the older
73/// flat `f1220H(canonical-bytes)`. The return shape is unchanged
74/// (`f1220<hex64>`, a drop-in content address) and the root is deterministic
75/// and injective under SHA-256 collision resistance exactly as the flat hash
76/// was, so every property that held of the flat hash (determinism,
77/// content-sensitivity, opaque injectivity — the Lean `contentHash_injective`
78/// assumption) holds unchanged; only the concrete digest *value* differs.
79pub fn message_content_hash(msg: &Message) -> String {
80    crate::typed_addr::typed_root(msg)
81}
82
83/// The `(any …)` choice points of a protocol: each distinct `NodeRef::Any`
84/// member set (predecessor or successor position, `begin` excluded) with at
85/// least two named alternatives.
86fn any_choice_sets(cp: &CausalProtocol) -> Vec<BTreeSet<String>> {
87    let mut sets: Vec<BTreeSet<String>> = Vec::new();
88    for step in cp.steps.values() {
89        for nr in step.predecessors.iter().chain(step.successors.iter()) {
90            if let NodeRef::Any(set) = nr {
91                let named: BTreeSet<String> = set
92                    .iter()
93                    .filter(|m| m.as_str() != BEGIN_KEYWORD)
94                    .cloned()
95                    .collect();
96                if named.len() >= 2 && !sets.contains(&named) {
97                    sets.push(named);
98                }
99            }
100        }
101    }
102    sets
103}
104
105/// Every performative name the protocol constrains (step keys plus all
106/// node-ref references, `begin` excluded) — the obligation schema the (b)
107/// form quantifies over. The protocol is a finite DAG in which each name
108/// occurs as one obligation (repeat expansion synthesises distinct copy
109/// names, REQ-704), so the name identifies the obligation instance.
110fn protocol_performatives(cp: &CausalProtocol) -> BTreeSet<String> {
111    let mut names = BTreeSet::new();
112    for (name, step) in &cp.steps {
113        if name != BEGIN_KEYWORD {
114            names.insert(name.clone());
115        }
116        for nr in step.predecessors.iter().chain(step.successors.iter()) {
117            for p in nr.performatives() {
118                if p != BEGIN_KEYWORD {
119                    names.insert(String::from(p));
120                }
121            }
122        }
123    }
124    names
125}
126
127// ---------------------------------------------------------------------------
128// REQ-705: the store-level equivocation predicate
129// ---------------------------------------------------------------------------
130
131/// Which clause of REQ-705 the offending pair satisfies.
132#[derive(Debug, Clone, PartialEq, Eq)]
133#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
134pub enum EquivocationKind {
135    /// (a) The two messages are messages of two distinct alternatives of
136    /// one `(any …)` choice point.
137    Choice {
138        /// The choice point's alternative set, as declared in the dialect.
139        alternatives: BTreeSet<String>,
140    },
141    /// (b) The two messages are two distinct discharges of the same
142    /// obligation: same performative, different content hash.
143    Obligation {
144        /// The doubly-discharged performative.
145        performative: String,
146    },
147}
148
149/// Evidence returned by [`equivocation`]: the convicted key, the thread,
150/// the clause satisfied, and the offending pair as stored (hash-sorted, so
151/// evidence is deterministic for a given store state).
152///
153/// Evidence is *not* yet a transferable proof — the store holds messages,
154/// not their detached signatures. Package the pair's signed forms into an
155/// [`EquivocationProof`] to convince a third party (REQ-706).
156#[derive(Debug, Clone, PartialEq, Eq)]
157#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
158pub struct EquivocationEvidence {
159    pub key: KeyId,
160    pub thread: ThreadId,
161    pub kind: EquivocationKind,
162    pub first: (ContentHash, Message),
163    pub second: (ContentHash, Message),
164}
165
166/// All messages of a thread, in ascending content-hash order, read through
167/// the store's existing public API only: every message is in the causal
168/// closure of some frontier leaf (a non-leaf is referenced by a successor,
169/// and reference chains are finite and acyclic by content addressing).
170fn thread_messages<S: MessageStore>(store: &S, thread: &ThreadId) -> Vec<(ContentHash, Message)> {
171    let mut hashes: BTreeSet<ContentHash> = BTreeSet::new();
172    let leaves: Vec<ContentHash> = store.frontier(thread).into_iter().cloned().collect();
173    for leaf in &leaves {
174        for h in store.causal_closure(leaf, thread) {
175            hashes.insert(h);
176        }
177    }
178    hashes
179        .into_iter()
180        .filter_map(|h| store.lookup_in_thread(&h, thread).cloned().map(|m| (h, m)))
181        .collect()
182}
183
184/// REQ-705: the monotone, thread-scoped equivocation predicate.
185///
186/// Returns `Some` evidence iff the store contains two distinct messages in
187/// `thread` whose (innermost) sender is canonically `key` and which satisfy
188/// clause (a) *choice* or (b) *obligation* of REQ-705 against the dialect's
189/// protocol. Message identity is store identity (content hash), so "same
190/// performative, different content hash" is exactly "two distinct store
191/// entries with the same performative".
192///
193/// Properties, by construction:
194/// - **Monotone / upward-closed**: a pure function of the store's message
195///   set; appending messages can only add candidate pairs, never remove
196///   one, so `Some` can never revert to `None` (which pair is reported may
197///   change, but existence cannot). Once true, forever true.
198/// - **Read-only / verdict-neutral** (ADR-703): takes `&S`, calls only the
199///   store's read API, and touches no verdict — both members keep the
200///   individual verdicts they earned. What a deployment does with a
201///   convicted key is action policy above the verdict lattice.
202/// - **Canonical identity** (REQ-708): senders are compared as parsed
203///   [`KeyId`]s, so `@alice` and `@ed25519:alice` cannot evade detection
204///   by spelling. A message whose sender is absent or unparsable is not
205///   attributed to anyone and never enters a pair.
206pub fn equivocation<S: MessageStore>(
207    key: &KeyId,
208    thread: &ThreadId,
209    store: &S,
210    dialect: &Dialect,
211) -> Option<EquivocationEvidence> {
212    let cp = dialect.causal_protocol.as_ref()?;
213    let choices = any_choice_sets(cp);
214    let obligations = protocol_performatives(cp);
215
216    // The key's messages in this thread: (hash, performative, message),
217    // ascending hash order (deterministic evidence).
218    let mut owned: Vec<(ContentHash, String, Message)> = Vec::new();
219    for (h, m) in thread_messages(store, thread) {
220        let Some(simple) = m.innermost_simple() else {
221            continue;
222        };
223        let Some(sender) = simple.sender() else {
224            continue;
225        };
226        let Ok(sender_id) = KeyId::parse(sender) else {
227            continue;
228        };
229        if &sender_id != key {
230            continue;
231        }
232        let Some(perf) = simple.performative() else {
233            continue;
234        };
235        owned.push((h, String::from(perf.name()), m));
236    }
237
238    for i in 0..owned.len() {
239        for j in (i + 1)..owned.len() {
240            let (h1, p1, m1) = &owned[i];
241            let (h2, p2, m2) = &owned[j];
242            let kind = if p1 == p2 {
243                // (b) obligation: distinct entries ⇒ distinct content
244                // hashes (store dedup), same performative — provided the
245                // protocol actually obliges that performative.
246                if obligations.contains(p1) {
247                    Some(EquivocationKind::Obligation {
248                        performative: p1.clone(),
249                    })
250                } else {
251                    None
252                }
253            } else {
254                // (a) choice: two distinct alternatives of one choice set.
255                choices
256                    .iter()
257                    .find(|set| set.contains(p1) && set.contains(p2))
258                    .map(|set| EquivocationKind::Choice {
259                        alternatives: set.clone(),
260                    })
261            };
262            if let Some(kind) = kind {
263                return Some(EquivocationEvidence {
264                    key: key.clone(),
265                    thread: thread.clone(),
266                    kind,
267                    first: (h1.clone(), m1.clone()),
268                    second: (h2.clone(), m2.clone()),
269                });
270            }
271        }
272    }
273    None
274}
275
276// ---------------------------------------------------------------------------
277// REQ-706: the transferable proof object (CON-702)
278// ---------------------------------------------------------------------------
279
280/// One member of an equivocation proof (CON-702 `member`).
281#[derive(Debug, Clone, PartialEq, Eq)]
282#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
283pub enum ProofMember {
284    /// A full signed message: the message plus its detached R4 v2
285    /// attestation signature (ADR-700). Verification reconstructs the
286    /// attestation preimage from the message and its computed content hash
287    /// — the full-message-holder arm of REQ-701.
288    SignedMessage {
289        message: Message,
290        signature: Vec<u8>,
291    },
292    /// A redacted envelope member (CON-702 `member := … | envelope`;
293    /// REQ-706). The envelope carries its authenticated header and thread
294    /// (REQ-701), so verification runs over exactly the same attestation
295    /// preimage as the full-message arm — relabelling a genuine message
296    /// into a fake conflict fails at the signature either way, and the
297    /// proof discloses no payload for the envelope member (NFR-701).
298    Envelope(crate::envelope::RedactedEnvelope),
299    /// An opened-envelope member (SPEC-017 REQ-813): the typed root, its v3
300    /// root-signature, and the header-field openings. Verification runs
301    /// [`crate::envelope::verify_opened`] — the v3 root-signature plus each
302    /// opening against that signed root — so the (performative, sender,
303    /// thread, content root) the predicate needs are read from authenticated
304    /// openings, at zero payload disclosure (NFR-701). Relabelling a genuine
305    /// message into a fake conflict fails at the opening or the signature,
306    /// exactly as the full-message and redacted-envelope arms do; the proof
307    /// stays pure and dialect-pinned.
308    OpenedEnvelope(crate::envelope::OpenedEnvelope),
309}
310
311/// The transferable proof object (REQ-706, CON-702):
312/// `(equivocation key thread dialect-hash member member)`.
313///
314/// The proof pins the governing dialect by content hash (SPEC-014 REQ-628)
315/// so it can never be verified against a same-named substitute dialect
316/// (SPEC-015 review finding 2).
317#[derive(Debug, Clone, PartialEq, Eq)]
318#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
319pub struct EquivocationProof {
320    /// The accused key (canonical identity, REQ-708).
321    pub key: KeyId,
322    /// The thread both members must carry.
323    pub thread: String,
324    /// Content hash of the governing dialect (`f1220<hex64>`).
325    pub dialect_hash: String,
326    /// The offending pair.
327    pub first: ProofMember,
328    pub second: ProofMember,
329}
330
331/// What is structurally wrong with a proof member (full recognition before
332/// any semantic action: a member missing a committed header field is
333/// rejected, never repaired).
334#[derive(Debug, Clone, PartialEq, Eq)]
335pub enum MemberDefect {
336    /// The member's message is not a `Simple` message carrying the header
337    /// fields the attestation commits to.
338    NotSimple,
339    /// No `:from` sender field.
340    MissingSender,
341    /// The sender spelling is not a well-formed key (REQ-708).
342    SenderSpelling(KeyIdError),
343    /// No `:thread` field.
344    MissingThread,
345    /// A recipient spelling is not a well-formed key (REQ-708).
346    RecipientSpelling(KeyIdError),
347}
348
349impl fmt::Display for MemberDefect {
350    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
351        match self {
352            MemberDefect::NotSimple => f.write_str("member is not a simple message"),
353            MemberDefect::MissingSender => f.write_str("member carries no sender"),
354            MemberDefect::SenderSpelling(e) => write!(f, "member sender is malformed: {e}"),
355            MemberDefect::MissingThread => f.write_str("member carries no thread"),
356            MemberDefect::RecipientSpelling(e) => {
357                write!(f, "member recipient is malformed: {e}")
358            }
359        }
360    }
361}
362
363/// Typed rejection for [`verify_equivocation_proof`] — anything short of a
364/// fully-verifying offending pair (LangSec discipline: reject, don't
365/// repair). `member` is the 0-based index of the offending member.
366#[derive(Debug, Clone, PartialEq, Eq)]
367pub enum EquivocationProofError {
368    /// The verifier's dialect carries no content hash, so the pin cannot
369    /// be checked (fail closed).
370    DialectUnhashed,
371    /// The proof pins a different dialect than the verifier holds
372    /// (REQ-706: never a same-named substitute).
373    DialectHashMismatch { pinned: String, installed: String },
374    /// A member does not parse into the committed header shape.
375    MalformedMember { member: usize, defect: MemberDefect },
376    /// A member's sender is not the accused key (canonical comparison).
377    KeyMismatch { member: usize },
378    /// A member does not carry the proof's thread.
379    ThreadMismatch { member: usize },
380    /// The two members are the same message (identical content hash) —
381    /// one message is never an equivocation.
382    IdenticalMembers,
383    /// A member's signature failed R4 v2 verification.
384    Signature { member: usize, error: AttestError },
385    /// Both members verify but the pair is compatible under the pinned
386    /// dialect: neither two alternatives of one choice point nor a double
387    /// discharge of one obligation.
388    CompatiblePair { first: String, second: String },
389}
390
391impl fmt::Display for EquivocationProofError {
392    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393        match self {
394            Self::DialectUnhashed => {
395                f.write_str("verifier's dialect carries no content hash; cannot check the pin")
396            }
397            Self::DialectHashMismatch { pinned, installed } => write!(
398                f,
399                "dialect hash mismatch: proof pins {pinned}, verifier holds {installed}"
400            ),
401            Self::MalformedMember { member, defect } => {
402                write!(f, "member {member} malformed: {defect}")
403            }
404            Self::KeyMismatch { member } => {
405                write!(f, "member {member} is not by the accused key")
406            }
407            Self::ThreadMismatch { member } => {
408                write!(f, "member {member} does not carry the proof's thread")
409            }
410            Self::IdenticalMembers => f.write_str("members are the same message"),
411            Self::Signature { member, error } => {
412                write!(f, "member {member} signature invalid: {error}")
413            }
414            Self::CompatiblePair { first, second } => write!(
415                f,
416                "pair ({first}, {second}) is compatible under the pinned dialect"
417            ),
418        }
419    }
420}
421
422/// Reconstruct the R4 v2 attestation header a full-message holder signs and
423/// verifies (REQ-701's full-message arm): every committed field read from
424/// the message, the content hash computed from its canonical bytes.
425///
426/// Pure. Rejects (typed) any message missing a committed field — a header
427/// that cannot be reconstructed in full is never guessed at.
428pub fn attestation_header_for(message: &Message) -> Result<AttestationHeader, MemberDefect> {
429    let Message::Simple {
430        performative,
431        thread,
432        sender,
433        caused_by,
434        ..
435    } = message
436    else {
437        return Err(MemberDefect::NotSimple);
438    };
439    let sender = sender.as_deref().ok_or(MemberDefect::MissingSender)?;
440    let from = KeyId::parse(sender).map_err(MemberDefect::SenderSpelling)?;
441    let thread = thread.as_deref().ok_or(MemberDefect::MissingThread)?;
442    let mut to = BTreeSet::new();
443    for r in message.recipient_set() {
444        to.insert(KeyId::parse(r).map_err(MemberDefect::RecipientSpelling)?);
445    }
446    Ok(AttestationHeader {
447        content_hash: message_content_hash(message),
448        performative: String::from(performative.name()),
449        from,
450        to,
451        thread: String::from(thread),
452        caused_by: caused_by.clone(),
453    })
454}
455
456/// A member that passed structural + cryptographic checks.
457struct CheckedMember {
458    performative: String,
459    content_hash: String,
460}
461
462fn check_member(
463    member: &ProofMember,
464    index: usize,
465    proof: &EquivocationProof,
466    signer: &dyn Signer,
467) -> Result<CheckedMember, EquivocationProofError> {
468    // The three member classes all yield the same (performative, sender,
469    // thread, content hash) the predicate needs. The two v2 classes
470    // reconstruct an attestation header (REQ-701): a full message from its
471    // fields and computed content hash, a redacted envelope from its own
472    // authenticated header. The opened-envelope class (REQ-813) instead
473    // authenticates native field-openings against the signed typed root.
474    let (header, signature): (AttestationHeader, &[u8]) = match member {
475        ProofMember::SignedMessage { message, signature } => {
476            let header = attestation_header_for(message).map_err(|defect| {
477                EquivocationProofError::MalformedMember {
478                    member: index,
479                    defect,
480                }
481            })?;
482            (header, signature)
483        }
484        ProofMember::Envelope(envelope) => (envelope.header.clone(), &envelope.signature),
485        ProofMember::OpenedEnvelope(env) => {
486            return check_opened_member(env, index, proof, signer);
487        }
488    };
489    // Canonical key identity (REQ-708): alias spellings of the accused key
490    // are one identity; a different identity is a typed mismatch.
491    if header.from != proof.key {
492        return Err(EquivocationProofError::KeyMismatch { member: index });
493    }
494    if header.thread != proof.thread {
495        return Err(EquivocationProofError::ThreadMismatch { member: index });
496    }
497    // R4 v2: the signature verifies under the canonical key over the
498    // reconstructed attestation preimage — relabelling a genuine message
499    // into a fake conflict (other thread, other recipients, other type)
500    // changes the preimage and dies here (ADR-700).
501    verify_attestation_v2(signer, &proof.key, &header, signature).map_err(|error| {
502        EquivocationProofError::Signature {
503            member: index,
504            error,
505        }
506    })?;
507    Ok(CheckedMember {
508        performative: header.performative,
509        content_hash: header.content_hash,
510    })
511}
512
513/// Structural + cryptographic check of an opened-envelope member (REQ-813),
514/// in the same order as [`check_member`]'s v2 arms: canonical key identity,
515/// then thread, then signature. The key/thread reads are of the *claimed*
516/// openings; both are then re-authenticated (with the performative and the
517/// root) by [`verify_opened`], so a forger cannot slip a wrong value past —
518/// relabelling a genuine message into a fake conflict changes an opening (or
519/// the root) and dies at the signature check, never at a repairable policy
520/// check. No payload is an input (NFR-701).
521fn check_opened_member(
522    env: &crate::envelope::OpenedEnvelope,
523    index: usize,
524    proof: &EquivocationProof,
525    signer: &dyn Signer,
526) -> Result<CheckedMember, EquivocationProofError> {
527    let from_spelling = env
528        .from_spelling()
529        .ok_or(EquivocationProofError::MalformedMember {
530            member: index,
531            defect: MemberDefect::MissingSender,
532        })?;
533    let from =
534        KeyId::parse(from_spelling).map_err(|e| EquivocationProofError::MalformedMember {
535            member: index,
536            defect: MemberDefect::SenderSpelling(e),
537        })?;
538    if from != proof.key {
539        return Err(EquivocationProofError::KeyMismatch { member: index });
540    }
541    let thread = env
542        .thread()
543        .ok_or(EquivocationProofError::MalformedMember {
544            member: index,
545            defect: MemberDefect::MissingThread,
546        })?;
547    if thread != proof.thread {
548        return Err(EquivocationProofError::ThreadMismatch { member: index });
549    }
550    // Authenticate: the v3 root-signature plus every opening against that
551    // signed root (REQ-813). An opening-level forgery maps to the same
552    // fail-closed Signature rejection the v2 arms produce.
553    verify_opened(env, signer).map_err(|error| EquivocationProofError::Signature {
554        member: index,
555        error: match error {
556            OpenedError::Attestation(a) => a,
557            OpenedError::OpeningFailed { .. } | OpenedError::MissingField { .. } => {
558                AttestError::InvalidSignature
559            }
560        },
561    })?;
562    let performative = env
563        .performative()
564        .ok_or(EquivocationProofError::MalformedMember {
565            member: index,
566            defect: MemberDefect::NotSimple,
567        })?;
568    Ok(CheckedMember {
569        performative: String::from(performative),
570        content_hash: String::from(env.content_hash()),
571    })
572}
573
574/// REQ-706: verify an equivocation proof from the pair and the pinned
575/// dialect alone — no store, no third-party testimony.
576///
577/// `signer` embodies signature verification for the accused key (the same
578/// [`Signer`] convention as the rest of the R4 path).
579///
580/// Checks, in order (CON-702), each failure a typed rejection:
581/// 1. the proof's dialect hash matches `dialect.hash` (the *pinned*
582///    dialect, never a same-named substitute);
583/// 2. both members parse into the committed header shape;
584/// 3. both members are by the accused key (canonical identity) and carry
585///    the proof's thread;
586/// 4. both signatures verify under the key via the existing R4 v2
587///    full-message path ([`verify_attestation_v2`]);
588/// 5. the members are two *distinct* messages; and
589/// 6. the pair satisfies clause (a) or (b) of REQ-705 against the pinned
590///    dialect's protocol.
591///
592/// On success returns the convicted [`KeyId`].
593pub fn verify_equivocation_proof(
594    proof: &EquivocationProof,
595    dialect: &Dialect,
596    signer: &dyn Signer,
597) -> Result<KeyId, EquivocationProofError> {
598    // 1. Pinned dialect only (review finding 2). A hashless dialect cannot
599    // witness the pin: fail closed.
600    let installed = dialect
601        .hash
602        .as_deref()
603        .ok_or(EquivocationProofError::DialectUnhashed)?;
604    if installed != proof.dialect_hash {
605        return Err(EquivocationProofError::DialectHashMismatch {
606            pinned: proof.dialect_hash.clone(),
607            installed: String::from(installed),
608        });
609    }
610
611    // 2–4. Per-member structural and cryptographic checks.
612    let a = check_member(&proof.first, 0, proof, signer)?;
613    let b = check_member(&proof.second, 1, proof, signer)?;
614
615    // 5. Two distinct messages (distinct canonical content).
616    if a.content_hash == b.content_hash {
617        return Err(EquivocationProofError::IdenticalMembers);
618    }
619
620    // 6. The pair conflicts under the pinned dialect (REQ-705 (a)/(b)).
621    let conflicting = match dialect.causal_protocol.as_ref() {
622        None => false, // no protocol ⇒ no choice points, no obligations
623        Some(cp) => {
624            if a.performative == b.performative {
625                protocol_performatives(cp).contains(&a.performative)
626            } else {
627                any_choice_sets(cp)
628                    .iter()
629                    .any(|set| set.contains(&a.performative) && set.contains(&b.performative))
630            }
631        }
632    };
633    if !conflicting {
634        return Err(EquivocationProofError::CompatiblePair {
635            first: a.performative,
636            second: b.performative,
637        });
638    }
639
640    Ok(proof.key.clone())
641}
642
643// ---------------------------------------------------------------------------
644// REQ-707: choice-transparency lint (opt-in, advisory)
645// ---------------------------------------------------------------------------
646
647/// Advisory warning: the alternatives of a choice point share no common
648/// recipient role other than the chooser, so no single honest endpoint is
649/// guaranteed to witness a choice equivocation locally — detection relies
650/// on proof gossip. A warning, never an [`crate::role::R6Violation`].
651#[derive(Debug, Clone, PartialEq, Eq)]
652#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
653pub struct ChoiceTransparencyWarning {
654    /// The choice point's alternatives.
655    pub alternatives: BTreeSet<String>,
656    /// The chooser role (the alternatives' common sender).
657    pub chooser: String,
658}
659
660impl fmt::Display for ChoiceTransparencyWarning {
661    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
662        write!(
663            f,
664            "choice-transparency: alternatives [{}] of chooser '{}' share no \
665             common recipient role other than the chooser; a choice \
666             equivocation has no guaranteed local witness",
667            self.alternatives
668                .iter()
669                .map(String::as_str)
670                .collect::<Vec<_>>()
671                .join(", "),
672            self.chooser
673        )
674    }
675}
676
677/// REQ-707: the opt-in choice-transparency lint, companion to the R6
678/// dialect checks (`crate::r6::r6_violations`) but advisory by design.
679///
680/// With `enabled == false` (the default posture) the lint is silent.
681/// When enabled, it warns for every `(any …)` choice point whose
682/// alternatives share no common recipient role beyond the chooser.
683/// Shared-recipient dialects (OAuth's branches both address `client`) are
684/// lint-clean. Choice points with unannotated alternatives or incoherent
685/// senders are skipped — those are R6's findings (REQ-601/REQ-603), not
686/// this lint's.
687pub fn choice_transparency_lint(d: &Dialect, enabled: bool) -> Vec<ChoiceTransparencyWarning> {
688    if !enabled {
689        return Vec::new();
690    }
691    let Some(cp) = &d.causal_protocol else {
692        return Vec::new();
693    };
694    let annotations: BTreeMap<&str, &RoleAnnotation> = d
695        .performatives
696        .iter()
697        .filter_map(|p| p.role.as_ref().map(|ann| (p.name.as_str(), ann)))
698        .collect();
699
700    let mut warnings = Vec::new();
701    for alternatives in any_choice_sets(cp) {
702        let anns: Option<Vec<&RoleAnnotation>> = alternatives
703            .iter()
704            .map(|a| annotations.get(a.as_str()).copied())
705            .collect();
706        let Some(anns) = anns else {
707            continue; // unannotated alternative: REQ-601's finding
708        };
709        let senders: BTreeSet<&str> = anns.iter().map(|a| a.from.as_str()).collect();
710        if senders.len() != 1 {
711            continue; // incoherent chooser: REQ-603's finding
712        }
713        let chooser = *senders.first().expect("len checked");
714        let mut common: BTreeSet<&str> = anns[0].to.iter().map(String::as_str).collect();
715        for ann in &anns[1..] {
716            let to: BTreeSet<&str> = ann.to.iter().map(String::as_str).collect();
717            common = common.intersection(&to).copied().collect();
718        }
719        common.remove(chooser);
720        if common.is_empty() {
721            warnings.push(ChoiceTransparencyWarning {
722                alternatives,
723                chooser: String::from(chooser),
724            });
725        }
726    }
727    warnings
728}
729
730// ---------------------------------------------------------------------------
731// Tests (TEST-705, TEST-706, TEST-707)
732// ---------------------------------------------------------------------------
733
734#[cfg(test)]
735mod tests {
736    use super::*;
737    use crate::attest::sign_attestation_v2;
738    use crate::dialect::{Dialect, PerformativeDef, ResourceBounds};
739    use crate::message::{CausedBy, Performative, Recipients};
740    use crate::protocol::{verify_causal, StepDecl, VerificationResult};
741    use crate::role::{RoleCardinality, RoleDecl};
742    use crate::sexpr::{Atom, SExpr};
743    use crate::store::ThreadedMessageStore;
744    use alloc::string::ToString;
745    use alloc::vec;
746
747    // ---- fixtures ----
748
749    fn single(name: &str) -> NodeRef {
750        NodeRef::Single(name.to_string())
751    }
752
753    fn any(names: &[&str]) -> NodeRef {
754        NodeRef::Any(names.iter().map(|s| s.to_string()).collect())
755    }
756
757    fn step(name: &str, preds: Vec<NodeRef>, succs: Vec<NodeRef>) -> (String, StepDecl) {
758        (
759            name.to_string(),
760            StepDecl {
761                performative: name.to_string(),
762                predecessors: preds,
763                successors: succs,
764            },
765        )
766    }
767
768    fn perf_def(name: &str, role: Option<RoleAnnotation>) -> PerformativeDef {
769        PerformativeDef {
770            name: name.to_string(),
771            params: Vec::new(),
772            template: SExpr::Atom(Atom::Symbol("t".to_string())),
773            role,
774        }
775    }
776
777    fn ann(from: &str, to: &[&str]) -> RoleAnnotation {
778        RoleAnnotation {
779            from: from.to_string(),
780            to: to.iter().map(|s| s.to_string()).collect(),
781        }
782    }
783
784    fn dialect(
785        roles: &[&str],
786        perfs: Vec<PerformativeDef>,
787        steps: Vec<(String, StepDecl)>,
788    ) -> Dialect {
789        let mut d = Dialect {
790            types: Default::default(),
791            roles: roles
792                .iter()
793                .map(|n| RoleDecl {
794                    name: n.to_string(),
795                    cardinality: RoleCardinality::Singleton,
796                })
797                .collect(),
798            state: None,
799            state_bounds: None,
800            causal_locality: Default::default(),
801            name: "equiv-test".to_string(),
802            extends: Vec::new(),
803            author: None,
804            performatives: perfs,
805            resources: ResourceBounds {
806                max_depth: 8,
807                max_expansion_size: 512,
808            },
809            examples: Vec::new(),
810            signature: None,
811            hash: None,
812            protocol: None,
813            causal_protocol: Some(CausalProtocol {
814                steps: steps.into_iter().collect(),
815            }),
816            shapes: Vec::new(),
817        };
818        d.hash = Some(crate::canonical::dialect_hash(&d));
819        d
820    }
821
822    /// begin → (any offer refuse); offer → settle. `offer`/`refuse` are one
823    /// choice point; `settle` is a compatible successor of `offer`.
824    fn choice_dialect() -> Dialect {
825        dialect(
826            &["chooser", "peer"],
827            vec![
828                perf_def("offer", None),
829                perf_def("refuse", None),
830                perf_def("settle", None),
831            ],
832            vec![
833                step("begin", vec![], vec![any(&["offer", "refuse"])]),
834                step("offer", vec![single("begin")], vec![single("settle")]),
835                step("refuse", vec![single("begin")], vec![]),
836                step("settle", vec![single("offer")], vec![]),
837            ],
838        )
839    }
840
841    fn msg(perf: &str, sender: &str, thread: &str, content: &str) -> Message {
842        Message::Simple {
843            performative: Performative::Custom(perf.to_string()),
844            recipient: Some(Recipients::One("@bob".to_string())),
845            content: SExpr::Atom(Atom::Str(content.to_string())),
846            params: Vec::new(),
847            thread: Some(thread.to_string()),
848            sender: Some(sender.to_string()),
849            caused_by: Some(CausedBy::Begin),
850        }
851    }
852
853    fn hash(s: &str) -> ContentHash {
854        ContentHash(s.to_string())
855    }
856
857    fn thread(s: &str) -> ThreadId {
858        ThreadId(s.to_string())
859    }
860
861    fn alice() -> KeyId {
862        KeyId::parse("@alice").unwrap()
863    }
864
865    // ---- TEST-705: the predicate ----
866
867    #[test]
868    fn choice_equivocation_flips_the_predicate() {
869        let d = choice_dialect();
870        let mut store = ThreadedMessageStore::new();
871        store.append(hash("h1"), thread("t1"), msg("offer", "@alice", "t1", "a"));
872        store.append(hash("h2"), thread("t1"), msg("refuse", "@alice", "t1", "b"));
873
874        let ev = equivocation(&alice(), &thread("t1"), &store, &d).expect("detected");
875        assert_eq!(ev.key, alice());
876        assert_eq!(ev.thread, thread("t1"));
877        assert_eq!(
878            ev.kind,
879            EquivocationKind::Choice {
880                alternatives: ["offer", "refuse"].iter().map(|s| s.to_string()).collect(),
881            }
882        );
883        let pair: BTreeSet<&str> = [ev.first.0 .0.as_str(), ev.second.0 .0.as_str()]
884            .into_iter()
885            .collect();
886        assert_eq!(pair, ["h1", "h2"].into_iter().collect());
887    }
888
889    #[test]
890    fn obligation_equivocation_flips_the_predicate() {
891        let d = choice_dialect();
892        let mut store = ThreadedMessageStore::new();
893        // Two distinct discharges of `offer`: same performative and
894        // occupant, different content (hence different content hash).
895        store.append(hash("h1"), thread("t1"), msg("offer", "@alice", "t1", "a"));
896        store.append(hash("h2"), thread("t1"), msg("offer", "@alice", "t1", "b"));
897
898        let ev = equivocation(&alice(), &thread("t1"), &store, &d).expect("detected");
899        assert_eq!(
900            ev.kind,
901            EquivocationKind::Obligation {
902                performative: "offer".to_string(),
903            }
904        );
905    }
906
907    /// REQ-708: spelling aliases cannot evade the predicate.
908    #[test]
909    fn alias_key_spellings_cannot_evade_detection() {
910        let d = choice_dialect();
911        let mut store = ThreadedMessageStore::new();
912        store.append(hash("h1"), thread("t1"), msg("offer", "@alice", "t1", "a"));
913        store.append(
914            hash("h2"),
915            thread("t1"),
916            msg("refuse", "@ed25519:alice", "t1", "b"),
917        );
918        assert!(equivocation(&alice(), &thread("t1"), &store, &d).is_some());
919    }
920
921    /// TEST-705: adding messages never unflips the predicate (monotone).
922    #[test]
923    fn predicate_is_monotone_under_store_growth() {
924        let d = choice_dialect();
925        let mut store = ThreadedMessageStore::new();
926        store.append(hash("h1"), thread("t1"), msg("offer", "@alice", "t1", "a"));
927        assert!(equivocation(&alice(), &thread("t1"), &store, &d).is_none());
928
929        store.append(hash("h2"), thread("t1"), msg("refuse", "@alice", "t1", "b"));
930        assert!(equivocation(&alice(), &thread("t1"), &store, &d).is_some());
931
932        // Grow the store every which way: other keys, other performatives,
933        // even more equivocation. The predicate never reverts.
934        let later = [
935            ("h3", msg("settle", "@bob", "t1", "c")),
936            ("h4", msg("offer", "@carol", "t1", "d")),
937            ("h5", msg("offer", "@alice", "t1", "e")),
938            ("h6", msg("refuse", "@alice", "t1", "f")),
939        ];
940        for (h, m) in later {
941            store.append(hash(h), thread("t1"), m);
942            assert!(
943                equivocation(&alice(), &thread("t1"), &store, &d).is_some(),
944                "predicate reverted after appending {h}"
945            );
946        }
947    }
948
949    /// TEST-705 / ADR-703: detection does not alter any verdict — both
950    /// members of the pair stay individually Valid.
951    #[test]
952    fn members_verdicts_remain_valid() {
953        let d = choice_dialect();
954        let cp = d.causal_protocol.as_ref().unwrap();
955        let mut store = ThreadedMessageStore::new();
956        let m1 = msg("offer", "@alice", "t1", "a");
957        let m2 = msg("refuse", "@alice", "t1", "b");
958        store.append(hash("h1"), thread("t1"), m1.clone());
959        store.append(hash("h2"), thread("t1"), m2.clone());
960
961        let verdict = |m: &Message| {
962            verify_causal(
963                m.performative().unwrap().name(),
964                m.caused_by(),
965                &store,
966                cp,
967                &thread("t1"),
968            )
969        };
970        assert_eq!(verdict(&m1), VerificationResult::Valid);
971        assert_eq!(verdict(&m2), VerificationResult::Valid);
972
973        assert!(equivocation(&alice(), &thread("t1"), &store, &d).is_some());
974
975        // Read-only detection: the verdicts after are the verdicts before.
976        assert_eq!(verdict(&m1), VerificationResult::Valid);
977        assert_eq!(verdict(&m2), VerificationResult::Valid);
978    }
979
980    #[test]
981    fn distinct_keys_are_not_an_equivocating_pair() {
982        let d = choice_dialect();
983        let mut store = ThreadedMessageStore::new();
984        store.append(hash("h1"), thread("t1"), msg("offer", "@alice", "t1", "a"));
985        store.append(hash("h2"), thread("t1"), msg("refuse", "@bob", "t1", "b"));
986        assert!(equivocation(&alice(), &thread("t1"), &store, &d).is_none());
987        assert!(equivocation(&KeyId::parse("@bob").unwrap(), &thread("t1"), &store, &d).is_none());
988    }
989
990    #[test]
991    fn predicate_is_thread_scoped() {
992        let d = choice_dialect();
993        let mut store = ThreadedMessageStore::new();
994        store.append(hash("h1"), thread("t1"), msg("offer", "@alice", "t1", "a"));
995        store.append(hash("h2"), thread("t2"), msg("refuse", "@alice", "t2", "b"));
996        assert!(equivocation(&alice(), &thread("t1"), &store, &d).is_none());
997        assert!(equivocation(&alice(), &thread("t2"), &store, &d).is_none());
998    }
999
1000    #[test]
1001    fn sequential_steps_are_compatible_not_equivocation() {
1002        // offer then its declared successor settle, both by alice: fine.
1003        let d = choice_dialect();
1004        let mut store = ThreadedMessageStore::new();
1005        store.append(hash("h1"), thread("t1"), msg("offer", "@alice", "t1", "a"));
1006        store.append(hash("h2"), thread("t1"), msg("settle", "@alice", "t1", "b"));
1007        assert!(equivocation(&alice(), &thread("t1"), &store, &d).is_none());
1008    }
1009
1010    #[test]
1011    fn same_key_suite_variant_is_a_distinct_identity() {
1012        // REQ-708: same bytes under another suite is a different identity;
1013        // its messages do not pair with the ed25519 identity's.
1014        let d = choice_dialect();
1015        let mut store = ThreadedMessageStore::new();
1016        store.append(hash("h1"), thread("t1"), msg("offer", "@alice", "t1", "a"));
1017        store.append(
1018            hash("h2"),
1019            thread("t1"),
1020            msg("refuse", "@pq-frodo:alice", "t1", "b"),
1021        );
1022        assert!(equivocation(&alice(), &thread("t1"), &store, &d).is_none());
1023    }
1024
1025    #[test]
1026    fn dialect_without_protocol_never_detects() {
1027        let mut d = choice_dialect();
1028        d.causal_protocol = None;
1029        let mut store = ThreadedMessageStore::new();
1030        store.append(hash("h1"), thread("t1"), msg("offer", "@alice", "t1", "a"));
1031        store.append(hash("h2"), thread("t1"), msg("refuse", "@alice", "t1", "b"));
1032        assert!(equivocation(&alice(), &thread("t1"), &store, &d).is_none());
1033    }
1034
1035    // ---- TEST-706: the proof object ----
1036
1037    /// Data-dependent test signer (same construction as `attest.rs` tests):
1038    /// sig = SHA-256(secret ‖ data), so any preimage change kills the
1039    /// signature and distinct secrets model distinct keys.
1040    struct TestSigner {
1041        secret: &'static [u8],
1042    }
1043
1044    impl Signer for TestSigner {
1045        fn sign(&self, data: &[u8]) -> Vec<u8> {
1046            use sha2::{Digest, Sha256};
1047            let mut h = Sha256::new();
1048            h.update(self.secret);
1049            h.update(data);
1050            h.finalize().to_vec()
1051        }
1052        fn verify(&self, data: &[u8], sig: &[u8]) -> bool {
1053            self.sign(data) == sig
1054        }
1055    }
1056
1057    const ALICE_SIGNER: TestSigner = TestSigner { secret: b"alice" };
1058    const BOB_SIGNER: TestSigner = TestSigner { secret: b"bob" };
1059
1060    fn signed_member(m: Message, signer: &dyn Signer) -> ProofMember {
1061        let header = attestation_header_for(&m).unwrap();
1062        let signature = sign_attestation_v2(signer, &header).unwrap();
1063        ProofMember::SignedMessage {
1064            message: m,
1065            signature,
1066        }
1067    }
1068
1069    fn proof_over(d: &Dialect, m1: Message, m2: Message) -> EquivocationProof {
1070        EquivocationProof {
1071            key: alice(),
1072            thread: "t1".to_string(),
1073            dialect_hash: d.hash.clone().unwrap(),
1074            first: signed_member(m1, &ALICE_SIGNER),
1075            second: signed_member(m2, &ALICE_SIGNER),
1076        }
1077    }
1078
1079    #[test]
1080    fn choice_proof_verifies_from_pair_and_dialect_alone() {
1081        // No store exists anywhere in this test (REQ-706).
1082        let d = choice_dialect();
1083        let proof = proof_over(
1084            &d,
1085            msg("offer", "@alice", "t1", "a"),
1086            msg("refuse", "@alice", "t1", "b"),
1087        );
1088        assert_eq!(
1089            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1090            Ok(alice())
1091        );
1092    }
1093
1094    #[test]
1095    fn obligation_proof_verifies() {
1096        let d = choice_dialect();
1097        let proof = proof_over(
1098            &d,
1099            msg("offer", "@alice", "t1", "a"),
1100            msg("offer", "@alice", "t1", "b"),
1101        );
1102        assert_eq!(
1103            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1104            Ok(alice())
1105        );
1106    }
1107
1108    /// REQ-708: an alias spelling in a member is the same canonical
1109    /// identity — the proof still convicts.
1110    #[test]
1111    fn alias_spelled_member_still_convicts() {
1112        let d = choice_dialect();
1113        let proof = proof_over(
1114            &d,
1115            msg("offer", "@alice", "t1", "a"),
1116            msg("refuse", "@ed25519:alice", "t1", "b"),
1117        );
1118        assert_eq!(
1119            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1120            Ok(alice())
1121        );
1122    }
1123
1124    #[test]
1125    fn forged_pair_different_keys_rejected() {
1126        let d = choice_dialect();
1127        let mut proof = proof_over(
1128            &d,
1129            msg("offer", "@alice", "t1", "a"),
1130            msg("refuse", "@alice", "t1", "b"),
1131        );
1132        // Bob's genuine message swapped in as the second member.
1133        proof.second = signed_member(msg("refuse", "@bob", "t1", "b"), &BOB_SIGNER);
1134        assert_eq!(
1135            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1136            Err(EquivocationProofError::KeyMismatch { member: 1 })
1137        );
1138    }
1139
1140    #[test]
1141    fn forged_pair_different_threads_rejected() {
1142        let d = choice_dialect();
1143        let mut proof = proof_over(
1144            &d,
1145            msg("offer", "@alice", "t1", "a"),
1146            msg("refuse", "@alice", "t1", "b"),
1147        );
1148        // A genuine message from another thread cannot be relabelled into
1149        // this conflict: its authenticated thread differs.
1150        proof.second = signed_member(msg("refuse", "@alice", "t2", "b"), &ALICE_SIGNER);
1151        assert_eq!(
1152            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1153            Err(EquivocationProofError::ThreadMismatch { member: 1 })
1154        );
1155    }
1156
1157    #[test]
1158    fn wrong_dialect_hash_rejected() {
1159        let d = choice_dialect();
1160        let mut proof = proof_over(
1161            &d,
1162            msg("offer", "@alice", "t1", "a"),
1163            msg("refuse", "@alice", "t1", "b"),
1164        );
1165        proof.dialect_hash =
1166            "f12200000000000000000000000000000000000000000000000000000000000000000".to_string();
1167        assert!(matches!(
1168            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1169            Err(EquivocationProofError::DialectHashMismatch { .. })
1170        ));
1171    }
1172
1173    #[test]
1174    fn unhashed_dialect_fails_closed() {
1175        let mut d = choice_dialect();
1176        let proof = proof_over(
1177            &d,
1178            msg("offer", "@alice", "t1", "a"),
1179            msg("refuse", "@alice", "t1", "b"),
1180        );
1181        d.hash = None;
1182        assert_eq!(
1183            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1184            Err(EquivocationProofError::DialectUnhashed)
1185        );
1186    }
1187
1188    #[test]
1189    fn compatible_pair_rejected() {
1190        // offer → settle is the declared sequence, not an equivocation.
1191        let d = choice_dialect();
1192        let proof = proof_over(
1193            &d,
1194            msg("offer", "@alice", "t1", "a"),
1195            msg("settle", "@alice", "t1", "b"),
1196        );
1197        assert_eq!(
1198            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1199            Err(EquivocationProofError::CompatiblePair {
1200                first: "offer".to_string(),
1201                second: "settle".to_string(),
1202            })
1203        );
1204    }
1205
1206    #[test]
1207    fn identical_members_rejected() {
1208        let d = choice_dialect();
1209        let proof = proof_over(
1210            &d,
1211            msg("offer", "@alice", "t1", "a"),
1212            msg("offer", "@alice", "t1", "a"),
1213        );
1214        assert_eq!(
1215            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1216            Err(EquivocationProofError::IdenticalMembers)
1217        );
1218    }
1219
1220    #[test]
1221    fn tampered_member_signature_dies() {
1222        let d = choice_dialect();
1223        let mut proof = proof_over(
1224            &d,
1225            msg("offer", "@alice", "t1", "a"),
1226            msg("refuse", "@alice", "t1", "b"),
1227        );
1228        // Re-content the second member after signing: the recomputed
1229        // content hash changes the attestation preimage.
1230        if let ProofMember::SignedMessage {
1231            message: Message::Simple { content, .. },
1232            ..
1233        } = &mut proof.second
1234        {
1235            *content = SExpr::Atom(Atom::Str("tampered".to_string()));
1236        }
1237        assert_eq!(
1238            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1239            Err(EquivocationProofError::Signature {
1240                member: 1,
1241                error: AttestError::InvalidSignature,
1242            })
1243        );
1244    }
1245
1246    // ---- REQ-706 + REQ-700..701: envelope proof members ----
1247
1248    fn envelope_member(m: Message, signer: &dyn Signer) -> ProofMember {
1249        let header = attestation_header_for(&m).unwrap();
1250        let signature = sign_attestation_v2(signer, &header).unwrap();
1251        ProofMember::Envelope(crate::envelope::redact(&m, signature).unwrap())
1252    }
1253
1254    #[test]
1255    fn envelope_member_convicts_without_payload() {
1256        // The second member travels as a redacted envelope: the proof
1257        // still verifies from the pair and the pinned dialect alone, and
1258        // the envelope member discloses no payload field.
1259        let d = choice_dialect();
1260        let mut proof = proof_over(
1261            &d,
1262            msg("offer", "@alice", "t1", "a"),
1263            msg("refuse", "@alice", "t1", "b"),
1264        );
1265        proof.second = envelope_member(msg("refuse", "@alice", "t1", "payload-b"), &ALICE_SIGNER);
1266        if let ProofMember::Envelope(env) = &proof.second {
1267            assert!(
1268                !env.to_sexpr().to_string().contains("payload-b"),
1269                "envelope member must disclose no payload field (NFR-701)"
1270            );
1271        }
1272        assert_eq!(
1273            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1274            Ok(alice())
1275        );
1276    }
1277
1278    #[test]
1279    fn all_envelope_pair_convicts() {
1280        let d = choice_dialect();
1281        let mut proof = proof_over(
1282            &d,
1283            msg("offer", "@alice", "t1", "a"),
1284            msg("offer", "@alice", "t1", "b"),
1285        );
1286        proof.first = envelope_member(msg("offer", "@alice", "t1", "a"), &ALICE_SIGNER);
1287        proof.second = envelope_member(msg("offer", "@alice", "t1", "b"), &ALICE_SIGNER);
1288        assert_eq!(
1289            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1290            Ok(alice())
1291        );
1292    }
1293
1294    #[test]
1295    fn relabelled_envelope_member_fails_at_the_signature() {
1296        // An envelope's thread is its authenticated field (REQ-701):
1297        // rewriting it to frame a cross-thread conflict changes the
1298        // attestation preimage, so the forgery dies at the signature —
1299        // never at a repairable policy check.
1300        let d = choice_dialect();
1301        let mut proof = proof_over(
1302            &d,
1303            msg("offer", "@alice", "t1", "a"),
1304            msg("refuse", "@alice", "t2", "b"), // genuinely from thread t2
1305        );
1306        let ProofMember::SignedMessage { message, .. } = proof.second.clone() else {
1307            unreachable!()
1308        };
1309        let mut env = match envelope_member(message, &ALICE_SIGNER) {
1310            ProofMember::Envelope(env) => env,
1311            _ => unreachable!(),
1312        };
1313        env.header.thread = "t1".to_string(); // relabel into the conflict
1314        proof.second = ProofMember::Envelope(env);
1315        assert_eq!(
1316            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1317            Err(EquivocationProofError::Signature {
1318                member: 1,
1319                error: AttestError::InvalidSignature,
1320            })
1321        );
1322    }
1323
1324    #[test]
1325    fn envelope_member_by_another_key_is_a_key_mismatch() {
1326        let d = choice_dialect();
1327        let mut proof = proof_over(
1328            &d,
1329            msg("offer", "@alice", "t1", "a"),
1330            msg("refuse", "@alice", "t1", "b"),
1331        );
1332        proof.second = envelope_member(msg("refuse", "@bob", "t1", "b"), &BOB_SIGNER);
1333        assert_eq!(
1334            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1335            Err(EquivocationProofError::KeyMismatch { member: 1 })
1336        );
1337    }
1338
1339    #[test]
1340    fn member_missing_committed_fields_rejected() {
1341        let d = choice_dialect();
1342        let mut senderless = msg("offer", "@alice", "t1", "a");
1343        if let Message::Simple { sender, .. } = &mut senderless {
1344            *sender = None;
1345        }
1346        let proof = EquivocationProof {
1347            key: alice(),
1348            thread: "t1".to_string(),
1349            dialect_hash: d.hash.clone().unwrap(),
1350            first: ProofMember::SignedMessage {
1351                message: senderless,
1352                signature: vec![0u8; 32],
1353            },
1354            second: signed_member(msg("refuse", "@alice", "t1", "b"), &ALICE_SIGNER),
1355        };
1356        assert_eq!(
1357            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1358            Err(EquivocationProofError::MalformedMember {
1359                member: 0,
1360                defect: MemberDefect::MissingSender,
1361            })
1362        );
1363    }
1364
1365    // ---- REQ-813: opened-envelope proof members ----
1366
1367    use crate::envelope::{build_opened, HEADER_FIELDS};
1368    use crate::keyid::SignatureSuite;
1369    use crate::typed_addr::FieldId;
1370
1371    fn opened_member(m: Message, signer: &dyn Signer) -> ProofMember {
1372        ProofMember::OpenedEnvelope(
1373            build_opened(&m, &HEADER_FIELDS, &SignatureSuite::Ed25519, signer).unwrap(),
1374        )
1375    }
1376
1377    #[test]
1378    fn opened_member_convicts_without_payload() {
1379        // The second member travels as an opened envelope (header openings
1380        // only): the proof verifies from the pair and the pinned dialect
1381        // alone, and the opened member discloses no payload field (NFR-701).
1382        let d = choice_dialect();
1383        let mut proof = proof_over(
1384            &d,
1385            msg("offer", "@alice", "t1", "a"),
1386            msg("refuse", "@alice", "t1", "b"),
1387        );
1388        proof.second = opened_member(msg("refuse", "@alice", "t1", "payload-b"), &ALICE_SIGNER);
1389        if let ProofMember::OpenedEnvelope(env) = &proof.second {
1390            assert!(env.opening(FieldId::Payload).is_none());
1391            for op in &env.openings {
1392                let bytes = crate::canonical::canonical_encode(&op.value);
1393                let s = core::str::from_utf8(&bytes).unwrap();
1394                assert!(
1395                    !s.contains("payload-b"),
1396                    "payload leaked via {:?}",
1397                    op.field
1398                );
1399            }
1400        }
1401        assert_eq!(
1402            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1403            Ok(alice())
1404        );
1405    }
1406
1407    #[test]
1408    fn all_opened_pair_convicts() {
1409        let d = choice_dialect();
1410        let mut proof = proof_over(
1411            &d,
1412            msg("offer", "@alice", "t1", "a"),
1413            msg("offer", "@alice", "t1", "b"),
1414        );
1415        proof.first = opened_member(msg("offer", "@alice", "t1", "a"), &ALICE_SIGNER);
1416        proof.second = opened_member(msg("offer", "@alice", "t1", "b"), &ALICE_SIGNER);
1417        assert_eq!(
1418            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1419            Ok(alice())
1420        );
1421    }
1422
1423    #[test]
1424    fn relabelled_opened_member_fails_at_the_signature() {
1425        // An opened envelope's thread is an authenticated opening (REQ-813):
1426        // rewriting it to frame a cross-thread conflict makes that opening
1427        // fail against the signed root, so the forgery dies at the signature
1428        // check — never at a repairable policy check.
1429        let d = choice_dialect();
1430        let mut proof = proof_over(
1431            &d,
1432            msg("offer", "@alice", "t1", "a"),
1433            msg("refuse", "@alice", "t2", "b"), // genuinely from thread t2
1434        );
1435        let mut env = match opened_member(msg("refuse", "@alice", "t2", "b"), &ALICE_SIGNER) {
1436            ProofMember::OpenedEnvelope(env) => env,
1437            _ => unreachable!(),
1438        };
1439        // Relabel the Thread opening into the conflict thread.
1440        for op in &mut env.openings {
1441            if op.field == FieldId::Thread {
1442                op.value = crate::sexpr::SExpr::List(alloc::vec![crate::sexpr::SExpr::Atom(
1443                    crate::sexpr::Atom::Str("t1".to_string())
1444                )]);
1445            }
1446        }
1447        proof.second = ProofMember::OpenedEnvelope(env);
1448        assert_eq!(
1449            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1450            Err(EquivocationProofError::Signature {
1451                member: 1,
1452                error: AttestError::InvalidSignature,
1453            })
1454        );
1455    }
1456
1457    #[test]
1458    fn opened_member_by_another_key_is_a_key_mismatch() {
1459        let d = choice_dialect();
1460        let mut proof = proof_over(
1461            &d,
1462            msg("offer", "@alice", "t1", "a"),
1463            msg("refuse", "@alice", "t1", "b"),
1464        );
1465        proof.second = opened_member(msg("refuse", "@bob", "t1", "b"), &BOB_SIGNER);
1466        assert_eq!(
1467            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1468            Err(EquivocationProofError::KeyMismatch { member: 1 })
1469        );
1470    }
1471
1472    /// A mixed pair — one redacted envelope, one opened envelope — still
1473    /// convicts: the arms interoperate through the shared `CheckedMember`.
1474    #[test]
1475    fn mixed_redacted_and_opened_pair_convicts() {
1476        let d = choice_dialect();
1477        let mut proof = proof_over(
1478            &d,
1479            msg("offer", "@alice", "t1", "a"),
1480            msg("refuse", "@alice", "t1", "b"),
1481        );
1482        proof.first = envelope_member(msg("offer", "@alice", "t1", "a"), &ALICE_SIGNER);
1483        proof.second = opened_member(msg("refuse", "@alice", "t1", "b"), &ALICE_SIGNER);
1484        assert_eq!(
1485            verify_equivocation_proof(&proof, &d, &ALICE_SIGNER),
1486            Ok(alice())
1487        );
1488    }
1489
1490    // ---- TEST-707: the transparency lint ----
1491
1492    /// The OAuth fragment of r6.rs, parameterised on the abort branch's
1493    /// recipient: branches `login`/`abort` are one `(any …)` choice by
1494    /// `server`; with `abort :to client` both branches share recipient
1495    /// `client` (the paper's shared-recipient shape).
1496    fn oauth_like(abort_to: &[&str]) -> Dialect {
1497        dialect(
1498            &["server", "client", "authoriser"],
1499            vec![
1500                perf_def("login", Some(ann("server", &["client"]))),
1501                perf_def("abort", Some(ann("server", abort_to))),
1502                perf_def("passwd", Some(ann("client", &["authoriser"]))),
1503                perf_def("auth", Some(ann("authoriser", &["server"]))),
1504                perf_def("quit", Some(ann("client", &["authoriser"]))),
1505            ],
1506            vec![
1507                step("begin", vec![], vec![any(&["login", "abort"])]),
1508                step("login", vec![single("begin")], vec![single("passwd")]),
1509                step("abort", vec![single("begin")], vec![single("quit")]),
1510                step("passwd", vec![single("login")], vec![single("auth")]),
1511                step("auth", vec![single("passwd")], vec![]),
1512                step("quit", vec![single("abort")], vec![]),
1513            ],
1514        )
1515    }
1516
1517    #[test]
1518    fn shared_recipient_choice_is_lint_clean() {
1519        // OAuth-style: both branches address `client` — a common witness
1520        // exists, nothing to warn about.
1521        let warnings = choice_transparency_lint(&oauth_like(&["client"]), true);
1522        assert_eq!(warnings, Vec::new());
1523    }
1524
1525    #[test]
1526    fn disjoint_recipient_choice_warns() {
1527        let warnings = choice_transparency_lint(&oauth_like(&["authoriser"]), true);
1528        assert_eq!(
1529            warnings,
1530            vec![ChoiceTransparencyWarning {
1531                alternatives: ["login", "abort"].iter().map(|s| s.to_string()).collect(),
1532                chooser: "server".to_string(),
1533            }]
1534        );
1535    }
1536
1537    #[test]
1538    fn flag_off_suppresses_the_lint() {
1539        assert_eq!(
1540            choice_transparency_lint(&oauth_like(&["authoriser"]), false),
1541            Vec::new()
1542        );
1543    }
1544
1545    #[test]
1546    fn chooser_as_only_common_recipient_still_warns() {
1547        // Both branches carry the chooser itself as the only shared
1548        // recipient: no *other* endpoint is a guaranteed witness.
1549        let d = dialect(
1550            &["server", "client", "authoriser"],
1551            vec![
1552                perf_def("login", Some(ann("server", &["server", "client"]))),
1553                perf_def("abort", Some(ann("server", &["server", "authoriser"]))),
1554            ],
1555            vec![
1556                step("begin", vec![], vec![any(&["login", "abort"])]),
1557                step("login", vec![single("begin")], vec![]),
1558                step("abort", vec![single("begin")], vec![]),
1559            ],
1560        );
1561        let warnings = choice_transparency_lint(&d, true);
1562        assert_eq!(warnings.len(), 1);
1563        assert_eq!(warnings[0].chooser, "server");
1564    }
1565
1566    #[test]
1567    fn unannotated_or_incoherent_choices_are_not_this_lints_finding() {
1568        // One branch unannotated → skipped (REQ-601's finding).
1569        let mut d = oauth_like(&["authoriser"]);
1570        d.performatives[1].role = None; // abort
1571        assert_eq!(choice_transparency_lint(&d, true), Vec::new());
1572
1573        // Incoherent senders → skipped (REQ-603's finding).
1574        let mut d = oauth_like(&["authoriser"]);
1575        d.performatives[1].role = Some(ann("client", &["authoriser"]));
1576        assert_eq!(choice_transparency_lint(&d, true), Vec::new());
1577    }
1578
1579    // ---- shared helpers ----
1580
1581    #[test]
1582    fn message_content_hash_is_canonical_and_content_sensitive() {
1583        let m1 = msg("offer", "@alice", "t1", "a");
1584        let m2 = msg("offer", "@alice", "t1", "b");
1585        let h1 = message_content_hash(&m1);
1586        assert_eq!(h1, message_content_hash(&m1), "deterministic");
1587        assert_ne!(h1, message_content_hash(&m2), "content-sensitive");
1588        assert!(h1.starts_with("f1220") && h1.len() == 5 + 64);
1589    }
1590}