wai-quantum 0.3.38

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
//! Signed-byte pins for every receipt in this crate that seals `joules_micro`.
//!
//! These receipts carried their energy figure with no acquisition class
//! before they were given an optional one. A receipt sealed without a class
//! must keep exactly the signed bytes it had before, or every receipt
//! already issued stops verifying. Each test builds one
//! fixed, unlabelled receipt with a non-zero figure and pins, as computed by
//! the code *before* the class was added:
//!
//! - `receipt_hash()`, which covers the whole signing payload and the
//!   signature;
//! - a BLAKE3 hash of `to_json()`, so the rendered form is byte-identical too.
//!
//! The hex values must never be edited to make a test pass. A failure here
//! means legacy receipts broke.

use ed25519_dalek::SigningKey;

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

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

#[allow(dead_code)]
fn json_hash(j: &str) -> String {
    hx(blake3::hash(j.as_bytes()).as_bytes())
}

#[cfg(feature = "quantum_receipt")]
#[test]
fn quantum_circuit_legacy_bytes() {
    use crate::quantum::{Circuit, Measure};
    use crate::quantum_receipt::QuantumReceipt;
    let mut c = Circuit::new(3);
    c.h(0).cx(0, 1).cx(1, 2);
    let r = QuantumReceipt::seal(&key(1), "did:key:pin", &c, Some(Measure { seed: 7, shots: 1024 }), 117_000, Some([0x21; 32]))
        .unwrap();
    assert!(r.verify());
    assert_eq!(hx(&r.receipt_hash()), "5f841f94b57ce254bea9e79cbc55cb48117c88c202a916659e4e8db5fae1fba1");
    assert_eq!(json_hash(&r.to_json()), "bc19d790962cecf2efea9d275f1b9494eb5a44bc1948e1f1bbaf2134f222b37d");
}

#[cfg(feature = "quantum_ops")]
mod ops {
    use super::*;
    use crate::quantum_ops::*;

    fn grant(cap: &str) -> GrantRef {
        GrantRef { grant_hash: content_hash(b"pin-grant"), capability: cap.into(), joule_ceiling_micro: 5_000_000, funds_ceiling: Some(100) }
    }

    fn evid() -> Vec<Evidence> {
        vec![Evidence { kind: "randomized_benchmarking".into(), blob_hash: content_hash(b"<rb>"), summary: "1q RB 0.9992".into() }]
    }

    #[test]
    fn calibration_legacy_bytes() {
        let r = CalibrationReceipt::seal(
            &key(1), "did:key:pin", "example:lab3-device", "q3", content_hash(b"cfg"), evid(),
            4_200_000, grant("quantum.calibrate"), None,
        );
        assert!(r.verify());
        // Recomputed 2026-09-30 when the device id became the neutral
        // "example:lab3-device": this receipt sealed by the code at 1c2af088 (the
        // commit before the acquisition class, d009db90), with that literal. The same
        // code with the previous literal reproduced the previous pins exactly.
        assert_eq!(hx(&r.receipt_hash()), "43326592236b428cb98124d94987b7c59c7ab09b2984ad3a4f622384992c2d03");
        assert_eq!(json_hash(&r.to_json()), "6803e8c6b38d2ce866f88a34313bd551272ad247646e0f258fa61142e87ee9f5");
    }

    #[test]
    fn job_legacy_bytes() {
        let r = JobReceipt::seal(
            &key(1), "did:key:pin", "wai.quantum.circuit", content_hash(b"c"), content_hash(b"r"),
            Some([0x31; 32]), 1000, 250, grant("quantum.job.run"), Some([0x32; 32]),
        );
        assert!(r.verify());
        assert_eq!(hx(&r.receipt_hash()), "52a38a0f7d6c9c58a67948b7ae12a92bfcb7a8a51507b50ec623adb13b05a42b");
        assert_eq!(json_hash(&r.to_json()), "9e8d951ad82084deb6f7ac3e48a049bb305de06adc5d77175bf3ce432abc786b");
    }

