engenho-substrate 0.53.147

engenho-substrate — the substrate leaf: every module a shipped engenho crate references (derivations and caches, receipts, quorum, ledgers, verifiers, rollout gates, freshness, owned tasks), with engenho-substrate-core re-exported whole so every engenho_substrate:: path keeps resolving.
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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
//! Concrete `Verifier` impls for the roça verification layer.
//!
//! Three implementations land here, each pluggable + composable
//! through `ChainedVerifier`:
//!
//!   * [`HashEqualityVerifier`] — recomputes BLAKE3 over given
//!     bytes; compares to the `Verificacao::HashEquality.expected`
//!     value. The substrate's cryptographic equality check.
//!
//!   * [`SmokeTestVerifier`] — runs a smoke-test drv through a
//!     pluggable `BuildBackend`-shape function; success of the
//!     build itself is the verification proof.
//!
//!   * [`IndependentVerifier`] — runs a second build path
//!     (operator-supplied async closure that returns NAR bytes)
//!     + emits a receipt whose evidence is the BLAKE3 of those
//!     bytes. Downstream `QuorumTracker` surfaces a Dissent
//!     outcome if the independent rebuild produces a different
//!     hash from the primary materializer's claim.

#[cfg(test)]
use std::sync::Arc;

use async_trait::async_trait;

use crate::derivation::NarHash;
use crate::receipt::{MaterializationReceipt, NodeId, ReceiptKind};
use crate::verifier::{Verificacao, VerificationReceipt, Verifier, VerifyError};

// =================================================================
// HashEqualityVerifier
// =================================================================

crate::async_closure_type! {
    /// Operator-supplied accessor that returns the bytes the verifier
    /// should hash for `subject_hash`. Production wires this to the
    /// `DerivationCacheBackend::get_nar` path; tests pin a synthetic
    /// byte-source.
    pub type BytesAccessor = ([u8; 32]) -> Result<Option<Vec<u8>>, VerifyError>;
}

/// Recomputes BLAKE3 of the bytes the accessor returns + compares
/// to the predicate's `expected` NAR hash. Only implements the
/// `HashEquality` variant; other Verificacao kinds return
/// `Unsupported`.
pub struct HashEqualityVerifier {
    name: &'static str,
    accessor: BytesAccessor,
}

impl HashEqualityVerifier {
    /// New verifier with telemetry name + bytes accessor.
    #[must_use]
    pub fn new(name: &'static str, accessor: BytesAccessor) -> Self {
        Self { name, accessor }
    }

    /// Convenience constructor with name `"hash-equality"`.
    #[must_use]
    pub fn default_named(accessor: BytesAccessor) -> Self {
        Self::new("hash-equality", accessor)
    }
}

#[async_trait]
impl Verifier for HashEqualityVerifier {
    fn name(&self) -> &'static str {
        self.name
    }

    async fn verify(
        &self,
        verificacao: &Verificacao,
        subject_hash: [u8; 32],
        emitter: NodeId,
        emitted_at: u64,
    ) -> Result<VerificationReceipt, VerifyError> {
        let expected = match verificacao {
            Verificacao::HashEquality { expected } => expected.clone(),
            _ => {
                return Err(VerifyError::Unsupported(
                    "HashEqualityVerifier only handles HashEquality".into(),
                ));
            }
        };
        let bytes = match (self.accessor)(subject_hash).await? {
            Some(b) => b,
            None => {
                return Err(VerifyError::Failed(format!(
                    "no bytes available for subject {}",
                    hex_encode(&subject_hash)
                )));
            }
        };
        let actual = NarHash::from_bytes(&bytes);
        if actual != expected {
            return Err(VerifyError::Failed(format!(
                "hash mismatch: expected {} got {}",
                expected, actual
            )));
        }
        let receipt = MaterializationReceipt::new(
            ReceiptKind::Shape("verify:hash_equality".into()),
            subject_hash,
            emitter,
            emitted_at,
            actual.0,
        );
        Ok(VerificationReceipt::new(
            verificacao.clone(),
            receipt,
            self.name.to_string(),
        ))
    }
}

