1pub mod artifact;
8pub mod check;
9pub mod demo;
10pub mod make;
11
12use std::collections::{HashMap, HashSet};
13
14pub const EXIT_OK: i32 = 0;
16pub const EXIT_FAIL: i32 = 1;
17pub const EXIT_ERR: i32 = 2;
18
19#[derive(Debug, Default)]
22pub struct Cli {
23 pub command: String,
24 pub positional: Vec<String>,
25 values: HashMap<String, String>,
26 multi: HashMap<String, Vec<String>>,
27 flags: HashSet<String>,
28}
29
30impl Cli {
31 pub fn parse(args: &[String]) -> Result<Cli, String> {
32 let mut it = args.iter().peekable();
33 let command = it
34 .next()
35 .ok_or_else(|| "missing command (try `help`)".to_string())?
36 .clone();
37 let mut cli = Cli {
38 command,
39 ..Cli::default()
40 };
41 while let Some(a) = it.next() {
42 let Some(name) = a.strip_prefix("--") else {
43 cli.positional.push(a.clone());
44 continue;
45 };
46 let (name, inline) = match name.split_once('=') {
47 Some((n, v)) => (n.to_string(), Some(v.to_string())),
48 None => (name.to_string(), None),
49 };
50 let value = match inline {
54 Some(v) => v,
55 None => match it.peek() {
56 Some(v) if !v.starts_with("--") => it.next().unwrap().clone(),
57 _ => {
58 cli.flags.insert(name);
60 continue;
61 }
62 },
63 };
64 cli.multi
65 .entry(name.clone())
66 .or_default()
67 .push(value.clone());
68 cli.values.insert(name, value);
69 }
70 Ok(cli)
71 }
72 pub fn req(&self, name: &str) -> Result<String, String> {
74 self.values
75 .get(name)
76 .cloned()
77 .ok_or_else(|| format!("missing required flag --{name}"))
78 }
79
80 pub fn opt(&self, name: &str) -> Option<String> {
82 self.values.get(name).cloned()
83 }
84
85 pub fn many(&self, name: &str) -> Vec<String> {
87 self.multi.get(name).cloned().unwrap_or_default()
88 }
89
90 pub fn has(&self, name: &str) -> bool {
92 self.flags.contains(name)
93 }
94
95 pub fn quiet(&self) -> bool {
97 self.has("quiet")
98 }
99
100 pub fn req_u64(&self, name: &str) -> Result<u64, String> {
102 self.req(name)?
103 .parse()
104 .map_err(|_| format!("--{name} must be a u64"))
105 }
106
107 pub fn opt_u64(&self, name: &str) -> Result<Option<u64>, String> {
109 match self.opt(name) {
110 None => Ok(None),
111 Some(v) => v
112 .parse()
113 .map(Some)
114 .map_err(|_| format!("--{name} must be a u64")),
115 }
116 }
117}
118
119pub fn parse_fields(
122 spec: Option<String>,
123) -> Result<Vec<(String, proof_core::model::MetaValue)>, String> {
124 let Some(spec) = spec else {
125 return Ok(vec![]);
126 };
127 let mut out = vec![];
128 for pair in spec.split(',') {
129 let Some((k, v)) = pair.split_once('=') else {
130 return Err(format!("bad field `{pair}` (expected k=v)"));
131 };
132 if k.is_empty() || v.is_empty() {
133 return Err(format!("bad field `{pair}` (empty key or value)"));
134 }
135 let mv = if v == "true" {
136 proof_core::model::MetaValue::Bool(true)
137 } else if v == "false" {
138 proof_core::model::MetaValue::Bool(false)
139 } else if let Ok(n) = v.parse::<u64>() {
140 proof_core::model::MetaValue::Uint(n)
141 } else {
142 proof_core::model::MetaValue::Text(v.to_string())
143 };
144 out.push((k.to_string(), mv));
145 }
146 Ok(out)
147}
148
149pub fn load_key(seed: &str) -> Result<proof_crypto::Ed25519Key, String> {
152 load_key_material(seed, "--seed")
153}
154
155fn load_key_material(seed: &str, what: &str) -> Result<proof_crypto::Ed25519Key, String> {
156 if seed == "test" {
157 return Ok(proof_crypto::build::fixtures::test_key());
158 }
159 let bytes = hex::decode(seed).map_err(|e| format!("{what} bad hex: {e}"))?;
160 let arr: [u8; 32] = bytes
161 .try_into()
162 .map_err(|_| format!("{what} must be `test` or 64 hex chars (32 bytes)"))?;
163 Ok(proof_crypto::Ed25519Key::from_seed(&arr))
164}
165
166pub fn load_key_opt(cli: &Cli) -> Result<proof_crypto::Ed25519Key, String> {
171 match (cli.opt("seed"), cli.opt("seed-file")) {
172 (Some(_), Some(_)) => Err("--seed and --seed-file are mutually exclusive".into()),
173 (None, Some(path)) => {
174 let seed = read_input_file(&path)?;
175 load_key_material(seed.trim(), "--seed-file")
176 }
177 (Some(seed), None) => load_key(&seed),
178 (None, None) => Err("missing required flag --seed (or --seed-file)".into()),
179 }
180}
181
182pub fn limits() -> proof_core::Limits {
183 proof_core::Limits::default()
184}
185
186pub fn progress(quiet: bool, msg: &str) {
188 if !quiet {
189 eprintln!("{msg}");
190 }
191}
192
193pub const MAX_INPUT_FILE_BYTES: u64 = 8 << 20;
198
199pub fn read_input_file(path: &str) -> Result<String, String> {
203 use std::io::Read;
204 let mut f = std::fs::File::open(path).map_err(|e| format!("read {path}: {e}"))?;
205 let mut buf = Vec::new();
206 f.by_ref()
207 .take(MAX_INPUT_FILE_BYTES + 1)
208 .read_to_end(&mut buf)
209 .map_err(|e| format!("read {path}: {e}"))?;
210 if buf.len() as u64 > MAX_INPUT_FILE_BYTES {
211 return Err(format!(
212 "{path}: file too large (>{MAX_INPUT_FILE_BYTES} bytes)"
213 ));
214 }
215 String::from_utf8(buf).map_err(|_| format!("{path}: invalid UTF-8"))
216}
217
218pub const USAGE: &str = "\
219proof-cli — Proof Engine command line (V1.0)
220
221Exit codes: 0 = PASS/valid, 1 = FAIL/INDETERMINATE verdict, 2 = usage or engine error.
222All commands accept --quiet to suppress progress output on stderr.
223
224Creation commands (write JSON artifact files wrapping canonical CBOR bytes):
225 create-event --type <event.type> --subject <id> --effective-at <u64>
226 --payload-hex <64 hex> [--meta k=v,...] --out <file>
227 attest --seed <test|64hex> --subject <id> --claim-type <t> [--claim k=v,...]
228 --issued-at <u64> [--expires-at <u64>] [--evidence-ref <id>] --out <file>
229 add-evidence --kind <kind> --digest-hex <64 hex> [--attestation-ref <id>] [--hint <t>]
230 --out <file>
231 relate --from <id> --type <TYPE> --to <id> [--evidence-ref <id>]
232 [--attestation-ref <id>] --out <file>
233 build --kind <t> --subject <s> --predicate <p> [--object <o>] [--at-time <u64>]
234 [--context k=v,...] --created-at <u64> --events <f[,f…]>
235 --attestations <f[,f…]> --evidence <f[,f…]> --relationships <f[,f…]>
236 --out <file>
237 revoke --seed <test|64hex> --target <id> [--reason <t>] --at <u64> --out <file>
238 supersede --seed <test|64hex> --old <id> --new <id> --at <u64> --out <file>
239
240Verification commands:
241 verify --proof <file> --clock <u64> [--skew <u64=300>]
242 [--revocations-known-at <u64>] [--status <file>]… [--authority <keyref>]…
243 evaluate --proof <file> --policy <file> --clock <u64> [--skew <u64=300>]
244 [--trusted <keyref>]… [--revoked <id,id,…>] [--revocations-known-at <u64>]
245 [--json] — machine-readable policy_outcome + report JSON on stdout
246 explain (same flags as evaluate; prints the full explanation)
247
248 demo [--out <dir>=demo/out] — deterministic end-to-end killer use-case
249 help — this text
250
251Artifacts are JSON wrappers around canonical CBOR bytes (hex); bytes are
252re-verified on every load — ids recomputed, signatures checked. Seeds are for
253demos/tests only; production key handling is out of scope for V1.0.
254Prefer --seed-file <path> over --seed <hex>: raw key material in argv is
255visible to ps(1) and shell history; the two flags never combine.";