    #[test]
    fn mitigation_legacy_bytes() {
        let r = MitigationReceipt::seal(
            &key(1), "did:key:pin", "wai.quantum.circuit", "zne.richardson", "ZZ",
            content_hash(b"raw"), Some(content_hash(b"model")), 744_178, 912_680, 20_971, 48_000,
            900_000, grant("quantum.mitigate"), None,
        );
        assert!(r.verify());
        assert_eq!(hx(&r.receipt_hash()), "df0427389afeb3e7943ab15f7318ab22d5828c2623f5ef7dd6607ce1c1415247");
        assert_eq!(json_hash(&r.to_json()), "99379161a41ecbfb63ecf2cd1217d6589a7566e0dfc923e6fc35b561a4a6dc08");
    }

    #[test]
    fn decode_legacy_bytes() {
        let r = DecodeReceipt::seal(
            &key(1), "did:key:pin", "toric:L7", "relay-bp.min-sum",
            content_hash(b"H"), content_hash(b"s"), content_hash(b"c"),
            true, 3, 46_656, 900_000, grant("quantum.decode"), None,
        );
        assert!(r.verify());
        assert_eq!(hx(&r.receipt_hash()), "27eecec2c2b92d4e4e6e1a6e5025199e000c51ad691b0c3d195a29965a9e17a2");
        assert_eq!(json_hash(&r.to_json()), "6c9a015980792a3baf33a230d009eb00fc2eda65e121edfc788659ee603387d7");
    }

    #[test]
    fn compile_legacy_bytes() {
        let r = CompileReceipt::seal(
            &key(1), "did:key:pin", "clifford-tableau",
            content_hash(b"s"), content_hash(b"t"), content_hash(b"cpl"),
            true, 3, 4096, 300_000, grant("quantum.compile"), None,
        );
        assert!(r.verify());
        assert_eq!(hx(&r.receipt_hash()), "79ba47b4b329b1d0e53967a8c84e95756266e3c47f5366bcdc99836307adcc0f");
        assert_eq!(json_hash(&r.to_json()), "eee5a71d7cdd318841f771fe5d5b435ee0252e70a71cc2bd54f50225d729c0a0");
    }

    #[test]
    fn rearrange_legacy_bytes() {
        let r = RearrangeReceipt::seal(
            &key(1), "did:key:pin", "hungarian-lsap",
            content_hash(b"i"), content_hash(b"t"), content_hash(b"p"),
            true, 41, 318, 450_000, grant("quantum.rearrange"), None,
        );
        assert!(r.verify());
        assert_eq!(hx(&r.receipt_hash()), "a77758a5de40f9684ea0b9618d42417cc318f88ab812020cbc09618095c51efc");
        assert_eq!(json_hash(&r.to_json()), "2f980e1ec6c3cb1eaebfb3a457ad0184b3a040637a398f02bf2a31850f1741fe");
    }
}

#[cfg(feature = "quantum_phasor_meter")]
#[test]
fn phasor_legacy_bytes() {
    use crate::quantum_phasor_meter::{computation_id, result_fingerprint, PhasorReceipt, PhasorWork};
    let work = PhasorWork { n_features: 200, input_dim: 2, n_samples: 300 };
    let r = PhasorReceipt::seal(
        &key(1), "did:key:pin", "wai.quantum.kernel",
        computation_id("wai.quantum.kernel", &[0.5, 1.25]), result_fingerprint(&[0.1, 0.2, 0.3]),
        work, 117_000, None,
    );
    assert!(r.verify());
    assert_eq!(hx(&r.receipt_hash()), "b18e364f7793943873c9070c6755709014d2cf6014bfc9610283b20eca9478e8");
    assert_eq!(json_hash(&r.to_json()), "0d74576475bb5d0a9629eac5954ae81d06947b24bb62527fb9789cbcdb9e1cb1");
}

#[cfg(feature = "quantum_qbom")]
#[test]
fn qbom_legacy_bytes() {
    use crate::quantum_qbom::QbomBuilder;
    let q = QbomBuilder::new("job-pin", [0x51; 32], "sim:device")
        .stage("compile", [0x52; 32], 120_000)
        .stage("execute", [0x53; 32], 90_000)
        .seal(&key(1), "did:key:pin");
    assert!(q.verify());
    assert_eq!(hx(&q.receipt_hash()), "fe651bcfa059621f4c237fd7163ec4ceb76a41a66dd55980937c6f7715276901");
    assert_eq!(json_hash(&q.to_json()), "9f16b7b0e72a8d6a0a712de3808d819bc6cdf1712ecbddc10125def0b0168986");
}

