vauban-claim 0.1.0

Vauban Claim Algebra — reference implementation of draft-vauban-claim-algebra-00 (post-quantum claim sextuplet + 5 composition operators, canonical CBOR/JSON codec).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
//! TranscriptT2 — Poseidon2-felt252 post-quantum Fiat-Shamir transcript.
//!
//! Implements the construction from `docs/research/06-orq-pq-transcript.md`
//! §3 (normative), providing a Poseidon2-based sponge transcript over the
//! felt252 (Stark251) field.
//!
//! # Security properties
//!
//! - **Post-quantum** — Poseidon2-felt252 width-3 sponge, indifferentiable from
//!   a random oracle up to `2^126` queries per Bonneau-Drake-Khovratovich
//!   ePrint 2025/118 (`BDK25`).
//! - **QROM-sound** — Fiat-Shamir compiled from a Σ-protocol with honest-verifier
//!   ZK and special soundness is PQ-sound under the Don-Fehr-Majenz 2019
//!   (`DFM19`) measure-and-rewind reduction with `O(q²)` security loss.
//! - **Label-per-field** — every field absorption is preceded by a label-felt
//!   commitment, defeating reordering attacks (Frozen Heart 2.0, Chen-Dao-Miller
//!   ePrint 2024/1124).
//! - **Length suffix** — the absorbed length is the last block per field,
//!   defeating ambiguous-boundary attacks.
//! - **Domain tag in IV** — sponge initialized from `vauban-claim-v2-transcript-t2`,
//!   defeating cross-protocol replay and version-downgrade attack Q5.
//!
//! # Sponge parameters (§3.1)
//!
//! | Parameter | Value |
//! |-----------|-------|
//! | Field     | felt252 (Stark251 prime) |
//! | Width     | 3 felts |
//! | Rate      | 2 felts |
//! | Capacity  | 1 felt = 252 bits |
//! | Permutation | Poseidon2-felt252 (Starknet round constants) |
//!
//! Width-2 Poseidon is explicitly rejected (known structural distinguisher
//! beyond `2^84` queries, Khovratovich 2024).
//!
//! # Migration plan (§6 dual-transcript period)
//!
//! During the T1→T2 migration, each [`crate::claim::Claim`] carries a
//! `transcript_version: TranscriptVersion` field (default `V1` for backward
//! compatibility). Verifiers route via [`crate::claim::Claim::verify_with_transcript`].
//! A version-tagged mismatch is rejected with
//! [`crate::error::TranscriptError::VersionMismatch`] — the domain-tag
//! difference in the sponge IV (v1 vs v2) makes cross-version challenges
//! structurally distinct, defeating downgrade attack Q5.
//!
//! See `docs/research/06-orq-pq-transcript.md` §6 for the full phased
//! migration timeline (Phase 0 → Phase 3, target 2030 for v1 deprecation).
//!
//! # References
//!
//! - `docs/research/06-orq-pq-transcript.md` §3 (normative construction), §6 (migration plan)
//! - BDK 2025/118: Bonneau-Drake-Khovratovich, *Indifferentiability of Poseidon for Fiat-Shamir*
//! - DFM 2019: Don-Fehr-Majenz, *Security of the Fiat-Shamir Transformation in the QROM*, CRYPTO 2019
//! - CDM 2024/1124: Chen-Dao-Miller, *Frozen-Heart 2.0*

use alloc::vec::Vec;
use starknet_crypto::{poseidon_hash_many, poseidon_permute_comp, Felt};

use crate::error::TranscriptError;

// ---------------------------------------------------------------------------
// Sponge width/rate constants (§3.1)
// ---------------------------------------------------------------------------

/// Sponge width: 3 felt252 elements (rate + capacity).
const WIDTH: usize = 3;
/// Sponge rate: 2 felt252 elements per permutation.
const RATE: usize = 2;
/// Capacity index in the sponge state (single felt = 252 bits).
const CAPACITY_IDX: usize = 2;

// ---------------------------------------------------------------------------
// Domain constants
// ---------------------------------------------------------------------------

