use serde_json::{json, Map, Value};
use super::capsule::{rfc3339_seconds, Capsule, ACTION_TYPE_FYI};
use super::check::Error;
use super::names::*;
use crate::canonical::jcs;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Checkpoint {
pub log_id: String,
pub mmr_size: u64,
pub root: String,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Report {
pub deal_id: String,
pub audience: String,
pub nonce: String,
pub body: Map<String, Value>,
pub checkpoint: Option<Checkpoint>,
}
fn is_hex64(s: &str) -> bool {
s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}
pub fn report_payload(r: &Report) -> Result<Vec<u8>, Error> {
if ![AUDIENCE_KEEP, AUDIENCE_COUNTERPARTY, AUDIENCE_ADJUDICATOR].contains(&r.audience.as_str())
{
return Err(Error::Invalid(format!(
"report audience {} is not a copy audience",
super::check::go_q(&r.audience)
)));
}
if !is_hex64(&r.nonce) {
return Err(Error::Invalid(
"report nonce must be 64 lowercase hex".into(),
));
}
let mut body = Value::Object(r.body.clone());
integral_floats_as_integers(&mut body);
let mut m = json!({
"type": REPORT_TYPE, "profile": PROFILE, "deal_id": r.deal_id, "audience": r.audience,
"nonce": r.nonce, "report": body,
});
if let Some(c) = &r.checkpoint {
m["deal_checkpoint"] = json!({"log_id": c.log_id, "mmr_size": c.mmr_size, "root": c.root});
}
Ok(jcs(&m)?)
}
fn integral_floats_as_integers(v: &mut Value) {
match v {
Value::Number(n) if n.is_f64() => {
if let Some(i) = exact_safe_integer(&n.to_string()) {
*v = Value::from(i);
}
}
Value::Object(m) => m.values_mut().for_each(integral_floats_as_integers),
Value::Array(a) => a.iter_mut().for_each(integral_floats_as_integers),
_ => {}
}
}
fn exact_safe_integer(lit: &str) -> Option<i64> {
let (neg, rest) = match lit.strip_prefix('-') {
Some(r) => (true, r),
None => (false, lit),
};
let (mantissa, exp) = match rest.find(['e', 'E']) {
Some(k) => (&rest[..k], rest[k + 1..].parse::<i64>().ok()?),
None => (rest, 0),
};
let (int, frac) = mantissa.split_once('.').unwrap_or((mantissa, ""));
let digits: String = format!("{int}{frac}");
let scale = exp.checked_sub(i64::try_from(frac.len()).ok()?)?;
let digits = digits.trim_start_matches('0');
let whole = if scale >= 0 {
if digits.is_empty() {
String::new()
} else {
if digits.len() as i64 + scale > 16 {
return None;
}
format!("{digits}{}", "0".repeat(scale as usize))
}
} else {
let cut = digits.len() as i64 + scale;
let (head, tail) = if cut <= 0 {
("", digits)
} else {
digits.split_at(cut as usize)
};
if tail.bytes().any(|b| b != b'0') {
return None;
}
head.to_string()
};
let n: i64 = if whole.is_empty() {
0
} else {
whole.parse().ok()?
};
if n > crate::canonical::MAX_SAFE_INTEGER {
return None;
}
Some(if neg { -n } else { n })
}
pub fn report_capsule(operator: &str, developer: &str, at: i64) -> Result<Capsule, Error> {
if developer.is_empty() {
return Err(Error::Invalid(
"a report needs the producer's developer name".into(),
));
}
Ok(Capsule {
action_id: REPORT_ACTION_ID.into(),
action_type: ACTION_TYPE_FYI.into(),
operator: operator.into(),
developer: developer.into(),
timestamp: rfc3339_seconds(at),
disposition: None,
effect: None,
chain: None,
extensions: Vec::new(),
})
}