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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! Filesystem-backed [`ZkConfigProvider`] — reads the
//! `compactc`-produced artifacts from a directory laid out as
//!
//! ```text
//! <root>/
//!   zkir/<circuit>.bzkir     — binary ZKIR bytes (what the prover consumes)
//!   keys/<circuit>.prover    — proving key
//!   keys/<circuit>.verifier  — verifier key
//! ```
//!
//! This is the canonical layout `compactc` emits, so the committed
//! moonproof fixture tree under
//! `crates/test-fixtures/contracts/<contract>/` plugs in directly with
//! no translation step.
//!
//! # Scope notes
//!
//! - Uses the **binary** `.bzkir` (not the JSON `.zkir`) because
//!   `moonproof_ledger::zkir::IrSource` consumes the tagged-serialized binary
//!   form directly.
//! - Resolves missing circuits to
//!   [`ContractRuntimeError::NotFound`] — matches the provider-error
//!   shape the rest of the runtime expects.
//! - I/O errors (permissions, partial reads, etc.) wrap the
//!   `io::Error` via [`ContractRuntimeError::Io`] with a short
//!   `context` string identifying which file / circuit failed.
//! - Verified artifacts are cached in memory keyed by relative path and
//!   validated via `(mtime, file_size)` metadata checks so repeated proof
//!   generations skip re-reading and re-SHA-256-hashing multi-megabyte
//!   `.prover` files while immediately noticing on-disk replacements.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::SystemTime;

use moonproof_macros::async_trait;
use parking_lot::RwLock;

use crate::error::{ContractRuntimeError, Result};
use crate::providers::zk_manifest::{
    assert_manifest_hash, parse_zk_artifact_manifest, verify_zk_artifact_integrity,
    ZkArtifactManifest, ZkConfigIntegrityOptions, ZK_MANIFEST_DIR, ZK_MANIFEST_FILE_NAME,
};
use crate::providers::ZkConfigProvider;
use crate::types::{CircuitId, ProverKey, VerifierKey, Zkir};

#[derive(Debug, Clone)]
struct CachedArtifact {
    modified: Option<SystemTime>,
    len: u64,
    bytes: Arc<[u8]>,
}

/// Port-and-improved version of the TS `NodeZkConfigProvider` class —
/// reads compiled Compact artifacts directly from disk, with an
/// mtime+size-validated in-memory cache so repeated calls avoid
/// re-reading and re-hashing multi-megabyte `.prover` files.
///
/// # Usage
///
/// ```no_run
/// use std::path::PathBuf;
/// use moonproof_contracts::providers::{FileSystemZkConfigProvider, ZkConfigProvider};
/// use moonproof_contracts::types::CircuitId;
///
/// # async fn example() -> moonproof_contracts::Result<()> {
/// let provider = FileSystemZkConfigProvider::new(
///     PathBuf::from("/path/to/contracts/counter"),
/// );
/// let vk = provider.get_verifier_key(&CircuitId::new("increment")).await?;
/// # Ok(()) }
/// ```
#[derive(Debug, Clone)]
pub struct FileSystemZkConfigProvider {
    root: PathBuf,
    integrity: ZkConfigIntegrityOptions,
    manifest: Arc<tokio::sync::OnceCell<Option<ZkArtifactManifest>>>,
    cache: Arc<RwLock<HashMap<String, CachedArtifact>>>,
}

