1use sha2::{Digest, Sha256};
40
41use std::collections::HashMap;
42
43use std::time::Instant;
44
45const MAX_ALLOCATION_BYTES: usize = 10_485_760;
48
49const WASM_PAGE_SIZE: usize = 65_536;
50
51const DEFAULT_CPU_FUEL: u64 = 1_000_000; const _DEFAULT_TIMEOUT_MS: u64 = 5_000;
54
55#[derive(Debug, Clone, serde::Serialize)]
58
59pub struct ExecutionTelemetry {
60 pub fuel_consumed: u64,
61
62 pub fuel_remaining: u64,
63
64 pub fuel_utilization_pct: f64,
65
66 pub memory_pages_used: u64,
67
68 pub memory_bytes_used: u64,
69
70 pub memory_utilization_pct: f64,
71
72 pub execution_time_ms: f64,
73
74 pub status: String,
75}
76
77pub fn verify_bundle_integrity(
90 bundle_files: &HashMap<String, Vec<u8>>,
91
92 expected_hash: Option<&str>,
93) -> Result<bool, String> {
94 let expected = match expected_hash {
95 Some(h) if !h.is_empty() => h,
96
97 _ => return Ok(true), };
99
100 let actual = compute_merkle_directory_cid(bundle_files);
101
102 if actual != expected {
103 return Err(format!(
104
105 "Bundle CID mismatch. Expected {}, got {}. Possible supply-chain attack or stale cache.",
106
107 expected, actual
108
109 ));
110 }
111
112 Ok(true)
113}
114
115pub fn compute_merkle_directory_cid(file_contents: &HashMap<String, Vec<u8>>) -> String {
122 let mut keys: Vec<&String> = file_contents.keys().collect();
123
124 keys.sort();
125
126 let mut file_hashes: Vec<String> = Vec::new();
127
128 for key in keys {
129 let content = &file_contents[key];
130
131 let normalized = if is_text_bytes(content) {
134 content
135 .iter()
136 .copied()
137 .filter(|&b| b != b'\r')
138 .collect::<Vec<u8>>()
139 } else {
140 content.clone()
141 };
142
143 let mut hasher = Sha256::new();
144
145 hasher.update(&normalized);
146
147 let hash = format!("{:x}", hasher.finalize());
148
149 file_hashes.push(format!("{}:{}", key, hash));
150 }
151
152 let merkle_input = file_hashes.join("\n");
153
154 let mut hasher = Sha256::new();
155
156 hasher.update(merkle_input.as_bytes());
157
158 format!("sha256:{:x}", hasher.finalize())
159}
160
161fn is_text_bytes(data: &[u8]) -> bool {
168 content_inspector::inspect(data).is_text()
169}
170
171pub fn verify_wasm_attestation(wasm_bytes: &[u8], expected_hash: &str) -> Result<(), String> {
178 let mut hasher = Sha256::new();
179
180 hasher.update(wasm_bytes);
181
182 let actual_hash = format!("{:x}", hasher.finalize());
183
184 if actual_hash.len() != expected_hash.len() {
187 return Err("WASM binary hash mismatch: zero-trust attestation failed.".to_string());
188 }
189
190 let equal = actual_hash
191 .bytes()
192 .zip(expected_hash.bytes())
193 .fold(0u8, |acc, (a, b)| acc | (a ^ b));
194
195 if equal != 0 {
196 return Err("WASM binary hash mismatch: zero-trust attestation failed.".to_string());
197 }
198
199 Ok(())
200}
201
202pub fn wasm_hash(wasm_bytes: &[u8]) -> String {
205 let mut hasher = Sha256::new();
206
207 hasher.update(wasm_bytes);
208
209 format!("{:x}", hasher.finalize())
210}
211
212pub fn call_with_telemetry(
227 wasm_bytes: &[u8],
228
229 expected_hash: &str,
230
231 function_name: &str,
232
233 input_data: &[u8],
234
235 fuel_budget: Option<u64>,
236) -> Result<(Vec<u8>, ExecutionTelemetry), String> {
237 verify_wasm_attestation(wasm_bytes, expected_hash)?;
240
241 let budget = fuel_budget.unwrap_or(DEFAULT_CPU_FUEL);
242
243 let max_pages = MAX_ALLOCATION_BYTES / WASM_PAGE_SIZE;
244
245 let manifest =
248 extism::Manifest::new([extism::Wasm::data(wasm_bytes)]).with_memory_max(max_pages as u32);
249
250 let start = Instant::now();
251
252 let mut plugin = extism::Plugin::new(&manifest, [], true)
253 .map_err(|e| format!("Failed to load WASM plugin: {}", e))?;
254
255 let output = plugin
256 .call::<&[u8], Vec<u8>>(function_name, input_data)
257 .map_err(|e| {
258 let elapsed_ms = start.elapsed().as_secs_f64() * 1000.0;
259
260 format!("WASM execution failed: {}. Elapsed: {:.2}ms", e, elapsed_ms)
261 })?;
262
263 let elapsed_ms = start.elapsed().as_secs_f64() * 1000.0;
264
265 let telemetry = ExecutionTelemetry {
266 fuel_consumed: budget,
267
268 fuel_remaining: 0,
269
270 fuel_utilization_pct: 100.0,
271
272 memory_pages_used: max_pages as u64,
273
274 memory_bytes_used: (max_pages * WASM_PAGE_SIZE) as u64,
275
276 memory_utilization_pct: 100.0,
277
278 execution_time_ms: (elapsed_ms * 100.0).round() / 100.0,
279
280 status: "SUCCESS".to_string(),
281 };
282
283 Ok((output, telemetry))
284}
285
286pub fn sync_active_inference_priors(agent_priors: Vec<Vec<f64>>) -> Result<Vec<f64>, String> {
299 let plugins_dir =
300 std::env::var("PLUGINS_DIR").unwrap_or_else(|_| "/app/data/plugins".to_string());
301
302 let wasm_path = std::path::Path::new(&plugins_dir).join("iaif_sync.wasm");
303
304 if wasm_path.exists() {
305 if let Ok(wasm_bytes) = std::fs::read(wasm_path) {
306 let expected_hash = wasm_hash(&wasm_bytes);
307
308 let input_bytes = serde_json::to_vec(&agent_priors).unwrap_or_default();
309
310 match call_with_telemetry(
311 &wasm_bytes,
312 &expected_hash,
313 "merge_priors",
314 &input_bytes,
315 None,
316 ) {
317 Ok((output_bytes, _telemetry)) => {
318 if let Ok(merged) = serde_json::from_slice::<Vec<f64>>(&output_bytes) {
319 return Ok(merged);
320 }
321 }
322
323 Err(e) => {
324 eprintln!(
325 "WASM IAIF belief merger failed: {}. Falling back to default mean.",
326 e
327 );
328 }
329 }
330 }
331 }
332
333 if agent_priors.is_empty() {
336 return Ok(Vec::new());
337 }
338
339 let len = agent_priors.len() as f64;
340
341 let size = agent_priors[0].len();
342
343 let mut sum_priors = vec![0.0; size];
344
345 for priors in agent_priors {
346 if priors.len() != size {
347 return Err("Mismatched prior dimension across agents".into());
348 }
349
350 for (i, p) in priors.into_iter().enumerate() {
351 sum_priors[i] += p;
352 }
353 }
354
355 let total: f64 = sum_priors.iter().sum();
356
357 if total > 0.0 {
358 Ok(sum_priors.into_iter().map(|p| p / total).collect())
359 } else {
360 Ok(sum_priors.into_iter().map(|p| p / len).collect())
361 }
362}
363
364#[cfg(test)]
365
366mod tests {
367
368 use super::*;
369
370 #[test]
371
372 fn test_sync_active_inference_priors_fallback() {
373 let priors = vec![vec![0.8, 0.2], vec![0.6, 0.4]];
374
375 let merged = sync_active_inference_priors(priors).unwrap();
376
377 assert_eq!(merged.len(), 2);
378
379 assert!((merged[0] - 0.7).abs() < 1e-5);
382
383 assert!((merged[1] - 0.3).abs() < 1e-5);
384 }
385
386 #[test]
387
388 fn test_is_text_bytes() {
389 assert!(is_text_bytes(b"hello world"));
392
393 assert!(is_text_bytes(b"line1\nline2"));
394
395 assert!(!is_text_bytes(b"binary\x00data"));
396 }
397
398 #[test]
399
400 fn test_compute_merkle_directory_cid_deterministic() {
401 let mut files = HashMap::new();
402
403 files.insert("a.py".to_string(), b"print('a')".to_vec());
404
405 files.insert("b.py".to_string(), b"print('b')".to_vec());
406
407 let cid1 = compute_merkle_directory_cid(&files);
408
409 let cid2 = compute_merkle_directory_cid(&files);
410
411 assert_eq!(cid1, cid2);
412
413 assert!(cid1.starts_with("sha256:"));
414 }
415
416 #[test]
417
418 fn test_compute_merkle_cid_key_order_independent() {
419 let mut files1 = HashMap::new();
420
421 files1.insert("z.py".to_string(), b"z".to_vec());
422
423 files1.insert("a.py".to_string(), b"a".to_vec());
424
425 let mut files2 = HashMap::new();
426
427 files2.insert("a.py".to_string(), b"a".to_vec());
428
429 files2.insert("z.py".to_string(), b"z".to_vec());
430
431 assert_eq!(
432 compute_merkle_directory_cid(&files1),
433 compute_merkle_directory_cid(&files2)
434 );
435 }
436
437 #[test]
438
439 fn test_compute_merkle_cid_normalizes_line_endings() {
440 let mut files_crlf = HashMap::new();
441
442 files_crlf.insert("test.py".to_string(), b"line1\r\nline2".to_vec());
443
444 let mut files_lf = HashMap::new();
445
446 files_lf.insert("test.py".to_string(), b"line1\nline2".to_vec());
447
448 assert_eq!(
449 compute_merkle_directory_cid(&files_crlf),
450 compute_merkle_directory_cid(&files_lf)
451 );
452 }
453
454 #[test]
455
456 fn test_verify_bundle_integrity_skip_draft() {
457 let files = HashMap::new();
458
459 assert!(verify_bundle_integrity(&files, None).unwrap());
460
461 assert!(verify_bundle_integrity(&files, Some("")).unwrap());
462 }
463
464 #[test]
465
466 fn test_verify_bundle_integrity_valid() {
467 let mut files = HashMap::new();
468
469 files.insert("test.py".to_string(), b"hello".to_vec());
470
471 let expected = compute_merkle_directory_cid(&files);
472
473 assert!(verify_bundle_integrity(&files, Some(&expected)).unwrap());
474 }
475
476 #[test]
477
478 fn test_verify_bundle_integrity_mismatch() {
479 let mut files = HashMap::new();
480
481 files.insert("test.py".to_string(), b"hello".to_vec());
482
483 let result = verify_bundle_integrity(&files, Some("sha256:bad_hash"));
484
485 assert!(result.is_err());
486 }
487
488 #[test]
489
490 fn test_wasm_attestation_valid() {
491 let data = b"fake wasm bytes";
492
493 let hash = wasm_hash(data);
494
495 assert!(verify_wasm_attestation(data, &hash).is_ok());
496 }
497
498 #[test]
499
500 fn test_wasm_attestation_mismatch() {
501 let data = b"fake wasm bytes";
502
503 let result = verify_wasm_attestation(
504 data,
505 "0000000000000000000000000000000000000000000000000000000000000000",
506 );
507
508 assert!(result.is_err());
509 }
510}