wai-quantum 0.4.0

A deterministic quantum stack in pure Rust: byte-exact circuit simulation (statevector / stabilizer / tensor-network MPS / sparse-Pauli backends), sparse Pauli dynamics at utility scale (arbitrary angles, 1024 qubits), belief-propagation tensor networks on the hardware graph, error mitigation, qLDPC decoding, noise learning, circuit-equivalence proofs, a phasor interference-ML layer, information-theoretic limits, noisy channels and state tomography, and signed energy-accounted receipts. No QPU, no cloud, no system libraries — identical results native, in the browser, and as a WASI component at the edge.
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
//! Quantum-circuit receipt — the energy-accounted seal for a
//! `wai.quantum.circuit` or `wai.quantum.circuit2` reconstruction
//! (extensions/quantum-sim § Receipt).
//!
//! This is the artifact WAI's determinism uniquely enables here: a signed record
//! that cleanly **separates the two halves** of a classical quantum-simulation's
//! cost, so each half is trusted the way it can honestly be trusted.
//!
//! - The **work** is *portable-exact*: `n_ops · 2^n` amplitude updates — a number
//!   anyone recomputes from `(n_ops, n_qubits)` alone, and which grows
//!   **exponentially** in qubits. It is the honest, machine-independent measure of
//!   what a classical sink actually did to reconstruct the state. **Verified by
//!   recomputation, not attested.**
//! - The **energy** is *measured-attested*: `joules_micro`, the real marginal CPU
//!   energy the sink's meter recorded (`wai_quantum_meter`, IOReport via `macmon`).
//!   Only the signer can vouch for what its own silicon drew. **Attested by
//!   signature, not verifiable by a third party.**
//!
//! The **`statevector_hash`** binds both to a byte-exact reconstruction anyone can
//! independently re-simulate and check ([`QuantumReceipt::verify_reconstruction`]).
//! So the receipt states, checkably: *"this circuit reconstructs to THIS
//! statevector [re-checkable], costing THIS exact deterministic work
//! [re-checkable], which drew THIS measured energy on my machine \[signed\]."*
//!
//! The figure's acquisition class is an optional label: a receipt sealed here
//! is unlabelled, with exactly the legacy bytes, and
//! `quantum_energy::Labelled::seal` labels and re-signs it (`quantum_energy`).
//!
//! The receipt's format is the same for both capabilities. It names its
//! capability through `circuit_hash`, which covers the circuit's contract and
//! so its [`Gateset`]: a circuit/1 receipt re-simulates only against the
//! circuit/1 circuit, never against its circuit2 twin with the same ops.
//! [`QuantumReceipt::gateset_of`] says which gateset a receipt was sealed
//! under, as a diagnosis when a reconstruction does not match.
//!
//! It is a JWP profile like every other receipt in this crate — the
//! worlds/provenance Merkle (`crate::merkle::merkle_root`) + Ed25519,
//! reused, not reinvented — and chains across a derivation via
//! `parent_receipt_hash`. Because a quantum computation carries no speedup here,
//! the receipt's value is exactly this: it makes the *cost* of the reconstruction
//! auditable, and the *result* reproducible.

use crate::quantum::{circuit_hash, Circuit, Gateset, Measure, QuantumError};
use crate::merkle::merkle_root;
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};

const DOMAIN_RECEIPT: &[u8] = b"wai:quantum-receipt\x01";
const DOMAIN_RECEIPT_ID: &[u8] = b"wai:quantum-receipt-id\x01";

fn hx(b: &[u8]) -> String {
    b.iter().map(|x| format!("{x:02x}")).collect()
}

fn from_hex32(s: &str) -> Option<[u8; 32]> {
    if s.len() != 64 || !s.bytes().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    let mut out = [0u8; 32];
    for (i, c) in s.as_bytes().chunks(2).enumerate() {
        out[i] = u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok()?;
    }
    Some(out)
}

fn from_hex64(s: &str) -> Option<[u8; 64]> {
    if s.len() != 128 || !s.bytes().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    let mut out = [0u8; 64];
    for (i, c) in s.as_bytes().chunks(2).enumerate() {
        out[i] = u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok()?;
    }
    Some(out)
}

