moonproof_runtime_ir/
loader.rs1use std::path::Path;
9
10use crate::error::{IrError, Result};
11use crate::ir::MoonIr;
12
13pub const MOON_IR_FILENAME: &str = "contract.mpir";
16
17pub const SUPPORTED_SCHEMA_VERSION: u32 = 3;
28
29pub const MIN_SCHEMA_VERSION: u32 = 1;
32
33pub fn from_cbor_slice(bytes: &[u8]) -> Result<MoonIr> {
35 let ir = crate::cbor_fast::decode_runtime_ir_slice(bytes)?;
36 check_schema_version(&ir)?;
37 Ok(ir)
38}
39
40#[must_use]
42pub fn to_cbor_vec(ir: &MoonIr) -> Vec<u8> {
43 crate::cbor_fast::encode_runtime_ir_vec(ir)
44}
45
46pub fn write_cbor(ir: &MoonIr, out: &mut Vec<u8>) {
48 crate::cbor_fast::encode_runtime_ir_into(ir, out);
49}
50
51pub fn from_path(path: impl AsRef<Path>) -> Result<MoonIr> {
53 let bytes = std::fs::read(path.as_ref())?;
54 from_cbor_slice(&bytes)
55}
56
57fn check_schema_version(ir: &MoonIr) -> Result<()> {
58 if (MIN_SCHEMA_VERSION..=SUPPORTED_SCHEMA_VERSION).contains(&ir.schema_version) {
59 Ok(())
60 } else {
61 Err(IrError::UnsupportedSchemaVersion {
62 actual: ir.schema_version,
63 supported: SUPPORTED_SCHEMA_VERSION,
64 })
65 }
66}
67
68#[cfg(test)]
69mod tests {
70 use super::*;
71
72 fn ir_with_version(v: u32) -> MoonIr {
73 let mut ir: MoonIr = serde_json::from_str(
74 r#"{"schema-version":1,"compiler-version":"x","language-version":"x",
75 "runtime-version":"x","constructor":{"arguments":[],"initial-state":
76 {"kind":"null"},"init-ops":[],"register-operations":[],
77 "body":{"stmt":"seq","items":[]}}}"#,
78 )
79 .expect("fixture parses");
80 ir.schema_version = v;
81 ir
82 }
83
84 #[test]
85 fn accepts_every_released_schema_version() {
86 for v in MIN_SCHEMA_VERSION..=SUPPORTED_SCHEMA_VERSION {
87 assert!(
88 check_schema_version(&ir_with_version(v)).is_ok(),
89 "schema {v} must stay readable"
90 );
91 }
92 }
93
94 #[test]
95 fn rejects_a_newer_schema_than_this_build_knows() {
96 let err = check_schema_version(&ir_with_version(SUPPORTED_SCHEMA_VERSION + 1));
97 assert!(err.is_err(), "a future schema must not be read as if known");
98 }
99}