// =================================================================
// SmokeTestVerifier
// =================================================================

crate::async_closure_type! {
    /// Operator-supplied function: given a `drv_hash_hex`, attempts a
    /// smoke-test build + returns Ok on success / Err on build failure.
    /// Production wires this to a BuildBackend-shape adapter; tests pin
    /// a deterministic outcome.
    pub type SmokeBuilder = (String) -> Result<(), VerifyError>;
}

/// Runs a smoke-test drv via an operator-supplied builder; success
/// of the build IS the verification proof.
pub struct SmokeTestVerifier {
    name: &'static str,
    builder: SmokeBuilder,
}

impl SmokeTestVerifier {
    /// New verifier with telemetry name + builder.
    #[must_use]
    pub fn new(name: &'static str, builder: SmokeBuilder) -> Self {
        Self { name, builder }
    }

    /// Convenience: name `"smoke-test"`.
    #[must_use]
    pub fn default_named(builder: SmokeBuilder) -> Self {
        Self::new("smoke-test", builder)
    }
}

#[async_trait]
impl Verifier for SmokeTestVerifier {
    fn name(&self) -> &'static str {
        self.name
    }

    async fn verify(
        &self,
        verificacao: &Verificacao,
        subject_hash: [u8; 32],
        emitter: NodeId,
        emitted_at: u64,
    ) -> Result<VerificationReceipt, VerifyError> {
        let drv_hex = match verificacao {
            Verificacao::SmokeTest { drv_hash_hex } => drv_hash_hex.clone(),
            _ => {
                return Err(VerifyError::Unsupported(
                    "SmokeTestVerifier only handles SmokeTest".into(),
                ));
            }
        };
        (self.builder)(drv_hex.clone()).await?;
        // Evidence: BLAKE3 over (smoke-test drv hash hex + subject_hash hex).
        // Same smoke test on different nodes produces same evidence
        // → QuorumTracker reaches Reached.
        let mut composed = drv_hex.into_bytes();
        composed.extend_from_slice(&subject_hash);
        let evidence = *blake3::hash(&composed).as_bytes();
        let receipt = MaterializationReceipt::new(
            ReceiptKind::Shape("verify:smoke_test".into()),
            subject_hash,
            emitter,
            emitted_at,
            evidence,
        );
        Ok(VerificationReceipt::new(
            verificacao.clone(),
            receipt,
            self.name.to_string(),
        ))
    }
}

// =================================================================
// IndependentVerifier
// =================================================================

crate::async_closure_type! {
    /// Operator-supplied independent rebuild: given the subject hash,
    /// runs an alternate build path + returns the NAR bytes the
    /// rebuild produced.
    pub type IndependentRebuild = ([u8; 32]) -> Result<Vec<u8>, VerifyError>;
}

/// Re-derives via a second backend; emits a receipt whose evidence
/// is BLAKE3 over the rebuilt bytes. Downstream `QuorumTracker`
/// surfaces Dissent if this evidence differs from the primary
/// materializer's claim.
pub struct IndependentVerifier {
    name: &'static str,
    rebuild: IndependentRebuild,
}

impl IndependentVerifier {
    /// New verifier with telemetry name + rebuild function.
    #[must_use]
    pub fn new(name: &'static str, rebuild: IndependentRebuild) -> Self {
        Self { name, rebuild }
    }

    /// Convenience: name `"independent"`.
    #[must_use]
    pub fn default_named(rebuild: IndependentRebuild) -> Self {
        Self::new("independent", rebuild)
    }
}

