clm_rust_core/layer2/sync/
codec.rs1use crate::layer2::sync::types::{
2 FramedRecordPage, MCardRecord, RecordFrame, SyncPageCursor, TransitionPayload,
3};
4use sha2::{Digest, Sha256};
5use std::collections::{BTreeMap, BTreeSet};
6
7pub const B64_CHUNK_BYTES: usize = 3 * 4096;
8pub const MAX_SYNC_PAGE_RECORDS: usize = 256;
9pub const MAX_SYNC_PAGE_BYTES: usize = 16 * 1024 * 1024;
10
11const B64_CHARS: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
12
13pub fn bytes_to_base64(bytes: &[u8]) -> String {
14 if bytes.is_empty() {
15 return String::new();
16 }
17 let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
18 for chunk in bytes.chunks(B64_CHUNK_BYTES) {
19 for g in chunk.chunks(3) {
20 let (a, b, c) = (g[0], *g.get(1).unwrap_or(&0), *g.get(2).unwrap_or(&0));
21 out.push(B64_CHARS[(a >> 2) as usize] as char);
22 out.push(B64_CHARS[(((a & 3) << 4) | (b >> 4)) as usize] as char);
23 out.push(if g.len() > 1 { B64_CHARS[(((b & 15) << 2) | (c >> 6)) as usize] as char } else { '=' });
24 out.push(if g.len() > 2 { B64_CHARS[(c & 63) as usize] as char } else { '=' });
25 }
26 }
27 out
28}
29
30fn b64_val(b: u8) -> Option<u8> {
31 match b {
32 b'A'..=b'Z' => Some(b - b'A'),
33 b'a'..=b'z' => Some(b - b'a' + 26),
34 b'0'..=b'9' => Some(b - b'0' + 52),
35 b'+' => Some(62),
36 b'/' => Some(63),
37 _ => None,
38 }
39}
40
41pub fn base64_to_bytes(b64: &str) -> Result<Vec<u8>, String> {
42 if b64.is_empty() {
43 return Ok(Vec::new());
44 }
45 if !b64.len().is_multiple_of(4) {
46 return Err("Invalid base64 string".to_string());
47 }
48 let mut out = Vec::with_capacity((b64.len() / 4) * 3);
49 for group in b64.as_bytes().chunks(4) {
50 let e1 = b64_val(group[0]).ok_or_else(|| "Invalid base64 string".to_string())?;
51 let e2 = b64_val(group[1]).ok_or_else(|| "Invalid base64 string".to_string())?;
52 out.push((e1 << 2) | (e2 >> 4));
53 if group[2] != b'=' {
54 let e3 = b64_val(group[2]).ok_or_else(|| "Invalid base64 string".to_string())?;
55 out.push(((e2 & 15) << 4) | (e3 >> 2));
56 if group[3] != b'=' {
57 let e4 = b64_val(group[3]).ok_or_else(|| "Invalid base64 string".to_string())?;
58 out.push(((e3 & 3) << 6) | e4);
59 }
60 } else if group[3] != b'=' {
61 return Err("Invalid base64 string".to_string());
62 }
63 }
64 Ok(out)
65}
66
67pub fn derive_transfer_id(qualified_ref: &str) -> String {
68 format!("rw:{}", qualified_ref.strip_prefix("rw:").unwrap_or(qualified_ref))
69}
70
71pub fn derive_delivery_id(qualified_ref: &str, target_node_id: &str) -> String {
72 format!(
73 "rw:deliver:{target_node_id}:{}",
74 qualified_ref.strip_prefix("rw:").unwrap_or(qualified_ref)
75 )
76}
77
78pub fn frame_record(record: &MCardRecord) -> RecordFrame {
79 RecordFrame {
80 hash: record.hash.clone(),
81 content_base64: bytes_to_base64(&record.content),
82 g_time: record.g_time.clone(),
83 }
84}
85
86pub fn unframe_record(
87 frame: &RecordFrame,
88 required_algorithm: &str,
89) -> Result<(MCardRecord, String), (String, String)> {
90 if frame.hash.is_empty() || frame.g_time.is_empty() {
91 return Err(("malformed".to_string(), "Missing hash or gTime".to_string()));
92 }
93 let content = base64_to_bytes(&frame.content_base64).map_err(|e| ("malformed".to_string(), e))?;
94 let parts: Vec<&str> = frame.g_time.split('|').collect();
95 if parts.len() == 1 && frame.g_time.starts_with("202") && frame.g_time.contains('T') {
96 return Err(("algorithm-downgrade".to_string(), format!("Expected {required_algorithm}")));
97 }
98 if parts.len() < 3 {
99 return Err(("malformed".to_string(), "Invalid g_time format".to_string()));
100 }
101 let algo = parts[0].split(':').next().unwrap_or("").to_lowercase();
102 if algo != "blake3" && algo != "sha256" {
103 return Err(("malformed".to_string(), "Unsupported algorithm".to_string()));
104 }
105 if algo != required_algorithm {
106 return Err(("algorithm-downgrade".to_string(), format!("Expected {required_algorithm}")));
107 }
108 let target_hex = frame.hash.split(':').next_back().unwrap_or("").to_lowercase();
109 let computed = if algo == "blake3" {
110 blake3::hash(&content).to_hex().to_string()
111 } else {
112 let mut h = Sha256::new();
113 h.update(&content);
114 hex::encode(h.finalize())
115 };
116 if target_hex != computed {
117 return Err(("declared-mismatch".to_string(), "Record hash mismatch".to_string()));
118 }
119 Ok((
120 MCardRecord {
121 hash: frame.hash.clone(),
122 content,
123 g_time: frame.g_time.clone(),
124 },
125 format!("{algo}:{computed}"),
126 ))
127}
128
129pub use crate::layer0::transition::{is_qualified_hash, validate_transition_payload};
130
131pub fn group_transitions_by_handle(
132 transitions: &[TransitionPayload],
133) -> BTreeMap<String, Vec<TransitionPayload>> {
134 let mut grouped: BTreeMap<String, Vec<TransitionPayload>> = BTreeMap::new();
135 let norm = |h: &str| h.strip_prefix("mcard:").unwrap_or(h).trim_start_matches('/').to_string();
136 for t in transitions {
137 grouped.entry(norm(&t.handle)).or_default().push(t.clone());
138 if t.kind == "RELOCATE" || t.kind == "FORK" {
139 if let Some(to_h) = &t.to_handle {
140 if to_h != &t.handle {
141 grouped.entry(norm(to_h)).or_default().push(t.clone());
142 }
143 }
144 }
145 }
146 grouped
147}
148
149pub fn frame_record_page(
150 records: &[MCardRecord],
151 known_hashes: &BTreeSet<String>,
152 cursor: Option<&SyncPageCursor>,
153 max_records: usize,
154 max_frame_bytes: usize,
155) -> FramedRecordPage {
156 let eligible: Vec<&MCardRecord> = records
157 .iter()
158 .filter(|r| {
159 let bare = r.hash.strip_prefix("blake3:").unwrap_or(&r.hash).to_lowercase();
160 !known_hashes.contains(&r.hash) && !known_hashes.contains(&bare) && !known_hashes.contains(&format!("blake3:{bare}"))
161 })
162 .collect();
163 let mut idx = cursor.map(|c| c.offset).unwrap_or(0);
164 let (mut out, mut total_bytes) = (Vec::new(), 64usize);
165 while idx < eligible.len() && out.len() < max_records {
166 let frame = frame_record(eligible[idx]);
167 let fb = frame.hash.len() + frame.content_base64.len() + frame.g_time.len() + 48;
168 if !out.is_empty() && total_bytes + fb > max_frame_bytes {
169 break;
170 }
171 out.push(frame);
172 total_bytes += fb;
173 idx += 1;
174 }
175 let has_more = idx < eligible.len();
176 let next_cursor = has_more.then(|| SyncPageCursor {
177 offset: idx,
178 last_hash: out.last().map(|f| f.hash.clone()),
179 });
180 FramedRecordPage { records: out, next_cursor, has_more, total_bytes }
181}