// ---------------------------------------------------------------------------
// The optional label (`crate::quantum_energy`), exercised identically on every
// receipt type.
// ---------------------------------------------------------------------------

#[allow(dead_code)]
fn chip(ppm: u32) -> crate::quantum_energy::EnergyClass {
    use crate::quantum_energy::{CounterFiltering, EnergyClass, Uncertainty};
    EnergyClass::OnChipCounter { uncertainty: Uncertainty { relative_ppm: ppm, window_us: 2_977_104 }, filtering: CounterFiltering::Unknown }
}

#[allow(dead_code)]
fn check_label_ok<R: crate::quantum_energy::Labellable>(l: &crate::quantum_energy::Labelled<R>) -> bool {
    crate::quantum_energy::check_label(l.receipt.figure(), &l.energy_class).is_ok()
}

/// Everything the label must do, on one pinned unlabelled receipt sealed by
/// `signer`. `figure` gives mutable access to its `joules_micro`.
#[allow(dead_code)]
fn exercise<R, F>(legacy: R, signer: &SigningKey, figure: F, verify: fn(&R) -> bool)
where
    R: crate::quantum_energy::Labellable,
    F: Fn(&mut R) -> &mut u64,
{
    use crate::quantum_energy::{ClassError, CounterFiltering, EnergyClass, Labelled, MaybeLabelled, Uncertainty};
    assert!(verify(&legacy));
    let legacy_json = legacy.unlabelled_json();

    let l = Labelled::seal(legacy.clone(), chip(15_403), signer).expect("a valid label");
    assert!(l.verify(), "a labelled receipt verifies");
    assert!(!verify(&l.receipt), "the unlabelled verify() refuses a labelled receipt: it fails closed");

    // Inside the signature: not strippable, restatable or promotable.
    let mut restated = l.clone();
    restated.energy_class = chip(15_404);
    assert!(check_label_ok(&restated), "the control: the restated label is itself valid");
    assert!(!restated.verify(), "so only the signature refuses it");
    let mut promoted = l.clone();
    promoted.energy_class = EnergyClass::CalibratedInstrument {
        uncertainty: Uncertainty { relative_ppm: 15_403, window_us: 2_977_104 },
        calibration_ref: "cert".into(),
    };
    assert!(!promoted.verify());
    let mut demoted = l.clone();
    demoted.energy_class = EnergyClass::ModelBased;
    assert!(!demoted.verify());

    // Refusals.
    assert_eq!(Labelled::seal(legacy.clone(), chip(15_403), &key(8)).unwrap_err(), ClassError::SignerMismatch);
    assert_eq!(Labelled::seal(legacy.clone(), chip(0), signer).unwrap_err(), ClassError::NoUncertainty);
    let mut zero = legacy.clone();
    *figure(&mut zero) = 0;
    assert_eq!(Labelled::seal(zero, chip(15_403), signer).unwrap_err(), ClassError::NoFigure);
    // verify() refuses a correctly signed label beside a zero figure.
    let mut zero = l.clone();
    *figure(&mut zero.receipt) = 0;
    let resigned = Labelled::seal(zero.receipt.clone(), EnergyClass::Estimator, signer);
    assert_eq!(resigned.unwrap_err(), ClassError::NoFigure);
    let undeclared = EnergyClass::OnChipCounter {
        uncertainty: Uncertainty { relative_ppm: 0, window_us: 1 },
        filtering: CounterFiltering::Unknown,
    };
    let mut bad = l.clone();
    bad.energy_class = undeclared.clone();
    assert!(!bad.verify());

    // And verify() refuses a label that breaks the rules even when the
    // signature over it is valid: the rule is checked, not just the bytes.
    let signed_over = |mut r: R, class: &EnergyClass| {
        use ed25519_dalek::Signer;
        let sig = signer.sign(&r.labelled_payload(Some(class))).to_bytes();
        r.set_signature(sig);
        Labelled { receipt: r, energy_class: class.clone() }
    };
    assert!(signed_over(legacy.clone(), &chip(15_403)).verify(), "the control: a valid label, signed, verifies");
    assert!(!signed_over(legacy.clone(), &undeclared).verify(), "a refined class without its uncertainty");
    let mut zero = legacy.clone();
    *figure(&mut zero) = 0;
    assert!(!signed_over(zero, &EnergyClass::Estimator).verify(), "a class beside a zero figure");

    // A declaration below the 0.5/√3 µJ the figure's rounding adds is refused,
    // sealed or signed over: `joules_micro × relative_ppm` must reach 288 676.
    let fig = {
        let mut probe = legacy.clone();
        *figure(&mut probe)
    };
    let least = crate::quantum_energy::RESOLUTION_FLOOR_UJ_PPM.div_ceil(fig);
    assert!(signed_over(legacy.clone(), &chip(least as u32)).verify(), "the control: exactly at the floor");
    if least > 1 {
        let below = chip((least - 1) as u32);
        assert_eq!(Labelled::seal(legacy.clone(), below.clone(), signer).unwrap_err(), ClassError::BelowResolution);
        assert!(!signed_over(legacy.clone(), &below).verify(), "a declaration below the figure's resolution");
    }

    // JSON: the unlabelled form is untouched; the labelled form carries the
    // class and the labelled identity, and round-trips.
    assert!(!legacy_json.contains("energy_provenance"));
    let j = l.to_json();
    let v: serde_json::Value = serde_json::from_str(&j).unwrap();
    assert_eq!(v["energy_provenance"], "OnChipCounter");
    assert_eq!(v["receipt_hash"], serde_json::Value::from(hx(&l.receipt_hash())));
    let back = Labelled::<R>::from_json(&j).expect("parse");
    assert_eq!(back, l);
    assert!(back.verify());
    assert!(Labelled::<R>::from_json(&legacy_json).is_none(), "no class, no labelled parse");

    // Either form through the one entry point a verifier uses: the form comes
    // from the JSON, and each verifies by its own rules.
    let any = MaybeLabelled::<R>::from_json(&legacy_json).expect("the unlabelled form parses");
    assert!(matches!(any, MaybeLabelled::Unlabelled(_)) && any.verify() && any.energy_class().is_none());
    assert_eq!(any.receipt_hash(), legacy.unlabelled_receipt_hash());
    assert_eq!(any.to_json(), legacy_json);
    let any = MaybeLabelled::<R>::from_json(&j).expect("the labelled form parses");
    assert!(matches!(any, MaybeLabelled::Labelled(_)) && any.verify());
    assert_eq!(any.energy_class(), Some(&chip(15_403)));
    assert_eq!(any.receipt_hash(), l.receipt_hash());
    assert_eq!(any.to_json(), j);
    // A label whose evidence is malformed, or evidence whose class was
    // stripped, is refused — never read as an unlabelled receipt.
    let mut broken = v.clone();
    broken["energy_uncertainty"] = serde_json::Value::Null;
    assert!(MaybeLabelled::<R>::from_json(&broken.to_string()).is_none());
    let mut stripped = v.clone();
    stripped.as_object_mut().unwrap().remove("energy_provenance");
    assert!(MaybeLabelled::<R>::from_json(&stripped.to_string()).is_none());
    // A restated label parses and is refused by verify().
    let mut restated_json = v.clone();
    restated_json["energy_uncertainty"]["relative_ppm"] = serde_json::Value::from(15_404);
    let any = MaybeLabelled::<R>::from_json(&restated_json.to_string()).expect("a well-formed label parses");
    assert!(!any.verify());
    assert_ne!(l.receipt_hash(), {
        let mut h = blake3::Hasher::new();
        h.update(legacy_json.as_bytes());
        *h.finalize().as_bytes()
    });
}

