1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28use sha2::{Digest, Sha256};
29use uuid::Uuid;
30
31use crate::node::NodeType;
32
33fn compute_sha256(bytes: &[u8]) -> [u8; 32] {
34 Sha256::digest(bytes).into()
35}
36
37pub const NODE_DATA_UUID: Uuid =
38 Uuid::from_u128(0x0c639d0043ac41b28a319fb9ce7910e0);
39pub const NODE_STATEMENTS_UUID: Uuid =
40 Uuid::from_u128(0x8cef315b818c46c0a509e9d538b557f9);
41pub const NODE_SYSTEM_UUID: Uuid =
42 Uuid::from_u128(0x7a832d2e65424159bbda0d01b9dbb0e9);
43
44pub struct PackagedNode {
45 pub node_type: NodeType,
46 pub timestamp: u128,
47 pub checksum: [u8; 32],
48 pub original_node_id: u128,
49 pub original_graph_id: u128,
50 pub body: Vec<u8>,
51}
52
53pub fn serialize_packaged_node(
54 node_type: NodeType,
55 timestamp: u128,
56 checksum: &[u8],
57 original_node_id: u128,
58 original_graph_id: u128,
59 body: &[u8],
60) -> Result<Vec<u8>> {
61 let mut out = Vec::with_capacity(105_usize.saturating_add(body.len()));
62
63 out.extend_from_slice(b"CTBNODE\x00");
65
66 out.push(3);
68
69 let type_uuid = match node_type {
71 NodeType::Data => NODE_DATA_UUID,
72 NodeType::Statements => NODE_STATEMENTS_UUID,
73 NodeType::System => NODE_SYSTEM_UUID,
74 };
75 out.extend_from_slice(type_uuid.as_bytes());
76
77 out.extend_from_slice(×tamp.to_le_bytes());
79
80 let mut ck = [0_u8; 32];
82 if !checksum.is_empty() {
83 let len = checksum.len().min(32);
84 if let (Some(dest), Some(src)) =
85 (ck.get_mut(..len), checksum.get(..len))
86 {
87 dest.copy_from_slice(src);
88 }
89 }
90 out.extend_from_slice(&ck);
91
92 out.extend_from_slice(&original_node_id.to_le_bytes());
94
95 out.extend_from_slice(&original_graph_id.to_le_bytes());
97
98 out.extend_from_slice(body);
100
101 Ok(out)
102}
103
104pub fn deserialize_packaged_node(bytes: &[u8]) -> Result<PackagedNode> {
105 if bytes.len() < 97 {
106 anyhow::bail!("Package too small: minimum size is 97 bytes");
107 }
108
109 if bytes.get(..8) != Some(b"CTBNODE\x00".as_slice()) {
111 anyhow::bail!("Invalid packaged node magic");
112 }
113
114 let version = *bytes.get(8).context("Missing version byte")?;
116
117 match version {
118 1 => {
119 if bytes.len() < 97 {
120 anyhow::bail!(
121 "Version 1 package too small: minimum size is 97 bytes"
122 );
123 }
124
125 let type_uuid_bytes: [u8; 16] = bytes
127 .get(9..25)
128 .context("Missing type UUID bytes")?
129 .try_into()?;
130 let type_uuid = Uuid::from_bytes(type_uuid_bytes);
131 let node_type = match type_uuid {
132 NODE_DATA_UUID => NodeType::Data,
133 NODE_STATEMENTS_UUID => NodeType::Statements,
134 NODE_SYSTEM_UUID => NodeType::System,
135 other => anyhow::bail!(
136 "Unsupported packaged node type UUID: {other}"
137 ),
138 };
139
140 let timestamp_bytes: [u8; 8] = bytes
142 .get(25..33)
143 .context("Missing timestamp bytes")?
144 .try_into()?;
145 let timestamp_u64 = u64::from_le_bytes(timestamp_bytes);
146 let timestamp = if timestamp_u64 < 10_000_000_000 {
147 u128::from(timestamp_u64).saturating_mul(1_000_000)
148 } else {
149 u128::from(timestamp_u64)
150 };
151
152 let checksum: [u8; 32] = bytes
154 .get(33..65)
155 .context("Missing checksum bytes")?
156 .try_into()?;
157
158 let original_node_id_bytes: [u8; 16] = bytes
160 .get(65..81)
161 .context("Missing original node ID bytes")?
162 .try_into()?;
163 let original_node_id = u128::from_le_bytes(original_node_id_bytes);
164
165 let original_graph_id_bytes: [u8; 16] = bytes
167 .get(81..97)
168 .context("Missing original graph ID bytes")?
169 .try_into()?;
170 let original_graph_id =
171 u128::from_le_bytes(original_graph_id_bytes);
172
173 let raw_body =
175 bytes.get(97..).context("Missing body bytes")?.to_vec();
176 let actual_raw_checksum = compute_sha256(&raw_body);
177 anyhow::ensure!(
178 actual_raw_checksum == checksum,
179 "Packaged node v1 body checksum mismatch"
180 );
181 let (body, checksum) =
182 if matches!(node_type, NodeType::Statements | NodeType::System)
183 {
184 let dc_string =
185 ctb_formats_dcstring::DcString::from_dcutf(raw_body)
186 .context(
187 "Invalid DcUtf in v1 packaged node body",
188 )?;
189 let body = dc_string.into_bytes();
190 let new_checksum = compute_sha256(&body);
191 (body, new_checksum)
192 } else {
193 (raw_body, checksum)
194 };
195
196 Ok(PackagedNode {
197 node_type,
198 timestamp,
199 checksum,
200 original_node_id,
201 original_graph_id,
202 body,
203 })
204 }
205 2 | 3 => {
206 if bytes.len() < 105 {
207 anyhow::bail!(
208 "Version {version} package too small: minimum size is 105 bytes"
209 );
210 }
211
212 let type_uuid_bytes: [u8; 16] = bytes
214 .get(9..25)
215 .context("Missing type UUID bytes")?
216 .try_into()?;
217 let type_uuid = Uuid::from_bytes(type_uuid_bytes);
218 let node_type = match type_uuid {
219 NODE_DATA_UUID => NodeType::Data,
220 NODE_STATEMENTS_UUID => NodeType::Statements,
221 NODE_SYSTEM_UUID => NodeType::System,
222 other => anyhow::bail!(
223 "Unsupported packaged node type UUID: {other}"
224 ),
225 };
226
227 let timestamp_bytes: [u8; 16] = bytes
229 .get(25..41)
230 .context("Missing timestamp bytes")?
231 .try_into()?;
232 let timestamp = u128::from_le_bytes(timestamp_bytes);
233
234 let checksum: [u8; 32] = bytes
236 .get(41..73)
237 .context("Missing checksum bytes")?
238 .try_into()?;
239
240 let original_node_id_bytes: [u8; 16] = bytes
242 .get(73..89)
243 .context("Missing original node ID bytes")?
244 .try_into()?;
245 let original_node_id = u128::from_le_bytes(original_node_id_bytes);
246
247 let original_graph_id_bytes: [u8; 16] = bytes
249 .get(89..105)
250 .context("Missing original graph ID bytes")?
251 .try_into()?;
252 let original_graph_id =
253 u128::from_le_bytes(original_graph_id_bytes);
254
255 let raw_body =
257 bytes.get(105..).context("Missing body bytes")?.to_vec();
258 let actual_raw_checksum = compute_sha256(&raw_body);
259 anyhow::ensure!(
260 actual_raw_checksum == checksum,
261 "Packaged node v{version} body checksum mismatch"
262 );
263 let (body, checksum) = if version == 2
264 && matches!(node_type, NodeType::Statements | NodeType::System)
265 {
266 let dc_string =
267 ctb_formats_dcstring::DcString::from_dcutf(raw_body)
268 .context("Invalid DcUtf in v2 packaged node body")?;
269 let body = dc_string.into_bytes();
270 let new_checksum = compute_sha256(&body);
271 (body, new_checksum)
272 } else {
273 if matches!(node_type, NodeType::Statements | NodeType::System)
274 {
275 ctb_formats_dcstring::DcStr::from_bytes(&raw_body)
276 .context("Invalid DcTF in v3 packaged node body")?;
277 }
278 (raw_body, checksum)
279 };
280
281 Ok(PackagedNode {
282 node_type,
283 timestamp,
284 checksum,
285 original_node_id,
286 original_graph_id,
287 body,
288 })
289 }
290 other => anyhow::bail!("Unsupported packaged node version: {other}"),
291 }
292}
293
294#[cfg(test)]
295#[allow(
296 clippy::panic,
297 clippy::expect_used,
298 clippy::unwrap_used,
299 clippy::unwrap_in_result,
300 clippy::panic_in_result_fn,
301 clippy::indexing_slicing,
302 clippy::arithmetic_side_effects,
303 reason = "Standard repository test boilerplate"
304)]
305mod tests {
306 use super::*;
307 use crate::get_storage_fixture;
308
309 #[crate::ctb_test]
310 fn test_packaged_node_v2_roundtrip() -> Result<()> {
311 let node_type = NodeType::Data;
312 let timestamp = 1700000000123456u128;
313 let body = b"hello, this is some packaged node body data";
314 let checksum = compute_sha256(body);
315 let original_node_id = 98765432101234567890u128;
316 let original_graph_id = 11223344556677889900u128;
317
318 let serialized = serialize_packaged_node(
319 node_type,
320 timestamp,
321 &checksum,
322 original_node_id,
323 original_graph_id,
324 body,
325 )?;
326
327 let deserialized = deserialize_packaged_node(&serialized)?;
328
329 assert_eq!(deserialized.node_type, node_type);
330 assert_eq!(deserialized.timestamp, timestamp);
331 assert_eq!(deserialized.checksum, checksum);
332 assert_eq!(deserialized.original_node_id, original_node_id);
333 assert_eq!(deserialized.original_graph_id, original_graph_id);
334 assert_eq!(deserialized.body, body.to_vec());
335
336 let mut bad = serialized.clone();
338 bad[41] ^= 0xFF;
339 assert!(deserialize_packaged_node(&bad).is_err());
340
341 Ok(())
342 }
343
344 #[crate::ctb_test]
345 fn test_packaged_node_legacy_v1_v2_migration_recomputes_checksum()
346 -> Result<()> {
347 let mut dc_string = ctb_formats_dcstring::DcString::new();
348 dc_string.push(DcChar::from_short(5));
349 dc_string.push(DcChar::from_short(7));
350 let mst = ctb_formats_dcstring::DcMstring::from_dc_string(&dc_string)?;
351 let (dcutf_body, _) =
352 ctb_formats_dcstring::converters::utf8::dcmstring_to_dcutf(&mst)?;
353 let dcutf_checksum = compute_sha256(&dcutf_body);
354 let dctf_body = dc_string.as_bytes().to_vec();
355 let dctf_checksum = compute_sha256(&dctf_body);
356 assert_ne!(dcutf_body, dctf_body);
357 assert_ne!(dcutf_checksum, dctf_checksum);
358
359 for (version, node_type, type_uuid) in [
360 (1_u8, NodeType::Statements, NODE_STATEMENTS_UUID),
361 (1_u8, NodeType::System, NODE_SYSTEM_UUID),
362 (2_u8, NodeType::Statements, NODE_STATEMENTS_UUID),
363 (2_u8, NodeType::System, NODE_SYSTEM_UUID),
364 ] {
365 let mut pkg = Vec::new();
366 pkg.extend_from_slice(b"CTBNODE\x00");
367 pkg.push(version);
368 pkg.extend_from_slice(type_uuid.as_bytes());
369 if version == 1 {
370 pkg.extend_from_slice(&1_700_000_000_u64.to_le_bytes());
371 } else {
372 pkg.extend_from_slice(
373 &1_700_000_000_000_000_u128.to_le_bytes(),
374 );
375 }
376 pkg.extend_from_slice(&dcutf_checksum);
377 pkg.extend_from_slice(&42_u128.to_le_bytes());
378 pkg.extend_from_slice(&7_u128.to_le_bytes());
379 pkg.extend_from_slice(&dcutf_body);
380
381 let deserialized = deserialize_packaged_node(&pkg)?;
382 assert_eq!(deserialized.node_type, node_type);
383 assert_eq!(deserialized.body, dctf_body);
384 assert_eq!(
385 deserialized.checksum, dctf_checksum,
386 "v{version} {node_type:?} migration must update checksum to match transcoded DcTF body"
387 );
388 assert_eq!(
389 compute_sha256(&deserialized.body),
390 deserialized.checksum
391 );
392
393 let mut bad_ck = pkg.clone();
395 let ck_offset = if version == 1 { 33 } else { 41 };
396 bad_ck[ck_offset] ^= 0xFF;
397 assert!(
398 deserialize_packaged_node(&bad_ck).is_err(),
399 "v{version} {node_type:?} with mismatched source checksum must be rejected"
400 );
401 }
402
403 Ok(())
404 }
405
406 #[crate::ctb_test]
407 fn test_deserialize_v1_sample() -> Result<()> {
408 let bytes =
409 get_storage_fixture("fixtures/packaged_node_v1_format_sample.ctbn")
410 .context("Missing v1 sample fixture file")?;
411 let deserialized = deserialize_packaged_node(&bytes)?;
412 assert_eq!(deserialized.node_type, NodeType::Data);
413 assert!(deserialized.timestamp > 0);
414 let expected_bytes =
415 get_storage_fixture("fixtures/example2 with lemurs.pan")
416 .context("Missing expected body fixture file")?;
417 assert_eq!(deserialized.body, expected_bytes);
418 Ok(())
419 }
420}