use serde_json::{json, Map, Value};
use sha2::{Digest, Sha256};
use zeroize::Zeroizing;
use crate::error::{CoreError, Result};
use crate::jcs;
use crate::robotics::{self as r, ChainProgress, ForkConflict, ForkFailure, ForkProgress};
pub const STATE_VERSION: u64 = 1;
pub const STATE_CHANGED: &str = "the segment state was changed, or was made under another stateKey";
pub const STATE_OTHER_HISTORY: &str = "the segment state belongs to another history";
fn process_key() -> &'static [u8; 32] {
static KEY: std::sync::OnceLock<[u8; 32]> = std::sync::OnceLock::new();
KEY.get_or_init(|| {
let mut k = [0u8; 32];
if getrandom::getrandom(&mut k).is_err() {
let seed = format!("{:?}{:p}", std::time::SystemTime::now(), &k as *const _);
k.copy_from_slice(&Sha256::digest(seed.as_bytes()));
}
k
})
}
pub fn hmac_sha256(key: &[u8], msg: &[u8]) -> [u8; 32] {
let mut k = [0u8; 64];
if key.len() > 64 {
k[..32].copy_from_slice(&Sha256::digest(key));
} else {
k[..key.len()].copy_from_slice(key);
}
let mut ipad = [0x36u8; 64];
let mut opad = [0x5cu8; 64];
for i in 0..64 {
ipad[i] ^= k[i];
opad[i] ^= k[i];
}
let inner = Sha256::new()
.chain_update(ipad)
.chain_update(msg)
.finalize();
Sha256::new()
.chain_update(opad)
.chain_update(inner)
.finalize()
.into()
}
fn state_key(key: Option<&[u8]>) -> Result<Zeroizing<Vec<u8>>> {
match key {
None | Some([]) => Ok(Zeroizing::new(process_key().to_vec())),
Some(k) if k.len() == 32 => Ok(Zeroizing::new(k.to_vec())),
Some(_) => Err(CoreError::Json("stateKey must be 32 bytes".into())),
}
}
fn check_value(body: &Map<String, Value>, key: &[u8]) -> String {
r::mb64(&hmac_sha256(
key,
&jcs::canonicalize(&Value::Object(body.clone())),
))
}
fn seal(mut body: Map<String, Value>, key: &[u8]) -> Value {
body.remove("check");
let check = check_value(&body, key);
body.insert("check".into(), json!(check));
Value::Object(body)
}
fn open(state: &Value, key: &[u8], kind: &str) -> std::result::Result<Map<String, Value>, String> {
let mut body = state
.as_object()
.cloned()
.ok_or_else(|| "the segment state must be an object".to_string())?;
let given = match body.remove("check") {
Some(Value::String(c)) => c,
_ => return Err(STATE_CHANGED.into()),
};
let want = check_value(&body, key);
let same = given.len() == want.len()
&& given
.bytes()
.zip(want.bytes())
.fold(0u8, |acc, (a, b)| acc | (a ^ b))
== 0;
if !same {
return Err(STATE_CHANGED.into());
}
if body.get("v").and_then(Value::as_u64) != Some(STATE_VERSION) {
return Err("the segment state version is not supported".into());
}
if body.get("kind").and_then(Value::as_str) != Some(kind) {
return Err(format!("the segment state is not a {kind} state"));
}
Ok(body)
}
fn set_history(body: &mut Map<String, Value>, history: Option<&str>) {
if let Some(h) = history {
body.insert("history".into(), json!(h));
}
}
pub fn check_history(state: &Value, history: Option<&str>) -> std::result::Result<(), String> {
let sealed = state.get("history").and_then(Value::as_str);
if sealed != history {
return Err(STATE_OTHER_HISTORY.into());
}
Ok(())
}
fn time_text(t: i128) -> String {
t.to_string()
}
fn time_of(v: &Value) -> Option<i128> {
v.as_str().and_then(|s| s.parse::<i128>().ok())
}
pub fn chain_state(progress: &ChainProgress, key: &[u8]) -> Value {
chain_state_for(progress, None, key)
}
pub fn chain_state_for(progress: &ChainProgress, history: Option<&str>, key: &[u8]) -> Value {
let mut body = Map::new();
set_history(&mut body, history);
body.insert("v".into(), json!(STATE_VERSION));
body.insert("kind".into(), json!("log"));
body.insert("genesis".into(), json!(progress.genesis));
body.insert("nextSeq".into(), json!(progress.next_seq));
body.insert("lastHash".into(), json!(progress.last_hash));
body.insert("failure".into(), json!(progress.failure));
seal(body, key)
}
pub fn read_chain_state(state: &Value, key: &[u8]) -> std::result::Result<ChainProgress, String> {
let body = open(state, key, "log")?;
let text = |k: &str| body.get(k).and_then(Value::as_str).map(String::from);
let bad = || "the segment state is malformed".to_string();
Ok(ChainProgress {
genesis: text("genesis").ok_or_else(bad)?,
next_seq: body
.get("nextSeq")
.and_then(Value::as_u64)
.ok_or_else(bad)?,
last_hash: text("lastHash").ok_or_else(bad)?,
failure: match body.get("failure") {
Some(Value::Null) => None,
Some(Value::String(s)) => Some(s.clone()),
_ => return Err(bad()),
},
})
}
pub fn fork_state(progress: &ForkProgress, digest: &str, key: &[u8]) -> Value {
fork_state_for(progress, digest, None, key)
}
pub fn fork_state_for(
progress: &ForkProgress,
digest: &str,
history: Option<&str>,
key: &[u8],
) -> Value {
let mut body = Map::new();
set_history(&mut body, history);
body.insert("v".into(), json!(STATE_VERSION));
body.insert("kind".into(), json!("fork"));
body.insert("count".into(), json!(progress.count));
body.insert("digest".into(), json!(digest));
body.insert(
"lastStart".into(),
json!(progress.last_start.map(time_text)),
);
body.insert("body".into(), json!(progress.body));
body.insert(
"windows".into(),
Value::Array(
progress
.windows
.iter()
.map(|(s, e)| json!([time_text(*s), e.map(time_text)]))
.collect(),
),
);
body.insert(
"conflict".into(),
match &progress.conflict {
Some(c) => json!({"bodyA": c.body_a, "bodyB": c.body_b}),
None => Value::Null,
},
);
body.insert(
"failure".into(),
match &progress.failure {
None => Value::Null,
Some(ForkFailure::Malformed(i)) => json!({"kind": "malformed", "at": i}),
Some(ForkFailure::OutOfOrder(i)) => json!({"kind": "order", "at": i}),
Some(ForkFailure::TooManyWindows(i)) => json!({"kind": "windows", "at": i}),
},
);
seal(body, key)
}
pub fn read_fork_state(
state: &Value,
key: &[u8],
) -> std::result::Result<(ForkProgress, String), String> {
let body = open(state, key, "fork")?;
let bad = || "the segment state is malformed".to_string();
let opt_time = |k: &str| -> std::result::Result<Option<i128>, String> {
match body.get(k) {
Some(Value::Null) => Ok(None),
Some(v) => time_of(v).map(Some).ok_or_else(bad),
None => Err(bad()),
}
};
let mut windows = Vec::new();
for w in body
.get("windows")
.and_then(Value::as_array)
.ok_or_else(bad)?
{
let pair = w.as_array().filter(|p| p.len() == 2).ok_or_else(bad)?;
let s = time_of(&pair[0]).ok_or_else(bad)?;
let e = match &pair[1] {
Value::Null => None,
v => Some(time_of(v).ok_or_else(bad)?),
};
windows.push((s, e));
}
if windows.len() > r::MAX_FORK_WINDOWS {
return Err(bad());
}
let conflict = match body.get("conflict") {
Some(Value::Null) => None,
Some(c) => Some(ForkConflict {
body_a: c
.get("bodyA")
.and_then(Value::as_str)
.ok_or_else(bad)?
.into(),
body_b: c
.get("bodyB")
.and_then(Value::as_str)
.ok_or_else(bad)?
.into(),
}),
None => return Err(bad()),
};
let failure = match body.get("failure") {
Some(Value::Null) => None,
Some(f) => {
let at = f.get("at").and_then(Value::as_u64).ok_or_else(bad)?;
match f.get("kind").and_then(Value::as_str) {
Some("malformed") => Some(ForkFailure::Malformed(at)),
Some("order") => Some(ForkFailure::OutOfOrder(at)),
Some("windows") => Some(ForkFailure::TooManyWindows(at)),
_ => return Err(bad()),
}
}
None => return Err(bad()),
};
let body_name = match body.get("body") {
Some(Value::Null) => None,
Some(Value::String(b)) => Some(b.clone()),
_ => return Err(bad()),
};
let progress = ForkProgress {
count: body.get("count").and_then(Value::as_u64).ok_or_else(bad)?,
last_start: opt_time("lastStart")?,
body: body_name,
windows,
conflict,
failure,
};
let digest = body
.get("digest")
.and_then(Value::as_str)
.ok_or_else(bad)?
.to_string();
Ok((progress, digest))
}
pub fn fork_digest_start() -> String {
r::mb64(&[0u8; 32])
}
pub fn fork_digest_step(digest: &[u8], embodiment: &Value) -> Vec<u8> {
let leaf = Sha256::digest(jcs::canonicalize(embodiment));
Sha256::new()
.chain_update(digest)
.chain_update(leaf)
.finalize()
.to_vec()
}
pub fn key_for(state_key_bytes: Option<&[u8]>) -> Result<Zeroizing<Vec<u8>>> {
state_key(state_key_bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hmac_matches_rfc4231_case_2() {
let mac = hmac_sha256(b"Jefe", b"what do ya want for nothing?");
let hex: String = mac.iter().map(|b| format!("{b:02x}")).collect();
assert_eq!(
hex,
"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
);
}
#[test]
fn hmac_long_key_rfc4231_case_6() {
let key = [0xaau8; 131];
let mac = hmac_sha256(
&key,
b"Test Using Larger Than Block-Size Key - Hash Key First",
);
let hex: String = mac.iter().map(|b| format!("{b:02x}")).collect();
assert_eq!(
hex,
"60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54"
);
}
}