moonproof-contracts 0.2.2

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
Documentation
//! Contract key locations: the name a contract call's proof preimage
//! gives its proving keys.
//!
//! A bare circuit id is ambiguous once a transaction calls more than
//! one contract, so on ledger 9 a call names its keys as
//! `contract:<address>/<circuit>?vk=<sha256 of the deployed verifier key>`,
//! the grammar midnight-js and compact-js use. Resolution joins on the
//! verifier key, which is what the chain checks a proof against, so a
//! redeploy, a second deployment of the same contract, or two contracts
//! sharing a circuit name all resolve to the right artifacts.

use crate::types::{CircuitId, ZkConfig};
use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::onchain_runtime::state::ContractOperation;
use moonproof_ledger::transient_crypto::proofs::ProvingKeyMaterial;
use sha2::{Digest, Sha256};

use crate::error::{ContractRuntimeError, Result};
use crate::providers::zk_config::ZkConfigProvider;

const PREFIX: &str = "contract:";

/// A parsed contract key location.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ContractKeyLocation {
    pub contract_address: ContractAddress,
    pub circuit_id: CircuitId,
    pub verifier_key_hash: [u8; 32],
}

impl ContractKeyLocation {
    /// The location of a call to `circuit_id` on the contract at
    /// `contract_address`, whose deployed operation is `op`.
    ///
    /// # Errors
    ///
    /// When `op` has no verifier key (a key location can only name a
    /// deployed key) or the circuit id is outside `[A-Za-z0-9_]+`.
    pub fn for_operation(
        contract_address: ContractAddress,
        circuit_id: &CircuitId,
        op: &ContractOperation,
    ) -> Result<Self> {
        let vk = moonproof_ledger::operation_verifier_key_bytes(op).ok_or_else(|| {
            ContractRuntimeError::Provider {
                provider: "key_location",
                message: format!(
                    "operation '{}' has no verifier key to name its proving keys by",
                    circuit_id.as_str()
                ),
            }
        })?;
        if !valid_circuit_id(circuit_id.as_str()) {
            return Err(ContractRuntimeError::Provider {
                provider: "key_location",
                message: format!(
                    "circuit id '{}' must match [A-Za-z0-9_]+",
                    circuit_id.as_str()
                ),
            });
        }
        Ok(Self {
            contract_address,
            circuit_id: circuit_id.clone(),
            verifier_key_hash: hash_verifier_key(&vk),
        })
    }

    #[must_use]
    pub fn encode(&self) -> String {
        format!(
            "{PREFIX}{}/{}?vk={}",
            hex::encode(self.contract_address.0 .0),
            self.circuit_id.as_str(),
            hex::encode(self.verifier_key_hash)
        )
    }

    /// `None` for anything that is not a contract key location: a bare
    /// circuit id, or a protocol built-in such as `midnight/zswap/spend`.
    #[must_use]
    pub fn parse(location: &str) -> Option<Self> {
        let rest = location.strip_prefix(PREFIX)?;
        let (address, rest) = rest.split_once('/')?;
        let (circuit, hash) = rest.split_once("?vk=")?;
        if address.len() != 64 || !valid_circuit_id(circuit) || hash.len() != 64 {
            return None;
        }
        // The digest is lowercase by definition; the address may be
        // written in either case.
        if hash.bytes().any(|b| b.is_ascii_uppercase()) {
            return None;
        }
        let address: [u8; 32] = hex::decode(address).ok()?.try_into().ok()?;
        let verifier_key_hash: [u8; 32] = hex::decode(hash).ok()?.try_into().ok()?;
        Some(Self {
            contract_address: ContractAddress(moonproof_ledger::base_crypto::hash::HashOutput(
                address,
            )),
            circuit_id: CircuitId::new(circuit.to_owned()),
            verifier_key_hash,
        })
    }
}

/// SHA-256 of a tagged-serialized verifier key, as deployed.
#[must_use]
pub fn hash_verifier_key(verifier_key: &[u8]) -> [u8; 32] {
    Sha256::digest(verifier_key).into()
}

fn valid_circuit_id(id: &str) -> bool {
    !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
}