/// Returns the domain tag felt for `vauban-claim-v2-transcript-t2`.
///
/// This felt is the Poseidon hash of the UTF-8 bytes of the tag string,
/// split into 31-byte chunks. It seeds the sponge IV, ensuring
/// cross-protocol isolation (attack Q5 in §4.3).
///
/// # Invariant
///
/// Must equal `poseidon_hash_many([Felt::from_bytes_be_slice(b"vauban-claim-v2-transcript-t2")])`
/// (29 bytes fit in a single felt252 chunk).
pub fn domain_tag_felt() -> Felt {
    bytes_to_felt(b"vauban-claim-v2-transcript-t2")
}

/// Returns the absent-field sentinel felt.
///
/// `SENTINEL_ABSENT = poseidon_hash_bytes_to_felt("vauban::absent")`
///
/// This constant is absorbed in place of any optional sextuplet field
/// that is absent, ensuring absent ≠ empty ≠ present-but-short
/// (defeats length-extension ambiguity on optional fields).
///
/// # Invariant
///
/// Must equal `poseidon_hash_many([Felt::from_bytes_be_slice(b"vauban::absent")])`
/// (14 bytes fit in a single felt252 chunk).
pub fn sentinel_absent() -> Felt {
    bytes_to_felt(b"vauban::absent")
}

// ---------------------------------------------------------------------------
// Bytes-to-felt helper (§3 canonical encoding)
// ---------------------------------------------------------------------------

/// Canonical bytes-to-field-element encoding.
///
/// Split `data` into 31-byte chunks (felt252 maximum safe encoding without
/// modular reduction ambiguity), convert each chunk to a `Felt` big-endian,
/// then hash with `poseidon_hash_many`. An empty input produces the hash
/// of a single-element empty slice (same semantics as the Poseidon padding
/// in `starknet-crypto`).
///
/// This matches the convention in `crate::poseidon::poseidon_felt252`.
pub fn bytes_to_felt(data: &[u8]) -> Felt {
    if data.is_empty() {
        return poseidon_hash_many(&[Felt::ZERO]);
    }
    let felts: Vec<Felt> = data
        .chunks(31)
        .map(Felt::from_bytes_be_slice)
        .collect();
    poseidon_hash_many(&felts)
}

// ---------------------------------------------------------------------------
// Sponge state
// ---------------------------------------------------------------------------

/// Poseidon2-felt252 sponge state for TranscriptT2.
///
/// Implements §3.1.1–§3.1.3 of `docs/research/06-orq-pq-transcript.md`.
///
/// # Layout
///
/// `state[0..RATE]` = rate lanes (absorption/squeezing).
/// `state[CAPACITY_IDX]` = capacity lane (initialized from domain tag, never
/// directly absorbed or output — provides `2^126` indifferentiability bound
/// per BDK 2025/118).
#[derive(Clone, Debug)]
pub struct SpongeState {
    state: [Felt; WIDTH],
}

impl SpongeState {
    /// Initialize the sponge with the domain tag IV (§3.1.1).
    ///
    /// ```text
    /// state = [0, 0, domain_tag_felt]
    /// ```
    ///
    /// The domain tag is placed in the capacity lane to ensure every
    /// protocol version produces an orthogonal sponge trajectory.
    pub fn init(domain_tag: &[u8]) -> Self {
        let tag_felt = bytes_to_felt(domain_tag);
        let mut state = [Felt::ZERO; WIDTH];
        // Invariant: capacity lane (index 2) carries the domain tag
        state[CAPACITY_IDX] = tag_felt;
        Self { state }
    }

    /// Absorb a labeled field value into the sponge (§3.1.2).
    ///
    /// ```text
    /// absorb(label, value):
    ///   label_felt = poseidon2_hash_bytes_to_felt(label)
    ///   state = permute(state ⊕ [label_felt, 0, 0])
    ///   for chunk in value.chunks(2):
    ///     state = permute(state ⊕ [chunk[0], chunk[1].unwrap_or(0), 0])
    ///   state = permute(state ⊕ [n_as_felt, 0, 0])
    /// ```
    ///
    /// Triple discipline:
    /// 1. **Label first** — label is committed before value (defeats reordering).
    /// 2. **Value in rate-sized chunks** — each chunk occupies rate lanes only.
    /// 3. **Length suffix** — `|value|` is the final absorbed block (defeats
    ///    ambiguous-boundary / Frozen Heart 2.0 attacks).
    pub fn absorb(&mut self, label: &[u8], value: &[Felt]) {
        // Step 1: absorb label
        let label_felt = bytes_to_felt(label);
        // XOR into rate lane 0, then permute
        self.state[0] += label_felt;
        poseidon_permute_comp(&mut self.state);

        // Step 2: absorb value in rate-sized chunks (rate = 2)
        let n = value.len();
        let mut idx = 0;
        while idx < n {
            let v0 = value[idx];
            let v1 = if idx + 1 < n { value[idx + 1] } else { Felt::ZERO };
            // XOR into rate lanes 0 and 1, then permute
            self.state[0] += v0;
            self.state[1] += v1;
            poseidon_permute_comp(&mut self.state);
            idx += RATE;
        }

        // Step 3: length suffix — absorb |value| as final block
        // Invariant: n < 2^252, so cast to u64 then to Felt is safe for
        // any realistic input
        let len_felt = Felt::from(n as u64);
        self.state[0] += len_felt;
        poseidon_permute_comp(&mut self.state);
    }

