use std::sync::Arc;
use std::time::Duration;
use dashmap::DashMap;
use serde_json::Value;
use crate::receipt_verify::{self, FetchError, Signed, TrustedKey, VerifyError};
pub const FETCH_TIMEOUT: Duration = Duration::from_secs(5);
const OK_TTL_SECS: u64 = 3600;
const FETCH_FAIL_TTL_SECS: u64 = 15;
const CACHE_CAP: usize = 4096;
pub fn worker_fingerprint(worker_id: &str) -> String {
let d = ring::digest::digest(
&ring::digest::SHA256,
format!("worker:{worker_id}").as_bytes(),
);
hex::encode(&d.as_ref()[..16])
}
pub fn is_receipt_hash(s: &str) -> bool {
s.len() == 64
&& s.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
#[derive(Debug, Clone, PartialEq)]
pub struct ReceiptFacts {
pub amount: f64,
pub status: String,
pub executor_worker: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Reject {
Fetch(String),
Unverified(String),
NotATransaction,
NotSettled(String),
Amount { earn: f64, receipt: f64 },
WrongExecutor,
Reused,
}
impl Reject {
pub fn code(&self) -> &'static str {
match self {
Self::Fetch(_) => "fetch_failed",
Self::Unverified(_) => "unverified",
Self::NotATransaction | Self::NotSettled(_) => "not_settled",
Self::Amount { .. } => "amount",
Self::WrongExecutor => "wrong_executor",
Self::Reused => "reused",
}
}
}
impl std::fmt::Display for Reject {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Fetch(e) => write!(f, "receipt not fetched: {e}"),
Self::Unverified(e) => write!(f, "receipt does not verify: {e}"),
Self::NotATransaction => write!(f, "not a transaction receipt"),
Self::NotSettled(s) => write!(f, "settlement is {s}"),
Self::Amount { earn, receipt } => {
write!(f, "earn {earn:.6} exceeds the settled {receipt:.6}")
}
Self::WrongExecutor => write!(f, "the debit is not for one of this node's workers"),
Self::Reused => write!(f, "the receipt already backs another earn"),
}
}
}
fn settled(status: &str) -> bool {
!matches!(
status.trim().to_ascii_lowercase().as_str(),
"failed" | "refunded" | "reversed" | "cancelled" | "canceled" | "pending"
)
}
pub fn facts_of(body: &Value) -> Result<ReceiptFacts, Reject> {
if body.get("kind").and_then(Value::as_str) != Some("transaction") {
return Err(Reject::NotATransaction);
}
let amount = body
.pointer("/settlement/amount")
.and_then(Value::as_str)
.and_then(|a| a.trim().parse::<f64>().ok())
.filter(|a| a.is_finite() && *a >= 0.0)
.ok_or_else(|| Reject::Unverified("no settlement amount".into()))?;
let status = body
.pointer("/settlement/status")
.and_then(Value::as_str)
.unwrap_or("completed")
.to_string();
if !settled(&status) {
return Err(Reject::NotSettled(status));
}
let executor_worker = body
.pointer("/executor/worker")
.and_then(Value::as_str)
.map(str::to_string);
Ok(ReceiptFacts {
amount,
status,
executor_worker,
})
}
pub struct ReceiptCache {
ok: DashMap<String, (u64, Arc<ReceiptFacts>)>,
failed: DashMap<String, (u64, Reject)>,
}
impl Default for ReceiptCache {
fn default() -> Self {
Self::new()
}
}
impl ReceiptCache {
pub fn new() -> Self {
Self {
ok: DashMap::new(),
failed: DashMap::new(),
}
}
pub fn facts(
&self,
hash: &str,
now: u64,
fetch: &dyn Fn(&str) -> Result<Signed, FetchError>,
keys: &dyn Fn(bool) -> Vec<TrustedKey>,
) -> Result<Arc<ReceiptFacts>, Reject> {
if let Some(e) = self.ok.get(hash) {
if now.saturating_sub(e.0) < OK_TTL_SECS {
return Ok(e.1.clone());
}
}
if let Some(e) = self.failed.get(hash) {
if now.saturating_sub(e.0) < FETCH_FAIL_TTL_SECS {
return Err(e.1.clone());
}
}
let signed = fetch(hash).map_err(|e| {
let r = if e.permanent() {
Reject::Unverified(format!("the hub has no such receipt ({})", e.message))
} else {
Reject::Fetch(e.message)
};
self.note_failed(hash, now, &r);
r
})?;
if receipt_verify::sha256_hex(signed.receipt_json.as_bytes()) != hash {
return Err(Reject::Unverified("served bytes do not hash to it".into()));
}
let mut verdict = receipt_verify::verify(&signed, &keys(false));
if matches!(verdict, Err(VerifyError::UnknownKey(_))) {
verdict = receipt_verify::verify(&signed, &keys(true));
}
let verified = verdict.map_err(|e| Reject::Unverified(e.to_string()))?;
let facts = Arc::new(facts_of(&verified.body)?);
if self.ok.len() >= CACHE_CAP {
self.ok.clear();
}
self.ok.insert(hash.to_string(), (now, facts.clone()));
Ok(facts)
}
fn note_failed(&self, hash: &str, now: u64, r: &Reject) {
if self.failed.len() >= CACHE_CAP {
self.failed.clear();
}
self.failed.insert(hash.to_string(), (now, r.clone()));
}
}
pub fn judge(
facts: &ReceiptFacts,
earn_amount: f64,
local_worker_fps: &[String],
) -> Result<(), Reject> {
if earn_amount > facts.amount + super::earn_expect::epsilon(facts.amount) {
return Err(Reject::Amount {
earn: earn_amount,
receipt: facts.amount,
});
}
match facts.executor_worker.as_deref() {
Some(w) if local_worker_fps.iter().any(|f| f == w) => Ok(()),
_ => Err(Reject::WrongExecutor),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::receipt_verify::testkit::Hub;
use std::cell::Cell;
fn fps(names: &[&str]) -> Vec<String> {
names.iter().map(|n| worker_fingerprint(n)).collect()
}
fn hash_of(s: &Signed) -> String {
receipt_verify::sha256_hex(s.receipt_json.as_bytes())
}
#[test]
fn worker_fingerprint_is_the_hubs_fp_of_the_name() {
assert_eq!(worker_fingerprint("w1"), "7d5fae5e9503a782301d74c397506cbc");
assert_eq!(worker_fingerprint("w1").len(), 32);
assert_ne!(worker_fingerprint("w1"), worker_fingerprint("w2"));
assert!(is_receipt_hash(&"a".repeat(64)));
assert!(!is_receipt_hash(&"A".repeat(64)) && !is_receipt_hash("abc"));
}
#[test]
fn a_settled_debit_for_one_of_our_workers_binds_an_earn_up_to_its_amount() {
let hub = Hub::new();
let r = hub.transaction_receipt(Some("w1"), "1.500000", "completed");
let h = hash_of(&r);
let cache = ReceiptCache::new();
let fetched = Cell::new(0);
let fetch = |_: &str| -> Result<Signed, FetchError> {
fetched.set(fetched.get() + 1);
Ok(r.clone())
};
let keys = |_: bool| vec![hub.trusted()];
let f = cache.facts(&h, 100, &fetch, &keys).unwrap();
assert_eq!(f.amount, 1.5);
assert!(judge(&f, 1.2, &fps(&["w1", "other"])).is_ok());
assert!(judge(&f, 1.5, &fps(&["w1"])).is_ok());
assert_eq!(
judge(&f, 2.0, &fps(&["w1"])),
Err(Reject::Amount {
earn: 2.0,
receipt: 1.5
})
);
assert_eq!(
judge(&f, 1.0, &fps(&["not-w1"])),
Err(Reject::WrongExecutor)
);
cache.facts(&h, 101, &fetch, &keys).unwrap();
assert_eq!(fetched.get(), 1);
}
#[test]
fn a_debit_that_names_no_worker_binds_nothing() {
let hub = Hub::new();
let r = hub.transaction_receipt(None, "1.000000", "completed");
let f = facts_of(&serde_json::from_str(&r.receipt_json).unwrap()).unwrap();
assert_eq!(judge(&f, 0.5, &fps(&["w1"])), Err(Reject::WrongExecutor));
}
#[test]
fn what_the_signature_does_not_cover_or_the_hub_refunded_is_refused() {
let hub = Hub::new();
let other = Hub::new();
let keys = |_: bool| vec![hub.trusted()];
let cache = ReceiptCache::new();
let forged = other.transaction_receipt(Some("w1"), "9.000000", "completed");
let fh = hash_of(&forged);
let calls = Cell::new(0);
let r = cache.facts(&fh, 1, &|_| Ok(forged.clone()), &|refresh| {
calls.set(calls.get() + 1);
let _ = refresh;
vec![hub.trusted()]
});
assert!(matches!(r, Err(Reject::Unverified(_))), "{r:?}");
assert_eq!(calls.get(), 2, "an unknown key refreshes the key set once");
let good = hub.transaction_receipt(Some("w1"), "1.000000", "completed");
let r = cache.facts(&"0".repeat(64), 1, &|_| Ok(good.clone()), &keys);
assert!(matches!(r, Err(Reject::Unverified(_))), "{r:?}");
let mut t = good.clone();
t.receipt_json = t.receipt_json.replace("1.000000", "9.000000");
let r = cache.facts(&hash_of(&t), 1, &|_| Ok(t.clone()), &keys);
assert!(matches!(r, Err(Reject::Unverified(_))), "{r:?}");
let refunded = hub.transaction_receipt(Some("w1"), "1.000000", "refunded");
let r = cache.facts(&hash_of(&refunded), 1, &|_| Ok(refunded.clone()), &keys);
assert_eq!(r, Err(Reject::NotSettled("refunded".into())));
let batch = hub.batch_receipt(&["a".repeat(64)], "5.000000");
let r = cache.facts(&hash_of(&batch), 1, &|_| Ok(batch.clone()), &keys);
assert_eq!(r, Err(Reject::NotATransaction));
}
#[test]
fn a_hub_that_has_no_such_receipt_is_final_and_a_hub_that_is_down_is_not() {
let hub = Hub::new();
let keys = |_: bool| vec![hub.trusted()];
let cache = ReceiptCache::new();
let missing = |_: &str| -> Result<Signed, FetchError> {
Err(FetchError {
status: Some(404),
message: "HTTP 404".into(),
})
};
assert!(matches!(
cache.facts(&"d".repeat(64), 1, &missing, &keys),
Err(Reject::Unverified(_))
));
let down = |_: &str| -> Result<Signed, FetchError> {
Err(FetchError {
status: Some(503),
message: "HTTP 503".into(),
})
};
assert!(matches!(
cache.facts(&"e".repeat(64), 1, &down, &keys),
Err(Reject::Fetch(_))
));
}
#[test]
fn a_failed_fetch_is_not_repeated_at_once() {
let hub = Hub::new();
let cache = ReceiptCache::new();
let calls = Cell::new(0);
let fetch = |_: &str| {
calls.set(calls.get() + 1);
Err(FetchError {
status: None,
message: "hub down".into(),
})
};
let keys = |_: bool| vec![hub.trusted()];
let h = "b".repeat(64);
assert!(matches!(
cache.facts(&h, 10, &fetch, &keys),
Err(Reject::Fetch(_))
));
assert!(cache.facts(&h, 12, &fetch, &keys).is_err());
assert_eq!(calls.get(), 1);
assert!(cache
.facts(&h, 10 + FETCH_FAIL_TTL_SECS, &fetch, &keys)
.is_err());
assert_eq!(calls.get(), 2);
}
}