/// The exact, portable, machine-independent reconstruction work in amplitude
/// updates: `n_ops · 2^n_qubits` (saturating). Every gate touches the whole
/// `2^n` state, so this is the count of complex fused-multiply-adds a faithful
/// statevector sink performs — the number that makes the *cost* auditable and
/// grows exponentially in qubits. Recomputable by anyone from the two inputs,
/// so a verifier never trusts the sink's claim of it.
pub fn work_amp_updates(n_qubits: u8, n_ops: u32) -> u64 {
    (n_ops as u64).saturating_mul(1u64 << n_qubits.min(63))
}

/// The measurement half of a receipt: a shot histogram at a pinned
/// `(seed, shots)` (sampled by the circuit's pinned `splitmix64`, so this hash
/// converges on every machine too — shot-histogram-equivalence).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MeasureRecord {
    pub seed: u64,
    pub shots: u64,
    pub histogram_hash: [u8; 32],
}

/// A signed, energy-accounted seal over one `wai.quantum.circuit` or
/// `wai.quantum.circuit2` reconstruction.
#[derive(Clone, Debug, PartialEq)]
pub struct QuantumReceipt {
    /// Identity: the WQC circuit hash (`crate::quantum::circuit_hash`), which
    /// binds the circuit's capability and phase table.
    pub circuit_hash: [u8; 32],
    /// The reconstruction result: the `2^n`-amplitude statevector's portable hash.
    pub statevector_hash: [u8; 32],
    pub n_qubits: u8,
    pub n_ops: u32,
    /// Present iff the receipt also vouches for a shot histogram.
    pub measurement: Option<MeasureRecord>,
    /// Merkle root over the receipt's leaf hashes (circuit, statevector,
    /// \[histogram\]) — JWP's exact domains, reused.
    pub merkle_root: [u8; 32],
    /// Exact, portable reconstruction work = `n_ops · 2^n` (see
    /// [`work_amp_updates`]). Verified by recomputation.
    pub work_amp_updates: u64,
    /// Measured microjoules the sink spent reconstructing (`0` = unmetered).
    /// Attested by the signature, not independently verifiable.
    pub joules_micro: u64,
    pub parent_receipt_hash: Option<[u8; 32]>,
    pub signer_pubkey: [u8; 32],
    pub signer_id: String,
    pub sig: [u8; 64],
}

impl QuantumReceipt {
    /// Leaf hashes, in fixed order: circuit hash, statevector hash, and (if the
    /// receipt vouches for a measurement) the histogram hash.
    fn leaves(&self) -> Vec<[u8; 32]> {
        let mut v = vec![self.circuit_hash, self.statevector_hash];
        if let Some(m) = &self.measurement {
            v.push(m.histogram_hash);
        }
        v
    }

    fn signing_payload(&self) -> Vec<u8> {
        self.payload_with(None)
    }

    /// The signing payload: unlabelled (the legacy bytes), or labelled
    /// (`crate::quantum_energy`) — the `0x02` domain, with the class after
    /// the figure it labels.
    fn payload_with(&self, label: Option<&crate::quantum_energy::EnergyClass>) -> Vec<u8> {
        let mut o = crate::quantum_energy::labelled_domain(DOMAIN_RECEIPT, label);
        o.extend_from_slice(&self.circuit_hash);
        o.extend_from_slice(&self.statevector_hash);
        o.push(self.n_qubits);
        o.extend_from_slice(&self.n_ops.to_be_bytes());
        o.extend_from_slice(&self.merkle_root);
        o.extend_from_slice(&self.work_amp_updates.to_be_bytes());
        o.extend_from_slice(&self.joules_micro.to_be_bytes());
        crate::quantum_energy::write_label(label, &mut o);
        match &self.measurement {
            Some(m) => {
                o.push(1);
                o.extend_from_slice(&m.seed.to_be_bytes());
                o.extend_from_slice(&m.shots.to_be_bytes());
                o.extend_from_slice(&m.histogram_hash);
            }
            None => o.push(0),
        }
        match self.parent_receipt_hash {
            Some(h) => {
                o.push(1);
                o.extend_from_slice(&h);
            }
            None => o.push(0),
        }
        o.extend_from_slice(&self.signer_pubkey);
        o.extend_from_slice(self.signer_id.as_bytes());
        o
    }