/// The proving keys a preimage's `key_location` names, from the
/// first of `sources` whose artifacts match it.
///
/// A contract key location matches the source whose verifier key for
/// the circuit hashes to the embedded digest; a bare circuit id (the
/// ledger 8 form) matches the first source that has the circuit.
/// `Ok(None)` for protocol built-ins, which the prover resolves itself.
///
/// # Errors
///
/// [`ContractRuntimeError::ZkArtifactIntegrity`] when a contract key
/// location matches no source: the local artifacts are not the ones
/// deployed, and proving with them could only fail on chain. An
/// integrity failure raised by a source while probing is returned in
/// preference, since it says more than "missing".
pub async fn resolve_key_location(
    key_location: &str,
    sources: &[&dyn ZkConfigProvider],
) -> Result<Option<ProvingKeyMaterial>> {
    if let Some(parsed) = ContractKeyLocation::parse(key_location) {
        let mut integrity_failure = None;
        for source in sources {
            let vk = match source.get_verifier_key(&parsed.circuit_id).await {
                Ok(vk) => vk,
                Err(e @ ContractRuntimeError::ZkArtifactIntegrity(_)) => {
                    integrity_failure.get_or_insert(e);
                    continue;
                }
                Err(_) => continue,
            };
            if hash_verifier_key(&vk.0) == parsed.verifier_key_hash {
                // Reuse the already-verified verifier key and fetch prover key + ZKIR concurrently.
                let (prover_key, zkir) = futures::try_join!(
                    source.get_prover_key(&parsed.circuit_id),
                    source.get_zkir(&parsed.circuit_id),
                )?;
                return Ok(Some(ProvingKeyMaterial {
                    prover_key: prover_key.0,
                    verifier_key: vk.0,
                    ir_source: zkir.0,
                }));
            }
        }
        return Err(integrity_failure.unwrap_or_else(|| {
            ContractRuntimeError::ZkArtifactIntegrity(format!(
                "no local artifacts for circuit '{}' match the verifier key deployed at {} \
                 (key location {key_location}); recompile or fetch the artifacts of the deployed contract",
                parsed.circuit_id.as_str(),
                hex::encode(parsed.contract_address.0 .0),
            ))
        }));
    }
    if key_location.starts_with("midnight/") {
        return Ok(None);
    }
    let circuit_id = CircuitId::new(key_location.to_owned());
    for source in sources {
        match source.get(&circuit_id).await {
            Ok(bundle) => return Ok(Some(material(bundle))),
            Err(e @ ContractRuntimeError::ZkArtifactIntegrity(_)) => return Err(e),
            Err(_) => {}
        }
    }
    Ok(None)
}

fn material(bundle: ZkConfig) -> ProvingKeyMaterial {
    ProvingKeyMaterial {
        prover_key: bundle.prover_key.0,
        verifier_key: bundle.verifier_key.0,
        ir_source: bundle.zkir.0,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::providers::FileSystemZkConfigProvider;
    use moonproof_ledger::base_crypto::hash::HashOutput;
    use moonproof_ledger::serialize::tagged_deserialize;

    fn counter() -> FileSystemZkConfigProvider {
        let mut p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        p.pop();
        p.push("test-fixtures/contracts/counter");
        FileSystemZkConfigProvider::new(p)
    }

    fn address() -> ContractAddress {
        ContractAddress(HashOutput([0xab; 32]))
    }

    async fn deployed_location(
        source: &FileSystemZkConfigProvider,
    ) -> (ContractKeyLocation, Vec<u8>) {
        let vk = source
            .get_verifier_key(&CircuitId::new("increment"))
            .await
            .unwrap()
            .0;
        let op = moonproof_ledger::contract_operation(Some(
            tagged_deserialize(&mut vk.as_slice()).unwrap(),
        ));
        let location =
            ContractKeyLocation::for_operation(address(), &CircuitId::new("increment"), &op)
                .unwrap();
        (location, vk)
    }

    #[test]
    fn encodes_the_midnight_js_grammar() {
        let location = ContractKeyLocation {
            contract_address: address(),
            circuit_id: CircuitId::new("increment"),
            verifier_key_hash: hash_verifier_key(b"abc"),
        };
        assert_eq!(
            location.encode(),
            format!(
                "contract:{}/increment?vk=ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
                "ab".repeat(32)
            )
        );
        assert_eq!(
            ContractKeyLocation::parse(&location.encode()),
            Some(location)
        );
    }

    #[test]
    fn anything_else_is_not_a_contract_location() {
        let vk = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
        for bad in [
            "increment".to_owned(),
            "midnight/zswap/spend".to_owned(),
            format!("contract:{}/increment?vk={}", "ab".repeat(31), vk),
            format!("contract:{}/inc-rement?vk={}", "ab".repeat(32), vk),
            format!(
                "contract:{}/increment?vk={}",
                "ab".repeat(32),
                vk.to_uppercase()
            ),
            format!("contract:{}/increment", "ab".repeat(32)),
        ] {
            assert_eq!(ContractKeyLocation::parse(&bad), None, "{bad}");
        }
    }

    #[tokio::test]
    async fn the_deployed_key_hashes_like_its_artifact() {
        let source = counter();
        let (location, vk) = deployed_location(&source).await;
        assert_eq!(location.verifier_key_hash, hash_verifier_key(&vk));
    }

    #[tokio::test]
    async fn a_contract_location_resolves_by_verifier_key() {
        let source = counter();
        let empty_dir = tempfile::tempdir().unwrap();
        let empty = FileSystemZkConfigProvider::new(empty_dir.path());
        let (location, vk) = deployed_location(&source).await;
        let material = resolve_key_location(&location.encode(), &[&empty, &source])
            .await
            .unwrap()
            .expect("the matching source serves it");
        assert_eq!(material.verifier_key, vk);
    }

    #[tokio::test]
    async fn drifted_artifacts_are_refused() {
        let source = counter();
        let (mut location, _) = deployed_location(&source).await;
        location.verifier_key_hash = [0; 32];
        let result = resolve_key_location(&location.encode(), &[&source]).await;
        assert!(matches!(
            result,
            Err(ContractRuntimeError::ZkArtifactIntegrity(_))
        ));
    }

    #[tokio::test]
    async fn bare_ids_and_builtins() {
        let source = counter();
        assert!(resolve_key_location("increment", &[&source])
            .await
            .unwrap()
            .is_some());
        assert!(resolve_key_location("decrement", &[&source])
            .await
            .unwrap()
            .is_none());
        assert!(resolve_key_location("midnight/zswap/spend", &[&source])
            .await
            .unwrap()
            .is_none());
    }
}