vela-protocol 0.940.3

Core library for the Vela scientific knowledge protocol: replayable frontier state, signed canonical events, and proof packets.
Documentation
//! Signed packet envelope for the Vela Sidon Producer Profile v1.
//!
//! A port of `research/sidon-producer-profile/reference/packets.py`. Every
//! profile packet (observation, task, result, gate receipt, acceptance,
//! support function, challenge, view decision, repair) is a string-keyed JSON
//! object signed by an Ed25519 actor key. The packet ID is a content
//! identifier over the body (everything except `packet_id` and `signature`);
//! the signature covers a domain-separated preimage binding the ID to the
//! body. Unknown packet types, unknown schema versions, and reserved-field
//! collisions fail closed.

use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64;
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};

use super::canonical::{canonical_bytes, content_id};

/// Schema version stamped into every packet body. Unknown versions fail closed.
pub const SCHEMA_VERSION: &str = "vela.sidon-producer-profile.v1";

/// Domain string mixed into the packet-id preimage. The trailing NUL is part of
/// the value (it is `PACKET_ID_DOMAIN.decode("latin1")` in the Python
/// reference) and encodes as `` in canonical JSON.
pub const PACKET_ID_DOMAIN: &str = "vela.packet-id.v1\u{0}";

/// Domain bytes prepended to the Ed25519 signing preimage.
pub const SIGNATURE_DOMAIN: &[u8] = b"vela.packet-signature.v1\x00";

/// The content-id prefix for each packet type, or `None` for unknown types.
pub fn prefix_for(packet_type: &str) -> Option<&'static str> {
    Some(match packet_type {
        "observation" => "vop_",
        "task" => "vtk_",
        "result" => "vrs_",
        "gate_receipt" => "vgr_",
        "acceptance" => "vac_",
        "support_function" => "vsf_",
        "challenge" => "vch_",
        "view_decision" => "vvd_",
        "repair" => "vrp_",
        _ => return None,
    })
}

/// The signable body of a packet: every field except `packet_id` and
/// `signature`.
pub fn packet_body(packet: &Value) -> Value {
    let mut obj = packet.as_object().cloned().unwrap_or_default();
    obj.remove("packet_id");
    obj.remove("signature");
    Value::Object(obj)
}

/// The packet ID: a content identifier over a packet-id-domain envelope around
/// the body. The second, packet-specific domain label keeps packet IDs from
/// colliding semantically with unrelated content-addressed objects sharing a
/// prefix.
pub fn packet_id(packet_type: &str, body: &Value) -> Result<String, String> {
    let prefix =
        prefix_for(packet_type).ok_or_else(|| format!("unknown packet type: {packet_type}"))?;
    let envelope = serde_json::json!({
        "domain": PACKET_ID_DOMAIN,
        "packet_type": packet_type,
        "body": body,
    });
    content_id(prefix, &envelope)
}

/// The Ed25519 signing preimage: `SIGNATURE_DOMAIN || pid || 0x00 ||
/// canonical_bytes(body)`.
pub fn signing_preimage(pid: &str, body: &Value) -> Result<Vec<u8>, String> {
    let mut buf = Vec::with_capacity(SIGNATURE_DOMAIN.len() + pid.len() + 1 + 64);
    buf.extend_from_slice(SIGNATURE_DOMAIN);
    buf.extend_from_slice(pid.as_bytes());
    buf.push(0u8);
    buf.extend_from_slice(&canonical_bytes(body)?);
    Ok(buf)
}

/// Base64 (standard alphabet) of a verifying key's 32 raw bytes — the
/// `signer_public_key` wire form.
pub fn public_key_b64(signing_key: &SigningKey) -> String {
    BASE64.encode(signing_key.verifying_key().to_bytes())
}

/// Build a signed packet from packet-type-specific `fields`. Reserved keys
/// (`packet_id`, `signature`, `schema_version`, `packet_type`, `signer_actor`,
/// `signer_public_key`) may not appear in `fields`.
pub fn signed_packet(
    packet_type: &str,
    fields: Map<String, Value>,
    signing_key: &SigningKey,
    actor: &str,
) -> Result<Value, String> {
    const RESERVED: [&str; 6] = [
        "packet_id",
        "signature",
        "schema_version",
        "packet_type",
        "signer_actor",
        "signer_public_key",
    ];
    if fields.keys().any(|k| RESERVED.contains(&k.as_str())) {
        return Err("reserved packet field supplied".to_string());
    }

    let mut body = Map::new();
    body.insert(
        "schema_version".into(),
        Value::String(SCHEMA_VERSION.into()),
    );
    body.insert("packet_type".into(), Value::String(packet_type.into()));
    body.insert("signer_actor".into(), Value::String(actor.into()));
    body.insert(
        "signer_public_key".into(),
        Value::String(public_key_b64(signing_key)),
    );
    for (k, v) in fields {
        body.insert(k, v);
    }
    let body = Value::Object(body);

    let pid = packet_id(packet_type, &body)?;
    let signature = signing_key.sign(&signing_preimage(&pid, &body)?);

    let mut packet = body.as_object().cloned().unwrap_or_default();
    packet.insert("packet_id".into(), Value::String(pid));
    let mut sig = Map::new();
    sig.insert("algorithm".into(), Value::String("ed25519".into()));
    sig.insert(
        "value".into(),
        Value::String(BASE64.encode(signature.to_bytes())),
    );
    packet.insert("signature".into(), Value::Object(sig));
    Ok(Value::Object(packet))
}