    /// Simulate `circuit`, then build and sign a receipt over the byte-exact
    /// reconstruction. Simulating *inside* seal is deliberate: the receipt's
    /// `statevector_hash` is always the true reconstruction, never a caller
    /// claim. `joules_micro` is the sink's measured energy (`0` if unmetered);
    /// pass `measure` to also vouch for a shot histogram.
    ///
    /// The circuit simulates under its own gateset, and the receipt binds that
    /// gateset's contract through `circuit_hash`. Fails as
    /// [`Circuit::simulate`] does.
    pub fn seal(
        signer: &SigningKey,
        signer_id: impl Into<String>,
        circuit: &Circuit,
        measure: Option<Measure>,
        joules_micro: u64,
        parent_receipt_hash: Option<[u8; 32]>,
    ) -> Result<QuantumReceipt, QuantumError> {
        let sv = circuit.simulate()?;
        let statevector_hash = sv.statevector_hash();
        let measurement = measure.map(|m| MeasureRecord {
            seed: m.seed,
            shots: m.shots,
            histogram_hash: sv.histogram_hash(m.seed, m.shots),
        });
        // `simulate` validated the circuit, which bounds its ops by `u32::MAX`.
        let mut r = QuantumReceipt {
            circuit_hash: circuit_hash(circuit)?,
            statevector_hash,
            n_qubits: circuit.n_qubits,
            n_ops: circuit.ops.len() as u32,
            measurement,
            merkle_root: [0u8; 32],
            work_amp_updates: work_amp_updates(circuit.n_qubits, circuit.ops.len() as u32),
            joules_micro,
            parent_receipt_hash,
            signer_pubkey: signer.verifying_key().to_bytes(),
            signer_id: signer_id.into(),
            sig: [0u8; 64],
        };
        r.merkle_root = merkle_root(&r.leaves());
        r.sig = signer.sign(&r.signing_payload()).to_bytes();
        Ok(r)
    }

    /// Every check [`Self::verify`] makes except the signature — shared with
    /// the labelled form (`crate::quantum_energy::Labelled`).
    fn body_verifies(&self) -> bool {
        if merkle_root(&self.leaves()) != self.merkle_root {
            return false;
        }
        if self.work_amp_updates != work_amp_updates(self.n_qubits, self.n_ops) {
            return false;
        }
        true
    }

    /// Verify the receipt is internally consistent and signed: the Merkle root
    /// recomputes over its leaves, the work equals `n_ops · 2^n` (a stated cost a
    /// sink cannot inflate), and the Ed25519 signature is valid. This does NOT
    /// re-run the simulation — see [`Self::verify_reconstruction`] for that.
    pub fn verify(&self) -> bool {
        if !self.body_verifies() {
            return false;
        }
        let Ok(k) = VerifyingKey::from_bytes(&self.signer_pubkey) else {
            return false;
        };
        k.verify(&self.signing_payload(), &Signature::from_bytes(&self.sig))
            .is_ok()
    }

    /// The strong, portable check: independently re-simulate `circuit` and
    /// confirm it reproduces this receipt's identity, reconstruction, shape, and
    /// (if present) histogram — then that the receipt itself verifies. Anyone
    /// holding the circuit can run this on any machine and reject a receipt whose
    /// claimed statevector is not what the circuit actually reconstructs to.
    /// (The measured `joules_micro` remains attested-only — re-simulation checks
    /// the *result and cost*, never the signer's energy draw.)
    ///
    /// The circuit is re-simulated under its own gateset, as decoded from its
    /// container. A receipt sealed under one gateset does not verify against
    /// the same ops in another; [`Self::gateset_of`] tells which one it was.
    pub fn verify_reconstruction(&self, circuit: &Circuit) -> bool {
        self.reconstruction_matches(circuit) && self.verify()
    }

