moonproof-contracts 0.2.1

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
Documentation
//! Integrity verification of compiled ZK artifacts against the
//! `compiler/contract-manifest.json` compactc writes beside them.
//!
//! Mirrors midnight-js's `zk-artifact-manifest.ts`: every prover key,
//! verifier key and ZKIR file a provider reads must match the size and
//! sha-256 the manifest records for it, and verification is required by
//! default. A swapped key would otherwise be proved against silently.
//! The manifest itself can be pinned by its own sha-256, which defends
//! against a coordinated swap of artifacts and manifest together.

use std::collections::BTreeMap;

use serde_json::Value;
use sha2::{Digest, Sha256};

use crate::error::{ContractRuntimeError, Result};

/// Directory, relative to the contract root, that holds the manifest.
pub const ZK_MANIFEST_DIR: &str = "compiler";
/// File name of the manifest.
pub const ZK_MANIFEST_FILE_NAME: &str = "contract-manifest.json";

const SUPPORTED_MANIFEST_VERSION: &str = "1";

/// How strictly a provider verifies the artifacts it reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ZkArtifactIntegrityMode {
    /// A manifest must exist and certify every artifact read.
    #[default]
    Require,
    /// Without a manifest, artifacts load unverified; with one, every
    /// artifact read must be certified by it.
    RequireIfPresent,
    /// Verify what the manifest certifies; log and continue where there
    /// is no manifest or no entry. A mismatch is still an error.
    Warn,
    /// No verification.
    Off,
}

/// Integrity options a provider is constructed with.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ZkConfigIntegrityOptions {
    pub mode: ZkArtifactIntegrityMode,
    /// sha-256 of the manifest file's bytes. When set, a missing or
    /// different manifest is an error regardless of `mode`.
    pub expected_manifest_hash: Option<[u8; 32]>,
}

/// One certified file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ZkArtifactManifestFile {
    pub size: u64,
    pub hash: [u8; 32],
}

/// A parsed manifest. `files` is keyed by `<directory>/<file>`, the
/// path relative to the contract root.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ZkArtifactManifest {
    pub compiler_version: Option<String>,
    pub language_version: Option<String>,
    pub runtime_version: Option<String>,
    pub files: BTreeMap<String, ZkArtifactManifestFile>,
}

fn integrity_error(message: impl Into<String>) -> ContractRuntimeError {
    ContractRuntimeError::ZkArtifactIntegrity(message.into())
}

/// Parse a manifest. A duplicate key anywhere is refused: JSON parsers
/// keep one of the two values, so an ambiguous manifest cannot certify
/// anything.
pub fn parse_zk_artifact_manifest(raw: &[u8]) -> Result<ZkArtifactManifest> {
    let text = std::str::from_utf8(raw)
        .map_err(|e| integrity_error(format!("ZK artifact manifest is not UTF-8: {e}")))?;
    let root: Value = serde_json::from_str(text)
        .map_err(|e| integrity_error(format!("ZK artifact manifest is not valid JSON: {e}")))?;
    if let Some(key) = find_duplicate_key(text) {
        return Err(integrity_error(format!(
            "ZK artifact manifest contains a duplicate key {key:?}; an ambiguous manifest \
             cannot be trusted as an integrity check"
        )));
    }
    let Value::Object(root) = root else {
        return Err(integrity_error(
            "ZK artifact manifest must be a JSON object",
        ));
    };
    let version = root.get("manifest-version");
    if version.and_then(Value::as_str) != Some(SUPPORTED_MANIFEST_VERSION) {
        return Err(integrity_error(format!(
            "unsupported ZK artifact manifest-version: expected {SUPPORTED_MANIFEST_VERSION:?}, \
             got {}",
            version.map_or_else(|| "nothing".to_owned(), ToString::to_string)
        )));
    }

    let mut files = BTreeMap::new();
    for (dir_name, dir_value) in &root {
        let Value::Object(dir) = dir_value else {
            continue;
        };
        if dir.get("type").and_then(Value::as_str) != Some("directory") {
            continue;
        }
        for (child_name, child_value) in dir {
            // Skip the `type` discriminator and anything that is not a
            // file directly in the directory (deeper nesting is not
            // certified, as upstream).
            let Value::Object(child) = child_value else {
                continue;
            };
            if child_name == "type" || child.get("type").and_then(Value::as_str) != Some("file") {
                continue;
            }
            let key = format!("{dir_name}/{child_name}");
            let size = child.get("size").and_then(Value::as_u64).ok_or_else(|| {
                integrity_error(format!(
                    "ZK artifact manifest entry {key:?} has an invalid size"
                ))
            })?;
            let hash = child
                .get("hash")
                .and_then(Value::as_str)
                .and_then(parse_sha256_hex)
                .ok_or_else(|| {
                    integrity_error(format!(
                        "ZK artifact manifest entry {key:?} has an invalid sha-256 hash"
                    ))
                })?;
            files.insert(key, ZkArtifactManifestFile { size, hash });
        }
    }

    let text_field = |name: &str| {
        root.get(name)
            .and_then(Value::as_str)
            .map(ToOwned::to_owned)
    };
    Ok(ZkArtifactManifest {
        compiler_version: text_field("compiler-version"),
        language_version: text_field("language-version"),
        runtime_version: text_field("runtime-version"),
        files,
    })
}