#[async_trait]
impl Verifier for IndependentVerifier {
    fn name(&self) -> &'static str {
        self.name
    }

    async fn verify(
        &self,
        verificacao: &Verificacao,
        subject_hash: [u8; 32],
        emitter: NodeId,
        emitted_at: u64,
    ) -> Result<VerificationReceipt, VerifyError> {
        match verificacao {
            Verificacao::Independent { .. } => {}
            _ => {
                return Err(VerifyError::Unsupported(
                    "IndependentVerifier only handles Independent".into(),
                ));
            }
        }
        let bytes = (self.rebuild)(subject_hash).await?;
        let evidence = *blake3::hash(&bytes).as_bytes();
        let receipt = MaterializationReceipt::new(
            ReceiptKind::Shape("verify:independent".into()),
            subject_hash,
            emitter,
            emitted_at,
            evidence,
        );
        Ok(VerificationReceipt::new(
            verificacao.clone(),
            receipt,
            self.name.to_string(),
        ))
    }
}

// =================================================================
// TameshiVerifier
// =================================================================

crate::async_closure_type! {
    /// Operator-supplied signature check: given a `signer` chain id +
    /// the subject hash, returns the typed evidence (typically the
    /// signature bytes) or a typed error. Production wires this to the
    /// cosign / tameshi PKI integration; tests pin a deterministic
    /// outcome.
    pub type SignerCheck = (String, [u8; 32]) -> Result<Vec<u8>, VerifyError>;
}

/// Verifies cosign-style signatures via an operator-supplied check.
/// Evidence is BLAKE3 over the returned signature bytes — faithful
/// nodes presenting the same signature for the same subject produce
/// identical evidence (QuorumTracker reaches; tampered nodes
/// produce a divergent signature → Dissent).
pub struct TameshiVerifier {
    name: &'static str,
    check: SignerCheck,
}

impl TameshiVerifier {
    /// New verifier with telemetry name + signature check.
    #[must_use]
    pub fn new(name: &'static str, check: SignerCheck) -> Self {
        Self { name, check }
    }

    /// Convenience: name `"tameshi"`.
    #[must_use]
    pub fn default_named(check: SignerCheck) -> Self {
        Self::new("tameshi", check)
    }
}

#[async_trait]
impl Verifier for TameshiVerifier {
    fn name(&self) -> &'static str {
        self.name
    }

    async fn verify(
        &self,
        verificacao: &Verificacao,
        subject_hash: [u8; 32],
        emitter: NodeId,
        emitted_at: u64,
    ) -> Result<VerificationReceipt, VerifyError> {
        let signer = match verificacao {
            Verificacao::TameshiSigned { signer } => signer.clone(),
            _ => {
                return Err(VerifyError::Unsupported(
                    "TameshiVerifier only handles TameshiSigned".into(),
                ));
            }
        };
        let sig_bytes = (self.check)(signer, subject_hash).await?;
        let evidence = *blake3::hash(&sig_bytes).as_bytes();
        let receipt = MaterializationReceipt::new(
            ReceiptKind::Shape("verify:tameshi_signed".into()),
            subject_hash,
            emitter,
            emitted_at,
            evidence,
        );
        Ok(VerificationReceipt::new(
            verificacao.clone(),
            receipt,
            self.name.to_string(),
        ))
    }
}

// =================================================================
// hex helper (shared)
// =================================================================

// hex_encode lives in crate::hex now (PRIME DIRECTIVE extraction).
use crate::hex::hex_encode;

#[cfg(test)]
mod tests {
    use super::*;
    use futures::FutureExt;

    fn subj() -> [u8; 32] {
        *blake3::hash(b"subj").as_bytes()
    }

    fn emit() -> NodeId {
        NodeId::from_bytes(b"n")
    }

    // ── HashEqualityVerifier ───────────────────────────────────

    fn bytes_accessor_returning(bytes: Vec<u8>) -> BytesAccessor {
        Arc::new(move |_hash| {
            let b = bytes.clone();
            async move { Ok(Some(b)) }.boxed()
        })
    }

    fn bytes_accessor_none() -> BytesAccessor {
        Arc::new(|_hash| async move { Ok(None) }.boxed())
    }