    /// Squeeze `n` challenge felts from the sponge (§3.1.3).
    ///
    /// ```text
    /// squeeze(n):
    ///   out = []
    ///   for i in 0..n:
    ///     if i % rate == 0: state = permute(state)
    ///     out.push(state[i % rate])
    /// ```
    ///
    /// Challenges are squeezed as field elements — no modular bias,
    /// no bytes-to-field conversion. For challenges requiring `r < 252` bits,
    /// the upper `252 - r` bits are discarded by the caller.
    pub fn squeeze(&mut self, n: usize) -> Vec<Felt> {
        let mut out = Vec::with_capacity(n);
        for i in 0..n {
            // Permute before reading each new rate block
            if i % RATE == 0 {
                poseidon_permute_comp(&mut self.state);
            }
            out.push(self.state[i % RATE]);
        }
        out
    }
}

// ---------------------------------------------------------------------------
// TranscriptT2 — high-level API (§3.1.4 sextuplet absorption order)
// ---------------------------------------------------------------------------

/// Poseidon2-felt252 TranscriptT2 for Vauban Claim sextuplet binding.
///
/// Maintains a [`SpongeState`] and exposes the same logical API surface
/// as `TranscriptT1` (`init` / `absorb` / `squeeze`) plus the canonical
/// six-field absorption method [`TranscriptT2::bind_sextuplet`].
///
/// # Sextuplet absorption order (§3.1.4)
///
/// ```text
/// absorb("subject",          S.canonical_felts())
/// absorb("predicate",        P.canonical_felts())
/// absorb("evidence",         E.canonical_felts())
/// absorb("temporal",         T.canonical_felts())
/// absorb("revelation_mask",  M.canonical_felts())
/// absorb("anchor",           A.canonical_felts() OR [SENTINEL_ABSENT])
/// ```
#[derive(Clone, Debug)]
pub struct TranscriptT2 {
    sponge: SpongeState,
}

impl TranscriptT2 {
    /// Initialize a TranscriptT2 with the canonical domain tag.
    ///
    /// Domain tag: `vauban-claim-v2-transcript-t2` (§3.1, §3.1.1).
    pub fn new() -> Self {
        Self {
            sponge: SpongeState::init(b"vauban-claim-v2-transcript-t2"),
        }
    }

    /// Initialize with an explicit domain tag bytes slice (for testing
    /// domain-tag isolation).
    pub fn with_domain_tag(tag: &[u8]) -> Self {
        Self {
            sponge: SpongeState::init(tag),
        }
    }

    /// Absorb a labeled field value (label-per-field discipline per §3.1.2).
    ///
    /// `label` is the ASCII field name (e.g. `b"subject"`).
    /// `value` is the canonical felt252 encoding of the field.
    pub fn absorb(&mut self, label: &[u8], value: &[Felt]) {
        self.sponge.absorb(label, value);
    }

    /// Squeeze `n` challenge felts (§3.1.3).
    ///
    /// No modular bias — challenges are felt252 elements directly.
    pub fn squeeze(&mut self, n: usize) -> Vec<Felt> {
        self.sponge.squeeze(n)
    }
}