fn parse_sha256_hex(s: &str) -> Option<[u8; 32]> {
    let bytes = hex::decode(s).ok()?;
    bytes.try_into().ok()
}

/// The first key repeated within one JSON object, scanning the text.
/// `serde_json`'s object type keeps the last value for a repeated key,
/// so duplicates have to be found before parsing loses them. The input
/// has already parsed as JSON, so the scanner only tracks strings and
/// nesting.
fn find_duplicate_key(json: &str) -> Option<String> {
    use std::collections::HashSet;
    let bytes = json.as_bytes();
    let mut stack: Vec<Option<HashSet<String>>> = Vec::new();
    let mut awaiting_key = false;
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'"' => {
                let start = i;
                i += 1;
                while bytes[i] != b'"' {
                    i += if bytes[i] == b'\\' { 2 } else { 1 };
                }
                i += 1;
                if awaiting_key {
                    if let Some(Some(keys)) = stack.last_mut() {
                        let key: String = serde_json::from_str(&json[start..i]).ok()?;
                        if !keys.insert(key.clone()) {
                            return Some(key);
                        }
                    }
                }
                awaiting_key = false;
                continue;
            }
            b'{' => {
                stack.push(Some(HashSet::new()));
                awaiting_key = true;
            }
            b'[' => {
                stack.push(None);
                awaiting_key = false;
            }
            b'}' | b']' => {
                stack.pop();
                awaiting_key = false;
            }
            b',' => awaiting_key = matches!(stack.last(), Some(Some(_))),
            b':' => awaiting_key = false,
            _ => {}
        }
        i += 1;
    }
    None
}

/// Refuse manifest bytes whose sha-256 is not `expected`.
pub fn assert_manifest_hash(raw: &[u8], expected: &[u8; 32]) -> Result<()> {
    let actual: [u8; 32] = Sha256::digest(raw).into();
    if &actual != expected {
        return Err(integrity_error(format!(
            "ZK artifact manifest failed integrity verification: expected sha-256 {}, got {}",
            hex::encode(expected),
            hex::encode(actual)
        )));
    }
    Ok(())
}

