use crate::error::{err, ErrorCode, Result};
use crate::json::{self, Value};
use crate::keys::Keys;
use crate::lexical::{self, limits};
use crate::receipt::Receipt;
use crate::schema;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Outcome {
Ok,
Stale,
NotCovered,
Unlicensed,
PaymentRequired,
RateLimited,
BadRequest,
Error,
}
impl Outcome {
pub const fn as_str(self) -> &'static str {
match self {
Outcome::Ok => "ok",
Outcome::Stale => "stale",
Outcome::NotCovered => "not_covered",
Outcome::Unlicensed => "unlicensed",
Outcome::PaymentRequired => "payment_required",
Outcome::RateLimited => "rate_limited",
Outcome::BadRequest => "bad_request",
Outcome::Error => "error",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Trust {
Primary,
Verified,
Unverified,
}
impl Trust {
pub const fn as_str(self) -> &'static str {
match self {
Trust::Primary => "primary",
Trust::Verified => "verified",
Trust::Unverified => "unverified",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Fault {
DivZero,
Domain,
Range,
Empty,
Absent,
Future,
}
impl Fault {
pub const ALL: &'static [Fault] =
&[Fault::DivZero, Fault::Domain, Fault::Range, Fault::Empty, Fault::Absent, Fault::Future];
pub const fn as_str(self) -> &'static str {
match self {
Fault::DivZero => "E_FORMULA_DIV_ZERO",
Fault::Domain => "E_FORMULA_DOMAIN",
Fault::Range => "E_FORMULA_RANGE",
Fault::Empty => "E_FORMULA_EMPTY",
Fault::Absent => "E_FORMULA_ABSENT",
Fault::Future => "E_FORMULA_FUTURE",
}
}
pub fn from_code(text: &str) -> Option<Fault> {
Fault::ALL.iter().copied().find(|f| f.as_str() == text)
}
}
impl core::fmt::Display for Fault {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct EnvelopeExtras {
pub fault: Option<Fault>,
pub fn_hash: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Quote {
pub amount: String,
pub currency: String,
pub authorise: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Request {
pub(crate) cell_id: String,
pub(crate) asof: Option<String>,
pub(crate) job: Option<String>,
pub(crate) pin: Option<String>,
pub(crate) mesh: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct InvalidRequest(String);
impl core::fmt::Display for InvalidRequest {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "invalid request: {}", self.0)
}
}
impl std::error::Error for InvalidRequest {}
impl Request {
pub fn new(cell_id: &str, asof: Option<&str>) -> core::result::Result<Request, InvalidRequest> {
if lexical::check_hex(cell_id, 64, "").is_err() {
return Err(InvalidRequest(format!("cell_id must be 64 lowercase hex digits: {cell_id:?}")));
}
if let Some(a) = asof {
if !lexical::is_instant(a) {
return Err(InvalidRequest(format!("asof must be an instant: {a:?}")));
}
}
Ok(Request { cell_id: cell_id.into(), asof: asof.map(String::from), job: None, pin: None, mesh: None })
}
pub fn with_job(cell_id: &str, asof: Option<&str>, job: &str) -> core::result::Result<Request, InvalidRequest> {
if !is_job(job) {
return Err(InvalidRequest(format!("job must be 32 to 64 lowercase hex digits: {job:?}")));
}
let mut r = Request::new(cell_id, asof)?;
r.job = Some(job.into());
Ok(r)
}
pub fn with_pin(self, fn_hash: &str) -> core::result::Result<Request, InvalidRequest> {
if lexical::check_hex(fn_hash, 64, "").is_err() {
return Err(InvalidRequest(format!("fn_hash must be 64 lowercase hex digits: {fn_hash:?}")));
}
Ok(Request { pin: Some(fn_hash.into()), ..self })
}
pub fn with_mesh(self, host: &str) -> core::result::Result<Request, InvalidRequest> {
if lexical::check_dns_name(host, "").is_err() {
return Err(InvalidRequest(format!("mesh must be a DNS name: {host:?}")));
}
Ok(Request { mesh: Some(host.into()), ..self })
}
pub fn fn_hash(&self) -> Option<&str> {
self.pin.as_deref()
}
pub fn mesh(&self) -> Option<&str> {
self.mesh.as_deref()
}
pub fn job(&self) -> Option<&str> {
self.job.as_deref()
}
pub fn cell_id(&self) -> &str {
&self.cell_id
}
pub fn asof(&self) -> Option<&str> {
self.asof.as_deref()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Envelope {
pub outcome: Outcome,
pub receipt: Option<Receipt>,
pub trust: Option<Trust>,
pub age_seconds: Option<u64>,
pub superseded_by: Option<String>,
pub reason: Option<String>,
pub quote: Option<Quote>,
pub retry_after_seconds: Option<u64>,
pub error: Option<ErrorCode>,
}
pub(crate) const BAD_REQUEST_CODES: [ErrorCode; 15] = [
ErrorCode::ParseUri,
ErrorCode::CanonName,
ErrorCode::CanonArgName,
ErrorCode::CanonArgDuplicate,
ErrorCode::CanonArgOrder,
ErrorCode::CanonPercent,
ErrorCode::CanonType,
ErrorCode::CanonNumber,
ErrorCode::CanonDate,
ErrorCode::CanonInstant,
ErrorCode::CanonString,
ErrorCode::CanonBlob,
ErrorCode::CanonLimit,
ErrorCode::ArgUnknown,
ErrorCode::ArgMissing,
];
pub(crate) fn env_err<T>(path: &str, detail: impl Into<String>) -> Result<T> {
err(ErrorCode::Envelope, path, detail)
}
pub(crate) fn integer_member(v: &Value, path: &str) -> Result<u64> {
let Some(t) = v.as_number_text() else {
return env_err(path, "must be a non-negative integer");
};
let ok =
!t.is_empty() && t.bytes().all(|c| c.is_ascii_digit()) && (t == "0" || !t.starts_with('0')) && t.len() <= 16;
match (ok, t.parse::<u64>()) {
(true, Ok(x)) if x <= limits::BLOB_LENGTH => Ok(x),
_ => env_err(path, format!("must be written 0|[1-9][0-9]* and at most 2^53 - 1, not {t}")),
}
}
pub fn check_envelope(status: u16, body: &[u8], keys: &Keys, request: &Request) -> Result<Envelope> {
check_envelope_extras(status, body, keys, request).map(|(env, _)| env)
}
pub fn check_envelope_extras(
status: u16,
body: &[u8],
keys: &Keys,
request: &Request,
) -> Result<(Envelope, EnvelopeExtras)> {
crate::answer::check_answer(status, body, keys, request)?.into_envelope()
}
pub fn check_envelope_any(status: u16, body: &[u8], keys: &Keys, request: &Request) -> Result<AnyEnvelope> {
let a = crate::answer::check_answer(status, body, keys, request)?;
if let Some(p) = a.pending {
return Ok(AnyEnvelope::Pending(p));
}
a.into_envelope().map(|(e, x)| AnyEnvelope::Envelope(e, x))
}
pub(crate) fn is_job(s: &str) -> bool {
(32..=64).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
}
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum AnyEnvelope {
Envelope(Envelope, EnvelopeExtras),
Pending(Pending),
}
impl AnyEnvelope {
pub fn outcome_str(&self) -> &'static str {
match self {
AnyEnvelope::Envelope(e, _) => e.outcome.as_str(),
AnyEnvelope::Pending(_) => "pending",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Pending {
pub job: String,
pub estimate_seconds: u64,
pub poll: String,
pub request: Request,
}
impl Pending {
pub const STATUS: u16 = 202;
pub fn new(job: &str, estimate_seconds: u64, poll: &str, request: Request) -> Result<Pending> {
check_job_and_poll(job, poll)?;
if estimate_seconds > limits::BLOB_LENGTH {
return env_err("$.estimate_seconds", "estimate_seconds is at most 2^53 - 1");
}
let request = Request { job: None, mesh: None, ..request };
Ok(Pending { job: job.into(), estimate_seconds, poll: poll.into(), request })
}
pub fn to_value(&self) -> Value {
json::parse(&self.to_json()).unwrap_or(Value::Null)
}
pub fn to_json(&self) -> Vec<u8> {
let mut out = String::new();
out.push_str("{\"estimate_seconds\":");
out.push_str(&self.estimate_seconds.to_string());
out.push_str(",\"job\":");
json::write_string(&self.job, &mut out);
out.push_str(",\"outcome\":\"pending\",\"poll\":");
json::write_string(&self.poll, &mut out);
out.push_str(",\"request\":{");
if let Some(a) = &self.request.asof {
out.push_str("\"asof\":");
json::write_string(a, &mut out);
out.push(',');
}
out.push_str("\"cell_id\":");
json::write_string(&self.request.cell_id, &mut out);
if let Some(p) = &self.request.pin {
out.push_str(",\"fn_hash\":");
json::write_string(p, &mut out);
}
out.push_str("}}");
out.into_bytes()
}
}
pub(crate) fn check_job_and_poll(job: &str, poll: &str) -> Result<()> {
if !is_job(job) {
return env_err("$.job", "job is 32 to 64 lowercase hex digits");
}
let url_ok =
poll.strip_prefix("https://").is_some_and(|r| !r.is_empty() && r.bytes().all(|c| (0x21..=0x7E).contains(&c)))
&& poll.len() <= limits::LICENCE_URL;
if !url_ok {
return env_err("$.poll", "poll is an https URL of printable ASCII, at most 512 characters");
}
let host = poll["https://".len()..].split('/').next().unwrap_or("");
if !poll["https://".len()..].contains('/') || lexical::check_dns_name(host, "").is_err() {
return env_err("$.poll", "poll's host is a DNS name");
}
if !poll.ends_with(&format!("/jobs/{job}")) {
return env_err("$.poll", "poll ends /jobs/<job>");
}
Ok(())
}
pub(crate) fn quote(q: &Value) -> Result<Quote> {
let m = schema::object_or(q, "$.quote", ErrorCode::Envelope, "quote")?;
schema::exact(m, &["amount", "authorise", "currency"], &[], "$.quote", ErrorCode::Envelope)?;
let amount = schema::string_or(m, "amount", "$.quote", ErrorCode::Envelope)?;
let authorise = schema::string_or(m, "authorise", "$.quote", ErrorCode::Envelope)?;
let currency = schema::string_or(m, "currency", "$.quote", ErrorCode::Envelope)?;
if lexical::check_number(amount, "").is_err() || amount.starts_with('-') || amount == "0" {
return env_err("$.quote.amount", "amount is a canonical decimal greater than zero");
}
let url_ok = authorise
.strip_prefix("https://")
.is_some_and(|r| !r.is_empty() && r.bytes().all(|c| (0x21..=0x7E).contains(&c)))
&& authorise.len() <= limits::LICENCE_URL;
if !url_ok {
return env_err("$.quote.authorise", "authorise is an https URL");
}
if !lexical::is_currency(currency) {
return env_err("$.quote.currency", "currency is a currency code from units.md");
}
Ok(Quote { amount: amount.into(), currency: currency.into(), authorise: authorise.into() })
}