impl FileSystemZkConfigProvider {
    /// Construct a provider rooted at `root`. The directory must
    /// contain `zkir/` and `keys/` subdirectories laid out as
    /// `compactc` emits them. Every artifact read is verified against
    /// `compiler/contract-manifest.json`, which must exist; see
    /// [`Self::with_integrity`] to relax that.
    #[must_use]
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self::with_integrity(root, ZkConfigIntegrityOptions::default())
    }

    /// Construct a provider with explicit integrity options.
    #[must_use]
    pub fn with_integrity(root: impl Into<PathBuf>, integrity: ZkConfigIntegrityOptions) -> Self {
        Self {
            root: root.into(),
            integrity,
            manifest: Arc::new(tokio::sync::OnceCell::new()),
            cache: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// The root directory this provider reads from.
    #[inline]
    #[must_use]
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// The artifact's path relative to the root, as the manifest keys
    /// it.
    ///
    /// A verifier key is tied to the proof stack that produced it:
    /// ledger 9 reads `verifier-key[v7]`, ledger 8 `verifier-key[v6]`.
    /// compactc 0.36 emits only the former into `keys/` and `zkir/`. A
    /// tree that also serves the ledger-8 build keeps the older set in
    /// `<subdir>-v2/`, which that build prefers when it exists.
    fn artifact_relative_path(&self, subdir: &str, circuit_id: &CircuitId, ext: &str) -> String {
        let file = format!("{}{}", circuit_id.as_str(), ext);
        if !moonproof_ledger::HAS_ZKIR_V3 {
            let v2 = format!("{subdir}-v2/{file}");
            if self.root.join(&v2).exists() {
                return v2;
            }
        }
        format!("{subdir}/{file}")
    }

    async fn manifest(&self) -> Result<Option<&ZkArtifactManifest>> {
        let loaded = self
            .manifest
            .get_or_try_init(|| async { self.read_manifest() })
            .await?;
        Ok(loaded.as_ref())
    }

    fn read_manifest(&self) -> Result<Option<ZkArtifactManifest>> {
        let path = self.root.join(ZK_MANIFEST_DIR).join(ZK_MANIFEST_FILE_NAME);
        let raw = match std::fs::read(&path) {
            Ok(raw) => raw,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                if self.integrity.expected_manifest_hash.is_some() {
                    return Err(ContractRuntimeError::ZkArtifactIntegrity(format!(
                        "expected a ZK artifact manifest at {} but it was not found",
                        path.display()
                    )));
                }
                return Ok(None);
            }
            Err(e) => {
                return Err(ContractRuntimeError::Io {
                    context: "zk artifact manifest",
                    source: e,
                })
            }
        };
        if let Some(expected) = &self.integrity.expected_manifest_hash {
            assert_manifest_hash(&raw, expected)?;
        }
        parse_zk_artifact_manifest(&raw).map(Some)
    }

    async fn read_artifact(
        &self,
        relative_path: &str,
        artifact_kind: &'static str,
        circuit_id: &CircuitId,
    ) -> Result<Vec<u8>> {
        let path = self.root.join(relative_path);
        let meta = match std::fs::metadata(&path) {
            Ok(meta) => meta,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                self.cache.write().remove(relative_path);
                return Err(ContractRuntimeError::NotFound(format!(
                    "{artifact_kind} for circuit '{}' at {}",
                    circuit_id.as_str(),
                    path.display(),
                )));
            }
            Err(e) => {
                return Err(ContractRuntimeError::Io {
                    context: artifact_kind,
                    source: e,
                })
            }
        };
        let modified = meta.modified().ok();
        let len = meta.len();

        if let Some(hit) = self
            .cache
            .read()
            .get(relative_path)
            .filter(|entry| {
                entry.len == len && entry.modified.is_some() && entry.modified == modified
            })
            .map(|entry| Arc::clone(&entry.bytes))
        {
            return Ok(hit.to_vec());
        }

        let bytes = match std::fs::read(&path) {
            Ok(bytes) => bytes,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                return Err(ContractRuntimeError::NotFound(format!(
                    "{artifact_kind} for circuit '{}' at {}",
                    circuit_id.as_str(),
                    path.display(),
                )));
            }
            Err(e) => {
                return Err(ContractRuntimeError::Io {
                    context: artifact_kind,
                    source: e,
                })
            }
        };
        // compactc's manifest certifies only what compactc emitted. The
        // ledger-8 `-v2` set predates 0.36 and no manifest covers it.
        if !relative_path.contains("-v2/") {
            let manifest = self.manifest().await?;
            verify_zk_artifact_integrity(manifest, relative_path, &bytes, self.integrity.mode)?;
        }
        if modified.is_some() {
            let cached = CachedArtifact {
                modified,
                len: bytes.len() as u64,
                bytes: Arc::from(bytes.as_slice()),
            };
            self.cache.write().insert(relative_path.to_owned(), cached);
        }
        Ok(bytes)
    }
}