#[cfg(feature = "quantum_receipt")]
#[test]
fn quantum_circuit_label() {
    use crate::quantum::{Circuit, Measure};
    use crate::quantum_energy::Labelled;
    use crate::quantum_receipt::QuantumReceipt;
    let mut c = Circuit::new(3);
    c.h(0).cx(0, 1).cx(1, 2);
    let r = QuantumReceipt::seal(&key(1), "did:key:pin", &c, Some(Measure { seed: 7, shots: 1024 }), 117_000, Some([0x21; 32])).unwrap();
    exercise(r.clone(), &key(1), |r| &mut r.joules_micro, QuantumReceipt::verify);
    let l = Labelled::seal(r, chip(15_403), &key(1)).unwrap();
    assert!(l.verify_reconstruction(&c));
    let mut other = Circuit::new(3);
    other.h(0);
    assert!(!l.verify_reconstruction(&other));
}

#[cfg(feature = "quantum_ops")]
mod ops_labels {
    use super::*;
    use crate::quantum_ops::*;

    fn grant(cap: &str) -> GrantRef {
        GrantRef { grant_hash: content_hash(b"pin-grant"), capability: cap.into(), joule_ceiling_micro: 5_000_000, funds_ceiling: Some(100) }
    }

    #[test]
    fn calibration_label() {
        let r = CalibrationReceipt::seal(
            &key(1), "did:key:pin", "example:lab3-device", "q3", content_hash(b"cfg"),
            vec![Evidence { kind: "rb".into(), blob_hash: content_hash(b"<rb>"), summary: "s".into() }],
            4_200_000, grant("quantum.calibrate"), None,
        );
        exercise(r, &key(1), |r| &mut r.joules_micro, CalibrationReceipt::verify);
    }