    #[tokio::test]
    async fn hash_equality_passes_when_bytes_match() {
        let bytes = b"hello-nar".to_vec();
        let expected = NarHash::from_bytes(&bytes);
        let v = HashEqualityVerifier::default_named(bytes_accessor_returning(bytes));
        let r = v
            .verify(
                &Verificacao::HashEquality {
                    expected: expected.clone(),
                },
                subj(),
                emit(),
                42,
            )
            .await
            .unwrap();
        assert_eq!(r.receipt.evidence_hash, expected.0);
    }

    #[tokio::test]
    async fn hash_equality_fails_when_bytes_differ() {
        let v = HashEqualityVerifier::default_named(bytes_accessor_returning(b"actual".to_vec()));
        let err = v
            .verify(
                &Verificacao::HashEquality {
                    expected: NarHash::from_bytes(b"different"),
                },
                subj(),
                emit(),
                42,
            )
            .await
            .unwrap_err();
        assert_eq!(err.kind(), "failed");
    }

    #[tokio::test]
    async fn hash_equality_fails_when_no_bytes_available() {
        let v = HashEqualityVerifier::default_named(bytes_accessor_none());
        let err = v
            .verify(
                &Verificacao::HashEquality {
                    expected: NarHash::from_bytes(b"x"),
                },
                subj(),
                emit(),
                42,
            )
            .await
            .unwrap_err();
        assert_eq!(err.kind(), "failed");
    }

    #[tokio::test]
    async fn hash_equality_rejects_wrong_variant() {
        let v = HashEqualityVerifier::default_named(bytes_accessor_returning(vec![]));
        let err = v
            .verify(
                &Verificacao::SmokeTest {
                    drv_hash_hex: "abc".into(),
                },
                subj(),
                emit(),
                42,
            )
            .await
            .unwrap_err();
        assert_eq!(err.kind(), "unsupported");
    }

    #[tokio::test]
    async fn hash_equality_name_is_configurable() {
        let v = HashEqualityVerifier::new("custom", bytes_accessor_returning(vec![]));
        assert_eq!(v.name(), "custom");
    }

    #[tokio::test]
    async fn hash_equality_default_name() {
        let v = HashEqualityVerifier::default_named(bytes_accessor_returning(vec![]));
        assert_eq!(v.name(), "hash-equality");
    }

    // ── SmokeTestVerifier ──────────────────────────────────────

    fn smoke_succeeds() -> SmokeBuilder {
        Arc::new(|_| async move { Ok(()) }.boxed())
    }

    fn smoke_fails(msg: &'static str) -> SmokeBuilder {
        Arc::new(move |_| async move { Err(VerifyError::Backend(msg.into())) }.boxed())
    }

    #[tokio::test]
    async fn smoke_test_passes_when_build_succeeds() {
        let v = SmokeTestVerifier::default_named(smoke_succeeds());
        let r = v
            .verify(
                &Verificacao::SmokeTest {
                    drv_hash_hex: "abc".into(),
                },
                subj(),
                emit(),
                42,
            )
            .await
            .unwrap();
        assert_eq!(r.verifier, "smoke-test");
    }

    #[tokio::test]
    async fn smoke_test_fails_when_build_fails() {
        let v = SmokeTestVerifier::default_named(smoke_fails("nope"));
        let err = v
            .verify(
                &Verificacao::SmokeTest {
                    drv_hash_hex: "abc".into(),
                },
                subj(),
                emit(),
                42,
            )
            .await
            .unwrap_err();
        assert_eq!(err.kind(), "backend");
    }

    #[tokio::test]
    async fn smoke_test_rejects_wrong_variant() {
        let v = SmokeTestVerifier::default_named(smoke_succeeds());
        let err = v
            .verify(
                &Verificacao::HashEquality {
                    expected: NarHash::from_bytes(b"x"),
                },
                subj(),
                emit(),
                42,
            )
            .await
            .unwrap_err();
        assert_eq!(err.kind(), "unsupported");
    }

