use sha2::{Digest, Sha256};
pub const LOG_KIND: &str = "anchorLog";
pub const CHECKPOINT_KIND: &str = "anchorCheckpoint";
fn sha256_hex(bytes: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(bytes);
let digest = hasher.finalize();
let mut hex = String::with_capacity(64);
for b in digest {
use std::fmt::Write as _;
let _ = write!(hex, "{b:02x}");
}
hex
}
pub struct AnchorLog {
pub entries: Vec<serde_json::Value>,
pub line_hashes: Vec<String>,
}
pub fn load(path: &str) -> Result<AnchorLog, String> {
load_kind(path, LOG_KIND)
}
pub fn load_kind(path: &str, kind: &str) -> Result<AnchorLog, String> {
let text = match std::fs::read_to_string(path) {
Ok(t) => t,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(e) => return Err(format!("로그를 읽을 수 없습니다 - {path}: {e}")),
};
let mut entries = Vec::new();
let mut line_hashes: Vec<String> = Vec::new();
for (i, line) in text.lines().enumerate() {
if line.trim().is_empty() {
continue;
}
let entry: serde_json::Value = serde_json::from_str(line)
.map_err(|e| format!("{path}:{}: 로그 줄 파싱 실패 - {e}", i + 1))?;
if entry["kind"] != kind {
return Err(format!("{path}:{}: kind 가 {kind} 가 아님", i + 1));
}
if entry["seq"].as_u64() != Some(entries.len() as u64) {
return Err(format!(
"{path}:{}: seq 연번 위반 (기대 {}, 실제 {})",
i + 1,
entries.len(),
entry["seq"]
));
}
let expected_prev = match line_hashes.last() {
Some(h) => serde_json::json!(h),
None => serde_json::Value::Null,
};
if entry["prevEntryHash"] != expected_prev {
return Err(format!(
"{path}:{}: prevEntryHash 불일치 — 이전 줄이 사후에 바뀌었다 (append-only 위반)",
i + 1
));
}
line_hashes.push(sha256_hex(line.as_bytes()));
entries.push(entry);
}
Ok(AnchorLog {
entries,
line_hashes,
})
}
pub fn make_entry_line(log: &AnchorLog, capsule_sha256: &str, logged_at: &str) -> String {
let entry = serde_json::json!({
"seq": log.entries.len(),
"kind": LOG_KIND,
"capsuleSha256": capsule_sha256,
"prevEntryHash": log.line_hashes.last().cloned(),
"loggedAt": logged_at,
});
entry.to_string()
}
pub fn merkle_root(leaves: &[String]) -> Option<String> {
if leaves.is_empty() {
return None;
}
let mut level: Vec<String> = leaves.to_vec();
while level.len() > 1 {
let mut next = Vec::with_capacity(level.len().div_ceil(2));
for pair in level.chunks(2) {
let right = pair.get(1).unwrap_or(&pair[0]);
next.push(sha256_hex(format!("{}{}", pair[0], right).as_bytes()));
}
level = next;
}
level.pop()
}
pub fn merkle_path(leaves: &[String], seq: usize) -> Vec<(String, bool)> {
let mut path = Vec::new();
let mut level: Vec<String> = leaves.to_vec();
let mut idx = seq;
while level.len() > 1 {
let left_child = idx.is_multiple_of(2);
let sibling = if left_child {
level.get(idx + 1).unwrap_or(&level[idx]).clone()
} else {
level[idx - 1].clone()
};
path.push((sibling, !left_child));
let mut next = Vec::with_capacity(level.len().div_ceil(2));
for pair in level.chunks(2) {
let right = pair.get(1).unwrap_or(&pair[0]);
next.push(sha256_hex(format!("{}{}", pair[0], right).as_bytes()));
}
level = next;
idx /= 2;
}
path
}
pub fn merkle_verify(leaf: &str, path: &[(String, bool)], root: &str) -> bool {
let mut acc = leaf.to_string();
for (sibling, sibling_is_left) in path {
acc = if *sibling_is_left {
sha256_hex(format!("{sibling}{acc}").as_bytes())
} else {
sha256_hex(format!("{acc}{sibling}").as_bytes())
};
}
acc == root
}