1use crate::span::Span;
43use crate::value::Value;
44use std::collections::BTreeMap;
45
46pub fn hash_result_value(algorithm: &str, hex: &str, bytes: usize) -> Value {
49 let mut rec = BTreeMap::new();
50 rec.insert("algorithm".into(), Value::String(algorithm.into()));
51 rec.insert("hex".into(), Value::String(hex.into()));
52 rec.insert("bytes".into(), Value::U64(bytes as u64));
53 Value::Record(rec)
54}
55
56pub fn encrypted_data_value(
59 algorithm: &str,
60 ciphertext_hex: &str,
61 tag_hex: &str,
62 nonce_hex: &str,
63) -> Value {
64 let mut rec = BTreeMap::new();
65 rec.insert("algorithm".into(), Value::String(algorithm.into()));
66 rec.insert(
67 "ciphertext_hex".into(),
68 Value::String(ciphertext_hex.into()),
69 );
70 rec.insert("tag_hex".into(), Value::String(tag_hex.into()));
71 rec.insert("nonce_hex".into(), Value::String(nonce_hex.into()));
72 Value::Record(rec)
73}
74
75pub fn signature_value(key_id: &str, signature_hex: &str, algorithm: &str) -> Value {
78 let mut rec = BTreeMap::new();
79 rec.insert("key_id".into(), Value::String(key_id.into()));
80 rec.insert("signature_hex".into(), Value::String(signature_hex.into()));
81 rec.insert("algorithm".into(), Value::String(algorithm.into()));
82 Value::Record(rec)
83}
84
85pub fn extract_string_arg(
87 args: &[Value],
88 index: usize,
89 name: &str,
90 span: Span,
91) -> Result<String, crate::error::Diagnostic> {
92 match args.get(index) {
93 Some(Value::String(s)) => Ok(s.clone()),
94 _ => Err(crate::error::Diagnostic::new(
95 crate::error::DiagCode::E100,
96 span,
97 format!("crypto: {name} expects a string argument at position {index}"),
98 )),
99 }
100}
101
102pub fn extract_u64_arg(
104 args: &[Value],
105 index: usize,
106 name: &str,
107 span: Span,
108) -> Result<u64, crate::error::Diagnostic> {
109 match args.get(index) {
110 Some(Value::U64(n)) => Ok(*n),
111 Some(Value::I64(n)) => Ok((*n).max(0) as u64),
112 _ => Err(crate::error::Diagnostic::new(
113 crate::error::DiagCode::E100,
114 span,
115 format!("crypto: {name} expects a number at position {index}"),
116 )),
117 }
118}
119
120pub fn extract_f64_arg(
122 args: &[Value],
123 index: usize,
124 name: &str,
125 span: Span,
126) -> Result<f64, crate::error::Diagnostic> {
127 match args.get(index) {
128 Some(Value::F64(n)) => Ok(*n),
129 Some(Value::I64(n)) => Ok(*n as f64),
130 Some(Value::U64(n)) => Ok(*n as f64),
131 _ => Err(crate::error::Diagnostic::new(
132 crate::error::DiagCode::E100,
133 span,
134 format!("{name} expects a number at position {index}"),
135 )),
136 }
137}
138
139pub fn to_hex(bytes: &[u8]) -> String {
141 let mut s = String::with_capacity(bytes.len() * 2);
142 for byte in bytes {
143 s.push_str(&format!("{byte:02x}"));
144 }
145 s
146}
147
148pub fn from_hex(hex: &str) -> Option<Vec<u8>> {
150 let hex = hex.trim();
151 if hex.len() % 2 != 0 {
152 return None;
153 }
154 let mut bytes = Vec::with_capacity(hex.len() / 2);
155 for i in (0..hex.len()).step_by(2) {
156 bytes.push(u8::from_str_radix(&hex[i..i + 2], 16).ok()?);
157 }
158 Some(bytes)
159}
160
161const SHA256_K: [u32; 64] = [
162 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
163 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
164 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
165 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
166 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
167 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
168 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
169 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
170];
171
172pub fn sha256_bytes(data: &[u8]) -> [u8; 32] {
174 let mut h: [u32; 8] = [
175 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
176 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
177 ];
178 let bit_len = (data.len() as u64).wrapping_mul(8);
179 let mut padded = Vec::with_capacity((data.len() + 72) & !63);
180 padded.extend_from_slice(data);
181 padded.push(0x80);
182 while (padded.len() % 64) != 56 {
183 padded.push(0x00);
184 }
185 padded.extend_from_slice(&bit_len.to_be_bytes());
186
187 for chunk in padded.chunks_exact(64) {
188 let mut w = [0u32; 64];
189 for (i, word) in chunk.chunks_exact(4).enumerate() {
190 w[i] = u32::from_be_bytes([word[0], word[1], word[2], word[3]]);
191 }
192 for i in 16..64 {
193 let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
194 let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
195 w[i] = w[i - 16]
196 .wrapping_add(s0)
197 .wrapping_add(w[i - 7])
198 .wrapping_add(s1);
199 }
200 let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h;
201 for i in 0..64 {
202 let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
203 let ch = (e & f) ^ ((!e) & g);
204 let temp1 = hh
205 .wrapping_add(s1)
206 .wrapping_add(ch)
207 .wrapping_add(SHA256_K[i])
208 .wrapping_add(w[i]);
209 let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
210 let maj = (a & b) ^ (a & c) ^ (b & c);
211 let temp2 = s0.wrapping_add(maj);
212 hh = g;
213 g = f;
214 f = e;
215 e = d.wrapping_add(temp1);
216 d = c;
217 c = b;
218 b = a;
219 a = temp1.wrapping_add(temp2);
220 }
221 for (st, delta) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) {
222 *st = st.wrapping_add(delta);
223 }
224 }
225 let mut out = [0u8; 32];
226 for (i, word) in h.iter().enumerate() {
227 out[i * 4..(i + 1) * 4].copy_from_slice(&word.to_be_bytes());
228 }
229 out
230}
231
232pub fn sha256_hex(data: &[u8]) -> String {
234 to_hex(&sha256_bytes(data))
235}
236
237pub const CRYPTO_CAPABILITIES: &[&str] = &[
239 "crypto.sha256",
240 "crypto.sha512",
241 "crypto.blake3",
242 "crypto.hkdf_sha256",
243 "crypto.aead_encrypt",
244 "crypto.aead_decrypt",
245 "crypto.sign",
246 "crypto.verify",
247 "crypto.generate_key",
248];
249
250pub const AEAD_ALGORITHMS: &[&str] = &["AES-256-GCM", "ChaCha20-Poly1305", "XChaCha20-Poly1305"];
252
253pub const HASH_ALGORITHMS: &[&str] = &["SHA-256", "SHA-512", "BLAKE3"];
255
256pub const SIGNING_ALGORITHMS: &[&str] = &["Ed25519", "ML-DSA-65"];
258
259pub const ZK_CAPABILITIES: &[&str] = &[
263 "zk.prove_threshold",
264 "zk.verify_threshold",
265 "zk.prove_range",
266 "zk.verify_range",
267 "zk.prove_matmul",
268 "zk.verify_matmul",
269 "zk.list_circuits",
270];
271
272pub fn zk_proof_value(proof_hex: &str, vk_hex: &str, proof_id: &str, circuit_id: &str) -> Value {
275 let mut rec = BTreeMap::new();
276 rec.insert("proof_hex".into(), Value::String(proof_hex.into()));
277 rec.insert("vk_hex".into(), Value::String(vk_hex.into()));
278 rec.insert("proof_id".into(), Value::String(proof_id.into()));
279 rec.insert("circuit_id".into(), Value::String(circuit_id.into()));
280 Value::Record(rec)
281}
282
283pub fn zk_verification_value(valid: bool, proof_id: &str, verification_time_ms: u64) -> Value {
286 let mut rec = BTreeMap::new();
287 rec.insert("valid".into(), Value::Bool(valid));
288 rec.insert("proof_id".into(), Value::String(proof_id.into()));
289 rec.insert(
290 "verification_time_ms".into(),
291 Value::U64(verification_time_ms),
292 );
293 Value::Record(rec)
294}
295
296pub fn zk_matmul_result_value(valid: bool, result: &[i128]) -> Value {
299 let mut rec = BTreeMap::new();
300 rec.insert("valid".into(), Value::Bool(valid));
301 rec.insert(
302 "result".into(),
303 Value::List(result.iter().map(|v| Value::I64(*v as i64)).collect()),
304 );
305 Value::Record(rec)
306}
307
308#[cfg(test)]
309mod tests {
310 use super::*;
311
312 #[test]
313 fn hash_result_value_structure() {
314 let v = hash_result_value("SHA-256", "abc123", 32);
315 let rec = match &v {
316 Value::Record(r) => r,
317 _ => panic!("expected Record"),
318 };
319 assert_eq!(
320 match rec.get("algorithm").unwrap() {
321 Value::String(s) => s.as_str(),
322 _ => panic!("expected String"),
323 },
324 "SHA-256"
325 );
326 assert_eq!(
327 match rec.get("hex").unwrap() {
328 Value::String(s) => s.as_str(),
329 _ => panic!("expected String"),
330 },
331 "abc123"
332 );
333 assert_eq!(
334 match rec.get("bytes").unwrap() {
335 Value::U64(n) => *n,
336 _ => panic!("expected U64"),
337 },
338 32
339 );
340 }
341
342 #[test]
343 fn encrypted_data_value_structure() {
344 let v = encrypted_data_value("AES-256-GCM", "ciphertext", "tag", "nonce");
345 let rec = match &v {
346 Value::Record(r) => r,
347 _ => panic!("expected Record"),
348 };
349 assert_eq!(rec.len(), 4);
350 assert!(rec.contains_key("ciphertext_hex"));
351 assert!(rec.contains_key("tag_hex"));
352 assert!(rec.contains_key("nonce_hex"));
353 }
354
355 #[test]
356 fn signature_value_structure() {
357 let v = signature_value("key:ed25519:0", "sig123", "Ed25519");
358 let rec = match &v {
359 Value::Record(r) => r,
360 _ => panic!("expected Record"),
361 };
362 assert_eq!(rec.len(), 3);
363 assert!(rec.contains_key("key_id"));
364 assert!(rec.contains_key("signature_hex"));
365 assert!(rec.contains_key("algorithm"));
366 }
367
368 #[test]
369 fn to_hex_round_trip() {
370 let bytes = vec![0x00, 0xFF, 0xAB, 0xCD];
371 let hex = to_hex(&bytes);
372 assert_eq!(hex, "00ffabcd");
373 let restored = from_hex(&hex).unwrap();
374 assert_eq!(restored, bytes);
375 }
376
377 #[test]
378 fn from_hex_invalid() {
379 assert!(from_hex("abc").is_none()); assert!(from_hex("xy").is_none()); assert!(from_hex("").is_some()); }
383
384 #[test]
385 fn from_hex_valid() {
386 assert_eq!(from_hex("48656c6c6f").unwrap(), b"Hello");
387 assert_eq!(from_hex("00ff").unwrap(), vec![0x00, 0xFF]);
388 }
389
390 #[test]
391 fn crypto_capabilities_listed() {
392 assert!(CRYPTO_CAPABILITIES.contains(&"crypto.sha256"));
393 assert!(CRYPTO_CAPABILITIES.contains(&"crypto.blake3"));
394 assert!(CRYPTO_CAPABILITIES.contains(&"crypto.aead_encrypt"));
395 assert!(CRYPTO_CAPABILITIES.contains(&"crypto.sign"));
396 assert!(CRYPTO_CAPABILITIES.contains(&"crypto.verify"));
397 }
398
399 #[test]
400 fn aead_algorithms_listed() {
401 assert!(AEAD_ALGORITHMS.contains(&"AES-256-GCM"));
402 assert!(AEAD_ALGORITHMS.contains(&"ChaCha20-Poly1305"));
403 assert!(AEAD_ALGORITHMS.contains(&"XChaCha20-Poly1305"));
404 }
405
406 #[test]
407 fn hash_algorithms_listed() {
408 assert!(HASH_ALGORITHMS.contains(&"SHA-256"));
409 assert!(HASH_ALGORITHMS.contains(&"SHA-512"));
410 assert!(HASH_ALGORITHMS.contains(&"BLAKE3"));
411 }
412
413 #[test]
414 fn signing_algorithms_listed() {
415 assert!(SIGNING_ALGORITHMS.contains(&"Ed25519"));
416 assert!(SIGNING_ALGORITHMS.contains(&"ML-DSA-65"));
417 }
418
419 #[test]
422 fn zk_capabilities_listed() {
423 assert!(ZK_CAPABILITIES.contains(&"zk.prove_threshold"));
424 assert!(ZK_CAPABILITIES.contains(&"zk.verify_threshold"));
425 assert!(ZK_CAPABILITIES.contains(&"zk.prove_range"));
426 assert!(ZK_CAPABILITIES.contains(&"zk.verify_range"));
427 assert!(ZK_CAPABILITIES.contains(&"zk.prove_matmul"));
428 assert!(ZK_CAPABILITIES.contains(&"zk.verify_matmul"));
429 }
430
431 #[test]
432 fn zk_proof_value_structure() {
433 let v = zk_proof_value("deadbeef", "vk123", "proof_1", "circuit_42");
434 let rec = match &v {
435 Value::Record(r) => r,
436 _ => panic!("expected Record"),
437 };
438 assert_eq!(rec.len(), 4);
439 assert!(rec.contains_key("proof_hex"));
440 assert!(rec.contains_key("vk_hex"));
441 assert!(rec.contains_key("proof_id"));
442 assert!(rec.contains_key("circuit_id"));
443 }
444
445 #[test]
446 fn zk_verification_value_structure() {
447 let v = zk_verification_value(true, "proof_1", 42);
448 let rec = match &v {
449 Value::Record(r) => r,
450 _ => panic!("expected Record"),
451 };
452 assert_eq!(rec.len(), 3);
453 assert_eq!(
454 match rec.get("valid").unwrap() {
455 Value::Bool(b) => *b,
456 _ => panic!("expected Bool"),
457 },
458 true
459 );
460 assert_eq!(
461 match rec.get("verification_time_ms").unwrap() {
462 Value::U64(n) => *n,
463 _ => panic!("expected U64"),
464 },
465 42
466 );
467 }
468
469 #[test]
470 fn zk_matmul_result_value_structure() {
471 let v = zk_matmul_result_value(true, &[1, 2, 3]);
472 let rec = match &v {
473 Value::Record(r) => r,
474 _ => panic!("expected Record"),
475 };
476 assert_eq!(rec.len(), 2);
477 assert_eq!(
478 match rec.get("valid").unwrap() {
479 Value::Bool(b) => *b,
480 _ => panic!("expected Bool"),
481 },
482 true
483 );
484 match rec.get("result").unwrap() {
485 Value::List(xs) => assert_eq!(xs.len(), 3),
486 _ => panic!("expected List"),
487 }
488 }
489}