    #[tokio::test]
    async fn smoke_test_evidence_is_deterministic_for_same_drv() {
        let v = SmokeTestVerifier::default_named(smoke_succeeds());
        let r1 = v
            .verify(
                &Verificacao::SmokeTest {
                    drv_hash_hex: "abc".into(),
                },
                subj(),
                emit(),
                42,
            )
            .await
            .unwrap();
        let r2 = v
            .verify(
                &Verificacao::SmokeTest {
                    drv_hash_hex: "abc".into(),
                },
                subj(),
                NodeId::from_bytes(b"different-node"),
                100, // different timestamp
            )
            .await
            .unwrap();
        // Faithful smoke test → identical evidence across nodes.
        assert_eq!(r1.receipt.evidence_hash, r2.receipt.evidence_hash);
    }

    #[tokio::test]
    async fn smoke_test_default_name() {
        let v = SmokeTestVerifier::default_named(smoke_succeeds());
        assert_eq!(v.name(), "smoke-test");
    }

    // ── IndependentVerifier ────────────────────────────────────

    fn rebuild_returning(bytes: Vec<u8>) -> IndependentRebuild {
        Arc::new(move |_subject| {
            let b = bytes.clone();
            async move { Ok(b) }.boxed()
        })
    }

    fn rebuild_failing(msg: &'static str) -> IndependentRebuild {
        Arc::new(move |_| async move { Err(VerifyError::Backend(msg.into())) }.boxed())
    }

    #[tokio::test]
    async fn independent_passes_with_evidence_from_rebuild() {
        let bytes = b"alt-nar".to_vec();
        let expected_evidence = *blake3::hash(&bytes).as_bytes();
        let v = IndependentVerifier::default_named(rebuild_returning(bytes));
        let r = v
            .verify(
                &Verificacao::Independent {
                    backend: "alt".into(),
                },
                subj(),
                emit(),
                42,
            )
            .await
            .unwrap();
        assert_eq!(r.receipt.evidence_hash, expected_evidence);
    }

    #[tokio::test]
    async fn independent_propagates_rebuild_failure() {
        let v = IndependentVerifier::default_named(rebuild_failing("rebuild died"));
        let err = v
            .verify(
                &Verificacao::Independent {
                    backend: "alt".into(),
                },
                subj(),
                emit(),
                42,
            )
            .await
            .unwrap_err();
        assert_eq!(err.kind(), "backend");
    }

    #[tokio::test]
    async fn independent_rejects_wrong_variant() {
        let v = IndependentVerifier::default_named(rebuild_returning(vec![]));
        let err = v
            .verify(
                &Verificacao::SmokeTest {
                    drv_hash_hex: "x".into(),
                },
                subj(),
                emit(),
                42,
            )
            .await
            .unwrap_err();
        assert_eq!(err.kind(), "unsupported");
    }

    #[tokio::test]
    async fn independent_default_name() {
        let v = IndependentVerifier::default_named(rebuild_returning(vec![]));
        assert_eq!(v.name(), "independent");
    }

    // ── TameshiVerifier ────────────────────────────────────────

    fn sig_returning(bytes: Vec<u8>) -> SignerCheck {
        Arc::new(move |_signer, _subject| {
            let b = bytes.clone();
            async move { Ok(b) }.boxed()
        })
    }

    fn sig_failing(msg: &'static str) -> SignerCheck {
        Arc::new(move |_, _| async move { Err(VerifyError::Backend(msg.into())) }.boxed())
    }

    #[tokio::test]
    async fn tameshi_passes_when_signer_returns_signature() {
        let v = TameshiVerifier::default_named(sig_returning(b"sig-bytes".to_vec()));
        let r = v
            .verify(
                &Verificacao::TameshiSigned {
                    signer: "engenho-pki".into(),
                },
                subj(),
                emit(),
                42,
            )
            .await
            .unwrap();
        assert_eq!(r.verifier, "tameshi");
        assert_eq!(
            r.receipt.evidence_hash,
            *blake3::hash(b"sig-bytes").as_bytes()
        );
    }

