use sha2::{Digest, Sha256};
pub const MODEL_RECEIPT_SCHEMA: &str = "buildlang-model-boundary-receipt/v0";
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ModelReceiptSeal {
pub algorithm: String,
pub hex: String,
}
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ModelReceiptShim {
pub name: String,
pub version: String,
pub mode: String,
}
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ModelReceiptSession {
pub listen: String,
pub nonce: String,
pub request_received_utc: String,
pub reply_written_utc: Option<String>,
}
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ModelReceiptHashedBytes {
pub sha256: String,
pub bytes: u64,
}
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ModelReceiptDaemonDigest {
pub status: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hex: Option<String>,
}
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ModelReceiptModel {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub endpoint: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub request_body_sha256: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub daemon_digest: Option<ModelReceiptDaemonDigest>,
}
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ModelReceiptSeed {
pub status: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<i64>,
}
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ModelBoundaryReceipt {
pub schema: String,
pub source: String,
pub shim: ModelReceiptShim,
pub session: ModelReceiptSession,
pub prompt: Option<ModelReceiptHashedBytes>,
pub reply: Option<ModelReceiptHashedBytes>,
pub model: ModelReceiptModel,
pub seed: ModelReceiptSeed,
pub outcome: String,
pub seal: ModelReceiptSeal,
}
fn sha256_hex(bytes: &[u8]) -> String {
let digest = Sha256::digest(bytes);
let mut hex = String::with_capacity(digest.len() * 2);
for byte in digest {
use std::fmt::Write as _;
let _ = write!(&mut hex, "{byte:02x}");
}
hex
}
#[allow(dead_code)]
pub fn seal_model_receipt(receipt: &mut ModelBoundaryReceipt) {
receipt.seal.algorithm = "sha256".to_string();
receipt.seal.hex.clear();
let canonical = serde_json::to_vec(receipt).expect("serialize model boundary receipt");
receipt.seal.hex = sha256_hex(&canonical);
}
pub fn recompute_seal_hex(receipt: &ModelBoundaryReceipt) -> String {
let mut probe = receipt.clone();
probe.seal.algorithm = "sha256".to_string();
probe.seal.hex.clear();
let canonical = serde_json::to_vec(&probe).expect("serialize model boundary receipt");
sha256_hex(&canonical)
}
fn digest_hex_is_well_formed(hex: &str) -> bool {
hex.len() == 64 && hex.chars().all(|ch| ch.is_ascii_hexdigit())
}
fn model_failure_class(json: bool, failure_class: &str, exit_code: i32) -> i32 {
eprintln!("failure_class: {failure_class}");
if json {
let report = serde_json::json!({
"status": "failed",
"failure_class": failure_class,
});
if let Ok(text) = serde_json::to_string_pretty(&report) {
println!("{text}");
}
}
exit_code
}
pub fn verify_model_boundary_receipt(
receipt_json: &serde_json::Value,
json: bool,
) -> Result<(), i32> {
let receipt: ModelBoundaryReceipt =
serde_json::from_value(receipt_json.clone()).map_err(|err| {
eprintln!("Error: model boundary receipt is malformed: {err}");
model_failure_class(json, "MALFORMED", 1)
})?;
let recomputed_seal = recompute_seal_hex(&receipt);
if !recomputed_seal.eq_ignore_ascii_case(&receipt.seal.hex) {
eprintln!(
"Error: seal mismatch: receipt sha256:{}, recomputed sha256:{}",
receipt.seal.hex, recomputed_seal
);
return Err(model_failure_class(json, "SEAL_MISMATCH", 1));
}
if let Some(prompt) = &receipt.prompt {
if !digest_hex_is_well_formed(&prompt.sha256) {
eprintln!("Error: malformed digest in `prompt.sha256`");
return Err(model_failure_class(json, "DIGEST_MALFORMED", 1));
}
}
if let Some(reply) = &receipt.reply {
if !digest_hex_is_well_formed(&reply.sha256) {
eprintln!("Error: malformed digest in `reply.sha256`");
return Err(model_failure_class(json, "DIGEST_MALFORMED", 1));
}
}
if let Some(request_body_sha256) = &receipt.model.request_body_sha256 {
if !digest_hex_is_well_formed(request_body_sha256) {
eprintln!("Error: malformed digest in `model.request_body_sha256`");
return Err(model_failure_class(json, "DIGEST_MALFORMED", 1));
}
}
if let Some(daemon_digest) = &receipt.model.daemon_digest {
if let Some(hex) = &daemon_digest.hex {
if !digest_hex_is_well_formed(hex) {
eprintln!("Error: malformed digest in `model.daemon_digest.hex`");
return Err(model_failure_class(json, "DIGEST_MALFORMED", 1));
}
}
}
if let Some(daemon_digest) = &receipt.model.daemon_digest {
if daemon_digest.status == "UNAVAILABLE" && daemon_digest.hex.is_some() {
eprintln!("Error: `model.daemon_digest.hex` is present alongside status `UNAVAILABLE`");
return Err(model_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
}
}
if receipt.outcome == "COMPLETED" && receipt.reply.is_none() {
eprintln!("Error: outcome `COMPLETED` carries a null `reply`");
return Err(model_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
}
if receipt.outcome == "PROTOCOL_VIOLATION" && receipt.prompt.is_some() {
eprintln!("Error: outcome `PROTOCOL_VIOLATION` carries a present `prompt`");
return Err(model_failure_class(json, "FIELD_CONTRACT_VIOLATION", 1));
}
if json {
let out = serde_json::json!({
"schema": MODEL_RECEIPT_SCHEMA,
"status": "verified",
"source": receipt.source,
"outcome": receipt.outcome,
"seal": { "algorithm": "sha256", "hex": receipt.seal.hex },
});
let text = serde_json::to_string_pretty(&out).map_err(|err| {
eprintln!("Error serializing model receipt verification report: {err}");
1
})?;
println!("{text}");
} else {
println!(
"model receipt: VERIFIED (seal intact, field contracts hold; source={}, outcome={}). \
This artifact witnesses a past boundary crossing only: no re-run, no claim about \
model quality, weights, or determinism.",
receipt.source, receipt.outcome
);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_receipt() -> ModelBoundaryReceipt {
let mut r = ModelBoundaryReceipt {
schema: MODEL_RECEIPT_SCHEMA.to_string(),
source: "model:echo:echo/v1".to_string(),
shim: ModelReceiptShim {
name: "model_shim.py".to_string(),
version: "0.1.0".to_string(),
mode: "echo".to_string(),
},
session: ModelReceiptSession {
listen: "127.0.0.1:8931".to_string(),
nonce: "a1b2c3d4".to_string(),
request_received_utc: "2026-07-29T00:00:00Z".to_string(),
reply_written_utc: Some("2026-07-29T00:00:00Z".to_string()),
},
prompt: Some(ModelReceiptHashedBytes {
sha256: "758d61f26a44448384e5c4468a0dcb7a2abe456067b0f7b505bc28b9411fe931"
.to_string(),
bytes: 4,
}),
reply: Some(ModelReceiptHashedBytes {
sha256: "de2406a7ccdb9add6361bdf86cfd31dfaa95806f8d42f91102290ae3abe5afae"
.to_string(),
bytes: 10,
}),
model: ModelReceiptModel {
name: "echo/v1".to_string(),
endpoint: None,
request_body_sha256: None,
daemon_digest: None,
},
seed: ModelReceiptSeed {
status: "NOT_SENT".to_string(),
value: None,
},
outcome: "COMPLETED".to_string(),
seal: ModelReceiptSeal {
algorithm: "sha256".to_string(),
hex: String::new(),
},
};
seal_model_receipt(&mut r);
r
}
#[test]
fn seal_round_trips_through_serialize_deserialize() {
let r = sample_receipt();
let value = serde_json::to_value(&r).expect("to_value");
let reloaded: ModelBoundaryReceipt = serde_json::from_value(value).expect("from_value");
assert_eq!(recompute_seal_hex(&reloaded), reloaded.seal.hex);
}
#[test]
fn a_valid_receipt_verifies() {
let r = sample_receipt();
let value = serde_json::to_value(&r).expect("to_value");
assert!(verify_model_boundary_receipt(&value, false).is_ok());
}
#[test]
fn seal_mismatch_is_rejected_before_any_field_contract_is_interpreted() {
let mut r = sample_receipt();
r.reply.as_mut().unwrap().sha256 = "0".repeat(64);
let value = serde_json::to_value(&r).expect("to_value");
let err = verify_model_boundary_receipt(&value, false).unwrap_err();
assert_eq!(err, 1);
}
#[test]
fn seal_mismatch_reports_the_expected_failure_class() {
let mut r = sample_receipt();
r.session.nonce = "ffffffff".to_string(); let value = serde_json::to_value(&r).expect("to_value");
assert!(verify_model_boundary_receipt(&value, true).is_err());
}
#[test]
fn resealed_daemon_digest_hex_with_unavailable_status_is_field_contract_violation() {
let mut r = sample_receipt();
r.shim.mode = "ollama".to_string();
r.model = ModelReceiptModel {
name: "llama3.2".to_string(),
endpoint: Some("http://127.0.0.1:11434".to_string()),
request_body_sha256: Some("1".repeat(64)),
daemon_digest: Some(ModelReceiptDaemonDigest {
status: "UNAVAILABLE".to_string(),
hex: Some("2".repeat(64)),
}),
};
seal_model_receipt(&mut r); let value = serde_json::to_value(&r).expect("to_value");
let err = verify_model_boundary_receipt(&value, false).unwrap_err();
assert_eq!(err, 1);
}
#[test]
fn resealed_completed_outcome_with_null_reply_is_field_contract_violation() {
let mut r = sample_receipt();
r.reply = None;
seal_model_receipt(&mut r);
let value = serde_json::to_value(&r).expect("to_value");
assert!(verify_model_boundary_receipt(&value, false).is_err());
}
#[test]
fn resealed_protocol_violation_with_present_prompt_is_field_contract_violation() {
let mut r = sample_receipt();
r.outcome = "PROTOCOL_VIOLATION".to_string();
r.reply = None; seal_model_receipt(&mut r);
let value = serde_json::to_value(&r).expect("to_value");
assert!(verify_model_boundary_receipt(&value, false).is_err());
}
#[test]
fn malformed_digest_is_rejected() {
let mut r = sample_receipt();
r.prompt.as_mut().unwrap().sha256 = "not-a-real-digest".to_string();
seal_model_receipt(&mut r);
let value = serde_json::to_value(&r).expect("to_value");
assert!(verify_model_boundary_receipt(&value, false).is_err());
}
#[test]
fn a_required_field_removed_is_malformed() {
let r = sample_receipt();
let mut value = serde_json::to_value(&r).expect("to_value");
value.as_object_mut().unwrap().remove("shim");
assert!(verify_model_boundary_receipt(&value, false).is_err());
}
#[test]
fn golden_fixture_reseals_to_its_pinned_seal() {
let text = include_str!("../tests/fixtures/model-receipt-golden.json");
let value: serde_json::Value = serde_json::from_str(text).expect("parse golden fixture");
let receipt: ModelBoundaryReceipt =
serde_json::from_value(value.clone()).expect("golden fixture matches schema");
let recomputed = recompute_seal_hex(&receipt);
assert_eq!(
recomputed, receipt.seal.hex,
"golden fixture seal must reseal identically (cross-language pin)"
);
assert_eq!(
receipt.seal.hex, "6bb2a09c47f5eaa2e3208a5eadcd6d57d1faffa74a567e024e920571c3794035",
"golden fixture's PINNED seal changed -- this breaks the cross-repo contract"
);
assert!(verify_model_boundary_receipt(&value, false).is_ok());
}
}