Skip to main content

zenkey_model/
history.rs

1//! Published revisions: `contracts/.history/<iface>.v<N>/<hex>.bundle.json`
2//! (r3 ยง3.11).
3//!
4//! The history is committed and append-only. Every revision of a major is
5//! kept, because compatibility is FULL_TRANSITIVE: a new revision is checked
6//! against every earlier one (#618). [`check`] verifies what is there: the
7//! layout, each bundle's integrity, its fingerprint against its file name,
8//! and its interface against its directory. That a file was never removed
9//! or rewritten is the VCS's to show (CI diffs the directory against the
10//! base branch).
11
12use std::path::{Path, PathBuf};
13
14use crate::bundle::Bundle;
15use crate::canonical::Fingerprint;
16use crate::contract::Contract;
17use crate::grammar::IfaceId;
18
19/// Where a revision's bundle lives under `root` (the `.history` directory).
20#[must_use]
21pub fn path_for(root: &Path, iface: &IfaceId, fp: &Fingerprint) -> PathBuf {
22    root.join(iface.to_string())
23        .join(format!("{}.bundle.json", fp.hex()))
24}
25
26/// Writes the contract's bundle unless that revision is already there.
27/// Returns the path and whether it was written.
28pub fn append(root: &Path, c: &Contract) -> std::io::Result<(PathBuf, bool)> {
29    let b = Bundle::build(c);
30    let path = path_for(root, &c.iface, &b.fingerprint());
31    if path.exists() {
32        return Ok((path, false));
33    }
34    if let Some(dir) = path.parent() {
35        std::fs::create_dir_all(dir)?;
36    }
37    std::fs::write(&path, b.to_bytes())?;
38    Ok((path, true))
39}
40
41/// One problem found in a history directory.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct Problem {
44    /// `<iface dir>` or `<iface dir>/<file>`.
45    pub at: String,
46    /// A stable name for the problem, as `spec/conformance/history/` spells
47    /// it: `directory`, `file_name`, `io`, `interface`, `jcs`, or a bundle
48    /// refusal tag ([`crate::bundle::BundleError::tag`]).
49    pub tag: &'static str,
50    pub message: String,
51}
52
53/// Verifies a history directory. Returns one message per problem.
54#[must_use]
55pub fn check(root: &Path) -> Vec<String> {
56    check_tagged(root)
57        .into_iter()
58        .map(|p| format!("{}: {}", p.at, p.message))
59        .collect()
60}
61
62/// Verifies a history directory: the layout, each bundle's integrity, its
63/// fingerprint against its file name, its interface against its directory,
64/// and its JCS form.
65#[must_use]
66pub fn check_tagged(root: &Path) -> Vec<Problem> {
67    let mut out = Vec::new();
68    let mut push = |at: &str, tag: &'static str, message: String| {
69        out.push(Problem {
70            at: at.to_owned(),
71            tag,
72            message,
73        });
74    };
75    let Ok(dirs) = std::fs::read_dir(root) else {
76        return out;
77    };
78    let mut dirs: Vec<_> = dirs.flatten().collect();
79    dirs.sort_by_key(std::fs::DirEntry::file_name);
80    for d in dirs {
81        let name = d.file_name().to_string_lossy().into_owned();
82        let Ok(iface) = name.parse::<IfaceId>() else {
83            push(
84                &name,
85                "directory",
86                "not an interface directory <name>.v<major>".into(),
87            );
88            continue;
89        };
90        let Ok(files) = std::fs::read_dir(d.path()) else {
91            push(&name, "directory", "not a directory".into());
92            continue;
93        };
94        let mut files: Vec<_> = files.flatten().collect();
95        files.sort_by_key(std::fs::DirEntry::file_name);
96        for f in files {
97            let fname = f.file_name().to_string_lossy().into_owned();
98            let at = format!("{name}/{fname}");
99            let Some(fp) = fname
100                .strip_suffix(".bundle.json")
101                .and_then(|h| Fingerprint::parse(&format!("sha256:{h}")).ok())
102            else {
103                push(
104                    &at,
105                    "file_name",
106                    "not <64 lowercase hex>.bundle.json".into(),
107                );
108                continue;
109            };
110            let bytes = match std::fs::read(f.path()) {
111                Ok(b) => b,
112                Err(e) => {
113                    push(&at, "io", e.to_string());
114                    continue;
115                }
116            };
117            match Bundle::verify_expecting(&bytes, &fp) {
118                Err(e) => push(&at, e.tag(), e.to_string()),
119                Ok(b) => {
120                    if b.contract.get("interface").and_then(|v| v.as_str())
121                        != Some(&iface.to_string())
122                    {
123                        push(
124                            &at,
125                            "interface",
126                            format!("the bundle's interface is not {iface}"),
127                        );
128                    }
129                    if b.to_bytes() != bytes {
130                        push(&at, "jcs", "not in JCS form".into());
131                    }
132                }
133            }
134        }
135    }
136    out
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142    use crate::contract::load_str;
143
144    #[test]
145    fn append_is_idempotent_and_checked() {
146        let tmp = std::env::temp_dir().join(format!("zk2-history-{}", std::process::id()));
147        let _ = std::fs::remove_dir_all(&tmp);
148        let src = "[interface]\nname = \"t\"\nmajor = 1\nminor = 0\n\
149                   [resources.\"a\"]\nkind = \"stream\"\ntype = { raw = \"text/plain\" }\n";
150        let c = load_str(src, Path::new("."), None).contract.unwrap();
151        let (p, wrote) = append(&tmp, &c).unwrap();
152        assert!(wrote);
153        assert!(!append(&tmp, &c).unwrap().1);
154        assert!(check(&tmp).is_empty(), "{:?}", check(&tmp));
155
156        let moved = p.with_file_name(format!("{}.bundle.json", "0".repeat(64)));
157        std::fs::rename(&p, &moved).unwrap();
158        assert_eq!(check(&tmp).len(), 1);
159        std::fs::remove_dir_all(&tmp).unwrap();
160    }
161}