#[async_trait]
impl ZkConfigProvider for FileSystemZkConfigProvider {
    async fn get_zkir(&self, circuit_id: &CircuitId) -> Result<Zkir> {
        let path = self.artifact_relative_path("zkir", circuit_id, ".bzkir");
        Ok(Zkir::new(
            self.read_artifact(&path, "zkir", circuit_id).await?,
        ))
    }

    async fn get_prover_key(&self, circuit_id: &CircuitId) -> Result<ProverKey> {
        let path = self.artifact_relative_path("keys", circuit_id, ".prover");
        Ok(ProverKey::new(
            self.read_artifact(&path, "prover-key", circuit_id).await?,
        ))
    }

    async fn get_verifier_key(&self, circuit_id: &CircuitId) -> Result<VerifierKey> {
        let path = self.artifact_relative_path("keys", circuit_id, ".verifier");
        Ok(VerifierKey::new(
            self.read_artifact(&path, "verifier-key", circuit_id)
                .await?,
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::ContractRuntimeError;
    use sha2::Digest;

    /// Path to the vendored counter fixture, relative to this crate's
    /// Cargo manifest.
    fn counter_fixture_root() -> PathBuf {
        // `CARGO_MANIFEST_DIR` is set to the package that the test
        // belongs to (`crates/runtime`). Walk up one level to the
        // workspace root, then down into test-fixtures.
        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        p.pop(); // crates/
        p.pop(); // workspace root
        p.push("crates/test-fixtures/contracts/counter");
        p
    }

    fn counter_provider() -> FileSystemZkConfigProvider {
        FileSystemZkConfigProvider::new(counter_fixture_root())
    }

    #[tokio::test]
    async fn get_verifier_key_returns_vendored_bytes() {
        let provider = counter_provider();
        let vk = provider
            .get_verifier_key(&CircuitId::new("increment"))
            .await
            .expect("counter fixture's increment.verifier should exist");
        // The vendored `increment.verifier` is a fixed size for the
        // proof stack that produced it — regression-guard against
        // accidental drift.
        assert_eq!(
            vk.as_bytes().len(),
            counter_sizes().verifier,
            "verifier key size drift — did the Compact compiler version change?",
        );
    }

    #[tokio::test]
    async fn get_prover_key_returns_vendored_bytes() {
        let provider = counter_provider();
        let pk = provider
            .get_prover_key(&CircuitId::new("increment"))
            .await
            .expect("counter fixture's increment.prover should exist");
        assert_eq!(
            pk.as_bytes().len(),
            counter_sizes().prover,
            "prover key size drift — did the Compact compiler version change?",
        );
    }

    /// Vendored counter artifact sizes, per proof stack. The two
    /// generations compile the same source to different circuits, so a
    /// single expected size cannot cover both — but pinning them still
    /// catches an unintended compiler bump, which is what these guards
    /// are for.
    struct CounterSizes {
        bzkir: usize,
        verifier: usize,
        prover: usize,
    }

    const fn counter_sizes() -> CounterSizes {
        if moonproof_ledger::HAS_ZKIR_V3 {
            CounterSizes {
                bzkir: 102,
                verifier: 1353,
                prover: 58166,
            }
        } else {
            CounterSizes {
                bzkir: 64,
                verifier: 1351,
                prover: 14071,
            }
        }
    }

    #[tokio::test]
    async fn get_zkir_returns_vendored_bytes() {
        let provider = counter_provider();
        let zkir = provider
            .get_zkir(&CircuitId::new("increment"))
            .await
            .expect("counter fixture's increment.bzkir should exist");
        assert_eq!(
            zkir.as_bytes().len(),
            counter_sizes().bzkir,
            "bzkir size drift — did the Compact compiler version change?",
        );
    }

    #[tokio::test]
    async fn get_returns_full_zk_config_bundle() {
        let provider = counter_provider();
        let bundle = provider
            .get(&CircuitId::new("increment"))
            .await
            .expect("counter fixture bundle should load");
        assert_eq!(bundle.circuit_id.as_str(), "increment");
        let sizes = counter_sizes();
        assert_eq!(bundle.verifier_key.as_bytes().len(), sizes.verifier);
        assert_eq!(bundle.prover_key.as_bytes().len(), sizes.prover);
        assert_eq!(bundle.zkir.as_bytes().len(), sizes.bzkir);
    }

    #[tokio::test]
    async fn get_verifier_keys_batched_preserves_order() {
        // Only the counter fixture is vendored, so the batch has one
        // element — still exercises the default-aggregator path.
        let provider = counter_provider();
        let pairs = provider
            .get_verifier_keys(&[CircuitId::new("increment")])
            .await
            .unwrap();
        assert_eq!(pairs.len(), 1);
        assert_eq!(pairs[0].0.as_str(), "increment");
        assert_eq!(pairs[0].1.as_bytes().len(), counter_sizes().verifier);
    }

    #[tokio::test]
    async fn missing_circuit_returns_not_found_for_every_artifact() {
        let provider = counter_provider();
        let missing = CircuitId::new("does_not_exist");

        let zkir_err = provider.get_zkir(&missing).await.unwrap_err();
        matches!(zkir_err, ContractRuntimeError::NotFound(_));
        assert!(format!("{zkir_err}").contains("does_not_exist"));

        let prover_err = provider.get_prover_key(&missing).await.unwrap_err();
        matches!(prover_err, ContractRuntimeError::NotFound(_));

        let verifier_err = provider.get_verifier_key(&missing).await.unwrap_err();
        matches!(verifier_err, ContractRuntimeError::NotFound(_));
    }

    #[tokio::test]
    async fn missing_root_dir_also_surfaces_as_not_found() {
        // An entirely non-existent root dir is semantically "no
        // artifacts here" — we flatten directory-level missingness
        // into the same NotFound the caller would get for a missing
        // individual circuit, so callers don't have to branch on the
        // error kind.
        let provider = FileSystemZkConfigProvider::new(PathBuf::from(
            "/tmp/moonproof-nonexistent-root-for-testing-that-really-does-not-exist",
        ));
        let err = provider
            .get_verifier_key(&CircuitId::new("anything"))
            .await
            .unwrap_err();
        matches!(err, ContractRuntimeError::NotFound(_));
    }

    #[test]
    fn root_accessor_returns_the_configured_path() {
        let p = FileSystemZkConfigProvider::new("/some/path");
        assert_eq!(p.root(), Path::new("/some/path"));
    }

    #[test]
    fn artifact_path_uses_expected_layout() {
        let p = FileSystemZkConfigProvider::new("/x");
        assert_eq!(
            p.artifact_relative_path("zkir", &CircuitId::new("foo"), ".bzkir"),
            "zkir/foo.bzkir"
        );
        assert_eq!(
            p.artifact_relative_path("keys", &CircuitId::new("foo"), ".prover"),
            "keys/foo.prover"
        );
        assert_eq!(
            p.artifact_relative_path("keys", &CircuitId::new("foo"), ".verifier"),
            "keys/foo.verifier"
        );
    }

    /// A key that does not match the manifest is refused, so a swapped
    /// key cannot be proved against silently.
    #[tokio::test]
    async fn a_tampered_key_is_refused() {
        let dir = canonical_counter_copy();
        let ok = FileSystemZkConfigProvider::new(dir.path());
        assert!(ok
            .get_verifier_key(&CircuitId::new("increment"))
            .await
            .is_ok());

        let vk = dir.path().join("keys/increment.verifier");
        let mut bytes = std::fs::read(&vk).unwrap();
        let last = bytes.len() - 1;
        bytes[last] ^= 0x01;
        std::fs::write(&vk, bytes).unwrap();
        let tampered = FileSystemZkConfigProvider::new(dir.path());
        assert!(matches!(
            tampered
                .get_verifier_key(&CircuitId::new("increment"))
                .await,
            Err(ContractRuntimeError::ZkArtifactIntegrity(_))
        ));
    }

    #[tokio::test]
    async fn artifact_cache_serves_hits_and_invalidates_on_change() {
        let dir = canonical_counter_copy();
        let provider = FileSystemZkConfigProvider::new(dir.path());
        let first = provider
            .get_prover_key(&CircuitId::new("increment"))
            .await
            .unwrap();
        let second = provider
            .get_prover_key(&CircuitId::new("increment"))
            .await
            .unwrap();
        assert_eq!(first.as_bytes(), second.as_bytes());
        assert!(
            provider.cache.read().contains_key("keys/increment.prover"),
            "prover key should be cached after first verified read"
        );

        // Mutating the file size/mtime on disk invalidates the cache entry and
        // re-triggers manifest verification on the same provider instance.
        let pk_path = dir.path().join("keys/increment.prover");
        let mut bytes = std::fs::read(&pk_path).unwrap();
        bytes.push(0x42);
        std::fs::write(&pk_path, bytes).unwrap();
        assert!(matches!(
            provider.get_prover_key(&CircuitId::new("increment")).await,
            Err(ContractRuntimeError::ZkArtifactIntegrity(_))
        ));
    }

    #[tokio::test]
    async fn a_missing_manifest_is_refused_unless_relaxed() {
        let dir = canonical_counter_copy();
        std::fs::remove_file(dir.path().join("compiler/contract-manifest.json")).unwrap();
        let strict = FileSystemZkConfigProvider::new(dir.path());
        assert!(matches!(
            strict.get_verifier_key(&CircuitId::new("increment")).await,
            Err(ContractRuntimeError::ZkArtifactIntegrity(_))
        ));
        let relaxed = FileSystemZkConfigProvider::with_integrity(
            dir.path(),
            ZkConfigIntegrityOptions {
                mode: crate::providers::ZkArtifactIntegrityMode::RequireIfPresent,
                expected_manifest_hash: None,
            },
        );
        assert!(relaxed
            .get_verifier_key(&CircuitId::new("increment"))
            .await
            .is_ok());
    }

    #[tokio::test]
    async fn a_pinned_manifest_hash_must_match() {
        let dir = canonical_counter_copy();
        let manifest = std::fs::read(dir.path().join("compiler/contract-manifest.json")).unwrap();
        let good: [u8; 32] = sha2::Sha256::digest(&manifest).into();
        let pinned = |hash| {
            FileSystemZkConfigProvider::with_integrity(
                dir.path(),
                ZkConfigIntegrityOptions {
                    mode: crate::providers::ZkArtifactIntegrityMode::Require,
                    expected_manifest_hash: Some(hash),
                },
            )
        };
        assert!(pinned(good)
            .get_verifier_key(&CircuitId::new("increment"))
            .await
            .is_ok());
        assert!(pinned([0u8; 32])
            .get_verifier_key(&CircuitId::new("increment"))
            .await
            .is_err());
    }

    /// The counter fixture without its ledger-8 `-v2` set, so every
    /// read goes through the manifest-certified layout on either build.
    fn canonical_counter_copy() -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        copy_tree(&counter_fixture_root(), dir.path());
        for v2 in ["keys-v2", "zkir-v2"] {
            std::fs::remove_dir_all(dir.path().join(v2)).unwrap();
        }
        dir
    }

    fn copy_tree(from: &Path, to: &Path) {
        for entry in std::fs::read_dir(from).unwrap() {
            let entry = entry.unwrap();
            let target = to.join(entry.file_name());
            if entry.file_type().unwrap().is_dir() {
                std::fs::create_dir_all(&target).unwrap();
                copy_tree(&entry.path(), &target);
            } else {
                std::fs::copy(entry.path(), target).unwrap();
            }
        }
    }
}