    /// The gateset under which `circuit`'s ops hash to this receipt's
    /// `circuit_hash`, whatever gateset `circuit` itself carries; `None` when
    /// no gateset does.
    ///
    /// A migration aid, not a check: it matches the circuit hash alone and
    /// re-simulates nothing, and [`Self::verify_reconstruction`] stays strict.
    /// Use it to explain a failed reconstruction, as [`Self::gateset_note`]
    /// does.
    pub fn gateset_of(&self, circuit: &Circuit) -> Option<Gateset> {
        let mut twin = circuit.clone();
        Gateset::ALL.into_iter().find(|&gs| {
            twin.gateset = gs;
            circuit_hash(&twin).ok() == Some(self.circuit_hash)
        })
    }

    /// When `circuit`'s ops match this receipt under a gateset other than
    /// `circuit`'s own, the text that says so, for example `"this is a
    /// circuit/1 receipt; rebuild with Gateset::V1"`. `None` when the gateset
    /// is not the reason the reconstruction fails.
    pub fn gateset_note(&self, circuit: &Circuit) -> Option<String> {
        let gs = self.gateset_of(circuit).filter(|&gs| gs != circuit.gateset)?;
        let (name, variant) = match gs {
            Gateset::V1 => ("circuit/1", "V1"),
            Gateset::V2 => ("circuit2", "V2"),
        };
        Some(format!("this is a {name} receipt; rebuild with Gateset::{variant}"))
    }

    /// The re-simulation half of [`Self::verify_reconstruction`], shared with
    /// the labelled form (`crate::quantum_energy::Labelled`).
    pub(crate) fn reconstruction_matches(&self, circuit: &Circuit) -> bool {
        if circuit_hash(circuit).ok() != Some(self.circuit_hash) {
            return false;
        }
        // A circuit with a hash is valid, so its ops fit a `u32`.
        if circuit.n_qubits != self.n_qubits || circuit.ops.len() as u32 != self.n_ops {
            return false;
        }
        let Ok(sv) = circuit.simulate() else {
            return false;
        };
        if sv.statevector_hash() != self.statevector_hash {
            return false;
        }
        if let Some(m) = &self.measurement
            && sv.histogram_hash(m.seed, m.shots) != m.histogram_hash
        {
            return false;
        }
        true
    }

    /// Stable id for chaining a derived receipt via `parent_receipt_hash`.
    pub fn receipt_hash(&self) -> [u8; 32] {
        let mut h = blake3::Hasher::new();
        h.update(DOMAIN_RECEIPT_ID);
        h.update(&self.signing_payload());
        h.update(&self.sig);
        *h.finalize().as_bytes()
    }

    /// Canonical JSON (hex-encoded hashes), fields in sorted key order — the
    /// portable receipt an out-of-band verifier reads.
    pub fn to_json(&self) -> String {
        let parent = match self.parent_receipt_hash {
            Some(h) => format!("\"{}\"", hx(&h)),
            None => "null".into(),
        };
        let measurement = match &self.measurement {
            Some(m) => format!(
                "{{\"histogram_hash\":\"{}\",\"seed\":{},\"shots\":{}}}",
                hx(&m.histogram_hash),
                m.seed,
                m.shots
            ),
            None => "null".into(),
        };
        format!(
            "{{\"kind\":\"quantum-circuit\",\"circuit_hash\":\"{}\",\"joules_micro\":{},\
             \"measurement\":{},\"n_ops\":{},\"n_qubits\":{},\"parent_receipt_hash\":{},\
             \"receipt_hash\":\"{}\",\"root_hash\":\"{}\",\"sig\":\"{}\",\"signer_id\":{},\
             \"signer_pubkey\":\"{}\",\"statevector_hash\":\"{}\",\"work_amp_updates\":{}}}",
            hx(&self.circuit_hash),
            self.joules_micro,
            measurement,
            self.n_ops,
            self.n_qubits,
            parent,
            hx(&self.receipt_hash()),
            hx(&self.merkle_root),
            hx(&self.sig),
            serde_json::to_string(&self.signer_id).unwrap(),
            hx(&self.signer_pubkey),
            hx(&self.statevector_hash),
            self.work_amp_updates,
        )
    }