    #[test]
    fn job_label() {
        let r = JobReceipt::seal(
            &key(1), "did:key:pin", "wai.quantum.circuit", content_hash(b"c"), content_hash(b"r"),
            Some([0x31; 32]), 1000, 250, grant("quantum.job.run"), Some([0x32; 32]),
        );
        exercise(r, &key(1), |r| &mut r.joules_micro, JobReceipt::verify);
    }

    #[test]
    fn mitigation_label() {
        let r = MitigationReceipt::seal(
            &key(1), "did:key:pin", "wai.quantum.circuit", "zne.richardson", "ZZ",
            content_hash(b"raw"), Some(content_hash(b"model")), 744_178, 912_680, 20_971, 48_000,
            900_000, grant("quantum.mitigate"), None,
        );
        exercise(r, &key(1), |r| &mut r.joules_micro, MitigationReceipt::verify);
    }

    #[test]
    fn decode_label() {
        let r = DecodeReceipt::seal(
            &key(1), "did:key:pin", "toric:L7", "relay-bp.min-sum",
            content_hash(b"H"), content_hash(b"s"), content_hash(b"c"),
            true, 3, 46_656, 900_000, grant("quantum.decode"), None,
        );
        exercise(r, &key(1), |r| &mut r.joules_micro, DecodeReceipt::verify);
    }

    #[test]
    fn compile_label() {
        let r = CompileReceipt::seal(
            &key(1), "did:key:pin", "clifford-tableau",
            content_hash(b"s"), content_hash(b"t"), content_hash(b"cpl"),
            true, 3, 4096, 300_000, grant("quantum.compile"), None,
        );
        exercise(r, &key(1), |r| &mut r.joules_micro, CompileReceipt::verify);
    }

    #[test]
    fn rearrange_label() {
        let r = RearrangeReceipt::seal(
            &key(1), "did:key:pin", "hungarian-lsap",
            content_hash(b"i"), content_hash(b"t"), content_hash(b"p"),
            true, 41, 318, 450_000, grant("quantum.rearrange"), None,
        );
        exercise(r, &key(1), |r| &mut r.joules_micro, RearrangeReceipt::verify);
    }

