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:";
#[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 {
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)
)
}
#[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;
}
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,
})
}
}
#[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'_')
}
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 {
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());
}
}