1use std::borrow::Cow;
4use std::collections::BTreeMap;
5
6use crate::crypto;
7use crate::descriptor::FunctionDescriptor;
8use crate::error::{err, member, Error, ErrorCode, Result};
9use crate::json::{self, Value};
10use crate::keys::Keys;
11use crate::lexical;
12use crate::model::{Cell, Scalar};
13use crate::receipt::{any_from_value, AnyReceipt, Stored};
14use crate::slice::{nest, Manifest};
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
18pub enum Level {
19 Signed,
21 Recomputed,
23}
24
25impl Level {
26 pub const fn as_str(self) -> &'static str {
28 match self {
29 Level::Signed => "signed",
30 Level::Recomputed => "recomputed",
31 }
32 }
33}
34
35pub trait Resolver {
59 fn descriptor(&self, fn_hash: &str) -> Option<Cow<'_, [u8]>>;
65
66 fn receipt(&self, hash: &str) -> Option<Cow<'_, [u8]>>;
69
70 fn evaluate(&self, cell: &Cell, asof: &str) -> Option<Scalar>;
75
76 fn manifest(&self, entry: &str) -> Option<Cow<'_, [u8]>> {
81 let _ = entry;
82 None
83 }
84
85 fn evaluation(&self, cell: &Cell, asof: &str) -> Option<Evaluation> {
94 self.evaluate(cell, asof).map(Evaluation::new)
95 }
96}
97
98#[derive(Clone, Debug, PartialEq, Eq, Hash)]
103#[non_exhaustive]
104pub struct Evaluation {
105 pub value: Scalar,
107 pub lineage: Option<Vec<String>>,
109}
110
111impl Evaluation {
112 pub fn new(value: Scalar) -> Evaluation {
114 Evaluation { value, lineage: None }
115 }
116
117 pub fn with_lineage(value: Scalar, lineage: Vec<String>) -> Evaluation {
119 Evaluation { value, lineage: Some(lineage) }
120 }
121}
122
123#[derive(Clone, Debug, Default, PartialEq, Eq)]
134pub struct MapResolver {
135 descriptors: BTreeMap<String, Vec<u8>>,
136 receipts: BTreeMap<String, Vec<u8>>,
137 values: BTreeMap<String, Scalar>,
138 manifests: BTreeMap<String, Vec<u8>>,
139 lineages: BTreeMap<String, Vec<String>>,
140}
141
142impl MapResolver {
143 pub fn new() -> MapResolver {
145 MapResolver::default()
146 }
147
148 pub fn insert_descriptor(&mut self, fn_hash: impl Into<String>, json: impl Into<Vec<u8>>) {
150 self.descriptors.insert(fn_hash.into(), json.into());
151 }
152
153 pub fn insert_receipt(&mut self, hash: impl Into<String>, json: impl Into<Vec<u8>>) {
155 self.receipts.insert(hash.into(), json.into());
156 }
157
158 pub fn insert_value(&mut self, cell_id: impl Into<String>, value: Scalar) {
160 self.values.insert(cell_id.into(), value);
161 }
162
163 pub fn insert_manifest(&mut self, entry: impl Into<String>, json: impl Into<Vec<u8>>) {
165 self.manifests.insert(entry.into(), json.into());
166 }
167
168 pub fn insert_lineage<I, S>(&mut self, cell_id: impl Into<String>, lineage: I)
171 where
172 I: IntoIterator<Item = S>,
173 S: Into<String>,
174 {
175 self.lineages.insert(cell_id.into(), lineage.into_iter().map(Into::into).collect());
176 }
177}
178
179impl Resolver for MapResolver {
180 fn descriptor(&self, fn_hash: &str) -> Option<Cow<'_, [u8]>> {
181 self.descriptors.get(fn_hash).map(|b| Cow::Borrowed(b.as_slice()))
182 }
183
184 fn receipt(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
185 self.receipts.get(hash).map(|b| Cow::Borrowed(b.as_slice()))
186 }
187
188 fn evaluate(&self, cell: &Cell, _asof: &str) -> Option<Scalar> {
189 self.values.get(&cell.id()).cloned()
190 }
191
192 fn manifest(&self, entry: &str) -> Option<Cow<'_, [u8]>> {
193 self.manifests.get(entry).map(|b| Cow::Borrowed(b.as_slice()))
194 }
195
196 fn evaluation(&self, cell: &Cell, _asof: &str) -> Option<Evaluation> {
197 let id = cell.id();
198 let value = self.values.get(&id)?.clone();
199 Some(match self.lineages.get(&id) {
200 Some(l) => Evaluation::with_lineage(value, l.clone()),
201 None => Evaluation::new(value),
202 })
203 }
204}
205
206#[derive(Clone, Debug, PartialEq, Eq)]
223pub struct VerifyResult {
224 pub ok: bool,
226 pub code: Option<ErrorCode>,
229 pub level: Option<Level>,
231 pub hash: Option<String>,
233 pub computed_by: Option<String>,
235 pub blob_checked: bool,
237 pub detail: String,
240 pub path: String,
242}
243
244impl VerifyResult {
245 pub fn error(&self) -> Option<Error> {
248 self.code.map(|c| Error::new(c, self.path.clone(), self.detail.clone()))
249 }
250}
251
252pub fn verify(receipt: &[u8], keys: &Keys, resolver: Option<&dyn Resolver>, blob: Option<&[u8]>) -> VerifyResult {
262 let mut out = VerifyResult {
263 ok: false,
264 code: None,
265 level: None,
266 hash: None,
267 computed_by: None,
268 blob_checked: false,
269 detail: String::new(),
270 path: String::new(),
271 };
272 let r = match signature_valid(receipt, keys) {
273 Ok(r) => r,
274 Err((e, r)) => {
275 if let Some(r) = r {
276 out.hash = Some(r.hash().to_string());
277 out.computed_by = Some(r.computed_by().to_string());
278 }
279 return fail(out, e);
280 }
281 };
282 out.hash = Some(r.hash().to_string());
283 out.computed_by = Some(r.computed_by().to_string());
284 let mut level = Level::Signed;
285 if let Some(res) = resolver.filter(|_| !r.is_withdrawal()) {
288 match recompute_steps(&r, keys, res) {
289 Ok(Recomputed::Yes) => level = Level::Recomputed,
290 Ok(Recomputed::Signed(e)) => out = fail(out, e),
291 Err(e) => return fail(out, e),
292 }
293 }
294 if let Some(content) = blob {
295 if let Err(e) = check_blob(&r, content) {
296 return fail(out, e);
297 }
298 out.blob_checked = true;
299 }
300 out.ok = true;
301 out.level = Some(level);
302 out
303}
304
305fn fail(mut out: VerifyResult, e: Error) -> VerifyResult {
306 out.code = Some(e.code());
307 out.detail = e.detail().to_string();
308 out.path = e.path().to_string();
309 out
310}
311
312type StepError = (Error, Option<Box<AnyReceipt>>);
314
315fn signature_valid(bytes: &[u8], keys: &Keys) -> core::result::Result<AnyReceipt, StepError> {
317 let v = json::parse(bytes).map_err(|e| (e, None))?;
318 signature_valid_value(&v, keys)
319}
320
321pub(crate) fn signature_valid_value(v: &Value, keys: &Keys) -> core::result::Result<AnyReceipt, StepError> {
323 let r = any_from_value(v).map_err(|e| (e, None))?;
324 match key_and_signature(&r, keys) {
325 Ok(()) => Ok(r),
326 Err(e) => Err((e, Some(Box::new(r)))),
327 }
328}
329
330fn key_and_signature(r: &dyn Stored, keys: &Keys) -> Result<()> {
331 let doc = keys.get(r.signer_host()).map_err(|e| Error::new(e.code(), "$.computed_by", e.detail()))?;
332 let Some(key) = doc.key(r.key_id()) else {
333 return err(
334 ErrorCode::KeyUnknown,
335 "$.computed_by",
336 format!("{} publishes no key {}", r.signer_host(), r.key_id()),
337 );
338 };
339 if !key.usable_at(r.issued()) {
340 return err(ErrorCode::KeyNotValid, "$.issued", "issued is outside the key's validity window");
341 }
342 let Some(sig) = lexical::decode_hex_lower::<64>(r.sig()) else {
343 return err(ErrorCode::Signature, "$.sig", "signature is not 64 bytes");
344 };
345 if !crypto::verify_ed25519(&key.public, r.payload(), &sig) {
346 return err(ErrorCode::Signature, "$.sig", "Ed25519 verification failed");
347 }
348 Ok(())
349}
350
351enum Recomputed {
353 Yes,
355 Signed(Error),
358}
359
360struct Inputs {
362 cells: BTreeMap<String, (String, String)>,
363}
364
365fn recompute_steps(r: &dyn Stored, keys: &Keys, res: &dyn Resolver) -> Result<Recomputed> {
366 let Some(desc_bytes) = res.descriptor(&r.cell().fn_hash) else {
368 return err(ErrorCode::FnUnavailable, "$.cell.fn_hash", "no descriptor for fn_hash");
369 };
370 let desc_v = json::parse(&desc_bytes)?;
371 if crypto::sha256_hex(&desc_v.to_jcs()) != r.cell().fn_hash {
372 return err(ErrorCode::FnHashMismatch, "$.cell.fn_hash", "the descriptor does not hash to fn_hash");
373 }
374 let d = FunctionDescriptor::from_value(&desc_v)?;
375 let decl = &d.signature.args;
376 for k in r.cell().args.keys() {
378 if !decl.contains_key(k) {
379 return err(ErrorCode::ArgUnknown, &member("$.cell.args", k), "the function declares no such argument");
380 }
381 }
382 for k in decl.keys() {
383 if !r.cell().args.contains_key(k) {
384 return err(ErrorCode::ArgMissing, &member("$.cell.args", k), "a declared argument is not bound");
385 }
386 }
387 for (k, a) in &r.cell().args {
388 let declared = decl.get(k).map(|x| x.ty);
389 if a.scalar().map(Scalar::ty) != declared {
390 return err(ErrorCode::ArgType, &member("$.cell.args", k), "type differs from the declaration");
391 }
392 }
393 let declared_valid: Vec<&String> = decl.iter().filter(|(_, x)| x.valid).map(|(k, _)| k).collect();
395 let given_valid: Vec<&String> = r.valid().keys().collect();
396 if declared_valid != given_valid {
397 return err(
398 ErrorCode::ValidMismatch,
399 "$.valid",
400 "valid does not hold exactly the declared valid-time arguments",
401 );
402 }
403 if r.scalar().is_some_and(|v| v.ty() != d.signature.returns.ty) {
405 return err(ErrorCode::ReturnType, "$.type", "type differs from the declared return type");
406 }
407 let mut latest_tx: Option<String> = None;
409 let mut seen = Inputs { cells: BTreeMap::new() };
410 for e in r.inputs() {
411 let p = member("$.inputs", e);
412 if lexical::split_slice_entry(e).is_some() {
413 slice_entry(r, keys, res, &d, e, &p, &mut latest_tx)?;
414 continue;
415 }
416 let input = obtain(keys, res, e, &p, "input")?;
417 if !d.inputs.contains(&input.cell().function_name()) {
418 return err(
419 ErrorCode::InputUndeclared,
420 &p,
421 format!("{} is not a declared input", input.cell().function_name()),
422 );
423 }
424 input_asof(r, &input, &p)?;
425 later_tx(&mut latest_tx, input.tx());
426 seen.cells.insert(e.clone(), (input.cell().id(), input.tx().to_string()));
427 }
428 if let Some(t) = latest_tx {
431 if r.tx() < t.as_str() {
432 return err(ErrorCode::TimeOrder, "$.tx", "tx is earlier than the latest input tx");
433 }
434 }
435 if r.is_withdrawal() {
437 return Ok(Recomputed::Yes);
438 }
439 let Some(ev) = res.evaluation(r.cell(), r.asof()) else {
440 return Ok(Recomputed::Signed(Error::new(
441 ErrorCode::EvalUnavailable,
442 "$.value",
443 "the resolver could not evaluate this function",
444 )));
445 };
446 if r.scalar() == Some(&ev.value) {
447 return Ok(Recomputed::Yes);
448 }
449 if let Some(lineage) = &ev.lineage {
450 if let Some(detail) = superseded(r, keys, res, &seen, lineage) {
451 return Ok(Recomputed::Signed(Error::new(ErrorCode::InputSuperseded, "$.inputs", detail)));
452 }
453 }
454 err(ErrorCode::ValueMismatch, "$.value", "recomputation gives a different type or value")
455}
456
457fn later_tx(latest: &mut Option<String>, tx: &str) {
458 if latest.as_ref().is_none_or(|t| tx > t.as_str()) {
459 *latest = Some(tx.to_string());
460 }
461}
462
463fn obtain(keys: &Keys, res: &dyn Resolver, hash: &str, p: &str, what: &str) -> Result<AnyReceipt> {
467 let Some(bytes) = res.receipt(hash) else {
468 return err(ErrorCode::InputUnavailable, p, format!("no receipt offered for this {what}"));
469 };
470 let input = match signature_valid(&bytes, keys) {
471 Ok(i) => i,
472 Err((e, _)) => return err(ErrorCode::InputInvalid, p, format!("{}: {}", e.code(), e.detail())),
473 };
474 if input.hash() != hash {
475 return err(ErrorCode::InputUnavailable, p, format!("the receipt offered for this {what} has another hash"));
476 }
477 Ok(input)
478}
479
480fn input_asof(r: &dyn Stored, input: &dyn Stored, p: &str) -> Result<()> {
483 if input.asof() > r.asof() {
484 return err(ErrorCode::TimeOrder, p, "an input's asof is after the receipt's asof");
485 }
486 Ok(())
487}
488
489fn slice_entry(
494 r: &dyn Stored,
495 keys: &Keys,
496 res: &dyn Resolver,
497 d: &FunctionDescriptor,
498 entry: &str,
499 p: &str,
500 latest_tx: &mut Option<String>,
501) -> Result<()> {
502 let Some((slice_id, members_hash)) = lexical::split_slice_entry(entry) else {
503 return err(ErrorCode::CanonHex, p, "not a slice entry");
504 };
505 let Some(bytes) = res.manifest(entry) else {
506 return err(ErrorCode::InputUnavailable, p, "no manifest offered for this slice entry");
507 };
508 let m = Manifest::from_json(&bytes).map_err(|e| nest(e, p))?;
509 if m.slice().id() != slice_id || m.members_hash() != members_hash {
510 return err(ErrorCode::InputUnavailable, p, "the manifest offered does not hash to the entry");
511 }
512 if !d.inputs.contains(&m.slice().function_name()) {
513 return err(
514 ErrorCode::InputUndeclared,
515 p,
516 format!("the slice's function {} is not a declared input", m.slice().function_name()),
517 );
518 }
519 let mut cells = std::collections::BTreeSet::new();
520 for h in m.members() {
521 let mp = format!("{p}.members.{h}");
522 let member = obtain(keys, res, h, &mp, "member")?;
523 let AnyReceipt::Value(rec) = &member else {
525 return err(ErrorCode::SliceMember, &mp, "a withdrawn cell is not a member of a slice");
526 };
527 if !m.slice().contains(rec) {
528 return err(ErrorCode::SliceMember, &mp, "the member does not belong to the slice");
529 }
530 if !m.slice().is_version_slice() && !cells.insert(member.cell().id()) {
531 return err(ErrorCode::SliceMember, &mp, "two members of the slice are one cell");
532 }
533 input_asof(r, &member, &mp)?;
534 later_tx(latest_tx, member.tx());
535 }
536 Ok(())
537}
538
539fn superseded(r: &dyn Stored, keys: &Keys, res: &dyn Resolver, seen: &Inputs, lineage: &[String]) -> Option<String> {
546 let dropped: Vec<&String> = r.inputs().iter().filter(|e| !lineage.contains(e)).collect();
547 if dropped.is_empty() {
548 return None;
549 }
550 let dropped_slices: Vec<&str> =
551 dropped.iter().filter_map(|e| lexical::split_slice_entry(e)).map(|(id, _)| id).collect();
552 let dropped_cells: Vec<&(String, String)> = dropped.iter().filter_map(|e| seen.cells.get(*e)).collect();
553 for e in lineage.iter().filter(|e| !r.inputs().contains(e)) {
554 if e.starts_with("slice:") {
557 if let Some(id) = dropped_slices.iter().find(|id| e.starts_with(&format!("slice:{id}:"))) {
558 return Some(format!("the evaluation read slice {id} with other members ({e})"));
559 }
560 continue;
561 }
562 if dropped_cells.is_empty() || lexical::check_hex(e, 64, "").is_err() {
563 continue;
564 }
565 let Ok(later) = obtain(keys, res, e, "", "receipt") else { continue };
566 let id = later.cell().id();
567 if dropped_cells.iter().any(|(cell, tx)| *cell == id && later.tx() > tx.as_str()) {
568 return Some(format!("the evaluation read a later version of an input's cell, receipt {e}"));
569 }
570 }
571 None
572}
573
574fn check_blob(r: &dyn Stored, content: &[u8]) -> Result<()> {
575 let Some(Scalar::Blob(b)) = r.scalar() else {
576 return err(ErrorCode::Schema, "$.value", "content supplied for a value that is not a blob");
577 };
578 let Ok((hash, len, _)) = lexical::parse_blob(b) else {
579 return err(ErrorCode::CanonBlob, "$.value", "not a blob");
580 };
581 if content.len() as u64 != len {
582 return err(
583 ErrorCode::BlobMismatch,
584 "$.value",
585 format!("content has {} bytes, the blob states {len}", content.len()),
586 );
587 }
588 if crypto::sha256(content) != hash {
589 return err(ErrorCode::BlobMismatch, "$.value", "content does not hash to the blob's sha256");
590 }
591 Ok(())
592}