    #[test]
    fn a_job_cross_links_to_a_calibration_in_either_form() {
        use crate::quantum_energy::{Labelled, MaybeLabelled};
        let cal = CalibrationReceipt::seal(
            &key(1), "did:key:pin", "example:lab3-device", "q3", content_hash(b"cfg"),
            vec![Evidence { kind: "rb".into(), blob_hash: content_hash(b"<rb>"), summary: "s".into() }],
            4_200_000, grant("quantum.calibrate"), None,
        );
        let cal_l = Labelled::seal(cal.clone(), chip(15_403), &key(1)).unwrap();
        let job_under = |cal_id: [u8; 32]| {
            JobReceipt::seal(
                &key(1), "did:key:pin", "wai.quantum.circuit", content_hash(b"c"), content_hash(b"r"),
                Some(cal_id), 1000, 250, grant("quantum.job.run"), None,
            )
        };

        // Both unlabelled: the legacy check and the either-form check agree.
        let j0 = job_under(cal.receipt_hash());
        assert!(j0.verify_against_calibration(&cal));
        assert!(MaybeLabelled::Unlabelled(j0.clone()).verify_against_calibration(&MaybeLabelled::Unlabelled(cal.clone())));

        // A job run under a labelled calibration names its labelled identity.
        // The unlabelled check cannot see that calibration at all; the
        // either-form check binds it, and only it.
        let j1 = job_under(cal_l.receipt_hash());
        assert!(!j1.verify_against_calibration(&cal_l.receipt));
        assert!(MaybeLabelled::Unlabelled(j1.clone()).verify_against_calibration(&cal_l.clone().into()));
        assert!(!MaybeLabelled::Unlabelled(j1.clone()).verify_against_calibration(&MaybeLabelled::Unlabelled(cal.clone())), "not the unlabelled calibration");

        // Labelled jobs, under either form of calibration.
        let j2 = Labelled::seal(j1.clone(), chip(20_000), &key(1)).unwrap();
        assert!(MaybeLabelled::from(j2.clone()).verify_against_calibration(&cal_l.clone().into()));
        let j3 = Labelled::seal(j0.clone(), chip(20_000), &key(1)).unwrap();
        assert!(MaybeLabelled::from(j3).verify_against_calibration(&MaybeLabelled::Unlabelled(cal.clone())));

        // A calibration whose label was restated no longer verifies, so the
        // link fails.
        let mut restated = cal_l.clone();
        restated.energy_class = chip(15_404);
        assert!(!MaybeLabelled::Unlabelled(j1).verify_against_calibration(&restated.into()));

        // From JSON, as a verifier receives them.
        let cal_any = MaybeLabelled::<CalibrationReceipt>::from_json(&cal_l.to_json()).unwrap();
        let job_any = MaybeLabelled::<JobReceipt>::from_json(&j2.to_json()).unwrap();
        assert!(job_any.verify_against_calibration(&cal_any));
    }

    #[test]
    fn a_labelled_receipt_still_honours_its_grant() {
        // The label does not bypass the receipt's own checks: an over-budget
        // run stays invalid when labelled.
        use crate::quantum_energy::Labelled;
        let tight = GrantRef { grant_hash: [0u8; 32], capability: "quantum.decode".into(), joule_ceiling_micro: 10, funds_ceiling: None };
        let r = DecodeReceipt::seal(
            &key(1), "m", "toric:L5", "relay-bp.min-sum",
            content_hash(b"H"), content_hash(b"s"), content_hash(b"c"),
            true, 1, 100, 900_000, tight, None,
        );
        let l = Labelled::seal(r, chip(15_403), &key(1)).unwrap();
        assert!(!l.verify(), "a run that blew its grant must not verify, labelled or not");
    }
}

#[cfg(feature = "quantum_phasor_meter")]
#[test]
fn phasor_label() {
    use crate::quantum_phasor_meter::{computation_id, result_fingerprint, PhasorReceipt, PhasorWork};
    let work = PhasorWork { n_features: 200, input_dim: 2, n_samples: 300 };
    let r = PhasorReceipt::seal(
        &key(1), "did:key:pin", "wai.quantum.kernel",
        computation_id("wai.quantum.kernel", &[0.5, 1.25]), result_fingerprint(&[0.1, 0.2, 0.3]),
        work, 117_000, None,
    );
    exercise(r, &key(1), |r| &mut r.joules_micro, PhasorReceipt::verify);
}