    #[tokio::test]
    async fn tameshi_propagates_signer_failure() {
        let v = TameshiVerifier::default_named(sig_failing("untrusted"));
        let err = v
            .verify(
                &Verificacao::TameshiSigned {
                    signer: "engenho-pki".into(),
                },
                subj(),
                emit(),
                42,
            )
            .await
            .unwrap_err();
        assert_eq!(err.kind(), "backend");
    }

    #[tokio::test]
    async fn tameshi_rejects_wrong_variant() {
        let v = TameshiVerifier::default_named(sig_returning(vec![]));
        let err = v
            .verify(
                &Verificacao::HashEquality {
                    expected: NarHash::from_bytes(b"x"),
                },
                subj(),
                emit(),
                42,
            )
            .await
            .unwrap_err();
        assert_eq!(err.kind(), "unsupported");
    }

    #[tokio::test]
    async fn tameshi_faithful_nodes_agree_on_evidence() {
        let v = TameshiVerifier::default_named(sig_returning(b"sig".to_vec()));
        let r1 = v
            .verify(
                &Verificacao::TameshiSigned {
                    signer: "engenho-pki".into(),
                },
                subj(),
                NodeId::from_bytes(b"node-1"),
                42,
            )
            .await
            .unwrap();
        let r2 = v
            .verify(
                &Verificacao::TameshiSigned {
                    signer: "engenho-pki".into(),
                },
                subj(),
                NodeId::from_bytes(b"node-2"),
                100,
            )
            .await
            .unwrap();
        // Same signature bytes → same evidence (QuorumTracker reaches).
        assert_eq!(r1.receipt.evidence_hash, r2.receipt.evidence_hash);
    }

    #[tokio::test]
    async fn tameshi_byzantine_node_diverges() {
        let v_real = TameshiVerifier::default_named(sig_returning(b"valid".to_vec()));
        let v_byz = TameshiVerifier::default_named(sig_returning(b"forged".to_vec()));
        let r_real = v_real
            .verify(
                &Verificacao::TameshiSigned {
                    signer: "engenho-pki".into(),
                },
                subj(),
                emit(),
                42,
            )
            .await
            .unwrap();
        let r_byz = v_byz
            .verify(
                &Verificacao::TameshiSigned {
                    signer: "engenho-pki".into(),
                },
                subj(),
                emit(),
                42,
            )
            .await
            .unwrap();
        // Different signature bytes → different evidence → Dissent
        // when QuorumTracker sees both.
        assert_ne!(r_real.receipt.evidence_hash, r_byz.receipt.evidence_hash);
    }

    #[tokio::test]
    async fn tameshi_default_name() {
        let v = TameshiVerifier::default_named(sig_returning(vec![]));
        assert_eq!(v.name(), "tameshi");
    }

    #[tokio::test]
    async fn tameshi_custom_name() {
        let v = TameshiVerifier::new("cosign-chain-prod", sig_returning(vec![]));
        assert_eq!(v.name(), "cosign-chain-prod");
    }

    #[tokio::test]
    async fn independent_disagrees_when_rebuild_differs_from_primary() {
        // The independent verifier emits evidence = BLAKE3(alt bytes).
        // If the alt path produces DIFFERENT bytes than the primary
        // materializer's claim, downstream QuorumTracker would
        // observe two distinct evidence hashes → Dissent.
        let v_primary_matching =
            IndependentVerifier::default_named(rebuild_returning(b"X".to_vec()));
        let v_primary_diff = IndependentVerifier::default_named(rebuild_returning(b"Y".to_vec()));
        let r1 = v_primary_matching
            .verify(
                &Verificacao::Independent {
                    backend: "alt".into(),
                },
                subj(),
                emit(),
                42,
            )
            .await
            .unwrap();
        let r2 = v_primary_diff
            .verify(
                &Verificacao::Independent {
                    backend: "alt".into(),
                },
                subj(),
                emit(),
                42,
            )
            .await
            .unwrap();
        assert_ne!(r1.receipt.evidence_hash, r2.receipt.evidence_hash);
    }
}