/// Verify a signed packet: recompute its ID from the body, check it against the
/// stored ID, and verify the Ed25519 signature over the domain-separated
/// preimage. Returns the verified packet ID.
pub fn verify_signed_packet(packet: &Value) -> Result<String, String> {
    let obj = packet
        .as_object()
        .ok_or_else(|| "packet is not an object".to_string())?;

    let ptype = obj
        .get("packet_type")
        .and_then(Value::as_str)
        .ok_or_else(|| "missing packet_type".to_string())?;
    if prefix_for(ptype).is_none() {
        return Err(format!("unknown packet type: {ptype}"));
    }
    if obj.get("schema_version").and_then(Value::as_str) != Some(SCHEMA_VERSION) {
        return Err("unsupported packet schema version".to_string());
    }

    let body = packet_body(packet);
    let expected = packet_id(ptype, &body)?;
    if obj.get("packet_id").and_then(Value::as_str) != Some(expected.as_str()) {
        return Err("packet id mismatch".to_string());
    }

    let signature = obj
        .get("signature")
        .and_then(Value::as_object)
        .ok_or_else(|| "missing signature".to_string())?;
    if signature.get("algorithm").and_then(Value::as_str) != Some("ed25519") {
        return Err("unsupported signature algorithm".to_string());
    }
    let key_b64 = obj
        .get("signer_public_key")
        .and_then(Value::as_str)
        .ok_or_else(|| "missing signer_public_key".to_string())?;
    let sig_b64 = signature
        .get("value")
        .and_then(Value::as_str)
        .ok_or_else(|| "missing signature value".to_string())?;

    let raw_key = BASE64
        .decode(key_b64)
        .map_err(|e| format!("invalid base64 in signer_public_key: {e}"))?;
    let raw_sig = BASE64
        .decode(sig_b64)
        .map_err(|e| format!("invalid base64 in signature: {e}"))?;
    let key_arr: [u8; 32] = raw_key
        .as_slice()
        .try_into()
        .map_err(|_| "invalid Ed25519 public key length".to_string())?;
    let sig_arr: [u8; 64] = raw_sig
        .as_slice()
        .try_into()
        .map_err(|_| "invalid Ed25519 signature length".to_string())?;

    let verifying_key =
        VerifyingKey::from_bytes(&key_arr).map_err(|e| format!("invalid verifying key: {e}"))?;
    let sig = Signature::from_bytes(&sig_arr);
    verifying_key
        .verify(&signing_preimage(&expected, &body)?, &sig)
        .map_err(|e| format!("signature verification failed: {e}"))?;
    Ok(expected)
}

/// The deterministic fixture key for `label`: an Ed25519 key seeded by
/// `sha256("vela-sidon-fixture:" || label)`. Matches the Python reference so
/// the Rust and Python implementations sign identically. Fixture/test use only.
pub fn deterministic_signing_key(label: &str) -> SigningKey {
    let mut hasher = Sha256::new();
    hasher.update(b"vela-sidon-fixture:");
    hasher.update(label.as_bytes());
    let seed: [u8; 32] = hasher.finalize().into();
    SigningKey::from_bytes(&seed)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn sign_then_verify_round_trips() {
        let key = deterministic_signing_key("producer-a");
        let mut fields = Map::new();
        fields.insert("n".into(), json!(4));
        fields.insert("claimed_size".into(), json!(6));
        let packet = signed_packet("result", fields, &key, "producer:test").unwrap();
        let pid = verify_signed_packet(&packet).unwrap();
        assert!(pid.starts_with("vrs_"));
        assert_eq!(packet["packet_id"], json!(pid));
    }

    #[test]
    fn tamper_breaks_verification() {
        let key = deterministic_signing_key("producer-a");
        let mut fields = Map::new();
        fields.insert("claimed_size".into(), json!(6));
        let mut packet = signed_packet("result", fields, &key, "producer:test").unwrap();
        // Mutate the body after signing: id and signature no longer match.
        packet["claimed_size"] = json!(7);
        assert!(verify_signed_packet(&packet).is_err());
    }

    #[test]
    fn reserved_field_rejected() {
        let key = deterministic_signing_key("x");
        let mut fields = Map::new();
        fields.insert("schema_version".into(), json!("nope"));
        assert!(signed_packet("result", fields, &key, "a").is_err());
    }

    #[test]
    fn unknown_packet_type_rejected() {
        assert!(packet_id("nonsense", &json!({})).is_err());
    }
}