#[cfg(feature = "quantum_qbom")]
#[test]
fn qbom_entry_labels() {
    use crate::quantum_energy::{ClassError, EnergyClass, LabelledQbom};
    use crate::quantum_qbom::{Qbom, QbomBuilder};
    let q = QbomBuilder::new("job-pin", [0x51; 32], "sim:device")
        .stage("compile", [0x52; 32], 120_000)
        .stage("execute", [0x53; 32], 90_000)
        .seal(&key(1), "did:key:pin");
    let classes = vec![Some(chip(15_403)), None];
    let l = LabelledQbom::seal(q.clone(), classes.clone(), &key(1)).unwrap();
    assert!(l.verify());
    assert!(!l.qbom.verify(), "the unlabelled verify() refuses a labelled bill");
    assert_ne!(l.provenance_root(), q.provenance_root());
    assert_ne!(l.receipt_hash(), q.receipt_hash());

    // Stripping, moving or restating an entry label breaks the bill.
    let mut moved = l.clone();
    moved.classes = vec![None, Some(chip(15_403))];
    assert!(!moved.verify());
    let mut restated = l.clone();
    restated.classes[0] = Some(chip(15_404));
    assert!(!restated.verify());
    // An entry declaring less than its figure's resolution is refused:
    // 120,000 µJ needs at least 3 ppm.
    assert_eq!(
        LabelledQbom::seal(q.clone(), vec![Some(chip(2)), None], &key(1)).unwrap_err(),
        ClassError::BelowResolution
    );
    assert!(LabelledQbom::seal(q.clone(), vec![Some(chip(3)), None], &key(1)).unwrap().verify());

    // Refusals: slot count, nothing labelled, zero figure, wrong signer.
    assert_eq!(LabelledQbom::seal(q.clone(), vec![Some(chip(1))], &key(1)).unwrap_err(), ClassError::EntryMismatch);
    assert_eq!(LabelledQbom::seal(q.clone(), vec![None, None], &key(1)).unwrap_err(), ClassError::EntryMismatch);
    assert_eq!(LabelledQbom::seal(q.clone(), classes.clone(), &key(2)).unwrap_err(), ClassError::SignerMismatch);
    let zero = QbomBuilder::new("j", [0; 32], "d").stage("compile", [1; 32], 0).seal(&key(1), "id");
    assert_eq!(LabelledQbom::seal(zero, vec![Some(EnergyClass::ModelBased)], &key(1)).unwrap_err(), ClassError::NoFigure);

    // verify() checks the rules, not just the signature: a bill signed over
    // classes that break them is refused.
    let signed_over = |q: &Qbom, classes: Vec<Option<EnergyClass>>| {
        use ed25519_dalek::Signer;
        let mut q = q.clone();
        q.sig = key(1).sign(&q.labelled_signing_payload(&classes)).to_bytes();
        LabelledQbom { qbom: q, classes }
    };
    assert!(signed_over(&q, classes.clone()).verify(), "the control verifies");
    assert!(!signed_over(&q, vec![None, None]).verify(), "a labelled bill that labels nothing");
    let zero = QbomBuilder::new("j", [0; 32], "d").stage("compile", [1; 32], 0).seal(&key(1), "id");
    assert!(!signed_over(&zero, vec![Some(EnergyClass::ModelBased)]).verify(), "a class beside a zero figure");

    // Binding checks each entry's class against its stage receipt's class.
    assert!(l.binds(&[([0x52; 32], true, Some(&chip(15_403))), ([0x53; 32], true, None)]));
    assert!(!l.binds(&[([0x52; 32], true, None), ([0x53; 32], true, None)]), "a stage whose class differs breaks the bill");

    // JSON round trip; the unlabelled bill parses as no labelled bill.
    let j = l.to_json();
    let v: serde_json::Value = serde_json::from_str(&j).unwrap();
    assert_eq!(v["entries"][0]["energy_provenance"], "OnChipCounter");
    assert!(v["entries"][1].get("energy_provenance").is_none());
    assert_eq!(v["receipt_hash"], serde_json::Value::from(hx(&l.receipt_hash())));
    let back = LabelledQbom::from_json(&j).expect("parse");
    assert_eq!(back, l);
    assert!(back.verify());
    assert!(LabelledQbom::from_json(&q.to_json()).is_none());
    let _: Option<Qbom> = Qbom::from_json(&q.to_json());
}