/// Check `bytes`, read from `relative_path` under the contract root,
/// against `manifest` under `mode`.
pub fn verify_zk_artifact_integrity(
    manifest: Option<&ZkArtifactManifest>,
    relative_path: &str,
    bytes: &[u8],
    mode: ZkArtifactIntegrityMode,
) -> Result<()> {
    if mode == ZkArtifactIntegrityMode::Off {
        return Ok(());
    }
    let Some(manifest) = manifest else {
        if mode == ZkArtifactIntegrityMode::Require {
            return Err(integrity_error(format!(
                "no ZK artifact manifest ({ZK_MANIFEST_DIR}/{ZK_MANIFEST_FILE_NAME}) was found; \
                 integrity verification is required. Recompile with a manifest-emitting compactc, \
                 or construct the provider with a RequireIfPresent, Warn or Off integrity mode"
            )));
        }
        tracing::warn!(
            artifact = relative_path,
            "no ZK artifact manifest was found; skipping integrity verification"
        );
        return Ok(());
    };
    let Some(entry) = manifest.files.get(relative_path) else {
        if mode == ZkArtifactIntegrityMode::Warn {
            tracing::warn!(
                artifact = relative_path,
                "the ZK artifact manifest has no entry for this artifact; skipping its \
                 integrity verification"
            );
            return Ok(());
        }
        return Err(integrity_error(format!(
            "ZK artifact manifest has no entry for {relative_path:?}; the manifest does not \
             certify this artifact, so the artifact set is stale or partial"
        )));
    };
    if bytes.len() as u64 != entry.size {
        return Err(integrity_error(format!(
            "ZK artifact {relative_path:?} failed integrity verification: expected {} bytes, \
             got {}",
            entry.size,
            bytes.len()
        )));
    }
    let actual: [u8; 32] = Sha256::digest(bytes).into();
    if actual != entry.hash {
        return Err(integrity_error(format!(
            "ZK artifact {relative_path:?} failed integrity verification: expected sha-256 {}, \
             got {}",
            hex::encode(entry.hash),
            hex::encode(actual)
        )));
    }
    Ok(())
}

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

    const HASH: &str = "fcb84b2a798341df6df4909a911b6590d928390fed3c5c93f8a3d8acf84db6c9";

    fn manifest_json(entries: &str) -> String {
        format!(
            r#"{{"manifest-version":"1","compiler-version":"0.36.1",
                "keys":{{"type":"directory",{entries}}}}}"#
        )
    }

    fn manifest_for(bytes: &[u8]) -> ZkArtifactManifest {
        let hash = hex::encode(Sha256::digest(bytes));
        let raw = manifest_json(&format!(
            r#""c.verifier":{{"type":"file","size":{},"hash":"{hash}"}}"#,
            bytes.len()
        ));
        parse_zk_artifact_manifest(raw.as_bytes()).unwrap()
    }

    #[test]
    fn parses_files_keyed_by_directory_and_name() {
        let raw = manifest_json(&format!(
            r#""c.prover":{{"type":"file","size":3,"hash":"{HASH}"}}"#
        ));
        let m = parse_zk_artifact_manifest(raw.as_bytes()).unwrap();
        assert_eq!(m.compiler_version.as_deref(), Some("0.36.1"));
        assert_eq!(m.files["keys/c.prover"].size, 3);
    }

    #[test]
    fn refuses_a_duplicate_key() {
        let raw = manifest_json(&format!(
            r#""c.prover":{{"type":"file","size":3,"hash":"{HASH}"}},
               "c.prover":{{"type":"file","size":4,"hash":"{HASH}"}}"#
        ));
        assert!(parse_zk_artifact_manifest(raw.as_bytes()).is_err());
    }

    #[test]
    fn refuses_an_unsupported_version_and_a_bad_hash() {
        assert!(parse_zk_artifact_manifest(br#"{"manifest-version":"2"}"#).is_err());
        let raw = manifest_json(r#""c.prover":{"type":"file","size":3,"hash":"abc"}"#);
        assert!(parse_zk_artifact_manifest(raw.as_bytes()).is_err());
    }

    #[test]
    fn verifies_size_and_hash() {
        let m = manifest_for(b"key");
        let mode = ZkArtifactIntegrityMode::Require;
        assert!(verify_zk_artifact_integrity(Some(&m), "keys/c.verifier", b"key", mode).is_ok());
        assert!(verify_zk_artifact_integrity(Some(&m), "keys/c.verifier", b"kez", mode).is_err());
        assert!(verify_zk_artifact_integrity(Some(&m), "keys/c.verifier", b"keys", mode).is_err());
    }

    #[test]
    fn modes_decide_what_a_missing_manifest_or_entry_means() {
        use ZkArtifactIntegrityMode::{Off, Require, RequireIfPresent, Warn};
        let m = manifest_for(b"key");
        assert!(verify_zk_artifact_integrity(None, "keys/c.verifier", b"x", Require).is_err());
        assert!(
            verify_zk_artifact_integrity(None, "keys/c.verifier", b"x", RequireIfPresent).is_ok()
        );
        assert!(
            verify_zk_artifact_integrity(Some(&m), "keys/d.verifier", b"x", RequireIfPresent)
                .is_err()
        );
        assert!(verify_zk_artifact_integrity(Some(&m), "keys/d.verifier", b"x", Warn).is_ok());
        assert!(verify_zk_artifact_integrity(Some(&m), "keys/c.verifier", b"bad", Warn).is_err());
        assert!(verify_zk_artifact_integrity(Some(&m), "keys/c.verifier", b"bad", Off).is_ok());
    }

    #[test]
    fn pinned_manifest_hash() {
        let raw = b"{}";
        let good: [u8; 32] = Sha256::digest(raw).into();
        assert!(assert_manifest_hash(raw, &good).is_ok());
        assert!(assert_manifest_hash(raw, &[0u8; 32]).is_err());
    }
}