zc2 0.0.52

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! Receipts: exactly the keys `lease_id, batch_id, space_id, node_pubkey,
//! image_digest, input_refs, output_hashes, started_at, finished_at,
//! exit_code`, signed over the exact `receipt_json` bytes with the node's
//! Ed25519 key (same scheme as node benchmarks).

use std::collections::BTreeMap;

use serde_json::json;

use super::client::Lease;
use crate::broker::node_identity::NodeKey;

#[derive(Debug, Clone, PartialEq)]
pub struct SignedReceipt {
    pub receipt_json: String,
    pub signature: String,
}

/// A lease input as recorded in a receipt: its name and its URL with the
/// (signed, secret) query string removed.
pub fn input_ref(name: &str, url: &str) -> serde_json::Value {
    json!({ "name": name, "ref": url.split('?').next().unwrap_or(url) })
}

pub fn build(
    lease: &Lease,
    output_hashes: &BTreeMap<String, String>,
    exit_code: i64,
    started: &str,
    finished: &str,
    node_key: &NodeKey,
) -> SignedReceipt {
    let input_refs: Vec<_> = lease
        .inputs
        .iter()
        .map(|i| input_ref(&i.name, &i.url))
        .collect();
    let receipt = json!({
        "lease_id": lease.lease_id,
        "batch_id": lease.batch_id,
        "space_id": lease.space_id,
        "node_pubkey": node_key.public_b64(),
        "image_digest": lease.image.digest,
        "input_refs": input_refs,
        "output_hashes": output_hashes,
        "started_at": started,
        "finished_at": finished,
        "exit_code": exit_code,
    });
    let receipt_json = receipt.to_string();
    let signature = node_key.sign(receipt_json.as_bytes());
    SignedReceipt {
        receipt_json,
        signature,
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::broker::node_identity::verify_sig;
    use crate::spaces::client::{parse_claim, Lease};

    pub fn fixture_lease() -> Lease {
        let text = r#"{"leases":[{"lease_id":"11111111-1111-4111-8111-111111111111","batch_id":123,"space_id":"22222222-2222-4222-8222-222222222222","seq":7,
 "image":{"mirror_ref":"registry:5000/spaces/x@sha256:aa","digest":"sha256:aa"},
 "pull":{"registry":"registry:5000","username":"zk-lease","token":"tok"},
 "inputs":[{"name":"a.fastq","url":"https://example.com/a?sig=1"}],
 "requirements":{"cpus":4,"memory_gb":8,"gpus":0,"min_vram_gb":0,"max_runtime_s":600,"est_runtime_s":120},
 "deadline":"2026-10-04T12:00:00Z","heartbeat_every_s":60}]}"#;
        parse_claim(text).unwrap().remove(0)
    }

    #[test]
    fn receipt_has_exact_keys_and_verifies() {
        let key = NodeKey::generate();
        let lease = fixture_lease();
        let mut hashes = BTreeMap::new();
        hashes.insert("out.txt".to_string(), "ab".repeat(32));
        let r = build(
            &lease,
            &hashes,
            0,
            "2026-10-04T11:00:00Z",
            "2026-10-04T11:01:00Z",
            &key,
        );
        let v: serde_json::Value = serde_json::from_str(&r.receipt_json).unwrap();
        let mut keys: Vec<&str> = v.as_object().unwrap().keys().map(|s| s.as_str()).collect();
        keys.sort();
        let mut want = vec![
            "lease_id",
            "batch_id",
            "space_id",
            "node_pubkey",
            "image_digest",
            "input_refs",
            "output_hashes",
            "started_at",
            "finished_at",
            "exit_code",
        ];
        want.sort();
        assert_eq!(keys, want);
        assert_eq!(v["image_digest"], "sha256:aa");
        assert_eq!(v["node_pubkey"], key.public_b64());
        // The signed query string never lands in the receipt.
        assert_eq!(v["input_refs"][0]["ref"], "https://example.com/a");
        assert!(verify_sig(
            &key.public_b64(),
            r.receipt_json.as_bytes(),
            &r.signature
        ));
        assert!(!verify_sig(&key.public_b64(), b"tampered", &r.signature));
    }
}