use crate::layer2::sync::types::{
FramedRecordPage, MCardRecord, RecordFrame, SyncPageCursor, TransitionPayload,
};
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet};
pub const B64_CHUNK_BYTES: usize = 3 * 4096;
pub const MAX_SYNC_PAGE_RECORDS: usize = 256;
pub const MAX_SYNC_PAGE_BYTES: usize = 16 * 1024 * 1024;
const B64_CHARS: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
pub fn bytes_to_base64(bytes: &[u8]) -> String {
if bytes.is_empty() {
return String::new();
}
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(B64_CHUNK_BYTES) {
for g in chunk.chunks(3) {
let (a, b, c) = (g[0], *g.get(1).unwrap_or(&0), *g.get(2).unwrap_or(&0));
out.push(B64_CHARS[(a >> 2) as usize] as char);
out.push(B64_CHARS[(((a & 3) << 4) | (b >> 4)) as usize] as char);
out.push(if g.len() > 1 { B64_CHARS[(((b & 15) << 2) | (c >> 6)) as usize] as char } else { '=' });
out.push(if g.len() > 2 { B64_CHARS[(c & 63) as usize] as char } else { '=' });
}
}
out
}
fn b64_val(b: u8) -> Option<u8> {
match b {
b'A'..=b'Z' => Some(b - b'A'),
b'a'..=b'z' => Some(b - b'a' + 26),
b'0'..=b'9' => Some(b - b'0' + 52),
b'+' => Some(62),
b'/' => Some(63),
_ => None,
}
}
pub fn base64_to_bytes(b64: &str) -> Result<Vec<u8>, String> {
if b64.is_empty() {
return Ok(Vec::new());
}
if !b64.len().is_multiple_of(4) {
return Err("Invalid base64 string".to_string());
}
let mut out = Vec::with_capacity((b64.len() / 4) * 3);
for group in b64.as_bytes().chunks(4) {
let e1 = b64_val(group[0]).ok_or_else(|| "Invalid base64 string".to_string())?;
let e2 = b64_val(group[1]).ok_or_else(|| "Invalid base64 string".to_string())?;
out.push((e1 << 2) | (e2 >> 4));
if group[2] != b'=' {
let e3 = b64_val(group[2]).ok_or_else(|| "Invalid base64 string".to_string())?;
out.push(((e2 & 15) << 4) | (e3 >> 2));
if group[3] != b'=' {
let e4 = b64_val(group[3]).ok_or_else(|| "Invalid base64 string".to_string())?;
out.push(((e3 & 3) << 6) | e4);
}
} else if group[3] != b'=' {
return Err("Invalid base64 string".to_string());
}
}
Ok(out)
}
pub fn derive_transfer_id(qualified_ref: &str) -> String {
format!("rw:{}", qualified_ref.strip_prefix("rw:").unwrap_or(qualified_ref))
}
pub fn derive_delivery_id(qualified_ref: &str, target_node_id: &str) -> String {
format!(
"rw:deliver:{target_node_id}:{}",
qualified_ref.strip_prefix("rw:").unwrap_or(qualified_ref)
)
}
pub fn frame_record(record: &MCardRecord) -> RecordFrame {
RecordFrame {
hash: record.hash.clone(),
content_base64: bytes_to_base64(&record.content),
g_time: record.g_time.clone(),
}
}
pub fn unframe_record(
frame: &RecordFrame,
required_algorithm: &str,
) -> Result<(MCardRecord, String), (String, String)> {
if frame.hash.is_empty() || frame.g_time.is_empty() {
return Err(("malformed".to_string(), "Missing hash or gTime".to_string()));
}
let content = base64_to_bytes(&frame.content_base64).map_err(|e| ("malformed".to_string(), e))?;
let parts: Vec<&str> = frame.g_time.split('|').collect();
if parts.len() == 1 && frame.g_time.starts_with("202") && frame.g_time.contains('T') {
return Err(("algorithm-downgrade".to_string(), format!("Expected {required_algorithm}")));
}
if parts.len() < 3 {
return Err(("malformed".to_string(), "Invalid g_time format".to_string()));
}
let algo = parts[0].split(':').next().unwrap_or("").to_lowercase();
if algo != "blake3" && algo != "sha256" {
return Err(("malformed".to_string(), "Unsupported algorithm".to_string()));
}
if algo != required_algorithm {
return Err(("algorithm-downgrade".to_string(), format!("Expected {required_algorithm}")));
}
let target_hex = frame.hash.split(':').next_back().unwrap_or("").to_lowercase();
let computed = if algo == "blake3" {
blake3::hash(&content).to_hex().to_string()
} else {
let mut h = Sha256::new();
h.update(&content);
hex::encode(h.finalize())
};
if target_hex != computed {
return Err(("declared-mismatch".to_string(), "Record hash mismatch".to_string()));
}
Ok((
MCardRecord {
hash: frame.hash.clone(),
content,
g_time: frame.g_time.clone(),
},
format!("{algo}:{computed}"),
))
}
pub use crate::layer0::transition::{is_qualified_hash, validate_transition_payload};
pub fn group_transitions_by_handle(
transitions: &[TransitionPayload],
) -> BTreeMap<String, Vec<TransitionPayload>> {
let mut grouped: BTreeMap<String, Vec<TransitionPayload>> = BTreeMap::new();
let norm = |h: &str| h.strip_prefix("mcard:").unwrap_or(h).trim_start_matches('/').to_string();
for t in transitions {
grouped.entry(norm(&t.handle)).or_default().push(t.clone());
if t.kind == "RELOCATE" || t.kind == "FORK" {
if let Some(to_h) = &t.to_handle {
if to_h != &t.handle {
grouped.entry(norm(to_h)).or_default().push(t.clone());
}
}
}
}
grouped
}
pub fn frame_record_page(
records: &[MCardRecord],
known_hashes: &BTreeSet<String>,
cursor: Option<&SyncPageCursor>,
max_records: usize,
max_frame_bytes: usize,
) -> FramedRecordPage {
let eligible: Vec<&MCardRecord> = records
.iter()
.filter(|r| {
let bare = r.hash.strip_prefix("blake3:").unwrap_or(&r.hash).to_lowercase();
!known_hashes.contains(&r.hash) && !known_hashes.contains(&bare) && !known_hashes.contains(&format!("blake3:{bare}"))
})
.collect();
let mut idx = cursor.map(|c| c.offset).unwrap_or(0);
let (mut out, mut total_bytes) = (Vec::new(), 64usize);
while idx < eligible.len() && out.len() < max_records {
let frame = frame_record(eligible[idx]);
let fb = frame.hash.len() + frame.content_base64.len() + frame.g_time.len() + 48;
if !out.is_empty() && total_bytes + fb > max_frame_bytes {
break;
}
out.push(frame);
total_bytes += fb;
idx += 1;
}
let has_more = idx < eligible.len();
let next_cursor = has_more.then(|| SyncPageCursor {
offset: idx,
last_hash: out.last().map(|f| f.hash.clone()),
});
FramedRecordPage { records: out, next_cursor, has_more, total_bytes }
}