    /// Parse a receipt from its canonical JSON (for a verifying sink).
    /// `n_qubits` must fit a `u8` and `n_ops` a `u32`; a value that does not
    /// is refused, never truncated.
    pub fn from_json(s: &str) -> Option<QuantumReceipt> {
        let v: serde_json::Value = serde_json::from_str(s).ok()?;
        let o = v.as_object()?;
        let u = |k: &str| o.get(k).and_then(|x| x.as_u64());
        let measurement = match o.get("measurement") {
            Some(serde_json::Value::Object(m)) => Some(MeasureRecord {
                seed: m.get("seed")?.as_u64()?,
                shots: m.get("shots")?.as_u64()?,
                histogram_hash: from_hex32(m.get("histogram_hash")?.as_str()?)?,
            }),
            _ => None,
        };
        let parent = match o.get("parent_receipt_hash") {
            Some(serde_json::Value::String(s)) => Some(from_hex32(s)?),
            _ => None,
        };
        Some(QuantumReceipt {
            circuit_hash: from_hex32(o.get("circuit_hash")?.as_str()?)?,
            statevector_hash: from_hex32(o.get("statevector_hash")?.as_str()?)?,
            n_qubits: u8::try_from(u("n_qubits")?).ok()?,
            n_ops: u32::try_from(u("n_ops")?).ok()?,
            measurement,
            merkle_root: from_hex32(o.get("root_hash")?.as_str()?)?,
            work_amp_updates: u("work_amp_updates")?,
            joules_micro: u("joules_micro")?,
            parent_receipt_hash: parent,
            signer_pubkey: from_hex32(o.get("signer_pubkey")?.as_str()?)?,
            signer_id: o.get("signer_id")?.as_str()?.to_owned(),
            sig: from_hex64(o.get("sig")?.as_str()?)?,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::quantum::Circuit;

    fn key(s: u8) -> SigningKey {
        SigningKey::from_bytes(&[s; 32])
    }

    #[test]
    fn seals_verifies_and_reconstructs() {
        let mut c = Circuit::new(3);
        c.h(0).cx(0, 1).cx(1, 2); // GHZ-3
        let r =
            QuantumReceipt::seal(&key(1), "did:key:test", &c, None, 117_000, None).unwrap();
        assert!(r.verify());
        assert!(r.verify_reconstruction(&c));
        // work is the exact, recomputable cost: 3 ops · 2^3 = 24 amplitude updates.
        assert_eq!(r.work_amp_updates, 24);
        assert_eq!(r.n_qubits, 3);
        assert_eq!(r.n_ops, 3);
        assert_eq!(r.joules_micro, 117_000);
    }

    #[test]
    fn measurement_histogram_is_vouched() {
        let mut c = Circuit::new(2);
        c.h(0).cx(0, 1); // Bell
        let m = Measure { seed: 0xC0FFEE, shots: 10_000 };
        let r = QuantumReceipt::seal(&key(2), "m", &c, Some(m), 0, None).unwrap();
        assert!(r.verify());
        assert!(r.verify_reconstruction(&c));
        let mr = r.measurement.expect("measurement present");
        assert_eq!(mr.seed, 0xC0FFEE);
        assert_eq!(mr.shots, 10_000);
    }

    #[test]
    fn tamper_breaks_verification() {
        let mut c = Circuit::new(2);
        c.h(0).cx(0, 1);
        let mut r = QuantumReceipt::seal(&key(3), "m", &c, None, 42, None).unwrap();
        // Flipping the claimed energy (a signed field) breaks the signature.
        r.joules_micro = 43;
        assert!(!r.verify());
    }

    #[test]
    fn a_lie_about_the_statevector_is_caught_by_resimulation() {
        let mut c = Circuit::new(2);
        c.h(0).cx(0, 1);
        let honest = QuantumReceipt::seal(&key(4), "m", &c, None, 0, None).unwrap();
        // A different circuit reconstructs to a different statevector; a receipt
        // that claims `honest`'s statevector for it must fail re-simulation.
        let mut other = Circuit::new(2);
        other.h(0); // NOT entangled — different state
        assert!(!honest.verify_reconstruction(&other));
    }

    #[test]
    fn json_round_trips() {
        let mut c = Circuit::new(3);
        c.h(0).cx(0, 1).cx(1, 2);
        let m = Measure { seed: 7, shots: 512 };
        let r = QuantumReceipt::seal(&key(5), "did:key:z6Mk", &c, Some(m), 900, None).unwrap();
        let back = QuantumReceipt::from_json(&r.to_json()).expect("parse");
        assert_eq!(r, back);
        assert!(back.verify());
    }

    #[test]
    fn chains_to_a_parent() {
        let mut c = Circuit::new(2);
        c.h(0).cx(0, 1);
        let root = QuantumReceipt::seal(&key(6), "m", &c, None, 10, None).unwrap();
        let mut c2 = Circuit::new(2);
        c2.h(0).cx(0, 1).z(1); // a derived run
        let child =
            QuantumReceipt::seal(&key(6), "m", &c2, None, 12, Some(root.receipt_hash()))
                .unwrap();
        assert!(child.verify());
        assert_eq!(child.parent_receipt_hash, Some(root.receipt_hash()));
    }

    /// GHZ-3 in `gs`. Its `H` reads the gateset's table, so the two gatesets
    /// give different statevectors as well as different circuit hashes.
    fn ghz3(gs: Gateset) -> Circuit {
        let mut c = Circuit::with_gateset(3, gs);
        c.h(0).cx(0, 1).cx(1, 2);
        c
    }

    #[test]
    fn a_receipt_reconstructs_only_under_its_own_gateset() {
        let m = Measure { seed: 7, shots: 1024 };
        for gs in Gateset::ALL {
            let r = QuantumReceipt::seal(&key(7), "m", &ghz3(gs), Some(m), 0, None).unwrap();
            assert!(r.verify_reconstruction(&ghz3(gs)));
            assert_eq!(r.gateset_of(&ghz3(gs)), Some(gs));
            assert_eq!(r.gateset_note(&ghz3(gs)), None);
            for other in Gateset::ALL.into_iter().filter(|&o| o != gs) {
                // The twin has the same ops and fails cleanly: no panic, a
                // false, and a diagnosis naming the receipt's gateset.
                let twin = ghz3(other);
                assert!(!r.verify_reconstruction(&twin), "{gs:?} receipt against its {other:?} twin");
                assert_eq!(r.gateset_of(&twin), Some(gs));
                assert!(r.gateset_note(&twin).is_some());
            }
        }
        // A circuit/1 receipt against its circuit2 twin, by name.
        let v1 = QuantumReceipt::seal(&key(7), "m", &ghz3(Gateset::V1), None, 0, None).unwrap();
        let v2_twin = ghz3(Gateset::V2);
        assert!(!v1.verify_reconstruction(&v2_twin));
        assert_eq!(v1.gateset_of(&v2_twin), Some(Gateset::V1));
        assert_eq!(v1.gateset_note(&v2_twin).as_deref(), Some("this is a circuit/1 receipt; rebuild with Gateset::V1"));
        let v2 = QuantumReceipt::seal(&key(7), "m", &v2_twin, None, 0, None).unwrap();
        assert_eq!(v2.gateset_note(&ghz3(Gateset::V1)).as_deref(), Some("this is a circuit2 receipt; rebuild with Gateset::V2"));
        // The gateset is bound even where it changes no amplitude: X and CX
        // read no table, so the twins reconstruct to one statevector, and the
        // receipt still holds only its own.
        let clifford = |gs| {
            let mut c = Circuit::with_gateset(2, gs);
            c.x(0).cx(0, 1);
            c
        };
        assert_eq!(clifford(Gateset::V1).simulate().unwrap(), clifford(Gateset::V2).simulate().unwrap());
        let r = QuantumReceipt::seal(&key(7), "m", &clifford(Gateset::V1), None, 0, None).unwrap();
        assert!(r.verify_reconstruction(&clifford(Gateset::V1)));
        assert!(!r.verify_reconstruction(&clifford(Gateset::V2)));
        // Ops that match under no gateset get no diagnosis.
        let mut unrelated = Circuit::with_gateset(3, Gateset::V1);
        unrelated.h(1);
        assert_eq!(v1.gateset_of(&unrelated), None);
        assert_eq!(v1.gateset_note(&unrelated), None);
        // Ops only circuit/1 allows still get their diagnosis: repeated
        // controls hash in circuit/1, and circuit2 refuses them.
        let mut repeated = Circuit::with_gateset(3, Gateset::V1);
        repeated.ops.push(crate::quantum::Gate { base: crate::quantum::BaseGate::X, controls: vec![0, 0], target: 1, param: 0 });
        let r = QuantumReceipt::seal(&key(7), "m", &repeated, None, 0, None).unwrap();
        let mut repeated_v2 = repeated.clone();
        repeated_v2.gateset = Gateset::V2;
        assert!(!r.verify_reconstruction(&repeated_v2));
        assert_eq!(r.gateset_of(&repeated_v2), Some(Gateset::V1));
    }

    /// A receipt that names one gateset's circuit and claims the other's
    /// statevector: well signed and internally consistent, and reconstructed
    /// by neither circuit.
    #[test]
    fn a_cross_gateset_forgery_is_rejected() {
        let forger = key(9);
        let (seed, shots) = (7, 1024);
        for (named, simulated) in [(Gateset::V1, Gateset::V2), (Gateset::V2, Gateset::V1)] {
            let mut r = QuantumReceipt::seal(&forger, "m", &ghz3(named), Some(Measure { seed, shots }), 0, None).unwrap();
            let sv = ghz3(simulated).simulate().unwrap();
            assert_ne!(sv.statevector_hash(), r.statevector_hash);
            r.statevector_hash = sv.statevector_hash();
            r.measurement = Some(MeasureRecord { seed, shots, histogram_hash: sv.histogram_hash(seed, shots) });
            r.merkle_root = merkle_root(&r.leaves());
            r.sig = forger.sign(&r.signing_payload()).to_bytes();
            assert!(r.verify(), "the forgery is well signed");
            for gs in Gateset::ALL {
                assert!(!r.verify_reconstruction(&ghz3(gs)), "named {named:?}, simulated {simulated:?}, checked {gs:?}");
            }
        }
    }

    #[test]
    fn json_refuses_counts_that_do_not_fit() {
        let r = QuantumReceipt::seal(&key(5), "m", &ghz3(Gateset::V2), None, 0, None).unwrap();
        let j = r.to_json();
        assert!(j.contains("\"n_qubits\":3,") && j.contains("\"n_ops\":3,"), "{j}");
        // 258 is 2 modulo 256, and 2^32 + 3 is 3 modulo 2^32: neither may be
        // read as the smaller number.
        assert!(QuantumReceipt::from_json(&j.replace("\"n_qubits\":3,", "\"n_qubits\":258,")).is_none());
        assert!(QuantumReceipt::from_json(&j.replace("\"n_qubits\":3,", "\"n_qubits\":256,")).is_none());
        assert!(QuantumReceipt::from_json(&j.replace("\"n_ops\":3,", "\"n_ops\":4294967299,")).is_none());
        // The largest values that fit still parse.
        let widest = j.replace("\"n_qubits\":3,", "\"n_qubits\":255,").replace("\"n_ops\":3,", "\"n_ops\":4294967295,");
        let back = QuantumReceipt::from_json(&widest).expect("fits");
        assert_eq!((back.n_qubits, back.n_ops), (255, u32::MAX));
    }
}

crate::quantum_energy::labellable!(QuantumReceipt, DOMAIN_RECEIPT_ID);