use crate::merkle::merkle_root;
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
pub const CAP_QUANTUM_CALIBRATION: &str = "wai.quantum.calibration";
pub const CAP_QUANTUM_JOB: &str = "wai.quantum.job";
pub const CAP_QUANTUM_MITIGATE: &str = "wai.quantum.mitigate";
pub const CAP_QUANTUM_DECODE: &str = "wai.quantum.decode";
pub const CAP_QUANTUM_COMPILE: &str = "wai.quantum.compile";
pub const CAP_QUANTUM_REARRANGE: &str = "wai.quantum.rearrange";
pub const CAP_QUANTUM_QBOM: &str = "wai.quantum.qbom";
const DOMAIN_CAL: &[u8] = b"wai:quantum-calibration\x01";
const DOMAIN_CAL_ID: &[u8] = b"wai:quantum-calibration-id\x01";
const DOMAIN_JOB: &[u8] = b"wai:quantum-job\x01";
const DOMAIN_JOB_ID: &[u8] = b"wai:quantum-job-id\x01";
const DOMAIN_MIT: &[u8] = b"wai:quantum-mitigate\x01";
const DOMAIN_MIT_ID: &[u8] = b"wai:quantum-mitigate-id\x01";
const DOMAIN_MIT_RESULT: &[u8] = b"wai:quantum-mitigate-result\x01";
const DOMAIN_DEC: &[u8] = b"wai:quantum-decode\x01";
const DOMAIN_DEC_ID: &[u8] = b"wai:quantum-decode-id\x01";
const DOMAIN_CMP: &[u8] = b"wai:quantum-compile\x01";
const DOMAIN_CMP_ID: &[u8] = b"wai:quantum-compile-id\x01";
const DOMAIN_REA: &[u8] = b"wai:quantum-rearrange\x01";
const DOMAIN_REA_ID: &[u8] = b"wai:quantum-rearrange-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)
}
pub fn content_hash(bytes: &[u8]) -> [u8; 32] {
*blake3::hash(bytes).as_bytes()
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GrantRef {
pub grant_hash: [u8; 32],
pub capability: String,
pub joule_ceiling_micro: u64,
pub funds_ceiling: Option<u64>,
}
impl GrantRef {
pub fn unbounded(capability: impl Into<String>) -> GrantRef {
GrantRef {
grant_hash: [0u8; 32],
capability: capability.into(),
joule_ceiling_micro: u64::MAX,
funds_ceiling: None,
}
}
fn append_to(&self, o: &mut Vec<u8>) {
o.extend_from_slice(&self.grant_hash);
o.extend_from_slice(self.capability.as_bytes());
o.push(0); o.extend_from_slice(&self.joule_ceiling_micro.to_be_bytes());
match self.funds_ceiling {
Some(f) => {
o.push(1);
o.extend_from_slice(&f.to_be_bytes());
}
None => o.push(0),
}
}
fn to_json(&self) -> String {
let funds = match self.funds_ceiling {
Some(f) => f.to_string(),
None => "null".into(),
};
format!(
"{{\"capability\":{},\"funds_ceiling\":{},\"grant_hash\":\"{}\",\"joule_ceiling_micro\":{}}}",
serde_json::to_string(&self.capability).unwrap(),
funds,
hx(&self.grant_hash),
self.joule_ceiling_micro,
)
}
fn from_json(v: &serde_json::Value) -> Option<GrantRef> {
let o = v.as_object()?;
Some(GrantRef {
grant_hash: from_hex32(o.get("grant_hash")?.as_str()?)?,
capability: o.get("capability")?.as_str()?.to_owned(),
joule_ceiling_micro: o.get("joule_ceiling_micro")?.as_u64()?,
funds_ceiling: match o.get("funds_ceiling") {
Some(serde_json::Value::Number(n)) => Some(n.as_u64()?),
_ => None,
},
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Evidence {
pub kind: String,
pub blob_hash: [u8; 32],
pub summary: String,
}
impl Evidence {
fn leaf(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(b"wai:qcal-evidence\x01");
h.update(self.kind.as_bytes());
h.update(&[0]);
h.update(&self.blob_hash);
*h.finalize().as_bytes()
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct CalibrationReceipt {
pub device_id: String,
pub target: String,
pub config_hash: [u8; 32],
pub evidence: Vec<Evidence>,
pub merkle_root: [u8; 32],
pub joules_micro: u64,
pub grant: GrantRef,
pub parent_receipt_hash: Option<[u8; 32]>,
pub signer_pubkey: [u8; 32],
pub signer_id: String,
pub sig: [u8; 64],
}
impl CalibrationReceipt {
fn leaves(&self) -> Vec<[u8; 32]> {
let mut v = vec![self.config_hash];
v.extend(self.evidence.iter().map(|e| e.leaf()));
v
}
fn signing_payload(&self) -> Vec<u8> {
self.payload_with(None)
}
fn payload_with(&self, label: Option<&crate::quantum_energy::EnergyClass>) -> Vec<u8> {
let mut o = crate::quantum_energy::labelled_domain(DOMAIN_CAL, label);
o.extend_from_slice(self.device_id.as_bytes());
o.push(0);
o.extend_from_slice(self.target.as_bytes());
o.push(0);
o.extend_from_slice(&self.config_hash);
o.extend_from_slice(&self.merkle_root);
o.extend_from_slice(&(self.evidence.len() as u64).to_be_bytes());
o.extend_from_slice(&self.joules_micro.to_be_bytes());
crate::quantum_energy::write_label(label, &mut o);
self.grant.append_to(&mut o);
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
}
#[allow(clippy::too_many_arguments)]
pub fn seal(
signer: &SigningKey,
signer_id: impl Into<String>,
device_id: impl Into<String>,
target: impl Into<String>,
config_hash: [u8; 32],
evidence: Vec<Evidence>,
joules_micro: u64,
grant: GrantRef,
parent_receipt_hash: Option<[u8; 32]>,
) -> CalibrationReceipt {
let mut r = CalibrationReceipt {
device_id: device_id.into(),
target: target.into(),
config_hash,
evidence,
merkle_root: [0u8; 32],
joules_micro,
grant,
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();
r
}
pub fn honors_budget(&self) -> bool {
self.joules_micro <= self.grant.joule_ceiling_micro
}
fn body_verifies(&self) -> bool {
if merkle_root(&self.leaves()) != self.merkle_root {
return false;
}
if !self.honors_budget() {
return false;
}
true
}
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()
}
pub fn evidence_matches(&self, i: usize, dataset_bytes: &[u8]) -> bool {
self.evidence
.get(i)
.is_some_and(|e| content_hash(dataset_bytes) == e.blob_hash)
}
pub fn receipt_hash(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(DOMAIN_CAL_ID);
h.update(&self.signing_payload());
h.update(&self.sig);
*h.finalize().as_bytes()
}
pub fn to_json(&self) -> String {
let ev: Vec<String> = self
.evidence
.iter()
.map(|e| {
format!(
"{{\"blob_hash\":\"{}\",\"kind\":{},\"summary\":{}}}",
hx(&e.blob_hash),
serde_json::to_string(&e.kind).unwrap(),
serde_json::to_string(&e.summary).unwrap(),
)
})
.collect();
let parent = match self.parent_receipt_hash {
Some(h) => format!("\"{}\"", hx(&h)),
None => "null".into(),
};
format!(
"{{\"kind\":\"quantum-calibration\",\"config_hash\":\"{}\",\"device_id\":{},\
\"evidence\":[{}],\"grant\":{},\"joules_micro\":{},\"merkle_root\":\"{}\",\
\"parent_receipt_hash\":{},\"receipt_hash\":\"{}\",\"sig\":\"{}\",\
\"signer_id\":{},\"signer_pubkey\":\"{}\",\"target\":{}}}",
hx(&self.config_hash),
serde_json::to_string(&self.device_id).unwrap(),
ev.join(","),
self.grant.to_json(),
self.joules_micro,
hx(&self.merkle_root),
parent,
hx(&self.receipt_hash()),
hx(&self.sig),
serde_json::to_string(&self.signer_id).unwrap(),
hx(&self.signer_pubkey),
serde_json::to_string(&self.target).unwrap(),
)
}
pub fn from_json(s: &str) -> Option<CalibrationReceipt> {
let v: serde_json::Value = serde_json::from_str(s).ok()?;
let o = v.as_object()?;
let mut evidence = Vec::new();
for ev in o.get("evidence")?.as_array()? {
let eo = ev.as_object()?;
evidence.push(Evidence {
kind: eo.get("kind")?.as_str()?.to_owned(),
blob_hash: from_hex32(eo.get("blob_hash")?.as_str()?)?,
summary: eo.get("summary")?.as_str()?.to_owned(),
});
}
let parent = match o.get("parent_receipt_hash") {
Some(serde_json::Value::String(s)) => Some(from_hex32(s)?),
_ => None,
};
Some(CalibrationReceipt {
device_id: o.get("device_id")?.as_str()?.to_owned(),
target: o.get("target")?.as_str()?.to_owned(),
config_hash: from_hex32(o.get("config_hash")?.as_str()?)?,
evidence,
merkle_root: from_hex32(o.get("merkle_root")?.as_str()?)?,
joules_micro: o.get("joules_micro")?.as_u64()?,
grant: GrantRef::from_json(o.get("grant")?)?,
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()?)?,
})
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct JobReceipt {
pub backend_id: String,
pub circuit_hash: [u8; 32],
pub calibration_ref: Option<[u8; 32]>,
pub result_hash: [u8; 32],
pub shots: u64,
pub merkle_root: [u8; 32],
pub joules_micro: u64,
pub grant: GrantRef,
pub parent_receipt_hash: Option<[u8; 32]>,
pub signer_pubkey: [u8; 32],
pub signer_id: String,
pub sig: [u8; 64],
}
impl JobReceipt {
fn leaves(&self) -> Vec<[u8; 32]> {
let mut v = vec![self.circuit_hash, self.result_hash];
if let Some(c) = self.calibration_ref {
v.push(c);
}
v
}
fn signing_payload(&self) -> Vec<u8> {
self.payload_with(None)
}
fn payload_with(&self, label: Option<&crate::quantum_energy::EnergyClass>) -> Vec<u8> {
let mut o = crate::quantum_energy::labelled_domain(DOMAIN_JOB, label);
o.extend_from_slice(self.backend_id.as_bytes());
o.push(0);
o.extend_from_slice(&self.circuit_hash);
o.extend_from_slice(&self.result_hash);
match self.calibration_ref {
Some(c) => {
o.push(1);
o.extend_from_slice(&c);
}
None => o.push(0),
}
o.extend_from_slice(&self.shots.to_be_bytes());
o.extend_from_slice(&self.merkle_root);
o.extend_from_slice(&self.joules_micro.to_be_bytes());
crate::quantum_energy::write_label(label, &mut o);
self.grant.append_to(&mut o);
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
}
#[allow(clippy::too_many_arguments)]
pub fn seal(
signer: &SigningKey,
signer_id: impl Into<String>,
backend_id: impl Into<String>,
circuit_hash: [u8; 32],
result_hash: [u8; 32],
calibration_ref: Option<[u8; 32]>,
shots: u64,
joules_micro: u64,
grant: GrantRef,
parent_receipt_hash: Option<[u8; 32]>,
) -> JobReceipt {
let mut r = JobReceipt {
backend_id: backend_id.into(),
circuit_hash,
calibration_ref,
result_hash,
shots,
merkle_root: [0u8; 32],
joules_micro,
grant,
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();
r
}
pub fn honors_budget(&self) -> bool {
self.joules_micro <= self.grant.joule_ceiling_micro
}
fn body_verifies(&self) -> bool {
if merkle_root(&self.leaves()) != self.merkle_root {
return false;
}
if !self.honors_budget() {
return false;
}
true
}
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()
}
pub fn verify_against_calibration(&self, cal: &CalibrationReceipt) -> bool {
self.calibration_ref == Some(cal.receipt_hash()) && cal.verify() && self.verify()
}
pub fn result_matches(&self, result_bytes: &[u8]) -> bool {
content_hash(result_bytes) == self.result_hash
}
pub fn receipt_hash(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(DOMAIN_JOB_ID);
h.update(&self.signing_payload());
h.update(&self.sig);
*h.finalize().as_bytes()
}
pub fn to_json(&self) -> String {
let cal = match self.calibration_ref {
Some(c) => format!("\"{}\"", hx(&c)),
None => "null".into(),
};
let parent = match self.parent_receipt_hash {
Some(h) => format!("\"{}\"", hx(&h)),
None => "null".into(),
};
format!(
"{{\"kind\":\"quantum-job\",\"backend_id\":{},\"calibration_ref\":{},\
\"circuit_hash\":\"{}\",\"grant\":{},\"joules_micro\":{},\"merkle_root\":\"{}\",\
\"parent_receipt_hash\":{},\"receipt_hash\":\"{}\",\"result_hash\":\"{}\",\
\"shots\":{},\"sig\":\"{}\",\"signer_id\":{},\"signer_pubkey\":\"{}\"}}",
serde_json::to_string(&self.backend_id).unwrap(),
cal,
hx(&self.circuit_hash),
self.grant.to_json(),
self.joules_micro,
hx(&self.merkle_root),
parent,
hx(&self.receipt_hash()),
hx(&self.result_hash),
self.shots,
hx(&self.sig),
serde_json::to_string(&self.signer_id).unwrap(),
hx(&self.signer_pubkey),
)
}
pub fn from_json(s: &str) -> Option<JobReceipt> {
let v: serde_json::Value = serde_json::from_str(s).ok()?;
let o = v.as_object()?;
let opt_hash = |k: &str| match o.get(k) {
Some(serde_json::Value::String(s)) => from_hex32(s),
_ => None,
};
Some(JobReceipt {
backend_id: o.get("backend_id")?.as_str()?.to_owned(),
circuit_hash: from_hex32(o.get("circuit_hash")?.as_str()?)?,
calibration_ref: opt_hash("calibration_ref"),
result_hash: from_hex32(o.get("result_hash")?.as_str()?)?,
shots: o.get("shots")?.as_u64()?,
merkle_root: from_hex32(o.get("merkle_root")?.as_str()?)?,
joules_micro: o.get("joules_micro")?.as_u64()?,
grant: GrantRef::from_json(o.get("grant")?)?,
parent_receipt_hash: opt_hash("parent_receipt_hash"),
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()?)?,
})
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct MitigationReceipt {
pub backend_id: String,
pub method: String,
pub observable: String,
pub input_hash: [u8; 32],
pub noise_model_hash: Option<[u8; 32]>,
pub raw_estimate_fx: i64,
pub mitigated_estimate_fx: i64,
pub error_bar_fx: i64,
pub shots: u64,
pub merkle_root: [u8; 32],
pub joules_micro: u64,
pub grant: GrantRef,
pub parent_receipt_hash: Option<[u8; 32]>,
pub signer_pubkey: [u8; 32],
pub signer_id: String,
pub sig: [u8; 64],
}
impl MitigationReceipt {
fn result_leaf(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(DOMAIN_MIT_RESULT);
h.update(self.method.as_bytes());
h.update(&[0]);
h.update(&self.raw_estimate_fx.to_be_bytes());
h.update(&self.mitigated_estimate_fx.to_be_bytes());
h.update(&self.error_bar_fx.to_be_bytes());
*h.finalize().as_bytes()
}
fn leaves(&self) -> Vec<[u8; 32]> {
let mut v = vec![self.input_hash];
if let Some(m) = self.noise_model_hash {
v.push(m);
}
v.push(self.result_leaf());
v
}
fn signing_payload(&self) -> Vec<u8> {
self.payload_with(None)
}
fn payload_with(&self, label: Option<&crate::quantum_energy::EnergyClass>) -> Vec<u8> {
let mut o = crate::quantum_energy::labelled_domain(DOMAIN_MIT, label);
o.extend_from_slice(self.backend_id.as_bytes());
o.push(0);
o.extend_from_slice(self.method.as_bytes());
o.push(0);
o.extend_from_slice(self.observable.as_bytes());
o.push(0);
o.extend_from_slice(&self.input_hash);
match self.noise_model_hash {
Some(m) => {
o.push(1);
o.extend_from_slice(&m);
}
None => o.push(0),
}
o.extend_from_slice(&self.raw_estimate_fx.to_be_bytes());
o.extend_from_slice(&self.mitigated_estimate_fx.to_be_bytes());
o.extend_from_slice(&self.error_bar_fx.to_be_bytes());
o.extend_from_slice(&self.shots.to_be_bytes());
o.extend_from_slice(&self.merkle_root);
o.extend_from_slice(&self.joules_micro.to_be_bytes());
crate::quantum_energy::write_label(label, &mut o);
self.grant.append_to(&mut o);
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
}
#[allow(clippy::too_many_arguments)]
pub fn seal(
signer: &SigningKey,
signer_id: impl Into<String>,
backend_id: impl Into<String>,
method: impl Into<String>,
observable: impl Into<String>,
input_hash: [u8; 32],
noise_model_hash: Option<[u8; 32]>,
raw_estimate_fx: i64,
mitigated_estimate_fx: i64,
error_bar_fx: i64,
shots: u64,
joules_micro: u64,
grant: GrantRef,
parent_receipt_hash: Option<[u8; 32]>,
) -> MitigationReceipt {
let mut r = MitigationReceipt {
backend_id: backend_id.into(),
method: method.into(),
observable: observable.into(),
input_hash,
noise_model_hash,
raw_estimate_fx,
mitigated_estimate_fx,
error_bar_fx,
shots,
merkle_root: [0u8; 32],
joules_micro,
grant,
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();
r
}
pub fn honors_budget(&self) -> bool {
self.joules_micro <= self.grant.joule_ceiling_micro
}
fn body_verifies(&self) -> bool {
if merkle_root(&self.leaves()) != self.merkle_root {
return false;
}
if !self.honors_budget() {
return false;
}
true
}
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()
}
pub fn input_matches(&self, input_bytes: &[u8]) -> bool {
content_hash(input_bytes) == self.input_hash
}
pub fn noise_model_matches(&self, model_bytes: &[u8]) -> bool {
self.noise_model_hash == Some(content_hash(model_bytes))
}
pub fn receipt_hash(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(DOMAIN_MIT_ID);
h.update(&self.signing_payload());
h.update(&self.sig);
*h.finalize().as_bytes()
}
pub fn to_json(&self) -> String {
let nm = match self.noise_model_hash {
Some(m) => format!("\"{}\"", hx(&m)),
None => "null".into(),
};
let parent = match self.parent_receipt_hash {
Some(h) => format!("\"{}\"", hx(&h)),
None => "null".into(),
};
format!(
"{{\"kind\":\"quantum-mitigate\",\"backend_id\":{},\"error_bar_fx\":{},\
\"grant\":{},\"input_hash\":\"{}\",\"joules_micro\":{},\"merkle_root\":\"{}\",\
\"method\":{},\"mitigated_estimate_fx\":{},\"noise_model_hash\":{},\
\"observable\":{},\"parent_receipt_hash\":{},\"raw_estimate_fx\":{},\
\"receipt_hash\":\"{}\",\"shots\":{},\"sig\":\"{}\",\"signer_id\":{},\
\"signer_pubkey\":\"{}\"}}",
serde_json::to_string(&self.backend_id).unwrap(),
self.error_bar_fx,
self.grant.to_json(),
hx(&self.input_hash),
self.joules_micro,
hx(&self.merkle_root),
serde_json::to_string(&self.method).unwrap(),
self.mitigated_estimate_fx,
nm,
serde_json::to_string(&self.observable).unwrap(),
parent,
self.raw_estimate_fx,
hx(&self.receipt_hash()),
self.shots,
hx(&self.sig),
serde_json::to_string(&self.signer_id).unwrap(),
hx(&self.signer_pubkey),
)
}
pub fn from_json(s: &str) -> Option<MitigationReceipt> {
let v: serde_json::Value = serde_json::from_str(s).ok()?;
let o = v.as_object()?;
let opt_hash = |k: &str| match o.get(k) {
Some(serde_json::Value::String(s)) => from_hex32(s),
_ => None,
};
Some(MitigationReceipt {
backend_id: o.get("backend_id")?.as_str()?.to_owned(),
method: o.get("method")?.as_str()?.to_owned(),
observable: o.get("observable")?.as_str()?.to_owned(),
input_hash: from_hex32(o.get("input_hash")?.as_str()?)?,
noise_model_hash: opt_hash("noise_model_hash"),
raw_estimate_fx: o.get("raw_estimate_fx")?.as_i64()?,
mitigated_estimate_fx: o.get("mitigated_estimate_fx")?.as_i64()?,
error_bar_fx: o.get("error_bar_fx")?.as_i64()?,
shots: o.get("shots")?.as_u64()?,
merkle_root: from_hex32(o.get("merkle_root")?.as_str()?)?,
joules_micro: o.get("joules_micro")?.as_u64()?,
grant: GrantRef::from_json(o.get("grant")?)?,
parent_receipt_hash: opt_hash("parent_receipt_hash"),
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()?)?,
})
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct DecodeReceipt {
pub code_id: String,
pub decoder: String,
pub check_matrix_hash: [u8; 32],
pub syndrome_hash: [u8; 32],
pub correction_hash: [u8; 32],
pub converged: bool,
pub rounds: u32,
pub work_messages: u64,
pub joules_micro: u64,
pub grant: GrantRef,
pub parent_receipt_hash: Option<[u8; 32]>,
pub signer_pubkey: [u8; 32],
pub signer_id: String,
pub sig: [u8; 64],
}
impl DecodeReceipt {
fn leaves(&self) -> Vec<[u8; 32]> {
vec![
self.check_matrix_hash,
self.syndrome_hash,
self.correction_hash,
]
}
fn signing_payload(&self) -> Vec<u8> {
self.payload_with(None)
}
fn payload_with(&self, label: Option<&crate::quantum_energy::EnergyClass>) -> Vec<u8> {
let mut o = crate::quantum_energy::labelled_domain(DOMAIN_DEC, label);
o.extend_from_slice(self.code_id.as_bytes());
o.push(0);
o.extend_from_slice(self.decoder.as_bytes());
o.push(0);
o.extend_from_slice(&self.check_matrix_hash);
o.extend_from_slice(&self.syndrome_hash);
o.extend_from_slice(&self.correction_hash);
o.push(self.converged as u8);
o.extend_from_slice(&self.rounds.to_be_bytes());
o.extend_from_slice(&self.work_messages.to_be_bytes());
o.extend_from_slice(&self.merkle_root_calc());
o.extend_from_slice(&self.joules_micro.to_be_bytes());
crate::quantum_energy::write_label(label, &mut o);
self.grant.append_to(&mut o);
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
}
fn merkle_root_calc(&self) -> [u8; 32] {
merkle_root(&self.leaves())
}
#[allow(clippy::too_many_arguments)]
pub fn seal(
signer: &SigningKey,
signer_id: impl Into<String>,
code_id: impl Into<String>,
decoder: impl Into<String>,
check_matrix_hash: [u8; 32],
syndrome_hash: [u8; 32],
correction_hash: [u8; 32],
converged: bool,
rounds: u32,
work_messages: u64,
joules_micro: u64,
grant: GrantRef,
parent_receipt_hash: Option<[u8; 32]>,
) -> DecodeReceipt {
let mut r = DecodeReceipt {
code_id: code_id.into(),
decoder: decoder.into(),
check_matrix_hash,
syndrome_hash,
correction_hash,
converged,
rounds,
work_messages,
joules_micro,
grant,
parent_receipt_hash,
signer_pubkey: signer.verifying_key().to_bytes(),
signer_id: signer_id.into(),
sig: [0u8; 64],
};
r.sig = signer.sign(&r.signing_payload()).to_bytes();
r
}
pub fn honors_budget(&self) -> bool {
self.joules_micro <= self.grant.joule_ceiling_micro
}
fn body_verifies(&self) -> bool {
if !self.honors_budget() {
return false;
}
true
}
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()
}
pub fn correction_matches(&self, correction_bytes: &[u8]) -> bool {
content_hash(correction_bytes) == self.correction_hash
}
pub fn code_matches(&self, matrix_bytes: &[u8]) -> bool {
content_hash(matrix_bytes) == self.check_matrix_hash
}
pub fn receipt_hash(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(DOMAIN_DEC_ID);
h.update(&self.signing_payload());
h.update(&self.sig);
*h.finalize().as_bytes()
}
pub fn to_json(&self) -> String {
let parent = match self.parent_receipt_hash {
Some(h) => format!("\"{}\"", hx(&h)),
None => "null".into(),
};
format!(
"{{\"kind\":\"quantum-decode\",\"check_matrix_hash\":\"{}\",\"code_id\":{},\
\"converged\":{},\"correction_hash\":\"{}\",\"decoder\":{},\"grant\":{},\
\"joules_micro\":{},\"merkle_root\":\"{}\",\"parent_receipt_hash\":{},\
\"receipt_hash\":\"{}\",\"rounds\":{},\"sig\":\"{}\",\"signer_id\":{},\
\"signer_pubkey\":\"{}\",\"syndrome_hash\":\"{}\",\"work_messages\":{}}}",
hx(&self.check_matrix_hash),
serde_json::to_string(&self.code_id).unwrap(),
self.converged,
hx(&self.correction_hash),
serde_json::to_string(&self.decoder).unwrap(),
self.grant.to_json(),
self.joules_micro,
hx(&self.merkle_root_calc()),
parent,
hx(&self.receipt_hash()),
self.rounds,
hx(&self.sig),
serde_json::to_string(&self.signer_id).unwrap(),
hx(&self.signer_pubkey),
hx(&self.syndrome_hash),
self.work_messages,
)
}
pub fn from_json(s: &str) -> Option<DecodeReceipt> {
let v: serde_json::Value = serde_json::from_str(s).ok()?;
let o = v.as_object()?;
let parent = match o.get("parent_receipt_hash") {
Some(serde_json::Value::String(s)) => Some(from_hex32(s)?),
_ => None,
};
Some(DecodeReceipt {
code_id: o.get("code_id")?.as_str()?.to_owned(),
decoder: o.get("decoder")?.as_str()?.to_owned(),
check_matrix_hash: from_hex32(o.get("check_matrix_hash")?.as_str()?)?,
syndrome_hash: from_hex32(o.get("syndrome_hash")?.as_str()?)?,
correction_hash: from_hex32(o.get("correction_hash")?.as_str()?)?,
converged: o.get("converged")?.as_bool()?,
rounds: o.get("rounds")?.as_u64()? as u32,
work_messages: o.get("work_messages")?.as_u64()?,
joules_micro: o.get("joules_micro")?.as_u64()?,
grant: GrantRef::from_json(o.get("grant")?)?,
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()?)?,
})
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct CompileReceipt {
pub source_hash: [u8; 32],
pub target_hash: [u8; 32],
pub coupling_hash: [u8; 32],
pub method: String,
pub equivalent: bool,
pub swaps: u32,
pub work: u64,
pub joules_micro: u64,
pub grant: GrantRef,
pub parent_receipt_hash: Option<[u8; 32]>,
pub signer_pubkey: [u8; 32],
pub signer_id: String,
pub sig: [u8; 64],
}
impl CompileReceipt {
fn leaves(&self) -> Vec<[u8; 32]> {
vec![self.source_hash, self.target_hash, self.coupling_hash]
}
fn merkle(&self) -> [u8; 32] {
merkle_root(&self.leaves())
}
fn signing_payload(&self) -> Vec<u8> {
self.payload_with(None)
}
fn payload_with(&self, label: Option<&crate::quantum_energy::EnergyClass>) -> Vec<u8> {
let mut o = crate::quantum_energy::labelled_domain(DOMAIN_CMP, label);
o.extend_from_slice(&self.source_hash);
o.extend_from_slice(&self.target_hash);
o.extend_from_slice(&self.coupling_hash);
o.extend_from_slice(self.method.as_bytes());
o.push(0);
o.push(self.equivalent as u8);
o.extend_from_slice(&self.swaps.to_be_bytes());
o.extend_from_slice(&self.work.to_be_bytes());
o.extend_from_slice(&self.merkle());
o.extend_from_slice(&self.joules_micro.to_be_bytes());
crate::quantum_energy::write_label(label, &mut o);
self.grant.append_to(&mut o);
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
}
#[allow(clippy::too_many_arguments)]
pub fn seal(
signer: &SigningKey,
signer_id: impl Into<String>,
method: impl Into<String>,
source_hash: [u8; 32],
target_hash: [u8; 32],
coupling_hash: [u8; 32],
equivalent: bool,
swaps: u32,
work: u64,
joules_micro: u64,
grant: GrantRef,
parent_receipt_hash: Option<[u8; 32]>,
) -> CompileReceipt {
let mut r = CompileReceipt {
source_hash,
target_hash,
coupling_hash,
method: method.into(),
equivalent,
swaps,
work,
joules_micro,
grant,
parent_receipt_hash,
signer_pubkey: signer.verifying_key().to_bytes(),
signer_id: signer_id.into(),
sig: [0u8; 64],
};
r.sig = signer.sign(&r.signing_payload()).to_bytes();
r
}
pub fn honors_budget(&self) -> bool {
self.joules_micro <= self.grant.joule_ceiling_micro
}
fn body_verifies(&self) -> bool {
if !self.honors_budget() {
return false;
}
true
}
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()
}
pub fn source_matches(&self, bytes: &[u8]) -> bool {
content_hash(bytes) == self.source_hash
}
pub fn target_matches(&self, bytes: &[u8]) -> bool {
content_hash(bytes) == self.target_hash
}
pub fn receipt_hash(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(DOMAIN_CMP_ID);
h.update(&self.signing_payload());
h.update(&self.sig);
*h.finalize().as_bytes()
}
pub fn to_json(&self) -> String {
let parent = match self.parent_receipt_hash {
Some(h) => format!("\"{}\"", hx(&h)),
None => "null".into(),
};
format!(
"{{\"kind\":\"quantum-compile\",\"coupling_hash\":\"{}\",\"equivalent\":{},\
\"grant\":{},\"joules_micro\":{},\"merkle_root\":\"{}\",\"method\":{},\
\"parent_receipt_hash\":{},\"receipt_hash\":\"{}\",\"sig\":\"{}\",\
\"signer_id\":{},\"signer_pubkey\":\"{}\",\"source_hash\":\"{}\",\"swaps\":{},\
\"target_hash\":\"{}\",\"work\":{}}}",
hx(&self.coupling_hash),
self.equivalent,
self.grant.to_json(),
self.joules_micro,
hx(&self.merkle()),
serde_json::to_string(&self.method).unwrap(),
parent,
hx(&self.receipt_hash()),
hx(&self.sig),
serde_json::to_string(&self.signer_id).unwrap(),
hx(&self.signer_pubkey),
hx(&self.source_hash),
self.swaps,
hx(&self.target_hash),
self.work,
)
}
pub fn from_json(s: &str) -> Option<CompileReceipt> {
let v: serde_json::Value = serde_json::from_str(s).ok()?;
let o = v.as_object()?;
let parent = match o.get("parent_receipt_hash") {
Some(serde_json::Value::String(s)) => Some(from_hex32(s)?),
_ => None,
};
Some(CompileReceipt {
source_hash: from_hex32(o.get("source_hash")?.as_str()?)?,
target_hash: from_hex32(o.get("target_hash")?.as_str()?)?,
coupling_hash: from_hex32(o.get("coupling_hash")?.as_str()?)?,
method: o.get("method")?.as_str()?.to_owned(),
equivalent: o.get("equivalent")?.as_bool()?,
swaps: o.get("swaps")?.as_u64()? as u32,
work: o.get("work")?.as_u64()?,
joules_micro: o.get("joules_micro")?.as_u64()?,
grant: GrantRef::from_json(o.get("grant")?)?,
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()?)?,
})
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct RearrangeReceipt {
pub initial_hash: [u8; 32],
pub target_hash: [u8; 32],
pub plan_hash: [u8; 32],
pub method: String,
pub success: bool,
pub atoms_moved: u32,
pub total_distance: u64,
pub joules_micro: u64,
pub grant: GrantRef,
pub parent_receipt_hash: Option<[u8; 32]>,
pub signer_pubkey: [u8; 32],
pub signer_id: String,
pub sig: [u8; 64],
}
impl RearrangeReceipt {
fn merkle(&self) -> [u8; 32] {
merkle_root(&[self.initial_hash, self.target_hash, self.plan_hash])
}
fn signing_payload(&self) -> Vec<u8> {
self.payload_with(None)
}
fn payload_with(&self, label: Option<&crate::quantum_energy::EnergyClass>) -> Vec<u8> {
let mut o = crate::quantum_energy::labelled_domain(DOMAIN_REA, label);
o.extend_from_slice(&self.initial_hash);
o.extend_from_slice(&self.target_hash);
o.extend_from_slice(&self.plan_hash);
o.extend_from_slice(self.method.as_bytes());
o.push(0);
o.push(self.success as u8);
o.extend_from_slice(&self.atoms_moved.to_be_bytes());
o.extend_from_slice(&self.total_distance.to_be_bytes());
o.extend_from_slice(&self.merkle());
o.extend_from_slice(&self.joules_micro.to_be_bytes());
crate::quantum_energy::write_label(label, &mut o);
self.grant.append_to(&mut o);
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
}
#[allow(clippy::too_many_arguments)]
pub fn seal(
signer: &SigningKey,
signer_id: impl Into<String>,
method: impl Into<String>,
initial_hash: [u8; 32],
target_hash: [u8; 32],
plan_hash: [u8; 32],
success: bool,
atoms_moved: u32,
total_distance: u64,
joules_micro: u64,
grant: GrantRef,
parent_receipt_hash: Option<[u8; 32]>,
) -> RearrangeReceipt {
let mut r = RearrangeReceipt {
initial_hash,
target_hash,
plan_hash,
method: method.into(),
success,
atoms_moved,
total_distance,
joules_micro,
grant,
parent_receipt_hash,
signer_pubkey: signer.verifying_key().to_bytes(),
signer_id: signer_id.into(),
sig: [0u8; 64],
};
r.sig = signer.sign(&r.signing_payload()).to_bytes();
r
}
pub fn honors_budget(&self) -> bool {
self.joules_micro <= self.grant.joule_ceiling_micro
}
fn body_verifies(&self) -> bool {
if !self.honors_budget() {
return false;
}
true
}
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()
}
pub fn plan_matches(&self, bytes: &[u8]) -> bool {
content_hash(bytes) == self.plan_hash
}
pub fn receipt_hash(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(DOMAIN_REA_ID);
h.update(&self.signing_payload());
h.update(&self.sig);
*h.finalize().as_bytes()
}
pub fn to_json(&self) -> String {
let parent = match self.parent_receipt_hash {
Some(h) => format!("\"{}\"", hx(&h)),
None => "null".into(),
};
format!(
"{{\"kind\":\"quantum-rearrange\",\"atoms_moved\":{},\"grant\":{},\
\"initial_hash\":\"{}\",\"joules_micro\":{},\"merkle_root\":\"{}\",\"method\":{},\
\"parent_receipt_hash\":{},\"plan_hash\":\"{}\",\"receipt_hash\":\"{}\",\"sig\":\"{}\",\
\"signer_id\":{},\"signer_pubkey\":\"{}\",\"success\":{},\"target_hash\":\"{}\",\
\"total_distance\":{}}}",
self.atoms_moved,
self.grant.to_json(),
hx(&self.initial_hash),
self.joules_micro,
hx(&self.merkle()),
serde_json::to_string(&self.method).unwrap(),
parent,
hx(&self.plan_hash),
hx(&self.receipt_hash()),
hx(&self.sig),
serde_json::to_string(&self.signer_id).unwrap(),
hx(&self.signer_pubkey),
self.success,
hx(&self.target_hash),
self.total_distance,
)
}
pub fn from_json(s: &str) -> Option<RearrangeReceipt> {
let v: serde_json::Value = serde_json::from_str(s).ok()?;
let o = v.as_object()?;
let parent = match o.get("parent_receipt_hash") {
Some(serde_json::Value::String(s)) => Some(from_hex32(s)?),
_ => None,
};
Some(RearrangeReceipt {
initial_hash: from_hex32(o.get("initial_hash")?.as_str()?)?,
target_hash: from_hex32(o.get("target_hash")?.as_str()?)?,
plan_hash: from_hex32(o.get("plan_hash")?.as_str()?)?,
method: o.get("method")?.as_str()?.to_owned(),
success: o.get("success")?.as_bool()?,
atoms_moved: o.get("atoms_moved")?.as_u64()? as u32,
total_distance: o.get("total_distance")?.as_u64()?,
joules_micro: o.get("joules_micro")?.as_u64()?,
grant: GrantRef::from_json(o.get("grant")?)?,
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::*;
fn key(s: u8) -> SigningKey {
SigningKey::from_bytes(&[s; 32])
}
fn evid() -> Vec<Evidence> {
vec![Evidence {
kind: "randomized_benchmarking".into(),
blob_hash: content_hash(b"<HDF5 RB dataset bytes>"),
summary: "1q RB fidelity 0.9992".into(),
}]
}
#[test]
fn calibration_seals_and_verifies() {
let grant = GrantRef {
grant_hash: content_hash(b"grant-A"),
capability: "quantum.calibrate".into(),
joule_ceiling_micro: 5_000_000,
funds_ceiling: Some(100),
};
let r = CalibrationReceipt::seal(
&key(1), "did:key:lab", "example:lab3-device", "q3",
content_hash(b"pulse-config-v7"), evid(), 4_200_000, grant, None,
);
assert!(r.verify());
assert!(r.honors_budget());
assert!(r.evidence_matches(0, b"<HDF5 RB dataset bytes>"));
assert!(!r.evidence_matches(0, b"<tampered dataset>"));
}
#[test]
fn over_budget_calibration_fails_verify() {
let grant = GrantRef {
grant_hash: [0u8; 32],
capability: "quantum.calibrate".into(),
joule_ceiling_micro: 1_000_000,
funds_ceiling: None,
};
let r = CalibrationReceipt::seal(
&key(2), "m", "dev", "q0", content_hash(b"cfg"), evid(),
2_000_000, grant, None,
);
assert!(!r.honors_budget());
assert!(!r.verify(), "a run that blew its energy grant must not verify");
}
#[test]
fn tamper_breaks_calibration() {
let mut r = CalibrationReceipt::seal(
&key(3), "m", "dev", "q0", content_hash(b"cfg"), evid(),
10, GrantRef::unbounded("quantum.calibrate"), None,
);
r.joules_micro += 1; assert!(!r.verify());
}
#[test]
fn job_binds_to_calibration_state() {
let cal = CalibrationReceipt::seal(
&key(4), "lab", "dev", "q3", content_hash(b"cfg"), evid(),
100, GrantRef::unbounded("quantum.calibrate"), None,
);
let job = JobReceipt::seal(
&key(4), "lab", "example:qpu-a",
content_hash(b"<QASM circuit>"), content_hash(b"{counts:{00:512,11:488}}"),
Some(cal.receipt_hash()), 1000, 250, GrantRef::unbounded("quantum.job.run"), None,
);
assert!(job.verify());
assert!(job.verify_against_calibration(&cal));
assert!(job.result_matches(b"{counts:{00:512,11:488}}"));
let other = CalibrationReceipt::seal(
&key(4), "lab", "dev", "q3", content_hash(b"cfg2"), evid(),
100, GrantRef::unbounded("quantum.calibrate"), None,
);
assert!(!job.verify_against_calibration(&other));
}
#[test]
fn over_budget_job_fails_verify() {
let grant = GrantRef {
grant_hash: [0u8; 32],
capability: "quantum.job.run".into(),
joule_ceiling_micro: 200,
funds_ceiling: None,
};
let job = JobReceipt::seal(
&key(5), "m", "sim", content_hash(b"c"), content_hash(b"r"),
None, 100, 500, grant, None,
);
assert!(!job.verify());
}
#[test]
fn json_round_trips() {
let cal = CalibrationReceipt::seal(
&key(6), "did:key:z", "dev", "cz(q3,q4)", content_hash(b"cfg"), evid(),
900, GrantRef { grant_hash: content_hash(b"g"), capability: "quantum.calibrate".into(), joule_ceiling_micro: 1_000_000, funds_ceiling: None },
None,
);
assert_eq!(CalibrationReceipt::from_json(&cal.to_json()).unwrap(), cal);
let job = JobReceipt::seal(
&key(6), "did:key:z", "example:qpu-a", content_hash(b"c"), content_hash(b"r"),
Some(cal.receipt_hash()), 2048, 42, GrantRef::unbounded("quantum.job.run"), Some(cal.receipt_hash()),
);
let back = JobReceipt::from_json(&job.to_json()).unwrap();
assert_eq!(back, job);
assert!(back.verify());
}
#[test]
fn calibration_lineage_chains() {
let g = GrantRef::unbounded("quantum.calibrate");
let v1 = CalibrationReceipt::seal(&key(7), "m", "dev", "q0", content_hash(b"c1"), evid(), 10, g.clone(), None);
let v2 = CalibrationReceipt::seal(&key(7), "m", "dev", "q0", content_hash(b"c2"), evid(), 12, g, Some(v1.receipt_hash()));
assert!(v2.verify());
assert_eq!(v2.parent_receipt_hash, Some(v1.receipt_hash()));
}
#[test]
fn mitigation_seals_and_binds_inputs() {
let raw = b"<noise-scaled expectation table: (1.0,0.71),(1.5,0.63),(2.0,0.57)>";
let r = MitigationReceipt::seal(
&key(1), "did:key:lab", "wai.quantum.circuit", "zne.richardson", "ZZ",
content_hash(raw), None,
744_178, 912_680, 20_971, 48_000, 900_000, GrantRef::unbounded("quantum.mitigate"), None,
);
assert!(r.verify());
assert!(r.input_matches(raw));
assert!(!r.input_matches(b"<different shots>"));
assert!(r.noise_model_hash.is_none());
}
#[test]
fn mitigation_binds_pinned_noise_model() {
let raw = b"<measured counts>";
let model = b"<readout assignment matrix A>";
let r = MitigationReceipt::seal(
&key(2), "lab", "ibm:torino", "readout.tensored", "<Z0>",
content_hash(raw), Some(content_hash(model)),
838_861, 1_048_576, 5_242, 32_000, 600_000,
GrantRef::unbounded("quantum.mitigate"), None,
);
assert!(r.verify());
assert!(r.noise_model_matches(model));
assert!(!r.noise_model_matches(b"<a different device's matrix>"));
}
#[test]
fn mitigation_over_budget_and_tamper_fail() {
let grant = GrantRef {
grant_hash: [0u8; 32],
capability: "quantum.mitigate".into(),
joule_ceiling_micro: 500_000,
funds_ceiling: None,
};
let over = MitigationReceipt::seal(
&key(3), "m", "sim", "zne.linear", "X",
content_hash(b"in"), None, 0, 100, 1, 100, 900_000, grant, None,
);
assert!(!over.verify(), "a mitigation that blew its energy grant must not verify");
let mut r = MitigationReceipt::seal(
&key(3), "m", "sim", "zne.linear", "X",
content_hash(b"in"), None, 0, 100, 1, 100, 10,
GrantRef::unbounded("quantum.mitigate"), None,
);
r.mitigated_estimate_fx += 1; assert!(!r.verify(), "tampering with the mitigated estimate must break the receipt");
}
#[test]
fn mitigation_json_round_trips() {
let r = MitigationReceipt::seal(
&key(4), "did:key:z", "wai.quantum.circuit", "shadow.pauli", "XYZ",
content_hash(b"<snapshots>"), None,
-262_144, -314_573, 15_728, 4096, 42,
GrantRef { grant_hash: content_hash(b"g"), capability: "quantum.mitigate".into(), joule_ceiling_micro: 1_000_000, funds_ceiling: None },
None,
);
let back = MitigationReceipt::from_json(&r.to_json()).unwrap();
assert_eq!(back, r);
assert!(back.verify());
assert_eq!(back.raw_estimate_fx, -262_144); }
#[test]
fn decode_seals_and_binds() {
let hmat = b"<parity-check matrix H_Z of the gross code>";
let synd = b"<syndrome 001011...>";
let corr = b"<correction 000010...>";
let r = DecodeReceipt::seal(
&key(1), "did:key:lab", "bb:[[72,12]]", "relay-bp.min-sum",
content_hash(hmat), content_hash(synd), content_hash(corr),
true, 3, 46_656, 900_000, GrantRef::unbounded("quantum.decode"), None,
);
assert!(r.verify());
assert!(r.converged);
assert!(r.correction_matches(corr));
assert!(!r.correction_matches(b"<a different correction>"));
assert!(r.code_matches(hmat));
}
#[test]
fn decode_over_budget_and_tamper_fail() {
let grant = GrantRef {
grant_hash: [0u8; 32],
capability: "quantum.decode".into(),
joule_ceiling_micro: 500_000,
funds_ceiling: None,
};
let over = DecodeReceipt::seal(
&key(2), "m", "toric:L5", "relay-bp.min-sum",
content_hash(b"H"), content_hash(b"s"), content_hash(b"c"),
true, 1, 100, 900_000, grant, None,
);
assert!(!over.verify(), "a decode that blew its energy grant must not verify");
let mut r = DecodeReceipt::seal(
&key(2), "m", "toric:L5", "relay-bp.min-sum",
content_hash(b"H"), content_hash(b"s"), content_hash(b"c"),
true, 1, 100, 10, GrantRef::unbounded("quantum.decode"), None,
);
r.work_messages += 1; assert!(!r.verify(), "tampering with the reported work must break the receipt");
}
#[test]
fn decode_json_round_trips() {
let r = DecodeReceipt::seal(
&key(3), "did:key:z", "toric:L7", "relay-bp.min-sum",
content_hash(b"H"), content_hash(b"s"), content_hash(b"c"),
false, 12, 1_234_567, 42,
GrantRef { grant_hash: content_hash(b"g"), capability: "quantum.decode".into(), joule_ceiling_micro: 2_000_000, funds_ceiling: None },
Some(content_hash(b"prev")),
);
let back = DecodeReceipt::from_json(&r.to_json()).unwrap();
assert_eq!(back, r);
assert!(back.verify());
assert!(!back.converged); }
#[test]
fn compile_seals_and_binds() {
let src = b"<logical circuit: H0 CX0,2 ...>";
let tgt = b"<routed circuit + final map: H0 SWAP1,2 CX0,1 ...>";
let cpl = b"<coupling: line 0-1-2-3-4>";
let r = CompileReceipt::seal(
&key(1), "did:key:lab", "clifford-tableau",
content_hash(src), content_hash(tgt), content_hash(cpl),
true, 3, 4096, 300_000, GrantRef::unbounded("quantum.compile"), None,
);
assert!(r.verify());
assert!(r.equivalent);
assert!(r.source_matches(src));
assert!(r.target_matches(tgt));
assert!(!r.target_matches(b"<a tampered routed circuit>"));
}
#[test]
fn compile_over_budget_and_tamper_fail() {
let grant = GrantRef {
grant_hash: [0u8; 32],
capability: "quantum.compile".into(),
joule_ceiling_micro: 100_000,
funds_ceiling: None,
};
let over = CompileReceipt::seal(
&key(2), "m", "clifford-tableau",
content_hash(b"s"), content_hash(b"t"), content_hash(b"c"),
true, 0, 10, 900_000, grant, None,
);
assert!(!over.verify(), "a compile that blew its energy grant must not verify");
let mut r = CompileReceipt::seal(
&key(2), "m", "clifford-tableau",
content_hash(b"s"), content_hash(b"t"), content_hash(b"c"),
true, 0, 10, 5, GrantRef::unbounded("quantum.compile"), None,
);
r.equivalent = false; assert!(!r.verify(), "tampering with the equivalence verdict must break the receipt");
}
#[test]
fn compile_json_round_trips() {
let r = CompileReceipt::seal(
&key(3), "did:key:z", "clifford-tableau",
content_hash(b"s"), content_hash(b"t"), content_hash(b"c"),
false, 7, 99_999, 21,
GrantRef { grant_hash: content_hash(b"g"), capability: "quantum.compile".into(), joule_ceiling_micro: 1_000_000, funds_ceiling: None },
None,
);
let back = CompileReceipt::from_json(&r.to_json()).unwrap();
assert_eq!(back, r);
assert!(back.verify());
assert!(!back.equivalent);
}
#[test]
fn rearrange_seals_binds_and_json_round_trips() {
let r = RearrangeReceipt::seal(
&key(1), "did:key:lab", "hungarian-lsap",
content_hash(b"<loaded 16x16, 58% fill>"),
content_hash(b"<target 8x8 centered>"),
content_hash(b"<moves: (12->20),(33->21),...>"),
true, 41, 318, 450_000, GrantRef::unbounded("quantum.rearrange"), None,
);
assert!(r.verify());
assert!(r.success);
assert!(r.plan_matches(b"<moves: (12->20),(33->21),...>"));
assert!(!r.plan_matches(b"<a different plan>"));
let back = RearrangeReceipt::from_json(&r.to_json()).unwrap();
assert_eq!(back, r);
assert!(back.verify());
}
#[test]
fn rearrange_over_budget_and_tamper_fail() {
let grant = GrantRef {
grant_hash: [0u8; 32], capability: "quantum.rearrange".into(),
joule_ceiling_micro: 100_000, funds_ceiling: None,
};
let over = RearrangeReceipt::seal(
&key(2), "m", "hungarian-lsap",
content_hash(b"i"), content_hash(b"t"), content_hash(b"p"),
true, 10, 50, 900_000, grant, None,
);
assert!(!over.verify(), "a solve that blew its energy grant must not verify");
let mut r = RearrangeReceipt::seal(
&key(2), "m", "hungarian-lsap",
content_hash(b"i"), content_hash(b"t"), content_hash(b"p"),
true, 10, 50, 5, GrantRef::unbounded("quantum.rearrange"), None,
);
r.success = false; assert!(!r.verify(), "tampering with the success verdict must break the receipt");
}
}
crate::quantum_energy::labellable!(CalibrationReceipt, DOMAIN_CAL_ID);
crate::quantum_energy::labellable!(JobReceipt, DOMAIN_JOB_ID);
crate::quantum_energy::labellable!(MitigationReceipt, DOMAIN_MIT_ID);
crate::quantum_energy::labellable!(DecodeReceipt, DOMAIN_DEC_ID);
crate::quantum_energy::labellable!(CompileReceipt, DOMAIN_CMP_ID);
crate::quantum_energy::labellable!(RearrangeReceipt, DOMAIN_REA_ID);