impl Default for TranscriptT2 {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Claim sextuplet canonical felt encodings
// ---------------------------------------------------------------------------

/// Canonical felt encoding helpers for Claim sextuplet fields.
///
/// Each field of the sextuplet must be representable as `[felt252]` for
/// absorption into TranscriptT2. For byte-payload fields, `bytes_to_felt`
/// is used (one-way binding sufficient for Fiat-Shamir — verifier has
/// original bytes from proof transcript, §3.3).
pub mod canonical {
    use alloc::vec::Vec;
    use starknet_crypto::Felt;

    use super::bytes_to_felt;
    use super::sentinel_absent;

    /// Encode arbitrary bytes as a single felt (via `bytes_to_felt`).
    ///
    /// Suitable for arbitrary-length byte payloads that do not have a
    /// native felt252 representation (e.g., CBOR-encoded sub-fields).
    pub fn bytes_as_felt(data: &[u8]) -> Vec<Felt> {
        alloc::vec![bytes_to_felt(data)]
    }

    /// Encode a u64 timestamp as a single felt.
    pub fn u64_as_felt(v: u64) -> Vec<Felt> {
        alloc::vec![Felt::from(v)]
    }

    /// Return the absent-field sentinel as a single-felt slice.
    ///
    /// Used when an optional sextuplet field is absent (§3.1.4).
    pub fn absent() -> Vec<Felt> {
        alloc::vec![sentinel_absent()]
    }
}

// ---------------------------------------------------------------------------
// TranscriptVersion enum (§6 migration)
// ---------------------------------------------------------------------------

/// Transcript version tag for Claims (`transcript_version` field per §6).
///
/// A `Claim` carries this tag in its evidence block so that verifiers can
/// select the correct transcript construction. Version-mismatch produces a
/// different IV state and fails challenge derivation, defeating downgrade
/// attack Q5 (§4.3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "std", serde(rename_all = "lowercase"))]
pub enum TranscriptVersion {
    /// TranscriptT1 — Merlin/Strobe-128, classical soundness only.
    ///
    /// Default for backward compatibility. Non-PQ; deprecated for new Claims
    /// targeting 2030+ security.
    V1,
    /// TranscriptT2 — Poseidon2-felt252, PQ-sound under DFM 2019 + BDK 2025/118.
    ///
    /// Required for recursive STARK composition (ORQ-2).
    V2,
}

impl Default for TranscriptVersion {
    /// Default to V1 for backward compatibility (§6 migration).
    fn default() -> Self {
        Self::V1
    }
}

// ---------------------------------------------------------------------------
// bind_claim_v2: high-level entry point matching TranscriptT1::bind_claim API
// ---------------------------------------------------------------------------

/// Bind a Claim sextuplet into a TranscriptT2 in canonical sextuplet order.
///
/// This is the primary entry point for TranscriptT2; it mirrors the
/// `bind_claim(claim, verifier_ctx, nonce)` API of `transcript.rs`
/// (TranscriptT1) so the dispatch trait works for both versions.
///
/// # Sextuplet absorption order (§3.1.4 normative)
///
/// 1. `subject`          — canonical CBOR bytes → felt
/// 2. `predicate`        — canonical CBOR bytes → felt
/// 3. `evidence`         — canonical CBOR bytes → felt
/// 4. `temporal`         — `not_before` as u64 felt + `not_after` (felt or sentinel)
/// 5. `revelation_mask`  — canonical CBOR bytes → felt
/// 6. `anchor`           — canonical CBOR bytes → felt (non-empty, always present)
/// 7. `verifier_ctx`     — bytes → felt (presentation context binding)
/// 8. `presentation_nonce` — bytes → felt (replay prevention)
///
/// Returns the transcript **before** challenge derivation — call
/// [`TranscriptT2::squeeze`] to extract challenges.
///
/// # Errors
///
/// Returns [`TranscriptError::Encoding`] if canonical CBOR serialization
/// fails for any sextuplet field.
pub fn bind_claim_v2(
    claim: &crate::claim::Claim,
    verifier_ctx: &[u8],
    nonce: &[u8],
) -> Result<TranscriptT2, TranscriptError> {
    use crate::codec::to_cbor_canonical;

    let mut t = TranscriptT2::new();

    // §3.1.4 Step 1: Subject
    let subject_bytes = to_cbor_canonical(&claim.subject)
        .map_err(|e| TranscriptError::Encoding(e.to_string()))?;
    t.absorb(b"subject", &canonical::bytes_as_felt(&subject_bytes));

    // §3.1.4 Step 2: Predicate
    let predicate_bytes = to_cbor_canonical(&claim.predicate)
        .map_err(|e| TranscriptError::Encoding(e.to_string()))?;
    t.absorb(b"predicate", &canonical::bytes_as_felt(&predicate_bytes));

    // §3.1.4 Step 3: Evidence
    let evidence_bytes = to_cbor_canonical(&claim.evidence)
        .map_err(|e| TranscriptError::Encoding(e.to_string()))?;
    t.absorb(b"evidence", &canonical::bytes_as_felt(&evidence_bytes));

    // §3.1.4 Step 4: Temporal
    {
        let tf = &claim.temporal_frame;
        t.absorb(b"temporal.not_before", &canonical::u64_as_felt(tf.not_before()));
        let not_after_felts = match tf.not_after() {
            Some(na) => canonical::u64_as_felt(na),
            None => canonical::absent(),
        };
        t.absorb(b"temporal.not_after", &not_after_felts);
    }

    // §3.1.4 Step 5: Revelation mask
    let mask_bytes = to_cbor_canonical(&claim.revelation_mask)
        .map_err(|e| TranscriptError::Encoding(e.to_string()))?;
    t.absorb(b"revelation_mask", &canonical::bytes_as_felt(&mask_bytes));

    // §3.1.4 Step 6: Anchor
    let anchor_bytes = to_cbor_canonical(&claim.anchor)
        .map_err(|e| TranscriptError::Encoding(e.to_string()))?;
    t.absorb(b"anchor", &canonical::bytes_as_felt(&anchor_bytes));

    // Verifier context + presentation nonce (binding against replay and context)
    t.absorb(b"verifier_ctx", &canonical::bytes_as_felt(verifier_ctx));
    t.absorb(b"presentation_nonce", &canonical::bytes_as_felt(nonce));

    Ok(t)
}

/// Extract a single felt252 challenge from a bound TranscriptT2.
///
/// Returns the first squeezed felt element. For multi-challenge protocols,
/// call [`TranscriptT2::squeeze`] directly.
pub fn extract_challenge_v2(transcript: &mut TranscriptT2) -> Felt {
    // Invariant: squeeze(1) always returns exactly one element
    transcript.squeeze(1).into_iter().next()
        .expect("invariant: squeeze(n=1) returns exactly 1 element")
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::builder::ClaimBuilder;
    use crate::primitives::{
        anchor::{Anchor, AnchorEntry, AnchorType},
        evidence::{ByteString, Evidence, EvidenceEnvelope, EvidenceScheme, StarkProofEnvelope},
        predicate::{Predicate, PredicateType},
        revelation_mask::RevelationMask,
        subject::Subject,
        temporal::TemporalFrame,
    };

    // -------------------------------------------------------------------------
    // TV-T2-001: Init determinism
    // -------------------------------------------------------------------------

    /// TV-T2-001: Two independently created TranscriptT2 with the same domain
    /// tag MUST produce identical sponge state after init.
    #[test]
    fn init_determinism() {
        let t1 = TranscriptT2::new();
        let t2 = TranscriptT2::new();
        // Sponge states must be identical — domain tag is deterministic
        assert_eq!(
            format!("{:?}", t1.sponge.state),
            format!("{:?}", t2.sponge.state),
            "TV-T2-001: init determinism"
        );
        // Capacity lane must be the domain tag felt
        let expected_tag = domain_tag_felt();
        assert_eq!(t1.sponge.state[CAPACITY_IDX], expected_tag);
    }

    // -------------------------------------------------------------------------
    // TV-T2-002: Single-field absorb determinism
    // -------------------------------------------------------------------------

    /// TV-T2-002: Absorbing the same label+value twice on fresh transcripts
    /// MUST produce the same challenge.
    #[test]
    fn single_field_absorb_determinism() {
        let value = alloc::vec![Felt::from(42u64), Felt::from(99u64)];

        let mut t1 = TranscriptT2::new();
        t1.absorb(b"field", &value);
        let c1 = t1.squeeze(1);

        let mut t2 = TranscriptT2::new();
        t2.absorb(b"field", &value);
        let c2 = t2.squeeze(1);

        assert_eq!(c1, c2, "TV-T2-002: single-field absorb determinism");
    }

    // -------------------------------------------------------------------------
    // TV-T2-003: Multi-field absorb determinism
    // -------------------------------------------------------------------------

    /// TV-T2-003: Absorbing multiple labeled fields in identical order on two
    /// fresh transcripts MUST produce the same challenge.
    #[test]
    fn multi_field_absorb_determinism() {
        let fields: &[(&[u8], &[u64])] = &[
            (b"subject", &[1, 2, 3]),
            (b"predicate", &[42]),
            (b"evidence", &[100, 200, 300, 400]),
        ];

        let mut t1 = TranscriptT2::new();
        let mut t2 = TranscriptT2::new();

        for (label, nums) in fields {
            let felts: Vec<Felt> = nums.iter().map(|&n| Felt::from(n)).collect();
            t1.absorb(label, &felts);
            t2.absorb(label, &felts);
        }

        let c1 = t1.squeeze(2);
        let c2 = t2.squeeze(2);

        assert_eq!(c1, c2, "TV-T2-003: multi-field absorb determinism");
    }

    // -------------------------------------------------------------------------
    // TV-T2-004: Label rebinding rejection
    // -------------------------------------------------------------------------

    /// TV-T2-004: Absorbing the same value under a different label MUST
    /// produce a different challenge (label commits to field identity).
    #[test]
    fn label_rebinding_rejection() {
        let value = alloc::vec![Felt::from(1337u64)];

        let mut t1 = TranscriptT2::new();
        t1.absorb(b"subject", &value);
        let c1 = t1.squeeze(1);

        let mut t2 = TranscriptT2::new();
        t2.absorb(b"predicate", &value);
        let c2 = t2.squeeze(1);

        assert_ne!(
            c1, c2,
            "TV-T2-004: different labels MUST produce different challenges"
        );
    }

    // -------------------------------------------------------------------------
    // TV-T2-005: Domain-tag isolation
    // -------------------------------------------------------------------------

    /// TV-T2-005: A transcript initialized with a different domain tag MUST
    /// produce a different challenge even for identical absorbed content.
    #[test]
    fn domain_tag_isolation() {
        let value = alloc::vec![Felt::from(42u64)];

        let mut t1 = TranscriptT2::new(); // canonical domain tag
        t1.absorb(b"field", &value);
        let c1 = t1.squeeze(1);

        let mut t2 = TranscriptT2::with_domain_tag(b"attacker-domain");
        t2.absorb(b"field", &value);
        let c2 = t2.squeeze(1);

        assert_ne!(
            c1, c2,
            "TV-T2-005: different domain tags MUST produce different challenges (Q5 mitigation)"
        );
    }

    // -------------------------------------------------------------------------
    // TV-T2-006: Absent-field sentinel correctness
    // -------------------------------------------------------------------------

    /// TV-T2-006: Absorbing the sentinel felt MUST produce a different challenge
    /// than absorbing an empty slice or a zero felt for the same label.
    #[test]
    fn absent_field_sentinel_correctness() {
        // Transcript using explicit sentinel (correct: field absent)
        let mut t_sentinel = TranscriptT2::new();
        t_sentinel.absorb(b"anchor", &canonical::absent());
        let c_sentinel = t_sentinel.squeeze(1);

        // Transcript absorbing empty slice (silent omission — incorrect)
        let mut t_empty = TranscriptT2::new();
        t_empty.absorb(b"anchor", &[]);
        let c_empty = t_empty.squeeze(1);

        // Transcript absorbing Felt::ZERO (could be confused with absent)
        let mut t_zero = TranscriptT2::new();
        t_zero.absorb(b"anchor", &[Felt::ZERO]);
        let c_zero = t_zero.squeeze(1);

        assert_ne!(
            c_sentinel, c_empty,
            "TV-T2-006a: sentinel ≠ empty-slice absorption"
        );
        assert_ne!(
            c_sentinel, c_zero,
            "TV-T2-006b: sentinel ≠ Felt::ZERO absorption"
        );
    }

    // -------------------------------------------------------------------------
    // TV-T2-007: bind_claim_v2 determinism (end-to-end)
    // -------------------------------------------------------------------------

    /// TV-T2-007: bind_claim_v2 on two identical claims with identical
    /// verifier_ctx and nonce MUST produce the same challenge.
    #[test]
    fn bind_claim_v2_determinism() {
        let claim = minimal_claim();

        let mut t1 = bind_claim_v2(&claim, b"verifier-1", b"nonce-1").unwrap();
        let mut t2 = bind_claim_v2(&claim, b"verifier-1", b"nonce-1").unwrap();

        let c1 = extract_challenge_v2(&mut t1);
        let c2 = extract_challenge_v2(&mut t2);

        assert_eq!(c1, c2, "TV-T2-007: bind_claim_v2 determinism");
    }

    // -------------------------------------------------------------------------
    // TV-T2-008: TranscriptVersion default
    // -------------------------------------------------------------------------

    /// TV-T2-008: `TranscriptVersion::default()` MUST be V1 for backward compat.
    #[test]
    fn transcript_version_default_is_v1() {
        assert_eq!(
            TranscriptVersion::default(),
            TranscriptVersion::V1,
            "TV-T2-008: default transcript version must be V1 (backward compat)"
        );
    }

    // -------------------------------------------------------------------------
    // TV-T2-009: Nonce binding (different nonce → different challenge)
    // -------------------------------------------------------------------------

    /// TV-T2-009: Different presentation nonces MUST produce different challenges.
    #[test]
    fn nonce_binding() {
        let claim = minimal_claim();

        let mut t1 = bind_claim_v2(&claim, b"verifier-1", b"nonce-A").unwrap();
        let mut t2 = bind_claim_v2(&claim, b"verifier-1", b"nonce-B").unwrap();

        let c1 = extract_challenge_v2(&mut t1);
        let c2 = extract_challenge_v2(&mut t2);

        assert_ne!(c1, c2, "TV-T2-009: nonce binding");
    }

    // -------------------------------------------------------------------------
    // TV-T2-010: Sextuplet order enforced (subject ≠ predicate swap)
    // -------------------------------------------------------------------------

    /// TV-T2-010: Swapping the absorption order of subject and predicate
    /// MUST produce a different challenge (order is canonical per §3.1.4).
    #[test]
    fn sextuplet_order_enforced() {
        let s = alloc::vec![Felt::from(1u64)];
        let p = alloc::vec![Felt::from(2u64)];

        let mut t1 = TranscriptT2::new();
        t1.absorb(b"subject", &s);
        t1.absorb(b"predicate", &p);
        let c1 = t1.squeeze(1);

        let mut t2 = TranscriptT2::new();
        t2.absorb(b"predicate", &p); // swapped
        t2.absorb(b"subject", &s);
        let c2 = t2.squeeze(1);

        assert_ne!(c1, c2, "TV-T2-010: sextuplet order must be canonical");
    }

    // -------------------------------------------------------------------------
    // Fixture helpers
    // -------------------------------------------------------------------------

    fn minimal_claim() -> crate::claim::Claim {
        ClaimBuilder::default()
            .subject(Subject::wallet(
                hex::decode(
                    "bbbe91b88ff2842d7f7af15cd8154cdcc753dc3997e46be3568e7ef1ab5e90f4",
                )
                .unwrap(),
            ))
            .predicate(
                Predicate::new(
                    PredicateType::Equality,
                    "vauban.claim",
                    b"body".to_vec(),
                )
                .unwrap(),
            )
            .evidence(fixture_evidence_stark())
            .temporal_frame(
                TemporalFrame::new(1_700_000_000, None, None).unwrap(),
            )
            .revelation_mask(
                RevelationMask::new(alloc::vec!["*".into()], alloc::vec![], None).unwrap(),
            )
            .anchor(
                Anchor::new(alloc::vec![AnchorEntry {
                    anchor_type: AnchorType::StarknetL3,
                    r#ref: alloc::vec![0xab; 32],
                    epoch: Some(42),
                    nullifier: None,
                    meta: None,
                }])
                .unwrap(),
            )
            .build()
            .expect("minimal_claim fixture")
    }

    fn fixture_evidence_stark() -> Evidence {
        Evidence::new(
            EvidenceScheme::Stark,
            alloc::vec![0xcd; 64],
            Some(EvidenceEnvelope::Stark(StarkProofEnvelope {
                scheme: "stark".into(),
                version: 1,
                proof: alloc::vec![0xcd; 64],
                public_inputs: alloc::vec![ByteString(alloc::vec![0x01; 32])],
                verifier_params: None,
                transcript_tag: None,
            })),
        )
        .unwrap()
    }
}