Skip to main content

moonproof_contracts/
key_location.rs

1//! Contract key locations: the name a contract call's proof preimage
2//! gives its proving keys.
3//!
4//! A bare circuit id is ambiguous once a transaction calls more than
5//! one contract, so on ledger 9 a call names its keys as
6//! `contract:<address>/<circuit>?vk=<sha256 of the deployed verifier key>`,
7//! the grammar midnight-js and compact-js use. Resolution joins on the
8//! verifier key, which is what the chain checks a proof against, so a
9//! redeploy, a second deployment of the same contract, or two contracts
10//! sharing a circuit name all resolve to the right artifacts.
11
12use crate::types::{CircuitId, ZkConfig};
13use moonproof_ledger::coin_structure::contract::ContractAddress;
14use moonproof_ledger::onchain_runtime::state::ContractOperation;
15use moonproof_ledger::transient_crypto::proofs::ProvingKeyMaterial;
16use sha2::{Digest, Sha256};
17
18use crate::error::{ContractRuntimeError, Result};
19use crate::providers::zk_config::ZkConfigProvider;
20
21const PREFIX: &str = "contract:";
22
23/// A parsed contract key location.
24#[derive(Debug, Clone, PartialEq, Eq, Hash)]
25pub struct ContractKeyLocation {
26    pub contract_address: ContractAddress,
27    pub circuit_id: CircuitId,
28    pub verifier_key_hash: [u8; 32],
29}
30
31impl ContractKeyLocation {
32    /// The location of a call to `circuit_id` on the contract at
33    /// `contract_address`, whose deployed operation is `op`.
34    ///
35    /// # Errors
36    ///
37    /// When `op` has no verifier key (a key location can only name a
38    /// deployed key) or the circuit id is outside `[A-Za-z0-9_]+`.
39    pub fn for_operation(
40        contract_address: ContractAddress,
41        circuit_id: &CircuitId,
42        op: &ContractOperation,
43    ) -> Result<Self> {
44        let vk = moonproof_ledger::operation_verifier_key_bytes(op).ok_or_else(|| {
45            ContractRuntimeError::Provider {
46                provider: "key_location",
47                message: format!(
48                    "operation '{}' has no verifier key to name its proving keys by",
49                    circuit_id.as_str()
50                ),
51            }
52        })?;
53        if !valid_circuit_id(circuit_id.as_str()) {
54            return Err(ContractRuntimeError::Provider {
55                provider: "key_location",
56                message: format!(
57                    "circuit id '{}' must match [A-Za-z0-9_]+",
58                    circuit_id.as_str()
59                ),
60            });
61        }
62        Ok(Self {
63            contract_address,
64            circuit_id: circuit_id.clone(),
65            verifier_key_hash: hash_verifier_key(&vk),
66        })
67    }
68
69    #[must_use]
70    pub fn encode(&self) -> String {
71        format!(
72            "{PREFIX}{}/{}?vk={}",
73            hex::encode(self.contract_address.0 .0),
74            self.circuit_id.as_str(),
75            hex::encode(self.verifier_key_hash)
76        )
77    }
78
79    /// `None` for anything that is not a contract key location: a bare
80    /// circuit id, or a protocol built-in such as `midnight/zswap/spend`.
81    #[must_use]
82    pub fn parse(location: &str) -> Option<Self> {
83        let rest = location.strip_prefix(PREFIX)?;
84        let (address, rest) = rest.split_once('/')?;
85        let (circuit, hash) = rest.split_once("?vk=")?;
86        if address.len() != 64 || !valid_circuit_id(circuit) || hash.len() != 64 {
87            return None;
88        }
89        // The digest is lowercase by definition; the address may be
90        // written in either case.
91        if hash.bytes().any(|b| b.is_ascii_uppercase()) {
92            return None;
93        }
94        let address: [u8; 32] = hex::decode(address).ok()?.try_into().ok()?;
95        let verifier_key_hash: [u8; 32] = hex::decode(hash).ok()?.try_into().ok()?;
96        Some(Self {
97            contract_address: ContractAddress(moonproof_ledger::base_crypto::hash::HashOutput(
98                address,
99            )),
100            circuit_id: CircuitId::new(circuit.to_owned()),
101            verifier_key_hash,
102        })
103    }
104}
105
106/// SHA-256 of a tagged-serialized verifier key, as deployed.
107#[must_use]
108pub fn hash_verifier_key(verifier_key: &[u8]) -> [u8; 32] {
109    Sha256::digest(verifier_key).into()
110}
111
112fn valid_circuit_id(id: &str) -> bool {
113    !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
114}
115
116/// The proving keys a preimage's `key_location` names, from the
117/// first of `sources` whose artifacts match it.
118///
119/// A contract key location matches the source whose verifier key for
120/// the circuit hashes to the embedded digest; a bare circuit id (the
121/// ledger 8 form) matches the first source that has the circuit.
122/// `Ok(None)` for protocol built-ins, which the prover resolves itself.
123///
124/// # Errors
125///
126/// [`ContractRuntimeError::ZkArtifactIntegrity`] when a contract key
127/// location matches no source: the local artifacts are not the ones
128/// deployed, and proving with them could only fail on chain. An
129/// integrity failure raised by a source while probing is returned in
130/// preference, since it says more than "missing".
131pub async fn resolve_key_location(
132    key_location: &str,
133    sources: &[&dyn ZkConfigProvider],
134) -> Result<Option<ProvingKeyMaterial>> {
135    if let Some(parsed) = ContractKeyLocation::parse(key_location) {
136        let mut integrity_failure = None;
137        for source in sources {
138            let vk = match source.get_verifier_key(&parsed.circuit_id).await {
139                Ok(vk) => vk,
140                Err(e @ ContractRuntimeError::ZkArtifactIntegrity(_)) => {
141                    integrity_failure.get_or_insert(e);
142                    continue;
143                }
144                Err(_) => continue,
145            };
146            if hash_verifier_key(&vk.0) == parsed.verifier_key_hash {
147                // Reuse the already-verified verifier key and fetch prover key + ZKIR concurrently.
148                let (prover_key, zkir) = futures::try_join!(
149                    source.get_prover_key(&parsed.circuit_id),
150                    source.get_zkir(&parsed.circuit_id),
151                )?;
152                return Ok(Some(ProvingKeyMaterial {
153                    prover_key: prover_key.0,
154                    verifier_key: vk.0,
155                    ir_source: zkir.0,
156                }));
157            }
158        }
159        return Err(integrity_failure.unwrap_or_else(|| {
160            ContractRuntimeError::ZkArtifactIntegrity(format!(
161                "no local artifacts for circuit '{}' match the verifier key deployed at {} \
162                 (key location {key_location}); recompile or fetch the artifacts of the deployed contract",
163                parsed.circuit_id.as_str(),
164                hex::encode(parsed.contract_address.0 .0),
165            ))
166        }));
167    }
168    if key_location.starts_with("midnight/") {
169        return Ok(None);
170    }
171    let circuit_id = CircuitId::new(key_location.to_owned());
172    for source in sources {
173        match source.get(&circuit_id).await {
174            Ok(bundle) => return Ok(Some(material(bundle))),
175            Err(e @ ContractRuntimeError::ZkArtifactIntegrity(_)) => return Err(e),
176            Err(_) => {}
177        }
178    }
179    Ok(None)
180}
181
182fn material(bundle: ZkConfig) -> ProvingKeyMaterial {
183    ProvingKeyMaterial {
184        prover_key: bundle.prover_key.0,
185        verifier_key: bundle.verifier_key.0,
186        ir_source: bundle.zkir.0,
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193    use crate::providers::FileSystemZkConfigProvider;
194    use moonproof_ledger::base_crypto::hash::HashOutput;
195    use moonproof_ledger::serialize::tagged_deserialize;
196
197    fn counter() -> FileSystemZkConfigProvider {
198        let mut p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
199        p.pop();
200        p.push("test-fixtures/contracts/counter");
201        FileSystemZkConfigProvider::new(p)
202    }
203
204    fn address() -> ContractAddress {
205        ContractAddress(HashOutput([0xab; 32]))
206    }
207
208    async fn deployed_location(
209        source: &FileSystemZkConfigProvider,
210    ) -> (ContractKeyLocation, Vec<u8>) {
211        let vk = source
212            .get_verifier_key(&CircuitId::new("increment"))
213            .await
214            .unwrap()
215            .0;
216        let op = moonproof_ledger::contract_operation(Some(
217            tagged_deserialize(&mut vk.as_slice()).unwrap(),
218        ));
219        let location =
220            ContractKeyLocation::for_operation(address(), &CircuitId::new("increment"), &op)
221                .unwrap();
222        (location, vk)
223    }
224
225    #[test]
226    fn encodes_the_midnight_js_grammar() {
227        let location = ContractKeyLocation {
228            contract_address: address(),
229            circuit_id: CircuitId::new("increment"),
230            verifier_key_hash: hash_verifier_key(b"abc"),
231        };
232        assert_eq!(
233            location.encode(),
234            format!(
235                "contract:{}/increment?vk=ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
236                "ab".repeat(32)
237            )
238        );
239        assert_eq!(
240            ContractKeyLocation::parse(&location.encode()),
241            Some(location)
242        );
243    }
244
245    #[test]
246    fn anything_else_is_not_a_contract_location() {
247        let vk = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
248        for bad in [
249            "increment".to_owned(),
250            "midnight/zswap/spend".to_owned(),
251            format!("contract:{}/increment?vk={}", "ab".repeat(31), vk),
252            format!("contract:{}/inc-rement?vk={}", "ab".repeat(32), vk),
253            format!(
254                "contract:{}/increment?vk={}",
255                "ab".repeat(32),
256                vk.to_uppercase()
257            ),
258            format!("contract:{}/increment", "ab".repeat(32)),
259        ] {
260            assert_eq!(ContractKeyLocation::parse(&bad), None, "{bad}");
261        }
262    }
263
264    #[tokio::test]
265    async fn the_deployed_key_hashes_like_its_artifact() {
266        let source = counter();
267        let (location, vk) = deployed_location(&source).await;
268        assert_eq!(location.verifier_key_hash, hash_verifier_key(&vk));
269    }
270
271    #[tokio::test]
272    async fn a_contract_location_resolves_by_verifier_key() {
273        let source = counter();
274        let empty_dir = tempfile::tempdir().unwrap();
275        let empty = FileSystemZkConfigProvider::new(empty_dir.path());
276        let (location, vk) = deployed_location(&source).await;
277        let material = resolve_key_location(&location.encode(), &[&empty, &source])
278            .await
279            .unwrap()
280            .expect("the matching source serves it");
281        assert_eq!(material.verifier_key, vk);
282    }
283
284    #[tokio::test]
285    async fn drifted_artifacts_are_refused() {
286        let source = counter();
287        let (mut location, _) = deployed_location(&source).await;
288        location.verifier_key_hash = [0; 32];
289        let result = resolve_key_location(&location.encode(), &[&source]).await;
290        assert!(matches!(
291            result,
292            Err(ContractRuntimeError::ZkArtifactIntegrity(_))
293        ));
294    }
295
296    #[tokio::test]
297    async fn bare_ids_and_builtins() {
298        let source = counter();
299        assert!(resolve_key_location("increment", &[&source])
300            .await
301            .unwrap()
302            .is_some());
303        assert!(resolve_key_location("decrement", &[&source])
304            .await
305            .unwrap()
306            .is_none());
307        assert!(resolve_key_location("midnight/zswap/spend", &[&source])
308            .await
309            .unwrap()
310            .is_none());
311    }
312}