use serde_json::{Map, Value};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use crate::data_integrity;
pub const GENESIS: &str = "genesis";
pub const EQUIVOCATION_TYPE: &str = "VouchHeartbeatEquivocation";
pub const HEARTBEAT_PROTOCOL_VERSION: &str = "1.0";
pub const HEARTBEAT_REQUEST_TYPE: &str = "heartbeat_request";
pub const SIDECAR_FIELDS: [&str; 2] = ["authorityState", "lineage"];
pub const MAX_DID_LENGTH: usize = 1024;
pub const MAX_SESSION_ID_LENGTH: usize = 256;
pub const MAX_AUDIENCE: usize = 16;
pub const MAX_EARLIER_REVEALS: usize = 16;
pub const MAX_MERKLE_ROOT_LENGTH: usize = 128;
pub const MAX_PROOFS_CHECKED: usize = 16;
const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1;
pub const EQUIVOCATION_PROVEN: &str = "equivocation_proven";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EquivocationVerdict {
pub valid: bool,
pub reason: String,
}
fn no(reason: &str) -> EquivocationVerdict {
EquivocationVerdict {
valid: false,
reason: reason.to_string(),
}
}
pub fn predecessor_problem(value: &Value) -> Option<String> {
if value.as_str() == Some(GENESIS) {
return None;
}
let Some(obj) = value
.as_object()
.filter(|o| o.len() == 1 && o.contains_key("session"))
else {
return Some(r#"predecessor must be "genesis" or {"session": "<session id>"}"#.into());
};
match obj["session"].as_str() {
Some(s) if !s.is_empty() && s.chars().count() <= MAX_SESSION_ID_LENGTH => None,
_ => Some(format!(
"predecessor.session must be a session id of 1 to {MAX_SESSION_ID_LENGTH} characters"
)),
}
}
pub fn predecessor_key(value: &Value) -> String {
match value.as_str() {
Some(GENESIS) => GENESIS.to_string(),
_ => format!(
"session:{}",
value
.get("session")
.and_then(Value::as_str)
.unwrap_or_default()
),
}
}
pub fn strip_sidecars(heartbeat: &Map<String, Value>) -> Map<String, Value> {
heartbeat
.iter()
.filter(|(k, _)| !SIDECAR_FIELDS.contains(&k.as_str()))
.map(|(k, v)| (k.clone(), v.clone()))
.collect()
}
fn is_safe_uint(v: &Value) -> bool {
let Value::Number(n) = v else {
return false;
};
if let Some(u) = n.as_u64() {
return u <= MAX_SAFE_INTEGER;
}
if n.as_i64().is_some() {
return false;
}
matches!(n.as_f64(), Some(f) if f == 0.0 && f.is_sign_negative())
}
fn is_id_char(c: u8) -> bool {
c.is_ascii_alphanumeric() || matches!(c, b'.' | b'-' | b'_')
}
pub fn is_did_syntax(s: &str) -> bool {
let Some(rest) = s.strip_prefix("did:") else {
return false;
};
let Some((method, id)) = rest.split_once(':') else {
return false;
};
if method.is_empty()
|| !method
.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
{
return false;
}
let b = id.as_bytes();
if b.is_empty() || b[b.len() - 1] == b':' {
return false;
}
let mut i = 0;
while i < b.len() {
match b[i] {
b':' => i += 1,
b'%' => {
if i + 2 >= b.len()
|| !b[i + 1].is_ascii_hexdigit()
|| !b[i + 2].is_ascii_hexdigit()
{
return false;
}
i += 3;
}
c if is_id_char(c) => i += 1,
_ => return false,
}
}
true
}
pub fn is_canary_value(v: &Value) -> bool {
let Some(s) = v.as_str() else {
return false;
};
let Some(body) = s.strip_prefix('u') else {
return false;
};
if body.len() != 43
|| !body
.bytes()
.all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
{
return false;
}
match URL_SAFE_NO_PAD.decode(body) {
Ok(raw) => raw.len() == 32 && URL_SAFE_NO_PAD.encode(&raw) == body,
Err(_) => false,
}
}
fn audience_ok(v: &Value) -> bool {
let items: Vec<&Value> = match v {
Value::String(_) => vec![v],
Value::Array(a) => a.iter().collect(),
_ => return false,
};
(1..=MAX_AUDIENCE).contains(&items.len())
&& items.iter().all(|i| {
i.as_str()
.is_some_and(|s| !s.is_empty() && s.chars().count() <= MAX_DID_LENGTH)
})
}
fn is_authority_digest(s: &str) -> bool {
s.len() == 47
&& s.starts_with("uEi")
&& s.bytes()
.skip(3)
.all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
}
pub fn heartbeat_request_problem(d: &Value) -> Option<String> {
let Some(d) = d.as_object() else {
return Some("heartbeat request must be a dict".into());
};
if d.get("version").and_then(Value::as_str) != Some(HEARTBEAT_PROTOCOL_VERSION) {
return Some(format!("version must be '{HEARTBEAT_PROTOCOL_VERSION}'"));
}
if d.get("type").and_then(Value::as_str) != Some(HEARTBEAT_REQUEST_TYPE) {
return Some(format!("type must be '{HEARTBEAT_REQUEST_TYPE}'"));
}
for required in [
"subject_did",
"session_id",
"interval_index",
"issued_at",
"actionMerkleRoot",
"canaryCommitment",
"behavioralDigest",
] {
if !d.contains_key(required) {
return Some(format!("{required} is required"));
}
}
for (name, limit) in [
("subject_did", MAX_DID_LENGTH),
("session_id", MAX_SESSION_ID_LENGTH),
] {
match d[name].as_str() {
Some(s) if !s.is_empty() => {
if s.chars().count() > limit {
return Some(format!("{name} is longer than {limit} characters"));
}
}
_ => return Some(format!("{name} must be a non-empty string")),
}
}
if !is_did_syntax(d["subject_did"].as_str().unwrap_or_default()) {
return Some("subject_did must be a DID".into());
}
if !is_safe_uint(&d["interval_index"]) {
return Some("interval_index must be a whole number from 0 to 2^53 - 1".into());
}
if d.get("authorityEpoch").is_some_and(|e| !is_safe_uint(e)) {
return Some("authorityEpoch must be a whole number from 0 to 2^53 - 1".into());
}
if d["actionMerkleRoot"]
.as_str()
.is_none_or(|s| s.chars().count() > MAX_MERKLE_ROOT_LENGTH)
{
return Some("actionMerkleRoot must be a multibase string".into());
}
if !is_canary_value(&d["canaryCommitment"]) {
return Some("canaryCommitment must be a canary value".into());
}
if d.get("canaryReveal").is_some_and(|v| !is_canary_value(v)) {
return Some("canaryReveal must be a canary value".into());
}
if let Some(earlier) = d.get("canaryEarlierReveals") {
match earlier.as_array() {
Some(list) if (1..=MAX_EARLIER_REVEALS).contains(&list.len()) => {
if !list.iter().all(is_canary_value) {
return Some("canaryEarlierReveals item must be a canary value".into());
}
}
_ => {
return Some(format!(
"canaryEarlierReveals must be a list of 1 to {MAX_EARLIER_REVEALS} canary values"
))
}
}
}
let Some(digest) = d["behavioralDigest"].as_object() else {
return Some("behavioralDigest must be an object".into());
};
for counter in ["apiCalls", "tokensConsumed"] {
if digest.get(counter).is_some_and(|v| !is_safe_uint(v)) {
return Some(format!(
"behavioralDigest.{counter} must be a whole number from 0 to 2^53 - 1"
));
}
}
if digest
.get("intentDriftScore")
.is_some_and(Value::is_boolean)
{
return Some("behavioralDigest.intentDriftScore must be a number".into());
}
if d.get("audience").is_some_and(|a| !audience_ok(a)) {
return Some(format!(
"audience must be a validator DID or a list of 1 to {MAX_AUDIENCE} of them"
));
}
if let Some(hashes) = d.get("actionLeafHashes") {
if !hashes
.as_array()
.is_some_and(|l| l.iter().all(Value::is_string))
{
return Some("actionLeafHashes must be a list of multibase strings".into());
}
}
if d.get("proof").is_some_and(|p| !p.is_object()) {
return Some("proof must be an object".into());
}
if let Some(v) = d.get("authorityStateDigest") {
if !v.as_str().is_some_and(is_authority_digest) {
return Some("authorityStateDigest must be a multibase SHA-256 digest".into());
}
}
if let Some(p) = d.get("predecessor") {
if let Some(problem) = predecessor_problem(p) {
return Some(problem);
}
}
let issued = d["issued_at"].as_str().unwrap_or_default();
if crate::time::parse_protocol_time_ns(issued).is_err() {
return Some("issued_at must be an ISO-8601 UTC timestamp".into());
}
None
}
pub fn verify_equivocation_proof(proof: &Value, public_key: &[u8]) -> EquivocationVerdict {
let Some(p) = proof
.as_object()
.filter(|p| p.get("type").and_then(Value::as_str) == Some(EQUIVOCATION_TYPE))
else {
return no("proof_malformed:type");
};
let Some(agent) = p
.get("agent")
.and_then(Value::as_str)
.filter(|a| !a.is_empty())
else {
return no("proof_malformed:agent");
};
let Some(beats) = p
.get("heartbeats")
.and_then(Value::as_array)
.filter(|b| b.len() == 2)
else {
return no("proof_malformed:two heartbeats are needed");
};
if public_key.len() != 32 || crate::keys::strict_verifying_key(public_key).is_err() {
return no("proof_key_unusable");
}
let mut openings: Vec<(String, String)> = Vec::with_capacity(2);
for beat in beats {
let Some(beat) = beat.as_object() else {
return no("proof_malformed:heartbeat");
};
let signed = Value::Object(strip_sidecars(beat));
if heartbeat_request_problem(&signed).is_some() {
return no("proof_malformed:heartbeat");
}
if signed["subject_did"].as_str() != Some(agent) {
return no("proof_subject_mismatch");
}
let Some(sig) = signed.get("proof").and_then(Value::as_object) else {
return no("proof_signature_invalid");
};
let method_ok = sig
.get("verificationMethod")
.and_then(Value::as_str)
.is_some_and(|m| m.split('#').next() == Some(agent));
if !method_ok || sig.get("proofPurpose").and_then(Value::as_str) != Some("assertionMethod")
{
return no("proof_signature_invalid");
}
if !matches!(data_integrity::verify_proof(&signed, public_key), Ok(true)) {
return no("proof_signature_invalid");
}
let Some(pred) = signed.get("predecessor") else {
return no("proof_not_an_opening");
};
openings.push((
predecessor_key(pred),
signed["session_id"]
.as_str()
.unwrap_or_default()
.to_string(),
));
}
if openings[0].0 != openings[1].0 {
return no("proof_predecessors_differ");
}
if openings[0].1 == openings[1].1 {
return no("proof_same_session");
}
if openings[0].0 == GENESIS {
return no("proof_genesis_openings");
}
EquivocationVerdict {
valid: true,
reason: EQUIVOCATION_PROVEN.to_string(),
}
}
pub fn public_key_from_text(key: &str) -> Option<Vec<u8>> {
if key.starts_with("did:key:") {
return crate::authority_state::did_key_ed25519(key);
}
use base64::engine::general_purpose::STANDARD;
STANDARD.decode(key).ok().filter(|k| k.len() == 32)
}
pub fn verify_equivocation_proof_text_key(proof: &Value, public_key: &str) -> EquivocationVerdict {
let key = public_key_from_text(public_key).unwrap_or_default();
verify_equivocation_proof(proof, &key)
}
impl EquivocationVerdict {
pub fn to_json(&self) -> Value {
serde_json::json!({"valid": self.valid, "reason": self.reason})
}
}
pub fn proof_applies_to<'a>(
proofs: &'a [Value],
did: &str,
public_key: &[u8],
) -> Option<&'a Value> {
proofs
.iter()
.filter(|proof| proof.get("agent").and_then(Value::as_str) == Some(did))
.take(MAX_PROOFS_CHECKED)
.find(|proof| verify_equivocation_proof(proof, public_key).valid)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn did_syntax_follows_the_reference() {
for ok in [
"did:key:z6Mk",
"did:web:example.com",
"did:web:example.com%3A8443:a:b",
"did:a1:x",
"did:web::x",
] {
assert!(is_did_syntax(ok), "{ok}");
}
for bad in [
"did:Web:x",
"did:web:",
"did:web:x:",
"did::x",
"did:web",
"dad:web:x",
"did:web:a%2",
"did:web:a%zz",
"did:web:a b",
"did:web:é",
] {
assert!(!is_did_syntax(bad), "{bad}");
}
}
#[test]
fn canary_values_are_canonical() {
let ok = format!("u{}", "A".repeat(43));
assert!(is_canary_value(&Value::String(ok)));
assert!(!is_canary_value(&Value::String(format!(
"u{}B",
"A".repeat(42)
))));
assert!(!is_canary_value(&Value::String(format!(
"u{}",
"A".repeat(42)
))));
assert!(!is_canary_value(&Value::String(format!(
"z{}",
"A".repeat(43)
))));
assert!(!is_canary_value(&serde_json::json!(5)));
}
#[test]
fn predecessor_shapes() {
use serde_json::json;
assert!(predecessor_problem(&json!("genesis")).is_none());
assert!(predecessor_problem(&json!({"session": "s"})).is_none());
assert!(predecessor_problem(&json!({"session": ""})).is_some());
assert!(predecessor_problem(&json!({"session": "s", "x": 1})).is_some());
assert!(predecessor_problem(&json!(null)).is_some());
assert!(predecessor_problem(&json!({"session": "s".repeat(257)})).is_some());
assert_eq!(predecessor_key(&json!("genesis")), "genesis");
assert_eq!(predecessor_key(&json!({"session": "s"})), "session:s");
}
}