1use crate::error::{err, ErrorCode, Result};
4use crate::json::{self, Value};
5use crate::keys::Keys;
6use crate::lexical::{self, limits};
7use crate::receipt::Receipt;
8use crate::schema;
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
12pub enum Outcome {
13 Ok,
17 Stale,
20 NotCovered,
23 Unlicensed,
25 PaymentRequired,
27 RateLimited,
29 BadRequest,
31 Error,
33}
34
35impl Outcome {
36 pub const fn as_str(self) -> &'static str {
38 match self {
39 Outcome::Ok => "ok",
40 Outcome::Stale => "stale",
41 Outcome::NotCovered => "not_covered",
42 Outcome::Unlicensed => "unlicensed",
43 Outcome::PaymentRequired => "payment_required",
44 Outcome::RateLimited => "rate_limited",
45 Outcome::BadRequest => "bad_request",
46 Outcome::Error => "error",
47 }
48 }
49}
50
51#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
53pub enum Trust {
54 Primary,
56 Verified,
58 Unverified,
60}
61
62impl Trust {
63 pub const fn as_str(self) -> &'static str {
65 match self {
66 Trust::Primary => "primary",
67 Trust::Verified => "verified",
68 Trust::Unverified => "unverified",
69 }
70 }
71}
72
73#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
78#[non_exhaustive]
79pub enum Fault {
80 DivZero,
82 Domain,
84 Range,
86 Empty,
88 Absent,
90 Future,
92 Key,
95 DispatchKey,
97}
98
99impl Fault {
100 pub const ALL: &'static [Fault] = &[
102 Fault::DivZero,
103 Fault::Domain,
104 Fault::Range,
105 Fault::Empty,
106 Fault::Absent,
107 Fault::Future,
108 Fault::Key,
109 Fault::DispatchKey,
110 ];
111
112 pub const fn as_str(self) -> &'static str {
114 match self {
115 Fault::DivZero => "E_FORMULA_DIV_ZERO",
116 Fault::Domain => "E_FORMULA_DOMAIN",
117 Fault::Range => "E_FORMULA_RANGE",
118 Fault::Empty => "E_FORMULA_EMPTY",
119 Fault::Absent => "E_FORMULA_ABSENT",
120 Fault::Future => "E_FORMULA_FUTURE",
121 Fault::Key => "E_FORMULA_KEY",
122 Fault::DispatchKey => "E_FORMULA_DISPATCH_KEY",
123 }
124 }
125
126 pub fn from_code(text: &str) -> Option<Fault> {
129 Fault::ALL.iter().copied().find(|f| f.as_str() == text)
130 }
131}
132
133impl core::fmt::Display for Fault {
134 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
135 f.write_str(self.as_str())
136 }
137}
138
139#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
144#[non_exhaustive]
145pub enum ForeignDetail {
146 Offline,
148 Network,
150 Dns,
152 Tls,
154 Timeout,
156 Refused,
158}
159
160impl ForeignDetail {
161 pub const ALL: &'static [ForeignDetail] = &[
163 ForeignDetail::Offline,
164 ForeignDetail::Network,
165 ForeignDetail::Dns,
166 ForeignDetail::Tls,
167 ForeignDetail::Timeout,
168 ForeignDetail::Refused,
169 ];
170
171 pub const fn as_str(self) -> &'static str {
173 match self {
174 ForeignDetail::Offline => "offline",
175 ForeignDetail::Network => "network",
176 ForeignDetail::Dns => "dns",
177 ForeignDetail::Tls => "tls",
178 ForeignDetail::Timeout => "timeout",
179 ForeignDetail::Refused => "refused",
180 }
181 }
182
183 pub fn from_name(text: &str) -> Option<ForeignDetail> {
185 ForeignDetail::ALL.iter().copied().find(|d| d.as_str() == text)
186 }
187}
188
189impl core::fmt::Display for ForeignDetail {
190 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
191 f.write_str(self.as_str())
192 }
193}
194
195#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
198#[non_exhaustive]
199pub struct EnvelopeExtras {
200 pub fault: Option<Fault>,
202 pub fn_hash: Option<String>,
205 pub detail: Option<ForeignDetail>,
207}
208
209#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
211#[non_exhaustive]
212pub enum ResolutionKind {
213 Alias,
215 Default,
217 Lookup,
220 Method,
222}
223
224impl ResolutionKind {
225 pub const ALL: &'static [ResolutionKind] =
227 &[ResolutionKind::Alias, ResolutionKind::Default, ResolutionKind::Lookup, ResolutionKind::Method];
228
229 pub const fn as_str(self) -> &'static str {
231 match self {
232 ResolutionKind::Alias => "alias",
233 ResolutionKind::Default => "default",
234 ResolutionKind::Lookup => "lookup",
235 ResolutionKind::Method => "method",
236 }
237 }
238
239 pub fn from_name(text: &str) -> Option<ResolutionKind> {
241 ResolutionKind::ALL.iter().copied().find(|k| k.as_str() == text)
242 }
243}
244
245#[derive(Clone, Debug, PartialEq, Eq, Hash)]
248#[non_exhaustive]
249pub struct Resolution {
250 pub from: String,
252 pub kind: ResolutionKind,
254 pub to: String,
256 pub asof: Option<String>,
258}
259
260impl Resolution {
261 pub fn new(from: &str, kind: ResolutionKind, to: &str) -> Result<Resolution> {
264 if kind == ResolutionKind::Lookup {
265 return env_err("$.resolutions", "a lookup resolution carries its asof: Resolution::lookup");
266 }
267 Ok(Resolution { from: from.into(), kind, to: to.into(), asof: None })
268 }
269
270 pub fn lookup(label: &str, key: &str, asof: &str) -> Result<Resolution> {
273 lexical::check_instant(asof, "$.resolutions.asof").map_err(|e| e.recode(ErrorCode::Envelope))?;
274 Ok(Resolution { from: label.into(), kind: ResolutionKind::Lookup, to: key.into(), asof: Some(asof.into()) })
275 }
276}
277
278#[derive(Clone, Debug, PartialEq, Eq, Hash)]
281#[non_exhaustive]
282pub struct Resolved {
283 pub call: String,
285 pub resolutions: Vec<Resolution>,
287 pub aliases_tx: Option<String>,
289}
290
291impl Resolved {
292 pub fn new(call: &str, resolutions: Vec<Resolution>) -> Result<Resolved> {
294 if call.is_empty() {
295 return env_err("$.resolved.call", "call is a non-empty string");
296 }
297 Ok(Resolved { call: call.into(), resolutions, aliases_tx: None })
298 }
299
300 pub fn with_aliases_tx(self, instant: &str) -> Result<Resolved> {
303 lexical::check_instant(instant, "$.resolved.aliases_tx").map_err(|e| e.recode(ErrorCode::Envelope))?;
304 Ok(Resolved { aliases_tx: Some(instant.into()), ..self })
305 }
306}
307
308#[derive(Clone, Debug, PartialEq, Eq, Hash)]
311#[non_exhaustive]
312pub struct Shadows {
313 pub class: String,
315 pub reference: String,
317}
318
319impl Shadows {
320 pub fn new(class: &str, reference: &str) -> Result<Shadows> {
323 lexical::check_function_name(class, "$.shadows.class").map_err(|e| e.recode(ErrorCode::Envelope))?;
324 lexical::check_hex(reference, 64, "$.shadows.reference").map_err(|e| e.recode(ErrorCode::Envelope))?;
325 Ok(Shadows { class: class.into(), reference: reference.into() })
326 }
327}
328
329#[derive(Clone, Debug, PartialEq, Eq, Hash)]
331pub struct Quote {
332 pub amount: String,
334 pub currency: String,
336 pub authorise: String,
338}
339
340#[derive(Clone, Debug, PartialEq, Eq, Hash)]
342pub struct Request {
343 pub(crate) cell_id: String,
344 pub(crate) asof: Option<String>,
345 pub(crate) job: Option<String>,
346 pub(crate) pin: Option<String>,
347 pub(crate) mesh: Option<String>,
348}
349
350#[derive(Clone, Debug, PartialEq, Eq, Hash)]
352pub struct InvalidRequest(String);
353
354impl core::fmt::Display for InvalidRequest {
355 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
356 write!(f, "invalid request: {}", self.0)
357 }
358}
359
360impl std::error::Error for InvalidRequest {}
361
362impl Request {
363 pub fn new(cell_id: &str, asof: Option<&str>) -> core::result::Result<Request, InvalidRequest> {
367 if lexical::check_hex(cell_id, 64, "").is_err() {
368 return Err(InvalidRequest(format!("cell_id must be 64 lowercase hex digits: {cell_id:?}")));
369 }
370 if let Some(a) = asof {
371 if !lexical::is_instant(a) {
372 return Err(InvalidRequest(format!("asof must be an instant: {a:?}")));
373 }
374 }
375 Ok(Request { cell_id: cell_id.into(), asof: asof.map(String::from), job: None, pin: None, mesh: None })
376 }
377
378 pub fn with_job(cell_id: &str, asof: Option<&str>, job: &str) -> core::result::Result<Request, InvalidRequest> {
384 if !is_job(job) {
385 return Err(InvalidRequest(format!("job must be 32 to 64 lowercase hex digits: {job:?}")));
386 }
387 let mut r = Request::new(cell_id, asof)?;
388 r.job = Some(job.into());
389 Ok(r)
390 }
391
392 pub fn with_pin(self, fn_hash: &str) -> core::result::Result<Request, InvalidRequest> {
396 if lexical::check_hex(fn_hash, 64, "").is_err() {
397 return Err(InvalidRequest(format!("fn_hash must be 64 lowercase hex digits: {fn_hash:?}")));
398 }
399 Ok(Request { pin: Some(fn_hash.into()), ..self })
400 }
401
402 pub fn with_mesh(self, host: &str) -> core::result::Result<Request, InvalidRequest> {
406 if lexical::check_dns_name(host, "").is_err() {
407 return Err(InvalidRequest(format!("mesh must be a DNS name: {host:?}")));
408 }
409 Ok(Request { mesh: Some(host.into()), ..self })
410 }
411
412 pub fn fn_hash(&self) -> Option<&str> {
414 self.pin.as_deref()
415 }
416
417 pub fn mesh(&self) -> Option<&str> {
419 self.mesh.as_deref()
420 }
421
422 pub fn job(&self) -> Option<&str> {
424 self.job.as_deref()
425 }
426
427 pub fn cell_id(&self) -> &str {
429 &self.cell_id
430 }
431
432 pub fn asof(&self) -> Option<&str> {
434 self.asof.as_deref()
435 }
436}
437
438#[derive(Clone, Debug, PartialEq, Eq)]
440pub struct Envelope {
441 pub outcome: Outcome,
443 pub receipt: Option<Receipt>,
445 pub trust: Option<Trust>,
447 pub age_seconds: Option<u64>,
449 pub superseded_by: Option<String>,
451 pub reason: Option<String>,
453 pub quote: Option<Quote>,
455 pub retry_after_seconds: Option<u64>,
457 pub error: Option<ErrorCode>,
459}
460
461pub(crate) const BAD_REQUEST_CODES: [ErrorCode; 15] = [
462 ErrorCode::ParseUri,
463 ErrorCode::CanonName,
464 ErrorCode::CanonArgName,
465 ErrorCode::CanonArgDuplicate,
466 ErrorCode::CanonArgOrder,
467 ErrorCode::CanonPercent,
468 ErrorCode::CanonType,
469 ErrorCode::CanonNumber,
470 ErrorCode::CanonDate,
471 ErrorCode::CanonInstant,
472 ErrorCode::CanonString,
473 ErrorCode::CanonBlob,
474 ErrorCode::CanonLimit,
475 ErrorCode::ArgUnknown,
476 ErrorCode::ArgMissing,
477];
478
479pub(crate) fn env_err<T>(path: &str, detail: impl Into<String>) -> Result<T> {
480 err(ErrorCode::Envelope, path, detail)
481}
482
483pub(crate) fn integer_member(v: &Value, path: &str) -> Result<u64> {
485 let Some(t) = v.as_number_text() else {
486 return env_err(path, "must be a non-negative integer");
487 };
488 let ok =
489 !t.is_empty() && t.bytes().all(|c| c.is_ascii_digit()) && (t == "0" || !t.starts_with('0')) && t.len() <= 16;
490 match (ok, t.parse::<u64>()) {
491 (true, Ok(x)) if x <= limits::BLOB_LENGTH => Ok(x),
492 _ => env_err(path, format!("must be written 0|[1-9][0-9]* and at most 2^53 - 1, not {t}")),
493 }
494}
495
496pub fn check_envelope(status: u16, body: &[u8], keys: &Keys, request: &Request) -> Result<Envelope> {
501 check_envelope_extras(status, body, keys, request).map(|(env, _)| env)
502}
503
504pub fn check_envelope_extras(
515 status: u16,
516 body: &[u8],
517 keys: &Keys,
518 request: &Request,
519) -> Result<(Envelope, EnvelopeExtras)> {
520 crate::answer::check_answer(status, body, keys, request)?.into_envelope()
521}
522
523pub fn check_envelope_any(status: u16, body: &[u8], keys: &Keys, request: &Request) -> Result<AnyEnvelope> {
530 let a = crate::answer::check_answer(status, body, keys, request)?;
531 if let Some(p) = a.pending {
532 return Ok(AnyEnvelope::Pending(p));
533 }
534 a.into_envelope().map(|(e, x)| AnyEnvelope::Envelope(e, x))
535}
536
537pub(crate) fn is_job(s: &str) -> bool {
539 (32..=64).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
540}
541
542#[allow(clippy::large_enum_variant)]
546#[derive(Clone, Debug, PartialEq, Eq)]
547#[non_exhaustive]
548pub enum AnyEnvelope {
549 Envelope(Envelope, EnvelopeExtras),
552 Pending(Pending),
554}
555
556impl AnyEnvelope {
557 pub fn outcome_str(&self) -> &'static str {
559 match self {
560 AnyEnvelope::Envelope(e, _) => e.outcome.as_str(),
561 AnyEnvelope::Pending(_) => "pending",
562 }
563 }
564}
565
566#[derive(Clone, Debug, PartialEq, Eq, Hash)]
570#[non_exhaustive]
571pub struct Pending {
572 pub job: String,
574 pub estimate_seconds: u64,
576 pub poll: String,
579 pub request: Request,
581}
582
583impl Pending {
584 pub const STATUS: u16 = 202;
586
587 pub fn new(job: &str, estimate_seconds: u64, poll: &str, request: Request) -> Result<Pending> {
594 check_job_and_poll_for(job, poll, request.mesh())?;
595 if estimate_seconds > limits::BLOB_LENGTH {
596 return env_err("$.estimate_seconds", "estimate_seconds is at most 2^53 - 1");
597 }
598 let request = Request { job: None, mesh: None, ..request };
599 Ok(Pending { job: job.into(), estimate_seconds, poll: poll.into(), request })
600 }
601
602 pub fn to_value(&self) -> Value {
604 json::parse(&self.to_json()).unwrap_or(Value::Null)
606 }
607
608 pub fn to_json(&self) -> Vec<u8> {
610 let mut out = String::new();
611 out.push_str("{\"estimate_seconds\":");
612 out.push_str(&self.estimate_seconds.to_string());
613 out.push_str(",\"job\":");
614 json::write_string(&self.job, &mut out);
615 out.push_str(",\"outcome\":\"pending\",\"poll\":");
616 json::write_string(&self.poll, &mut out);
617 out.push_str(",\"request\":{");
618 if let Some(a) = &self.request.asof {
619 out.push_str("\"asof\":");
620 json::write_string(a, &mut out);
621 out.push(',');
622 }
623 out.push_str("\"cell_id\":");
624 json::write_string(&self.request.cell_id, &mut out);
625 if let Some(p) = &self.request.pin {
626 out.push_str(",\"fn_hash\":");
627 json::write_string(p, &mut out);
628 }
629 out.push_str("}}");
630 out.into_bytes()
631 }
632}
633
634pub(crate) fn check_job_and_poll_for(job: &str, poll: &str, mesh: Option<&str>) -> Result<()> {
637 if !is_job(job) {
638 return env_err("$.job", "job is 32 to 64 lowercase hex digits");
639 }
640 if poll.starts_with("http://") {
641 if !mesh.is_some_and(lexical::is_unrooted) {
642 return env_err("$.poll", "a loopback poll is only for an unrooted mesh the request names");
643 }
644 if lexical::loopback_origin(poll).is_none() || !poll.ends_with(&format!("/jobs/{job}")) {
645 return env_err("$.poll", "poll is a loopback URL ending /jobs/<job>");
646 }
647 return Ok(());
648 }
649 let url_ok =
650 poll.strip_prefix("https://").is_some_and(|r| !r.is_empty() && r.bytes().all(|c| (0x21..=0x7E).contains(&c)))
651 && poll.len() <= limits::LICENCE_URL;
652 if !url_ok {
653 return env_err("$.poll", "poll is an https URL of printable ASCII, at most 512 characters");
654 }
655 let host = poll["https://".len()..].split('/').next().unwrap_or("");
657 if !poll["https://".len()..].contains('/') || lexical::check_dns_name(host, "").is_err() {
658 return env_err("$.poll", "poll's host is a DNS name");
659 }
660 if !poll.ends_with(&format!("/jobs/{job}")) {
661 return env_err("$.poll", "poll ends /jobs/<job>");
662 }
663 Ok(())
664}
665
666pub(crate) fn quote(q: &Value) -> Result<Quote> {
667 let m = schema::object_or(q, "$.quote", ErrorCode::Envelope, "quote")?;
668 schema::exact(m, &["amount", "authorise", "currency"], &[], "$.quote", ErrorCode::Envelope)?;
669 let amount = schema::string_or(m, "amount", "$.quote", ErrorCode::Envelope)?;
670 let authorise = schema::string_or(m, "authorise", "$.quote", ErrorCode::Envelope)?;
671 let currency = schema::string_or(m, "currency", "$.quote", ErrorCode::Envelope)?;
672 if lexical::check_number(amount, "").is_err() || amount.starts_with('-') || amount == "0" {
673 return env_err("$.quote.amount", "amount is a canonical decimal greater than zero");
674 }
675 let url_ok = authorise
676 .strip_prefix("https://")
677 .is_some_and(|r| !r.is_empty() && r.bytes().all(|c| (0x21..=0x7E).contains(&c)))
678 && authorise.len() <= limits::LICENCE_URL;
679 if !url_ok {
680 return env_err("$.quote.authorise", "authorise is an https URL");
681 }
682 if !lexical::is_currency(currency) {
683 return env_err("$.quote.currency", "currency is a currency code from units.md");
684 }
685 Ok(Quote { amount: amount.into(), currency: currency.into(), authorise: authorise.into() })
686}