polycomp 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/bundle.rs ADDED
@@ -0,0 +1,3180 @@
1
+ use crate::diagnostics::PolyError;
2
+ use crate::ir::*;
3
+ use chacha20poly1305::aead::{Aead, KeyInit, Payload};
4
+ use chacha20poly1305::{XChaCha20Poly1305, XNonce};
5
+ use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
6
+ use rustc_hash::FxHashSet;
7
+ use std::fmt::Write as _;
8
+ use std::path::Path;
9
+
10
+ pub const PLAIN_BANNER: &str = "; === POLYCOMP-IR-V3 ===";
11
+ pub const PLAIN_BEGIN_IR: &str = "; --- BEGIN IR ---";
12
+ pub const PLAIN_END_IR: &str = "; --- END IR ---";
13
+
14
+ pub const ARMOR_BEGIN: &str = "-----BEGIN POLYCOMP SECURE IR-----";
15
+ pub const ARMOR_END: &str = "-----END POLYCOMP SECURE IR-----";
16
+
17
+ pub const FORMAT_VERSION: u16 = 3;
18
+
19
+ const FLAG_ENCRYPTED: u8 = 1 << 0;
20
+ const FLAG_OBFUSCATED: u8 = 1 << 1;
21
+
22
+ const KDF_ARGON2ID: u8 = 1;
23
+ const KDF_RAW_BLAKE3: u8 = 2;
24
+ const KDF_VM_SEALED: u8 = 3;
25
+
26
+ const VERIFY_DOMAIN: &[u8] = b"POLYCOMP-IR-VERIFY-V3\0";
27
+
28
+ // Embedded toolchain signing seed used when no explicit --sign-key is supplied.
29
+ const DEFAULT_TOOLCHAIN_SIGN_SEED: [u8; 32] = [
30
+ 0x71, 0x4b, 0x92, 0xe8, 0x10, 0xc3, 0x55, 0xa9, 0x2d, 0x84, 0x0f, 0x6c, 0xbe, 0x37, 0x91, 0x44,
31
+ 0xd0, 0x62, 0x1a, 0xf3, 0x88, 0x4e, 0x29, 0x7c, 0x5b, 0xa1, 0xd6, 0x03, 0x99, 0xe5, 0x18, 0x6f,
32
+ ];
33
+
34
+ // Internal VM sealing domain material for keyless self-contained .polyx bundles.
35
+ const VM_SEAL_MIX: [u8; 32] = [
36
+ 0xa4, 0x19, 0x7d, 0x52, 0xe0, 0x8c, 0x31, 0x6b, 0xf7, 0x42, 0x95, 0x0e, 0x83, 0xc6, 0x11, 0xda,
37
+ 0x58, 0x07, 0xbe, 0x64, 0x2a, 0xd9, 0x4f, 0x73, 0x91, 0xe2, 0x3c, 0x85, 0x16, 0xab, 0x60, 0xf4,
38
+ ];
39
+
40
+ #[derive(Debug, Clone)]
41
+ pub struct IrBundle {
42
+ pub entry_fn: FnId,
43
+ pub entry_name: String,
44
+ pub init_fns: Vec<FnId>,
45
+ pub exports: Vec<(String, FnId)>,
46
+ pub functions: Vec<IrFunction>,
47
+ }
48
+
49
+ #[derive(Debug, Clone)]
50
+ pub enum SecretKeyMaterial {
51
+ Passphrase(String),
52
+ Raw32([u8; 32]),
53
+ }
54
+
55
+ impl SecretKeyMaterial {
56
+ pub fn parse(input: &str) -> Self {
57
+ let trimmed = input.trim();
58
+ if let Some(hex_str) = trimmed.strip_prefix("hex:")
59
+ && let Some(raw) = decode_hex_32(hex_str.trim())
60
+ {
61
+ return Self::Raw32(raw);
62
+ }
63
+ if trimmed.len() == 64
64
+ && trimmed.bytes().all(|b| b.is_ascii_hexdigit())
65
+ && let Some(raw) = decode_hex_32(trimmed)
66
+ {
67
+ return Self::Raw32(raw);
68
+ }
69
+ Self::Passphrase(input.to_string())
70
+ }
71
+
72
+ pub fn from_env_or_cli(
73
+ cli_key: Option<&str>,
74
+ keyfile: Option<&Path>,
75
+ ) -> Result<Option<Self>, PolyError> {
76
+ if let Some(k) = cli_key {
77
+ return Ok(Some(Self::parse(k)));
78
+ }
79
+ if let Some(path) = keyfile {
80
+ let content = std::fs::read_to_string(path).map_err(|e| {
81
+ PolyError::msg(
82
+ "E0701",
83
+ format!("failed to read keyfile '{}': {e}", path.display()),
84
+ )
85
+ })?;
86
+ return Ok(Some(Self::parse(&content)));
87
+ }
88
+ if let Ok(env_k) = std::env::var("POLYCOMP_KEY")
89
+ && !env_k.is_empty()
90
+ {
91
+ return Ok(Some(Self::parse(&env_k)));
92
+ }
93
+ if let Some(seal_k) = option_env!("POLYCOMP_SEAL_KEY")
94
+ && !seal_k.is_empty()
95
+ {
96
+ return Ok(Some(Self::parse(seal_k)));
97
+ }
98
+ Ok(None)
99
+ }
100
+ }
101
+
102
+ #[derive(Debug, Clone)]
103
+ pub struct SaveOptions {
104
+ pub obfuscate: bool,
105
+ pub secret_key: Option<SecretKeyMaterial>,
106
+ pub signing_key: Option<[u8; 32]>,
107
+ }
108
+
109
+ #[derive(Debug, Clone)]
110
+ pub struct VerifyReport {
111
+ pub format: &'static str,
112
+ pub version: u16,
113
+ pub encrypted: bool,
114
+ pub obfuscated: bool,
115
+ pub signed: bool,
116
+ pub keyless: bool,
117
+ pub signer_pubkey_hex: String,
118
+ pub pinned_publisher_match: Option<bool>,
119
+ pub payload_bytes: usize,
120
+ }
121
+
122
+ pub fn is_bundle_bytes(bytes: &[u8]) -> bool {
123
+ let Ok(s) = std::str::from_utf8(bytes) else {
124
+ return false;
125
+ };
126
+ let trimmed = s.trim_start_matches('\u{feff}').trim_start();
127
+ trimmed.starts_with(PLAIN_BANNER)
128
+ || trimmed.starts_with(ARMOR_BEGIN)
129
+ || trimmed.starts_with(PLAIN_BEGIN_IR)
130
+ }
131
+
132
+ pub fn is_bundle_path(path: &Path) -> bool {
133
+ if let Some(ext) = path.extension().and_then(|s| s.to_str())
134
+ && (ext.eq_ignore_ascii_case("polyir") || ext.eq_ignore_ascii_case("polyx"))
135
+ {
136
+ return true;
137
+ }
138
+ if let Ok(mut f) = std::fs::File::open(path) {
139
+ use std::io::Read;
140
+ let mut head = [0u8; 128];
141
+ if let Ok(n) = f.read(&mut head) {
142
+ return is_bundle_bytes(&head[..n]);
143
+ }
144
+ }
145
+ false
146
+ }
147
+
148
+ pub fn generate_keypair_files(out_dir: &Path) -> Result<(String, String, String), PolyError> {
149
+ std::fs::create_dir_all(out_dir)?;
150
+ let mut sign_seed = [0u8; 32];
151
+ let mut enc_key = [0u8; 32];
152
+ getrandom::getrandom(&mut sign_seed)
153
+ .map_err(|e| PolyError::msg("E0702", format!("CSPRNG error: {e}")))?;
154
+ getrandom::getrandom(&mut enc_key)
155
+ .map_err(|e| PolyError::msg("E0702", format!("CSPRNG error: {e}")))?;
156
+
157
+ let signing_key = SigningKey::from_bytes(&sign_seed);
158
+ let verifying_key = signing_key.verifying_key();
159
+
160
+ let sign_priv_hex = encode_hex(&sign_seed);
161
+ let sign_pub_hex = encode_hex(verifying_key.as_bytes());
162
+ let enc_hex = format!("hex:{}", encode_hex(&enc_key));
163
+
164
+ let priv_path = out_dir.join("polycomp_sign.key");
165
+ let pub_path = out_dir.join("polycomp_sign.pub");
166
+ let enc_path = out_dir.join("polycomp_enc.key");
167
+
168
+ std::fs::write(&priv_path, format!("{sign_priv_hex}\n"))?;
169
+ std::fs::write(&pub_path, format!("{sign_pub_hex}\n"))?;
170
+ std::fs::write(&enc_path, format!("{enc_hex}\n"))?;
171
+
172
+ Ok((
173
+ priv_path.display().to_string(),
174
+ pub_path.display().to_string(),
175
+ enc_path.display().to_string(),
176
+ ))
177
+ }
178
+
179
+ pub fn load_key_32_from_arg_or_file(val: &str) -> Result<[u8; 32], PolyError> {
180
+ let trimmed = val.trim();
181
+ if let Some(raw) = decode_hex_32(trimmed.strip_prefix("hex:").unwrap_or(trimmed)) {
182
+ return Ok(raw);
183
+ }
184
+ let path = Path::new(trimmed);
185
+ if path.is_file() {
186
+ let txt = std::fs::read_to_string(path)?;
187
+ let clean = txt.trim();
188
+ if let Some(raw) = decode_hex_32(clean.strip_prefix("hex:").unwrap_or(clean)) {
189
+ return Ok(raw);
190
+ }
191
+ }
192
+ Err(PolyError::msg(
193
+ "E0703",
194
+ format!("expected 64-char hex key or keyfile path, got '{trimmed}'"),
195
+ ))
196
+ }
197
+
198
+ /// Applies deep IR obfuscation:
199
+ /// 1. Symbol/metadata stripping
200
+ /// 2. IEEE-754 float bit-blinding (`Float` -> `I64` bits -> `BitsToF64`)
201
+ /// 3. Mixed Boolean-Arithmetic (MBA) expression substitution on `I64`
202
+ /// 4. Intra-block micro-splitting (chunk size 2)
203
+ /// 5. Control-Flow Flattening (CFF) + opaque predicates + dead decoy blocks
204
+ /// 6. Full integer constant blinding (`k -> (k ^ mask) ^ mask`) across program & CFF state IDs
205
+ /// 7. Fisher-Yates basic block shuffling
206
+ pub fn obfuscate_bundle(bundle: &mut IrBundle) -> Result<(), PolyError> {
207
+ let mut seed = [0u8; 32];
208
+ getrandom::getrandom(&mut seed)
209
+ .map_err(|e| PolyError::msg("E0702", format!("CSPRNG error: {e}")))?;
210
+ let mut counter: u64 = 0;
211
+ let mut next_u64 = || -> u64 {
212
+ counter = counter.wrapping_add(1);
213
+ let mut h = blake3::Hasher::new();
214
+ h.update(&seed);
215
+ h.update(&counter.to_le_bytes());
216
+ let out = h.finalize();
217
+ u64::from_le_bytes(out.as_bytes()[..8].try_into().unwrap())
218
+ };
219
+
220
+ bundle.exports = vec![(bundle.entry_name.clone(), bundle.entry_fn)];
221
+ for func in &mut bundle.functions {
222
+ func.qualified_name = format!("_f{:04x}", func.id.0);
223
+ obfuscate_function(func, &mut next_u64);
224
+ }
225
+ Ok(())
226
+ }
227
+
228
+ fn obfuscate_function<F: FnMut() -> u64>(func: &mut IrFunction, rng: &mut F) {
229
+ if func.blocks.is_empty() {
230
+ return;
231
+ }
232
+
233
+ // 1. Blind Float constants into integer bit-patterns + BitsToF64 (later blinded + MBA'd!)
234
+ for bb in &mut func.blocks {
235
+ let mut out = Vec::with_capacity(bb.instructions.len());
236
+ for instr in &bb.instructions {
237
+ if let IrInstruction::LoadConst(dst, Constant::Float(f)) = instr {
238
+ let raw_bits = f.to_bits() as i64;
239
+ let tmp = Register(func.register_types.len());
240
+ func.register_types.push(IrType::I64);
241
+ out.push(IrInstruction::LoadConst(tmp, Constant::Int(raw_bits)));
242
+ out.push(IrInstruction::UnaryOp(IrUnaryOp::BitsToF64, *dst, tmp));
243
+ } else {
244
+ out.push(instr.clone());
245
+ }
246
+ }
247
+ bb.instructions = out;
248
+ }
249
+
250
+ // 2. Mixed Boolean-Arithmetic (MBA) on strictly I64 arithmetic/bitwise/neg ops
251
+ apply_mba_pass(func, rng);
252
+
253
+ // 3. Split large blocks into 2-instruction micro-blocks so sequential expressions break apart
254
+ split_blocks_into_microchunks(func);
255
+
256
+ // 4. Control-Flow Flattening (CFF) + Opaque Predicate + Dead Decoy Blocks
257
+ const DISPATCH_PLACEHOLDER: usize = usize::MAX;
258
+ let orig_blocks = std::mem::take(&mut func.blocks);
259
+ let b_count = orig_blocks.len();
260
+
261
+ let mut used_states = FxHashSet::default();
262
+ let mut states = Vec::with_capacity(b_count + 2);
263
+ while states.len() < b_count + 2 {
264
+ let cand = rng() as i64;
265
+ if used_states.insert(cand) {
266
+ states.push(cand);
267
+ }
268
+ }
269
+
270
+ let r_state = Register(func.register_types.len());
271
+ func.register_types.push(IrType::I64);
272
+
273
+ // Opaque predicate in block 0: ((seed | 1) * (seed | 1)) & 1 == 1
274
+ let mut entry_instrs = Vec::new();
275
+ let seed_r = if let Some((pr, IrType::I64)) = func.params.first() {
276
+ *pr
277
+ } else {
278
+ let s = Register(func.register_types.len());
279
+ func.register_types.push(IrType::I64);
280
+ entry_instrs.push(IrInstruction::LoadConst(s, Constant::Int(rng() as i64)));
281
+ s
282
+ };
283
+ let c_one = Register(func.register_types.len());
284
+ func.register_types.push(IrType::I64);
285
+ let r_odd = Register(func.register_types.len());
286
+ func.register_types.push(IrType::I64);
287
+ let r_sq = Register(func.register_types.len());
288
+ func.register_types.push(IrType::I64);
289
+ let r_lsb = Register(func.register_types.len());
290
+ func.register_types.push(IrType::I64);
291
+ let r_cond = Register(func.register_types.len());
292
+ func.register_types.push(IrType::Bool);
293
+
294
+ entry_instrs.push(IrInstruction::LoadConst(c_one, Constant::Int(1)));
295
+ entry_instrs.push(IrInstruction::BinOp(IrBinOp::BitOr, r_odd, seed_r, c_one));
296
+ entry_instrs.push(IrInstruction::BinOp(IrBinOp::Mul, r_sq, r_odd, r_odd));
297
+ entry_instrs.push(IrInstruction::BinOp(IrBinOp::BitAnd, r_lsb, r_sq, c_one));
298
+ entry_instrs.push(IrInstruction::BinOp(IrBinOp::Eq, r_cond, r_lsb, c_one));
299
+ entry_instrs.push(IrInstruction::BranchIf(
300
+ r_cond,
301
+ BasicBlockId(1),
302
+ BasicBlockId(2),
303
+ ));
304
+
305
+ let mut new_blocks = Vec::with_capacity(b_count * 2 + 8);
306
+ new_blocks.push(BasicBlock {
307
+ id: BasicBlockId(0),
308
+ instructions: entry_instrs,
309
+ });
310
+ new_blocks.push(BasicBlock {
311
+ id: BasicBlockId(1),
312
+ instructions: vec![
313
+ IrInstruction::LoadConst(r_state, Constant::Int(states[0])),
314
+ IrInstruction::Jump(BasicBlockId(DISPATCH_PLACEHOLDER)),
315
+ ],
316
+ });
317
+ new_blocks.push(BasicBlock {
318
+ id: BasicBlockId(2),
319
+ instructions: vec![
320
+ IrInstruction::LoadConst(r_state, Constant::Int(states[b_count])),
321
+ IrInstruction::Jump(BasicBlockId(DISPATCH_PLACEHOLDER)),
322
+ ],
323
+ });
324
+
325
+ let mut real_ids = Vec::with_capacity(b_count);
326
+ for i in 0..b_count {
327
+ let id = BasicBlockId(3 + i);
328
+ real_ids.push(id);
329
+ new_blocks.push(BasicBlock {
330
+ id,
331
+ instructions: Vec::new(),
332
+ });
333
+ }
334
+
335
+ for (i, ob) in orig_blocks.into_iter().enumerate() {
336
+ let mut ins_out = Vec::with_capacity(ob.instructions.len() + 2);
337
+ let len = ob.instructions.len();
338
+ let mut terminated = false;
339
+
340
+ for (idx, instr) in ob.instructions.into_iter().enumerate() {
341
+ let is_last = idx + 1 == len;
342
+ if is_last {
343
+ match instr {
344
+ IrInstruction::Return(opt) => {
345
+ ins_out.push(IrInstruction::Return(opt));
346
+ terminated = true;
347
+ }
348
+ IrInstruction::Jump(target) => {
349
+ ins_out.push(IrInstruction::LoadConst(
350
+ r_state,
351
+ Constant::Int(states[target.0]),
352
+ ));
353
+ ins_out.push(IrInstruction::Jump(BasicBlockId(DISPATCH_PLACEHOLDER)));
354
+ terminated = true;
355
+ }
356
+ IrInstruction::BranchIf(cond, t_bb, f_bb) => {
357
+ let set_t_id = BasicBlockId(new_blocks.len());
358
+ new_blocks.push(BasicBlock {
359
+ id: set_t_id,
360
+ instructions: vec![
361
+ IrInstruction::LoadConst(
362
+ r_state,
363
+ Constant::Int(states[t_bb.0]),
364
+ ),
365
+ IrInstruction::Jump(BasicBlockId(DISPATCH_PLACEHOLDER)),
366
+ ],
367
+ });
368
+ let set_f_id = BasicBlockId(new_blocks.len());
369
+ new_blocks.push(BasicBlock {
370
+ id: set_f_id,
371
+ instructions: vec![
372
+ IrInstruction::LoadConst(
373
+ r_state,
374
+ Constant::Int(states[f_bb.0]),
375
+ ),
376
+ IrInstruction::Jump(BasicBlockId(DISPATCH_PLACEHOLDER)),
377
+ ],
378
+ });
379
+ ins_out.push(IrInstruction::BranchIf(cond, set_t_id, set_f_id));
380
+ terminated = true;
381
+ }
382
+ other => ins_out.push(other),
383
+ }
384
+ } else {
385
+ ins_out.push(instr);
386
+ }
387
+ }
388
+
389
+ if !terminated {
390
+ if i + 1 < b_count {
391
+ ins_out.push(IrInstruction::LoadConst(
392
+ r_state,
393
+ Constant::Int(states[i + 1]),
394
+ ));
395
+ ins_out.push(IrInstruction::Jump(BasicBlockId(DISPATCH_PLACEHOLDER)));
396
+ } else {
397
+ ins_out.push(IrInstruction::Return(None));
398
+ }
399
+ }
400
+
401
+ new_blocks[3 + i].instructions = ins_out;
402
+ }
403
+
404
+ // 2 dead decoy blocks with realistic arithmetic
405
+ let mut decoy_ids = Vec::with_capacity(2);
406
+ for d_idx in 0..2 {
407
+ let d_id = BasicBlockId(new_blocks.len());
408
+ decoy_ids.push(d_id);
409
+ let d1 = Register(func.register_types.len());
410
+ func.register_types.push(IrType::I64);
411
+ let d2 = Register(func.register_types.len());
412
+ func.register_types.push(IrType::I64);
413
+ let d3 = Register(func.register_types.len());
414
+ func.register_types.push(IrType::I64);
415
+ let next_st = states[(d_idx + 1) % states.len()];
416
+ new_blocks.push(BasicBlock {
417
+ id: d_id,
418
+ instructions: vec![
419
+ IrInstruction::LoadConst(d1, Constant::Int(rng() as i64)),
420
+ IrInstruction::LoadConst(d2, Constant::Int(rng() as i64)),
421
+ IrInstruction::BinOp(IrBinOp::Mul, d3, d1, d2),
422
+ IrInstruction::LoadConst(r_state, Constant::Int(next_st)),
423
+ IrInstruction::Jump(BasicBlockId(DISPATCH_PLACEHOLDER)),
424
+ ],
425
+ });
426
+ }
427
+
428
+ // Shuffled CFF Dispatcher Chain
429
+ let dispatch_start = BasicBlockId(new_blocks.len());
430
+ let mut cases: Vec<(i64, BasicBlockId)> = (0..b_count)
431
+ .map(|i| (states[i], real_ids[i]))
432
+ .collect();
433
+ cases.push((states[b_count], decoy_ids[0]));
434
+ cases.push((states[b_count + 1], decoy_ids[1]));
435
+
436
+ for i in (1..cases.len()).rev() {
437
+ let j = rng() as usize % (i + 1);
438
+ cases.swap(i, j);
439
+ }
440
+
441
+ for (idx, (sv, target_bb)) in cases.iter().enumerate() {
442
+ let bb_id = BasicBlockId(new_blocks.len());
443
+ if idx + 1 == cases.len() {
444
+ new_blocks.push(BasicBlock {
445
+ id: bb_id,
446
+ instructions: vec![IrInstruction::Jump(*target_bb)],
447
+ });
448
+ } else {
449
+ let next_dispatch = BasicBlockId(bb_id.0 + 1);
450
+ let r_sv = Register(func.register_types.len());
451
+ func.register_types.push(IrType::I64);
452
+ let r_cmp = Register(func.register_types.len());
453
+ func.register_types.push(IrType::Bool);
454
+ new_blocks.push(BasicBlock {
455
+ id: bb_id,
456
+ instructions: vec![
457
+ IrInstruction::LoadConst(r_sv, Constant::Int(*sv)),
458
+ IrInstruction::BinOp(IrBinOp::Eq, r_cmp, r_state, r_sv),
459
+ IrInstruction::BranchIf(r_cmp, *target_bb, next_dispatch),
460
+ ],
461
+ });
462
+ }
463
+ }
464
+
465
+ for bb in &mut new_blocks {
466
+ for instr in &mut bb.instructions {
467
+ if let IrInstruction::Jump(t) = instr
468
+ && t.0 == DISPATCH_PLACEHOLDER
469
+ {
470
+ *t = dispatch_start;
471
+ }
472
+ }
473
+ }
474
+
475
+ // 5. Constant Blinding: split every Int(k) into k ^ m1 ^ m2 with 2-stage XOR
476
+ for bb in &mut new_blocks {
477
+ let mut blinded = Vec::with_capacity(bb.instructions.len());
478
+ for instr in &bb.instructions {
479
+ if let IrInstruction::LoadConst(dst, Constant::Int(k)) = instr {
480
+ let m1 = rng() as i64;
481
+ let m2 = rng() as i64;
482
+ let t1 = Register(func.register_types.len());
483
+ func.register_types.push(IrType::I64);
484
+ let t2 = Register(func.register_types.len());
485
+ func.register_types.push(IrType::I64);
486
+ let t3 = Register(func.register_types.len());
487
+ func.register_types.push(IrType::I64);
488
+ let t4 = Register(func.register_types.len());
489
+ func.register_types.push(IrType::I64);
490
+ blinded.push(IrInstruction::LoadConst(t1, Constant::Int(*k ^ m1 ^ m2)));
491
+ blinded.push(IrInstruction::LoadConst(t2, Constant::Int(m1)));
492
+ blinded.push(IrInstruction::BinOp(IrBinOp::BitXor, t3, t1, t2));
493
+ blinded.push(IrInstruction::LoadConst(t4, Constant::Int(m2)));
494
+ blinded.push(IrInstruction::BinOp(IrBinOp::BitXor, *dst, t3, t4));
495
+ } else {
496
+ blinded.push(instr.clone());
497
+ }
498
+ }
499
+ bb.instructions = blinded;
500
+ }
501
+
502
+ // 6. Shuffle blocks[1..] and remap all BasicBlockIds
503
+ let n = new_blocks.len();
504
+ let mut perm: Vec<usize> = (0..n).collect();
505
+ for i in (1..n).rev() {
506
+ let j = 1 + (rng() as usize % i);
507
+ perm.swap(i, j);
508
+ }
509
+ let mut inv = vec![0usize; n];
510
+ for (new_idx, &old_idx) in perm.iter().enumerate() {
511
+ inv[old_idx] = new_idx;
512
+ }
513
+ let mut reordered = Vec::with_capacity(n);
514
+ for (new_idx, &old_idx) in perm.iter().enumerate() {
515
+ let mut bb = new_blocks[old_idx].clone();
516
+ bb.id = BasicBlockId(new_idx);
517
+ for instr in &mut bb.instructions {
518
+ match instr {
519
+ IrInstruction::Jump(t) => *t = BasicBlockId(inv[t.0]),
520
+ IrInstruction::BranchIf(_, a, b) => {
521
+ *a = BasicBlockId(inv[a.0]);
522
+ *b = BasicBlockId(inv[b.0]);
523
+ }
524
+ _ => {}
525
+ }
526
+ }
527
+ reordered.push(bb);
528
+ }
529
+ func.blocks = reordered;
530
+ }
531
+
532
+ /// Bit-exact two's-complement Mixed Boolean-Arithmetic (MBA) substitutions on I64 operations.
533
+ fn apply_mba_pass<F: FnMut() -> u64>(func: &mut IrFunction, rng: &mut F) {
534
+ let alloc_i64 = |reg_types: &mut Vec<IrType>| -> Register {
535
+ let r = Register(reg_types.len());
536
+ reg_types.push(IrType::I64);
537
+ r
538
+ };
539
+
540
+ let reg_types = &mut func.register_types;
541
+ for bb in &mut func.blocks {
542
+ let mut out = Vec::with_capacity(bb.instructions.len());
543
+ for instr in &bb.instructions {
544
+ match instr {
545
+ IrInstruction::BinOp(op, dst, l, r)
546
+ if reg_types[l.0] == IrType::I64
547
+ && reg_types[r.0] == IrType::I64
548
+ && reg_types[dst.0] == IrType::I64 =>
549
+ {
550
+ let (x, y, d) = (*l, *r, *dst);
551
+ match op {
552
+ IrBinOp::Add => match rng() % 3 {
553
+ 0 => {
554
+ let t_xor = alloc_i64(reg_types);
555
+ let t_and = alloc_i64(reg_types);
556
+ let t_one = alloc_i64(reg_types);
557
+ let t_shl = alloc_i64(reg_types);
558
+ out.push(IrInstruction::BinOp(IrBinOp::BitXor, t_xor, x, y));
559
+ out.push(IrInstruction::BinOp(IrBinOp::BitAnd, t_and, x, y));
560
+ out.push(IrInstruction::LoadConst(t_one, Constant::Int(1)));
561
+ out.push(IrInstruction::BinOp(IrBinOp::Shl, t_shl, t_and, t_one));
562
+ out.push(IrInstruction::BinOp(IrBinOp::Add, d, t_xor, t_shl));
563
+ }
564
+ 1 => {
565
+ let t_or = alloc_i64(reg_types);
566
+ let t_and = alloc_i64(reg_types);
567
+ out.push(IrInstruction::BinOp(IrBinOp::BitOr, t_or, x, y));
568
+ out.push(IrInstruction::BinOp(IrBinOp::BitAnd, t_and, x, y));
569
+ out.push(IrInstruction::BinOp(IrBinOp::Add, d, t_or, t_and));
570
+ }
571
+ _ => {
572
+ let t_ny = alloc_i64(reg_types);
573
+ let t_sub = alloc_i64(reg_types);
574
+ let t_one = alloc_i64(reg_types);
575
+ out.push(IrInstruction::UnaryOp(IrUnaryOp::BitNot, t_ny, y));
576
+ out.push(IrInstruction::BinOp(IrBinOp::Sub, t_sub, x, t_ny));
577
+ out.push(IrInstruction::LoadConst(t_one, Constant::Int(1)));
578
+ out.push(IrInstruction::BinOp(IrBinOp::Sub, d, t_sub, t_one));
579
+ }
580
+ },
581
+ IrBinOp::Sub => match rng() % 2 {
582
+ 0 => {
583
+ let t_nx = alloc_i64(reg_types);
584
+ let t_ny = alloc_i64(reg_types);
585
+ let t_a = alloc_i64(reg_types);
586
+ let t_b = alloc_i64(reg_types);
587
+ out.push(IrInstruction::UnaryOp(IrUnaryOp::BitNot, t_nx, x));
588
+ out.push(IrInstruction::UnaryOp(IrUnaryOp::BitNot, t_ny, y));
589
+ out.push(IrInstruction::BinOp(IrBinOp::BitAnd, t_a, x, t_ny));
590
+ out.push(IrInstruction::BinOp(IrBinOp::BitAnd, t_b, t_nx, y));
591
+ out.push(IrInstruction::BinOp(IrBinOp::Sub, d, t_a, t_b));
592
+ }
593
+ _ => {
594
+ let t_ny = alloc_i64(reg_types);
595
+ let t_xor = alloc_i64(reg_types);
596
+ let t_and = alloc_i64(reg_types);
597
+ let t_one = alloc_i64(reg_types);
598
+ let t_shl = alloc_i64(reg_types);
599
+ let t_sum = alloc_i64(reg_types);
600
+ out.push(IrInstruction::UnaryOp(IrUnaryOp::BitNot, t_ny, y));
601
+ out.push(IrInstruction::BinOp(IrBinOp::BitXor, t_xor, x, t_ny));
602
+ out.push(IrInstruction::BinOp(IrBinOp::BitAnd, t_and, x, t_ny));
603
+ out.push(IrInstruction::LoadConst(t_one, Constant::Int(1)));
604
+ out.push(IrInstruction::BinOp(IrBinOp::Shl, t_shl, t_and, t_one));
605
+ out.push(IrInstruction::BinOp(IrBinOp::Add, t_sum, t_xor, t_shl));
606
+ out.push(IrInstruction::BinOp(IrBinOp::Add, d, t_sum, t_one));
607
+ }
608
+ },
609
+ IrBinOp::BitXor => {
610
+ let t_or = alloc_i64(reg_types);
611
+ let t_and = alloc_i64(reg_types);
612
+ out.push(IrInstruction::BinOp(IrBinOp::BitOr, t_or, x, y));
613
+ out.push(IrInstruction::BinOp(IrBinOp::BitAnd, t_and, x, y));
614
+ out.push(IrInstruction::BinOp(IrBinOp::Sub, d, t_or, t_and));
615
+ }
616
+ IrBinOp::BitAnd => {
617
+ let t_add = alloc_i64(reg_types);
618
+ let t_or = alloc_i64(reg_types);
619
+ out.push(IrInstruction::BinOp(IrBinOp::Add, t_add, x, y));
620
+ out.push(IrInstruction::BinOp(IrBinOp::BitOr, t_or, x, y));
621
+ out.push(IrInstruction::BinOp(IrBinOp::Sub, d, t_add, t_or));
622
+ }
623
+ IrBinOp::BitOr => {
624
+ let t_xor = alloc_i64(reg_types);
625
+ let t_and = alloc_i64(reg_types);
626
+ out.push(IrInstruction::BinOp(IrBinOp::BitXor, t_xor, x, y));
627
+ out.push(IrInstruction::BinOp(IrBinOp::BitAnd, t_and, x, y));
628
+ out.push(IrInstruction::BinOp(IrBinOp::Add, d, t_xor, t_and));
629
+ }
630
+ _ => out.push(instr.clone()),
631
+ }
632
+ }
633
+ IrInstruction::UnaryOp(IrUnaryOp::Neg, dst, src)
634
+ if reg_types[src.0] == IrType::I64
635
+ && reg_types[dst.0] == IrType::I64 =>
636
+ {
637
+ let t_not = alloc_i64(reg_types);
638
+ let t_one = alloc_i64(reg_types);
639
+ out.push(IrInstruction::UnaryOp(IrUnaryOp::BitNot, t_not, *src));
640
+ out.push(IrInstruction::LoadConst(t_one, Constant::Int(1)));
641
+ out.push(IrInstruction::BinOp(IrBinOp::Add, *dst, t_not, t_one));
642
+ }
643
+ _ => out.push(instr.clone()),
644
+ }
645
+ }
646
+ bb.instructions = out;
647
+ }
648
+ }
649
+ /// Splits basic blocks with >2 instructions into 2-instruction chunks linked by `Jump`.
650
+ fn split_blocks_into_microchunks(func: &mut IrFunction) {
651
+ let orig = std::mem::take(&mut func.blocks);
652
+ let mut chunk_groups: Vec<Vec<Vec<IrInstruction>>> = Vec::with_capacity(orig.len());
653
+ let mut old_to_first_new = Vec::with_capacity(orig.len());
654
+ let mut next_id = 0usize;
655
+
656
+ for bb in orig {
657
+ old_to_first_new.push(BasicBlockId(next_id));
658
+ if bb.instructions.len() <= 2 {
659
+ chunk_groups.push(vec![bb.instructions]);
660
+ next_id += 1;
661
+ } else {
662
+ let mut chunks: Vec<Vec<IrInstruction>> = bb
663
+ .instructions
664
+ .chunks(2)
665
+ .map(|c| c.to_vec())
666
+ .collect();
667
+ // Avoid isolating a single terminator in a trailing 1-instr chunk if avoidable
668
+ if chunks.len() >= 2 && chunks.last().is_some_and(|c| c.len() == 1) {
669
+ let last = chunks.pop().unwrap();
670
+ chunks.last_mut().unwrap().extend(last);
671
+ }
672
+ next_id += chunks.len();
673
+ chunk_groups.push(chunks);
674
+ }
675
+ }
676
+
677
+ let mut out_blocks = Vec::with_capacity(next_id);
678
+ for chunks in chunk_groups {
679
+ let count = chunks.len();
680
+ for (c_idx, mut ins) in chunks.into_iter().enumerate() {
681
+ let my_id = BasicBlockId(out_blocks.len());
682
+ for instr in &mut ins {
683
+ match instr {
684
+ IrInstruction::Jump(t) => *t = old_to_first_new[t.0],
685
+ IrInstruction::BranchIf(_, a, b) => {
686
+ *a = old_to_first_new[a.0];
687
+ *b = old_to_first_new[b.0];
688
+ }
689
+ _ => {}
690
+ }
691
+ }
692
+ if c_idx + 1 < count {
693
+ ins.push(IrInstruction::Jump(BasicBlockId(my_id.0 + 1)));
694
+ }
695
+ out_blocks.push(BasicBlock {
696
+ id: my_id,
697
+ instructions: ins,
698
+ });
699
+ }
700
+ }
701
+ func.blocks = out_blocks;
702
+ }
703
+
704
+ pub fn save_bundle_file(
705
+ path: &Path,
706
+ bundle: &IrBundle,
707
+ opts: &SaveOptions,
708
+ ) -> Result<(), PolyError> {
709
+ let bytes = encode_container(bundle, opts)?;
710
+ if let Some(parent) = path.parent()
711
+ && !parent.as_os_str().is_empty()
712
+ {
713
+ std::fs::create_dir_all(parent)?;
714
+ }
715
+ std::fs::write(path, bytes)?;
716
+ Ok(())
717
+ }
718
+
719
+ pub fn sign_plain_ir_file(
720
+ input: &Path,
721
+ output: Option<&Path>,
722
+ signing_key: Option<[u8; 32]>,
723
+ ) -> Result<(), PolyError> {
724
+ let (bundle, _) = load_bundle_file_with_options(input, None, None, true)?;
725
+ let out_path = output.unwrap_or(input);
726
+ save_bundle_file(
727
+ out_path,
728
+ &bundle,
729
+ &SaveOptions {
730
+ obfuscate: false,
731
+ secret_key: None,
732
+ signing_key,
733
+ },
734
+ )
735
+ }
736
+
737
+ pub fn encode_container(bundle: &IrBundle, opts: &SaveOptions) -> Result<Vec<u8>, PolyError> {
738
+ let armored_mode = opts.obfuscate || opts.secret_key.is_some();
739
+
740
+ let mut work_bundle = bundle.clone();
741
+ if opts.obfuscate {
742
+ obfuscate_bundle(&mut work_bundle)?;
743
+ }
744
+
745
+ let mut salt = [0u8; 16];
746
+ getrandom::getrandom(&mut salt)
747
+ .map_err(|e| PolyError::msg("E0702", format!("CSPRNG error: {e}")))?;
748
+
749
+ let signing_key = resolve_signing_key(opts.signing_key);
750
+ let verifying_key = signing_key.verifying_key();
751
+ let pubkey_bytes = verifying_key.as_bytes();
752
+
753
+ if !armored_mode {
754
+ let flags = 0u8;
755
+ let origin_fp = compute_origin_fingerprint(pubkey_bytes, flags, &salt);
756
+ let ir_body = format_ir_body(&work_bundle);
757
+ let meta = format_plain_meta(&work_bundle, &salt, pubkey_bytes, &origin_fp);
758
+
759
+ let mut sig_msg = Vec::with_capacity(VERIFY_DOMAIN.len() + meta.len() + ir_body.len());
760
+ sig_msg.extend_from_slice(VERIFY_DOMAIN);
761
+ sig_msg.extend_from_slice(meta.as_bytes());
762
+ sig_msg.extend_from_slice(ir_body.as_bytes());
763
+ let sig = signing_key.sign(&sig_msg);
764
+
765
+ let text = format!(
766
+ "{PLAIN_BANNER}\n\
767
+ ; format: POLYIR03\n\
768
+ ; version: {FORMAT_VERSION}\n\
769
+ ; entry: {} {}\n\
770
+ ; inits: {}\n\
771
+ ; exports: {}\n\
772
+ ; salt: {}\n\
773
+ ; signer: {}\n\
774
+ ; origin: {}\n\
775
+ ; signature: {}\n\
776
+ {PLAIN_BEGIN_IR}\n\
777
+ {ir_body}\
778
+ {PLAIN_END_IR}\n",
779
+ work_bundle.entry_fn.0,
780
+ escape_str(&work_bundle.entry_name),
781
+ format_fn_id_list(&work_bundle.init_fns),
782
+ format_exports_list(&work_bundle.exports),
783
+ encode_hex(&salt),
784
+ encode_hex(pubkey_bytes),
785
+ encode_hex(&origin_fp),
786
+ encode_hex(&sig.to_bytes()),
787
+ );
788
+ return Ok(text.into_bytes());
789
+ }
790
+
791
+ // Pure UTF-8 Armored Container (POLYX003) — keyless (`vm-sealed`) OR key-locked
792
+ let mut nonce = [0u8; 24];
793
+ getrandom::getrandom(&mut nonce)
794
+ .map_err(|e| PolyError::msg("E0702", format!("CSPRNG error: {e}")))?;
795
+
796
+ let flags = FLAG_ENCRYPTED | if opts.obfuscate { FLAG_OBFUSCATED } else { 0 };
797
+ let (_kdf_mode, kdf_name, aead_key) = match &opts.secret_key {
798
+ None => (
799
+ KDF_VM_SEALED,
800
+ "vm-sealed",
801
+ derive_vm_sealed_key(&salt, &nonce, pubkey_bytes),
802
+ ),
803
+ Some(secret @ SecretKeyMaterial::Passphrase(_)) => (
804
+ KDF_ARGON2ID,
805
+ "argon2id",
806
+ derive_aead_key(secret, KDF_ARGON2ID, &salt)?,
807
+ ),
808
+ Some(secret @ SecretKeyMaterial::Raw32(_)) => (
809
+ KDF_RAW_BLAKE3,
810
+ "blake3-raw",
811
+ derive_aead_key(secret, KDF_RAW_BLAKE3, &salt)?,
812
+ ),
813
+ };
814
+
815
+ let origin_fp = compute_origin_fingerprint(pubkey_bytes, flags, &salt);
816
+ let canonical_header = format!(
817
+ "Format: POLYX003\n\
818
+ Version: {FORMAT_VERSION}\n\
819
+ Obfuscated: {}\n\
820
+ Encrypted: true\n\
821
+ KDF: {kdf_name}\n\
822
+ Signer: {}\n\
823
+ Origin: {}\n\
824
+ Salt: {}\n\
825
+ Nonce: {}\n\
826
+ Payload-Encoding: base64",
827
+ opts.obfuscate,
828
+ encode_hex(pubkey_bytes),
829
+ encode_hex(&origin_fp),
830
+ encode_hex(&salt),
831
+ encode_hex(&nonce),
832
+ );
833
+
834
+ let inner_vm_bytes = serialize_permuted_bytecode(&work_bundle, &salt, &nonce)?;
835
+
836
+ let cipher = XChaCha20Poly1305::new((&aead_key).into());
837
+ let ciphertext = cipher
838
+ .encrypt(
839
+ XNonce::from_slice(&nonce),
840
+ Payload {
841
+ msg: &inner_vm_bytes,
842
+ aad: canonical_header.as_bytes(),
843
+ },
844
+ )
845
+ .map_err(|_| PolyError::msg("E0705", "XChaCha20-Poly1305 sealing failed"))?;
846
+
847
+ let mut sig_msg =
848
+ Vec::with_capacity(VERIFY_DOMAIN.len() + canonical_header.len() + 2 + ciphertext.len());
849
+ sig_msg.extend_from_slice(VERIFY_DOMAIN);
850
+ sig_msg.extend_from_slice(canonical_header.as_bytes());
851
+ sig_msg.extend_from_slice(b"\n\n");
852
+ sig_msg.extend_from_slice(&ciphertext);
853
+ let signature = signing_key.sign(&sig_msg);
854
+
855
+ let b64_wrapped = base64_encode_wrapped(&ciphertext, 76);
856
+ let armored = format!(
857
+ "{ARMOR_BEGIN}\n\
858
+ {canonical_header}\n\n\
859
+ {b64_wrapped}\n\
860
+ {ARMOR_END}\n\
861
+ Signature: {}\n",
862
+ encode_hex(&signature.to_bytes())
863
+ );
864
+ Ok(armored.into_bytes())
865
+ }
866
+
867
+ pub fn verify_container_bytes(
868
+ bytes: &[u8],
869
+ pinned_pubkey: Option<[u8; 32]>,
870
+ ) -> Result<VerifyReport, PolyError> {
871
+ let raw_str = std::str::from_utf8(bytes).map_err(|_| {
872
+ PolyError::msg(
873
+ "E0707",
874
+ "container is not valid UTF-8 text (expected POLYIR03 or POLYX003 UTF-8 format)",
875
+ )
876
+ })?;
877
+ let norm = normalize_utf8_text(raw_str);
878
+ let trimmed = norm.trim_start();
879
+
880
+ if trimmed.starts_with(ARMOR_BEGIN) {
881
+ let parsed = parse_armored_polyx(&norm)?;
882
+ verify_signature_and_pin(
883
+ &parsed.pubkey_bytes,
884
+ parsed.flags,
885
+ &parsed.salt,
886
+ &parsed.origin_fp,
887
+ &parsed.sig_bytes,
888
+ &parsed.sig_msg,
889
+ pinned_pubkey,
890
+ )?;
891
+ let match_flag = resolve_effective_pin(pinned_pubkey).map(|_| true);
892
+ Ok(VerifyReport {
893
+ format: "POLYX003",
894
+ version: FORMAT_VERSION,
895
+ encrypted: true,
896
+ obfuscated: parsed.obfuscated,
897
+ signed: true,
898
+ keyless: parsed.kdf_mode == KDF_VM_SEALED,
899
+ signer_pubkey_hex: encode_hex(&parsed.pubkey_bytes),
900
+ pinned_publisher_match: match_flag,
901
+ payload_bytes: parsed.ciphertext.len(),
902
+ })
903
+ } else if trimmed.starts_with(PLAIN_BANNER) || trimmed.starts_with(PLAIN_BEGIN_IR) {
904
+ let parsed = parse_plain_polyir_envelope(&norm)?;
905
+ let Some(sig_info) = &parsed.sig_info else {
906
+ return Err(PolyError::msg(
907
+ "E0712",
908
+ "Part 1 Verifier failed: unsigned .polyir container (sign with `polycomp sign` or pass `--allow-unsigned` to `run`)",
909
+ ));
910
+ };
911
+ let meta = format_plain_meta(
912
+ &parsed.bundle,
913
+ &sig_info.salt,
914
+ &sig_info.pubkey_bytes,
915
+ &sig_info.origin_fp,
916
+ );
917
+ let mut sig_msg =
918
+ Vec::with_capacity(VERIFY_DOMAIN.len() + meta.len() + parsed.ir_body.len());
919
+ sig_msg.extend_from_slice(VERIFY_DOMAIN);
920
+ sig_msg.extend_from_slice(meta.as_bytes());
921
+ sig_msg.extend_from_slice(parsed.ir_body.as_bytes());
922
+
923
+ verify_signature_and_pin(
924
+ &sig_info.pubkey_bytes,
925
+ 0,
926
+ &sig_info.salt,
927
+ &sig_info.origin_fp,
928
+ &sig_info.sig_bytes,
929
+ &sig_msg,
930
+ pinned_pubkey,
931
+ )?;
932
+ let match_flag = resolve_effective_pin(pinned_pubkey).map(|_| true);
933
+ Ok(VerifyReport {
934
+ format: "POLYIR03",
935
+ version: FORMAT_VERSION,
936
+ encrypted: false,
937
+ obfuscated: false,
938
+ signed: true,
939
+ keyless: true,
940
+ signer_pubkey_hex: encode_hex(&sig_info.pubkey_bytes),
941
+ pinned_publisher_match: match_flag,
942
+ payload_bytes: parsed.ir_body.len(),
943
+ })
944
+ } else {
945
+ Err(PolyError::msg(
946
+ "E0707",
947
+ "unrecognized PolyComp UTF-8 container header (expected POLYIR03 or POLYX003)",
948
+ ))
949
+ }
950
+ }
951
+
952
+ pub fn verify_bundle_file(
953
+ path: &Path,
954
+ pinned_pubkey: Option<[u8; 32]>,
955
+ ) -> Result<VerifyReport, PolyError> {
956
+ let bytes = std::fs::read(path)?;
957
+ verify_container_bytes(&bytes, pinned_pubkey)
958
+ }
959
+
960
+ pub fn decode_container_bytes(
961
+ bytes: &[u8],
962
+ secret_key: Option<&SecretKeyMaterial>,
963
+ pinned_pubkey: Option<[u8; 32]>,
964
+ ) -> Result<(IrBundle, VerifyReport), PolyError> {
965
+ decode_container_bytes_opts(bytes, secret_key, pinned_pubkey, false)
966
+ }
967
+
968
+ pub fn decode_container_bytes_opts(
969
+ bytes: &[u8],
970
+ secret_key: Option<&SecretKeyMaterial>,
971
+ pinned_pubkey: Option<[u8; 32]>,
972
+ allow_unsigned: bool,
973
+ ) -> Result<(IrBundle, VerifyReport), PolyError> {
974
+ let raw_str = std::str::from_utf8(bytes).map_err(|_| {
975
+ PolyError::msg(
976
+ "E0707",
977
+ "container is not valid UTF-8 text (expected POLYIR03 or POLYX003 UTF-8 format)",
978
+ )
979
+ })?;
980
+ let norm = normalize_utf8_text(raw_str);
981
+ let trimmed = norm.trim_start();
982
+
983
+ if trimmed.starts_with(ARMOR_BEGIN) {
984
+ let report = verify_container_bytes(bytes, pinned_pubkey)?;
985
+ let parsed = parse_armored_polyx(&norm)?;
986
+
987
+ let aead_key = if parsed.kdf_mode == KDF_VM_SEALED {
988
+ derive_vm_sealed_key(&parsed.salt, &parsed.nonce, &parsed.pubkey_bytes)
989
+ } else {
990
+ let key_mat = secret_key.ok_or_else(|| {
991
+ PolyError::msg(
992
+ "E0713",
993
+ "Part 2 Decryption failed: key-locked .polyx requires --key, --keyfile, or POLYCOMP_KEY",
994
+ )
995
+ })?;
996
+ derive_aead_key(key_mat, parsed.kdf_mode, &parsed.salt)?
997
+ };
998
+
999
+ let cipher = XChaCha20Poly1305::new((&aead_key).into());
1000
+ let plaintext = cipher
1001
+ .decrypt(
1002
+ XNonce::from_slice(&parsed.nonce),
1003
+ Payload {
1004
+ msg: &parsed.ciphertext,
1005
+ aad: parsed.canonical_header.as_bytes(),
1006
+ },
1007
+ )
1008
+ .map_err(|_| {
1009
+ PolyError::msg(
1010
+ "E0714",
1011
+ "Part 2 Decryption failed: wrong decryption key or corrupted payload",
1012
+ )
1013
+ })?;
1014
+
1015
+ let bundle = deserialize_permuted_bytecode(&plaintext, &parsed.salt, &parsed.nonce)?;
1016
+ Ok((bundle, report))
1017
+ } else if trimmed.starts_with(PLAIN_BANNER) || trimmed.starts_with(PLAIN_BEGIN_IR) {
1018
+ let parsed = parse_plain_polyir_envelope(&norm)?;
1019
+ if parsed.sig_info.is_none() && allow_unsigned {
1020
+ let report = VerifyReport {
1021
+ format: "POLYIR03",
1022
+ version: FORMAT_VERSION,
1023
+ encrypted: false,
1024
+ obfuscated: false,
1025
+ signed: false,
1026
+ keyless: true,
1027
+ signer_pubkey_hex: "unsigned".to_string(),
1028
+ pinned_publisher_match: None,
1029
+ payload_bytes: parsed.ir_body.len(),
1030
+ };
1031
+ return Ok((parsed.bundle, report));
1032
+ }
1033
+ let report = verify_container_bytes(bytes, pinned_pubkey)?;
1034
+ Ok((parsed.bundle, report))
1035
+ } else {
1036
+ Err(PolyError::msg(
1037
+ "E0707",
1038
+ "unrecognized PolyComp UTF-8 container header",
1039
+ ))
1040
+ }
1041
+ }
1042
+
1043
+ pub fn load_bundle_file(
1044
+ path: &Path,
1045
+ secret_key: Option<&SecretKeyMaterial>,
1046
+ pinned_pubkey: Option<[u8; 32]>,
1047
+ ) -> Result<(IrBundle, VerifyReport), PolyError> {
1048
+ load_bundle_file_with_options(path, secret_key, pinned_pubkey, false)
1049
+ }
1050
+
1051
+ pub fn load_bundle_file_with_options(
1052
+ path: &Path,
1053
+ secret_key: Option<&SecretKeyMaterial>,
1054
+ pinned_pubkey: Option<[u8; 32]>,
1055
+ allow_unsigned: bool,
1056
+ ) -> Result<(IrBundle, VerifyReport), PolyError> {
1057
+ let bytes = std::fs::read(path)?;
1058
+ decode_container_bytes_opts(&bytes, secret_key, pinned_pubkey, allow_unsigned)
1059
+ }
1060
+
1061
+ fn resolve_signing_key(explicit: Option<[u8; 32]>) -> SigningKey {
1062
+ let seed = explicit.unwrap_or_else(|| {
1063
+ if let Ok(env_s) = std::env::var("POLYCOMP_SIGN_KEY")
1064
+ && let Ok(k) = load_key_32_from_arg_or_file(&env_s)
1065
+ {
1066
+ return k;
1067
+ }
1068
+ if let Some(build_s) = option_env!("POLYCOMP_BUILD_SIGN_KEY")
1069
+ && let Some(k) = decode_hex_32(build_s.trim())
1070
+ {
1071
+ return k;
1072
+ }
1073
+ DEFAULT_TOOLCHAIN_SIGN_SEED
1074
+ });
1075
+ SigningKey::from_bytes(&seed)
1076
+ }
1077
+
1078
+ fn resolve_effective_pin(pinned_pubkey: Option<[u8; 32]>) -> Option<[u8; 32]> {
1079
+ pinned_pubkey.or_else(|| {
1080
+ std::env::var("POLYCOMP_VERIFY_KEY")
1081
+ .ok()
1082
+ .and_then(|s| load_key_32_from_arg_or_file(&s).ok())
1083
+ .or_else(|| {
1084
+ option_env!("POLYCOMP_TRUSTED_PUBKEY")
1085
+ .and_then(|s| decode_hex_32(s.trim()))
1086
+ })
1087
+ })
1088
+ }
1089
+
1090
+ fn verify_signature_and_pin(
1091
+ pubkey_bytes: &[u8; 32],
1092
+ flags: u8,
1093
+ salt: &[u8; 16],
1094
+ origin_fp: &[u8; 32],
1095
+ sig_bytes: &[u8; 64],
1096
+ sig_msg: &[u8],
1097
+ pinned_pubkey: Option<[u8; 32]>,
1098
+ ) -> Result<(), PolyError> {
1099
+ let expected_fp = compute_origin_fingerprint(pubkey_bytes, flags, salt);
1100
+ if origin_fp != &expected_fp {
1101
+ return Err(PolyError::msg(
1102
+ "E0709",
1103
+ "Part 1 Verifier failed: invalid PolyComp origin fingerprint",
1104
+ ));
1105
+ }
1106
+
1107
+ let verifying_key = VerifyingKey::from_bytes(pubkey_bytes).map_err(|_| {
1108
+ PolyError::msg("E0710", "Part 1 Verifier failed: malformed Ed25519 public key")
1109
+ })?;
1110
+ if verifying_key.is_weak() {
1111
+ return Err(PolyError::msg(
1112
+ "E0710",
1113
+ "Part 1 Verifier failed: weak Ed25519 public key rejected",
1114
+ ));
1115
+ }
1116
+
1117
+ if let Some(pinned) = resolve_effective_pin(pinned_pubkey)
1118
+ && pubkey_bytes != &pinned
1119
+ {
1120
+ return Err(PolyError::msg(
1121
+ "E0711",
1122
+ "Part 1 Verifier failed: artifact signer does not match pinned publisher public key",
1123
+ ));
1124
+ }
1125
+
1126
+ let signature = Signature::from_bytes(sig_bytes);
1127
+ verifying_key.verify_strict(sig_msg, &signature).map_err(|_| {
1128
+ PolyError::msg(
1129
+ "E0712",
1130
+ "Part 1 Verifier failed: Ed25519 signature invalid (tampered or forged artifact)",
1131
+ )
1132
+ })?;
1133
+
1134
+ Ok(())
1135
+ }
1136
+
1137
+ fn normalize_utf8_text(s: &str) -> String {
1138
+ let s = s.strip_prefix('\u{feff}').unwrap_or(s);
1139
+ s.replace("\r\n", "\n").replace('\r', "\n")
1140
+ }
1141
+
1142
+ fn compute_origin_fingerprint(pubkey: &[u8; 32], flags: u8, salt: &[u8; 16]) -> [u8; 32] {
1143
+ let mut h = blake3::Hasher::new_derive_key("polycomp-origin-fingerprint-v3");
1144
+ h.update(pubkey);
1145
+ h.update(&[flags]);
1146
+ h.update(salt);
1147
+ h.finalize().into()
1148
+ }
1149
+
1150
+ /// Multi-round ARX + BLAKE3 whitebox key schedule for keyless VM-sealed payloads.
1151
+ fn derive_vm_sealed_key(salt: &[u8; 16], nonce: &[u8; 24], pubkey: &[u8; 32]) -> [u8; 32] {
1152
+ let mut state: [u64; 4] = [0; 4];
1153
+ for (i, slot) in state.iter_mut().enumerate() {
1154
+ *slot = u64::from_le_bytes(VM_SEAL_MIX[i * 8..i * 8 + 8].try_into().unwrap())
1155
+ ^ u64::from_le_bytes(pubkey[i * 8..i * 8 + 8].try_into().unwrap());
1156
+ }
1157
+ let s0 = u64::from_le_bytes(salt[0..8].try_into().unwrap());
1158
+ let s1 = u64::from_le_bytes(salt[8..16].try_into().unwrap());
1159
+ let n0 = u64::from_le_bytes(nonce[0..8].try_into().unwrap());
1160
+ let n1 = u64::from_le_bytes(nonce[8..16].try_into().unwrap());
1161
+ let n2 = u64::from_le_bytes(nonce[16..24].try_into().unwrap());
1162
+
1163
+ state[0] ^= s0;
1164
+ state[1] ^= s1.wrapping_add(n0);
1165
+ state[2] ^= n1;
1166
+ state[3] ^= n2.rotate_left(17);
1167
+
1168
+ for round in 0..16u64 {
1169
+ state[0] = state[0]
1170
+ .wrapping_add(state[1])
1171
+ .wrapping_add(round.wrapping_mul(0x9e37_79b9_7f4a_7c15));
1172
+ state[3] = (state[3] ^ state[0]).rotate_left(23);
1173
+ state[2] = state[2].wrapping_add(state[3]);
1174
+ state[1] = (state[1] ^ state[2]).rotate_left(13);
1175
+ state[0] = state[0].wrapping_mul(0xbf58_476d_1ce4_e5b9);
1176
+ state.rotate_left(1);
1177
+ }
1178
+
1179
+ let mut mix_bytes = [0u8; 32];
1180
+ for (i, &w) in state.iter().enumerate() {
1181
+ mix_bytes[i * 8..i * 8 + 8].copy_from_slice(&w.to_le_bytes());
1182
+ }
1183
+ let mut h = blake3::Hasher::new_derive_key("polycomp-v4-vm-sealed-stream");
1184
+ h.update(&mix_bytes);
1185
+ h.update(salt);
1186
+ h.update(nonce);
1187
+ h.update(pubkey);
1188
+ h.finalize().into()
1189
+ }
1190
+
1191
+ fn derive_aead_key(
1192
+ secret: &SecretKeyMaterial,
1193
+ kdf_mode: u8,
1194
+ salt: &[u8; 16],
1195
+ ) -> Result<[u8; 32], PolyError> {
1196
+ match (secret, kdf_mode) {
1197
+ (SecretKeyMaterial::Raw32(raw), _) => {
1198
+ let mut h = blake3::Hasher::new_derive_key("polycomp-v3-xchacha20-raw");
1199
+ h.update(raw);
1200
+ h.update(salt);
1201
+ Ok(h.finalize().into())
1202
+ }
1203
+ (SecretKeyMaterial::Passphrase(pass), KDF_ARGON2ID) => {
1204
+ let params = argon2::Params::new(16 * 1024, 2, 1, Some(32))
1205
+ .map_err(|e| PolyError::msg("E0715", format!("Argon2 param error: {e}")))?;
1206
+ let a2 = argon2::Argon2::new(
1207
+ argon2::Algorithm::Argon2id,
1208
+ argon2::Version::V0x13,
1209
+ params,
1210
+ );
1211
+ let mut key = [0u8; 32];
1212
+ a2.hash_password_into(pass.as_bytes(), salt, &mut key)
1213
+ .map_err(|e| PolyError::msg("E0715", format!("Argon2 KDF error: {e}")))?;
1214
+ Ok(key)
1215
+ }
1216
+ (SecretKeyMaterial::Passphrase(pass), KDF_RAW_BLAKE3) => {
1217
+ if let Some(raw) = decode_hex_32(pass.trim()) {
1218
+ let mut h = blake3::Hasher::new_derive_key("polycomp-v3-xchacha20-raw");
1219
+ h.update(&raw);
1220
+ h.update(salt);
1221
+ Ok(h.finalize().into())
1222
+ } else {
1223
+ Err(PolyError::msg(
1224
+ "E0714",
1225
+ "Part 2 Decryption failed: artifact expects a 32-byte hex key",
1226
+ ))
1227
+ }
1228
+ }
1229
+ _ => Err(PolyError::msg("E0715", "unsupported KDF mode")),
1230
+ }
1231
+ }
1232
+
1233
+ // ============================================================================
1234
+ // Rolling Stream-Whitened + Opcode-Permuted VM Bytecode + Chaff + Decoy Strings
1235
+ // ============================================================================
1236
+
1237
+ struct OpcodeSbox {
1238
+ enc: [u8; 256],
1239
+ dec: [u8; 256],
1240
+ }
1241
+
1242
+ impl OpcodeSbox {
1243
+ fn from_seed(salt: &[u8; 16], nonce: &[u8; 24]) -> Self {
1244
+ let mut h = blake3::Hasher::new_derive_key("polycomp-vm-opcode-sbox-v4");
1245
+ h.update(&VM_SEAL_MIX);
1246
+ h.update(salt);
1247
+ h.update(nonce);
1248
+ let mut xof = h.finalize_xof();
1249
+ let mut rand_bytes = [0u8; 512];
1250
+ xof.fill(&mut rand_bytes);
1251
+
1252
+ let mut enc: [u8; 256] = core::array::from_fn(|i| i as u8);
1253
+ for i in (1..256).rev() {
1254
+ let r = u16::from_le_bytes([rand_bytes[i * 2], rand_bytes[i * 2 + 1]]) as usize;
1255
+ let j = r % (i + 1);
1256
+ enc.swap(i, j);
1257
+ }
1258
+ let mut dec = [0u8; 256];
1259
+ for (plain, &cipher) in enc.iter().enumerate() {
1260
+ dec[cipher as usize] = plain as u8;
1261
+ }
1262
+ Self { enc, dec }
1263
+ }
1264
+ }
1265
+
1266
+ fn splitmix64_next(state: &mut u64) -> u64 {
1267
+ *state = state.wrapping_add(0x9e37_79b9_7f4a_7c15);
1268
+ let mut z = *state;
1269
+ z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
1270
+ z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
1271
+ z ^ (z >> 31)
1272
+ }
1273
+
1274
+ fn initial_stream_state(salt: &[u8; 16], nonce: &[u8; 24]) -> u64 {
1275
+ let mut h = blake3::Hasher::new_derive_key("polycomp-vm-rolling-whitener-v4");
1276
+ h.update(&VM_SEAL_MIX);
1277
+ h.update(salt);
1278
+ h.update(nonce);
1279
+ let digest = h.finalize();
1280
+ u64::from_le_bytes(digest.as_bytes()[..8].try_into().unwrap())
1281
+ }
1282
+
1283
+ fn mask_string_bytes(data: &[u8], salt: &[u8; 16], nonce: &[u8; 24], str_idx: u32) -> Vec<u8> {
1284
+ let mut h = blake3::Hasher::new_derive_key("polycomp-str-mask-v4");
1285
+ h.update(&VM_SEAL_MIX);
1286
+ h.update(salt);
1287
+ h.update(nonce);
1288
+ h.update(&str_idx.to_le_bytes());
1289
+ let mut xof = h.finalize_xof();
1290
+ let mut mask = vec![0u8; data.len()];
1291
+ xof.fill(&mut mask);
1292
+ data.iter().zip(mask.iter()).map(|(a, b)| a ^ b).collect()
1293
+ }
1294
+
1295
+ struct PermBinWriter {
1296
+ buf: Vec<u8>,
1297
+ sbox: OpcodeSbox,
1298
+ salt: [u8; 16],
1299
+ nonce: [u8; 24],
1300
+ stream_state: u64,
1301
+ str_counter: u32,
1302
+ }
1303
+
1304
+ impl PermBinWriter {
1305
+ fn new(salt: [u8; 16], nonce: [u8; 24]) -> Self {
1306
+ Self {
1307
+ buf: Vec::with_capacity(2048),
1308
+ sbox: OpcodeSbox::from_seed(&salt, &nonce),
1309
+ salt,
1310
+ nonce,
1311
+ stream_state: initial_stream_state(&salt, &nonce),
1312
+ str_counter: 0,
1313
+ }
1314
+ }
1315
+ fn op(&mut self, tag: u8) {
1316
+ self.buf.push(self.sbox.enc[tag as usize]);
1317
+ }
1318
+ fn u8(&mut self, v: u8) {
1319
+ let m = splitmix64_next(&mut self.stream_state) as u8;
1320
+ self.buf.push(v ^ m);
1321
+ }
1322
+ fn u32(&mut self, v: u32) {
1323
+ let m = splitmix64_next(&mut self.stream_state) as u32;
1324
+ self.buf.extend_from_slice(&(v ^ m).to_le_bytes());
1325
+ }
1326
+ fn i64(&mut self, v: i64) {
1327
+ let m = splitmix64_next(&mut self.stream_state);
1328
+ self.buf.extend_from_slice(&((v as u64) ^ m).to_le_bytes());
1329
+ }
1330
+ fn f64(&mut self, v: f64) {
1331
+ let m = splitmix64_next(&mut self.stream_state);
1332
+ self.buf.extend_from_slice(&(v.to_bits() ^ m).to_le_bytes());
1333
+ }
1334
+ fn str(&mut self, s: &str) -> Result<(), PolyError> {
1335
+ let bytes = s.as_bytes();
1336
+ // Interleave random-length decoy padding inside each string record
1337
+ let mut pad_byte = [0u8; 1];
1338
+ getrandom::getrandom(&mut pad_byte)
1339
+ .map_err(|e| PolyError::msg("E0702", format!("CSPRNG error: {e}")))?;
1340
+ let pad_len = (pad_byte[0] as usize % 13) + 3;
1341
+ let mut pad = vec![0u8; pad_len];
1342
+ getrandom::getrandom(&mut pad)
1343
+ .map_err(|e| PolyError::msg("E0702", format!("CSPRNG error: {e}")))?;
1344
+ self.u32(bytes.len() as u32);
1345
+ self.u8(pad_len as u8);
1346
+ self.buf.extend_from_slice(&pad);
1347
+ let masked = mask_string_bytes(bytes, &self.salt, &self.nonce, self.str_counter);
1348
+ self.str_counter = self.str_counter.wrapping_add(1);
1349
+ self.buf.extend_from_slice(&masked);
1350
+ Ok(())
1351
+ }
1352
+ }
1353
+
1354
+ struct PermBinReader<'a> {
1355
+ data: &'a [u8],
1356
+ pos: usize,
1357
+ sbox: OpcodeSbox,
1358
+ salt: [u8; 16],
1359
+ nonce: [u8; 24],
1360
+ stream_state: u64,
1361
+ str_counter: u32,
1362
+ }
1363
+
1364
+ impl<'a> PermBinReader<'a> {
1365
+ fn new(data: &'a [u8], salt: [u8; 16], nonce: [u8; 24]) -> Self {
1366
+ Self {
1367
+ data,
1368
+ pos: 0,
1369
+ sbox: OpcodeSbox::from_seed(&salt, &nonce),
1370
+ salt,
1371
+ nonce,
1372
+ stream_state: initial_stream_state(&salt, &nonce),
1373
+ str_counter: 0,
1374
+ }
1375
+ }
1376
+ fn take(&mut self, n: usize) -> Result<&'a [u8], PolyError> {
1377
+ let end = self
1378
+ .pos
1379
+ .checked_add(n)
1380
+ .filter(|&e| e <= self.data.len())
1381
+ .ok_or_else(|| PolyError::msg("E0716", "unexpected EOF in VM bytecode"))?;
1382
+ let s = &self.data[self.pos..end];
1383
+ self.pos = end;
1384
+ Ok(s)
1385
+ }
1386
+ fn op(&mut self) -> Result<u8, PolyError> {
1387
+ let raw = self.take(1)?[0];
1388
+ Ok(self.sbox.dec[raw as usize])
1389
+ }
1390
+ fn u8(&mut self) -> Result<u8, PolyError> {
1391
+ let raw = self.take(1)?[0];
1392
+ let m = splitmix64_next(&mut self.stream_state) as u8;
1393
+ Ok(raw ^ m)
1394
+ }
1395
+ fn u32(&mut self) -> Result<u32, PolyError> {
1396
+ let raw = u32::from_le_bytes(self.take(4)?.try_into().unwrap());
1397
+ let m = splitmix64_next(&mut self.stream_state) as u32;
1398
+ Ok(raw ^ m)
1399
+ }
1400
+ fn i64(&mut self) -> Result<i64, PolyError> {
1401
+ let raw = u64::from_le_bytes(self.take(8)?.try_into().unwrap());
1402
+ let m = splitmix64_next(&mut self.stream_state);
1403
+ Ok((raw ^ m) as i64)
1404
+ }
1405
+ fn f64(&mut self) -> Result<f64, PolyError> {
1406
+ let raw = u64::from_le_bytes(self.take(8)?.try_into().unwrap());
1407
+ let m = splitmix64_next(&mut self.stream_state);
1408
+ Ok(f64::from_bits(raw ^ m))
1409
+ }
1410
+ fn str(&mut self) -> Result<String, PolyError> {
1411
+ let len = self.u32()? as usize;
1412
+ let pad_len = self.u8()? as usize;
1413
+ let _ = self.take(pad_len)?;
1414
+ let raw = self.take(len)?;
1415
+ let decoded = mask_string_bytes(raw, &self.salt, &self.nonce, self.str_counter);
1416
+ self.str_counter = self.str_counter.wrapping_add(1);
1417
+ String::from_utf8(decoded)
1418
+ .map_err(|_| PolyError::msg("E0716", "invalid UTF-8 string in VM bytecode"))
1419
+ }
1420
+ }
1421
+
1422
+ fn serialize_permuted_bytecode(
1423
+ bundle: &IrBundle,
1424
+ salt: &[u8; 16],
1425
+ nonce: &[u8; 24],
1426
+ ) -> Result<Vec<u8>, PolyError> {
1427
+ let mut w = PermBinWriter::new(*salt, *nonce);
1428
+
1429
+ // Random-length leading chaff padding
1430
+ let mut chaff_rng = [0u8; 2];
1431
+ getrandom::getrandom(&mut chaff_rng)
1432
+ .map_err(|e| PolyError::msg("E0702", format!("CSPRNG error: {e}")))?;
1433
+ let head_chaff = ((chaff_rng[0] as usize) % 64) + 24;
1434
+ let tail_chaff = ((chaff_rng[1] as usize) % 64) + 24;
1435
+ let mut head_bytes = vec![0u8; head_chaff];
1436
+ let mut tail_bytes = vec![0u8; tail_chaff];
1437
+ getrandom::getrandom(&mut head_bytes)
1438
+ .map_err(|e| PolyError::msg("E0702", format!("CSPRNG error: {e}")))?;
1439
+ getrandom::getrandom(&mut tail_bytes)
1440
+ .map_err(|e| PolyError::msg("E0702", format!("CSPRNG error: {e}")))?;
1441
+
1442
+ w.op(head_chaff as u8);
1443
+ w.buf.extend_from_slice(&head_bytes);
1444
+
1445
+ w.u32(bundle.entry_fn.0);
1446
+ w.str(&bundle.entry_name)?;
1447
+
1448
+ w.u32(bundle.init_fns.len() as u32);
1449
+ for id in &bundle.init_fns {
1450
+ w.u32(id.0);
1451
+ }
1452
+
1453
+ w.u32(bundle.exports.len() as u32);
1454
+ for (name, id) in &bundle.exports {
1455
+ w.str(name)?;
1456
+ w.u32(id.0);
1457
+ }
1458
+
1459
+ w.u32(bundle.functions.len() as u32);
1460
+ for f in &bundle.functions {
1461
+ w.u32(f.id.0);
1462
+ w.u32(f.module_id as u32);
1463
+ w.str(&f.qualified_name)?;
1464
+
1465
+ w.u32(f.params.len() as u32);
1466
+ for (reg, ty) in &f.params {
1467
+ w.u32(reg.0 as u32);
1468
+ w.op(encode_ir_type(*ty));
1469
+ }
1470
+ w.op(encode_ir_type(f.return_type));
1471
+
1472
+ w.u32(f.register_types.len() as u32);
1473
+ for &ty in &f.register_types {
1474
+ w.op(encode_ir_type(ty));
1475
+ }
1476
+
1477
+ w.u32(f.blocks.len() as u32);
1478
+ for bb in &f.blocks {
1479
+ w.u32(bb.id.0 as u32);
1480
+ w.u32(bb.instructions.len() as u32);
1481
+ for instr in &bb.instructions {
1482
+ encode_perm_instr(&mut w, instr)?;
1483
+ }
1484
+ }
1485
+ }
1486
+
1487
+ w.buf.extend_from_slice(&tail_bytes);
1488
+ Ok(w.buf)
1489
+ }
1490
+
1491
+ fn deserialize_permuted_bytecode(
1492
+ bytes: &[u8],
1493
+ salt: &[u8; 16],
1494
+ nonce: &[u8; 24],
1495
+ ) -> Result<IrBundle, PolyError> {
1496
+ let mut r = PermBinReader::new(bytes, *salt, *nonce);
1497
+ let head_chaff = r.op()? as usize;
1498
+ let _ = r.take(head_chaff)?;
1499
+
1500
+ let entry_fn = FnId(r.u32()?);
1501
+ let entry_name = r.str()?;
1502
+
1503
+ let init_len = r.u32()? as usize;
1504
+ let mut init_fns = Vec::with_capacity(init_len);
1505
+ for _ in 0..init_len {
1506
+ init_fns.push(FnId(r.u32()?));
1507
+ }
1508
+
1509
+ let exp_len = r.u32()? as usize;
1510
+ let mut exports = Vec::with_capacity(exp_len);
1511
+ for _ in 0..exp_len {
1512
+ let name = r.str()?;
1513
+ let id = FnId(r.u32()?);
1514
+ exports.push((name, id));
1515
+ }
1516
+
1517
+ let fn_len = r.u32()? as usize;
1518
+ let mut functions = Vec::with_capacity(fn_len);
1519
+ for _ in 0..fn_len {
1520
+ let id = FnId(r.u32()?);
1521
+ let module_id = r.u32()? as usize;
1522
+ let qualified_name = r.str()?;
1523
+
1524
+ let p_len = r.u32()? as usize;
1525
+ let mut params = Vec::with_capacity(p_len);
1526
+ for _ in 0..p_len {
1527
+ let reg = Register(r.u32()? as usize);
1528
+ let ty = decode_ir_type(r.op()?)?;
1529
+ params.push((reg, ty));
1530
+ }
1531
+ let return_type = decode_ir_type(r.op()?)?;
1532
+
1533
+ let rt_len = r.u32()? as usize;
1534
+ let mut register_types = Vec::with_capacity(rt_len);
1535
+ for _ in 0..rt_len {
1536
+ register_types.push(decode_ir_type(r.op()?)?);
1537
+ }
1538
+
1539
+ let bb_len = r.u32()? as usize;
1540
+ let mut blocks = Vec::with_capacity(bb_len);
1541
+ for _ in 0..bb_len {
1542
+ let bb_id = BasicBlockId(r.u32()? as usize);
1543
+ let ins_len = r.u32()? as usize;
1544
+ let mut instructions = Vec::with_capacity(ins_len);
1545
+ for _ in 0..ins_len {
1546
+ instructions.push(decode_perm_instr(&mut r)?);
1547
+ }
1548
+ blocks.push(BasicBlock {
1549
+ id: bb_id,
1550
+ instructions,
1551
+ });
1552
+ }
1553
+
1554
+ functions.push(IrFunction {
1555
+ id,
1556
+ module_id,
1557
+ qualified_name,
1558
+ params,
1559
+ return_type,
1560
+ register_types,
1561
+ blocks,
1562
+ });
1563
+ }
1564
+
1565
+ Ok(IrBundle {
1566
+ entry_fn,
1567
+ entry_name,
1568
+ init_fns,
1569
+ exports,
1570
+ functions,
1571
+ })
1572
+ }
1573
+
1574
+ fn encode_ir_type(t: IrType) -> u8 {
1575
+ match t {
1576
+ IrType::Dynamic => 0,
1577
+ IrType::Void => 1,
1578
+ IrType::Bool => 2,
1579
+ IrType::I64 => 3,
1580
+ IrType::F64 => 4,
1581
+ IrType::Str => 5,
1582
+ }
1583
+ }
1584
+
1585
+ fn decode_ir_type(b: u8) -> Result<IrType, PolyError> {
1586
+ match b {
1587
+ 0 => Ok(IrType::Dynamic),
1588
+ 1 => Ok(IrType::Void),
1589
+ 2 => Ok(IrType::Bool),
1590
+ 3 => Ok(IrType::I64),
1591
+ 4 => Ok(IrType::F64),
1592
+ 5 => Ok(IrType::Str),
1593
+ _ => Err(PolyError::msg("E0716", "invalid IrType tag")),
1594
+ }
1595
+ }
1596
+
1597
+ fn encode_perm_reg_list(w: &mut PermBinWriter, regs: &[Register]) {
1598
+ w.u32(regs.len() as u32);
1599
+ for r in regs {
1600
+ w.u32(r.0 as u32);
1601
+ }
1602
+ }
1603
+
1604
+ fn decode_perm_reg_list(r: &mut PermBinReader<'_>) -> Result<Vec<Register>, PolyError> {
1605
+ let n = r.u32()? as usize;
1606
+ let mut out = Vec::with_capacity(n);
1607
+ for _ in 0..n {
1608
+ out.push(Register(r.u32()? as usize));
1609
+ }
1610
+ Ok(out)
1611
+ }
1612
+
1613
+ fn encode_perm_instr(w: &mut PermBinWriter, instr: &IrInstruction) -> Result<(), PolyError> {
1614
+ match instr {
1615
+ IrInstruction::LoadConst(d, c) => {
1616
+ w.op(1);
1617
+ w.u32(d.0 as u32);
1618
+ match c {
1619
+ Constant::Nil => w.op(0),
1620
+ Constant::Bool(b) => {
1621
+ w.op(1);
1622
+ w.u8(u8::from(*b));
1623
+ }
1624
+ Constant::Int(i) => {
1625
+ w.op(2);
1626
+ w.i64(*i);
1627
+ }
1628
+ Constant::Float(f) => {
1629
+ w.op(3);
1630
+ w.f64(*f);
1631
+ }
1632
+ Constant::String(s) => {
1633
+ w.op(4);
1634
+ w.str(s)?;
1635
+ }
1636
+ }
1637
+ }
1638
+ IrInstruction::Move(d, s) => {
1639
+ w.op(2);
1640
+ w.u32(d.0 as u32);
1641
+ w.u32(s.0 as u32);
1642
+ }
1643
+ IrInstruction::Cast(d, ty, s) => {
1644
+ w.op(3);
1645
+ w.u32(d.0 as u32);
1646
+ w.op(encode_ir_type(*ty));
1647
+ w.u32(s.0 as u32);
1648
+ }
1649
+ IrInstruction::BinOp(op, d, l, r) => {
1650
+ w.op(4);
1651
+ w.op(*op as u8);
1652
+ w.u32(d.0 as u32);
1653
+ w.u32(l.0 as u32);
1654
+ w.u32(r.0 as u32);
1655
+ }
1656
+ IrInstruction::UnaryOp(op, d, s) => {
1657
+ w.op(5);
1658
+ w.op(*op as u8);
1659
+ w.u32(d.0 as u32);
1660
+ w.u32(s.0 as u32);
1661
+ }
1662
+ IrInstruction::CallLazy(d, site, args) => {
1663
+ w.op(6);
1664
+ w.u32(d.0 as u32);
1665
+ w.u32(site.0);
1666
+ encode_perm_reg_list(w, args);
1667
+ }
1668
+ IrInstruction::CallFn(d, fn_id, args) => {
1669
+ w.op(7);
1670
+ w.u32(d.0 as u32);
1671
+ w.u32(fn_id.0);
1672
+ encode_perm_reg_list(w, args);
1673
+ }
1674
+ IrInstruction::CallIndirect(d, f, args) => {
1675
+ w.op(8);
1676
+ w.u32(d.0 as u32);
1677
+ w.u32(f.0 as u32);
1678
+ encode_perm_reg_list(w, args);
1679
+ }
1680
+ IrInstruction::CallBuiltin(d, b, args) => {
1681
+ w.op(9);
1682
+ w.u32(d.0 as u32);
1683
+ w.u32(*b as u32);
1684
+ encode_perm_reg_list(w, args);
1685
+ }
1686
+ IrInstruction::ResolveFn(d, site) => {
1687
+ w.op(10);
1688
+ w.u32(d.0 as u32);
1689
+ w.u32(site.0);
1690
+ }
1691
+ IrInstruction::LoadFnRef(d, fn_id) => {
1692
+ w.op(11);
1693
+ w.u32(d.0 as u32);
1694
+ w.u32(fn_id.0);
1695
+ }
1696
+ IrInstruction::Return(opt) => {
1697
+ w.op(12);
1698
+ match opt {
1699
+ None => w.op(0),
1700
+ Some(r) => {
1701
+ w.op(1);
1702
+ w.u32(r.0 as u32);
1703
+ }
1704
+ }
1705
+ }
1706
+ IrInstruction::BranchIf(c, t, f) => {
1707
+ w.op(13);
1708
+ w.u32(c.0 as u32);
1709
+ w.u32(t.0 as u32);
1710
+ w.u32(f.0 as u32);
1711
+ }
1712
+ IrInstruction::Jump(t) => {
1713
+ w.op(14);
1714
+ w.u32(t.0 as u32);
1715
+ }
1716
+ IrInstruction::CreateArray(d, items) => {
1717
+ w.op(15);
1718
+ w.u32(d.0 as u32);
1719
+ encode_perm_reg_list(w, items);
1720
+ }
1721
+ IrInstruction::GetIndex(d, o, i) => {
1722
+ w.op(16);
1723
+ w.u32(d.0 as u32);
1724
+ w.u32(o.0 as u32);
1725
+ w.u32(i.0 as u32);
1726
+ }
1727
+ IrInstruction::SetIndex(o, i, v) => {
1728
+ w.op(17);
1729
+ w.u32(o.0 as u32);
1730
+ w.u32(i.0 as u32);
1731
+ w.u32(v.0 as u32);
1732
+ }
1733
+ IrInstruction::CreateObject(d, cname) => {
1734
+ w.op(18);
1735
+ w.u32(d.0 as u32);
1736
+ w.str(cname)?;
1737
+ }
1738
+ IrInstruction::SetField(o, field, v) => {
1739
+ w.op(19);
1740
+ w.u32(o.0 as u32);
1741
+ w.str(field)?;
1742
+ w.u32(v.0 as u32);
1743
+ }
1744
+ IrInstruction::GetField(d, o, field) => {
1745
+ w.op(20);
1746
+ w.u32(d.0 as u32);
1747
+ w.u32(o.0 as u32);
1748
+ w.str(field)?;
1749
+ }
1750
+ IrInstruction::AllocBuffer(d, s) => {
1751
+ w.op(21);
1752
+ w.u32(d.0 as u32);
1753
+ w.u32(s.0 as u32);
1754
+ }
1755
+ IrInstruction::StoreByte(b, o, v) => {
1756
+ w.op(22);
1757
+ w.u32(b.0 as u32);
1758
+ w.u32(o.0 as u32);
1759
+ w.u32(v.0 as u32);
1760
+ }
1761
+ IrInstruction::LoadByte(d, b, o) => {
1762
+ w.op(23);
1763
+ w.u32(d.0 as u32);
1764
+ w.u32(b.0 as u32);
1765
+ w.u32(o.0 as u32);
1766
+ }
1767
+ }
1768
+ Ok(())
1769
+ }
1770
+
1771
+ fn decode_perm_instr(r: &mut PermBinReader<'_>) -> Result<IrInstruction, PolyError> {
1772
+ let op_tag = r.op()?;
1773
+ match op_tag {
1774
+ 1 => {
1775
+ let d = Register(r.u32()? as usize);
1776
+ let c = match r.op()? {
1777
+ 0 => Constant::Nil,
1778
+ 1 => Constant::Bool(r.u8()? != 0),
1779
+ 2 => Constant::Int(r.i64()?),
1780
+ 3 => Constant::Float(r.f64()?),
1781
+ 4 => Constant::String(r.str()?),
1782
+ _ => return Err(PolyError::msg("E0716", "invalid Constant tag")),
1783
+ };
1784
+ Ok(IrInstruction::LoadConst(d, c))
1785
+ }
1786
+ 2 => Ok(IrInstruction::Move(
1787
+ Register(r.u32()? as usize),
1788
+ Register(r.u32()? as usize),
1789
+ )),
1790
+ 3 => Ok(IrInstruction::Cast(
1791
+ Register(r.u32()? as usize),
1792
+ decode_ir_type(r.op()?)?,
1793
+ Register(r.u32()? as usize),
1794
+ )),
1795
+ 4 => {
1796
+ let op = decode_binop(r.op()?)?;
1797
+ Ok(IrInstruction::BinOp(
1798
+ op,
1799
+ Register(r.u32()? as usize),
1800
+ Register(r.u32()? as usize),
1801
+ Register(r.u32()? as usize),
1802
+ ))
1803
+ }
1804
+ 5 => {
1805
+ let op = decode_unaryop(r.op()?)?;
1806
+ Ok(IrInstruction::UnaryOp(
1807
+ op,
1808
+ Register(r.u32()? as usize),
1809
+ Register(r.u32()? as usize),
1810
+ ))
1811
+ }
1812
+ 6 => Ok(IrInstruction::CallLazy(
1813
+ Register(r.u32()? as usize),
1814
+ CallSiteId(r.u32()?),
1815
+ decode_perm_reg_list(r)?,
1816
+ )),
1817
+ 7 => Ok(IrInstruction::CallFn(
1818
+ Register(r.u32()? as usize),
1819
+ FnId(r.u32()?),
1820
+ decode_perm_reg_list(r)?,
1821
+ )),
1822
+ 8 => Ok(IrInstruction::CallIndirect(
1823
+ Register(r.u32()? as usize),
1824
+ Register(r.u32()? as usize),
1825
+ decode_perm_reg_list(r)?,
1826
+ )),
1827
+ 9 => {
1828
+ let d = Register(r.u32()? as usize);
1829
+ let b = decode_builtin(r.u32()?)?;
1830
+ Ok(IrInstruction::CallBuiltin(d, b, decode_perm_reg_list(r)?))
1831
+ }
1832
+ 10 => Ok(IrInstruction::ResolveFn(
1833
+ Register(r.u32()? as usize),
1834
+ CallSiteId(r.u32()?),
1835
+ )),
1836
+ 11 => Ok(IrInstruction::LoadFnRef(
1837
+ Register(r.u32()? as usize),
1838
+ FnId(r.u32()?),
1839
+ )),
1840
+ 12 => {
1841
+ let has = r.op()? != 0;
1842
+ let reg = if has {
1843
+ Some(Register(r.u32()? as usize))
1844
+ } else {
1845
+ None
1846
+ };
1847
+ Ok(IrInstruction::Return(reg))
1848
+ }
1849
+ 13 => Ok(IrInstruction::BranchIf(
1850
+ Register(r.u32()? as usize),
1851
+ BasicBlockId(r.u32()? as usize),
1852
+ BasicBlockId(r.u32()? as usize),
1853
+ )),
1854
+ 14 => Ok(IrInstruction::Jump(BasicBlockId(r.u32()? as usize))),
1855
+ 15 => Ok(IrInstruction::CreateArray(
1856
+ Register(r.u32()? as usize),
1857
+ decode_perm_reg_list(r)?,
1858
+ )),
1859
+ 16 => Ok(IrInstruction::GetIndex(
1860
+ Register(r.u32()? as usize),
1861
+ Register(r.u32()? as usize),
1862
+ Register(r.u32()? as usize),
1863
+ )),
1864
+ 17 => Ok(IrInstruction::SetIndex(
1865
+ Register(r.u32()? as usize),
1866
+ Register(r.u32()? as usize),
1867
+ Register(r.u32()? as usize),
1868
+ )),
1869
+ 18 => Ok(IrInstruction::CreateObject(
1870
+ Register(r.u32()? as usize),
1871
+ r.str()?,
1872
+ )),
1873
+ 19 => Ok(IrInstruction::SetField(
1874
+ Register(r.u32()? as usize),
1875
+ r.str()?,
1876
+ Register(r.u32()? as usize),
1877
+ )),
1878
+ 20 => Ok(IrInstruction::GetField(
1879
+ Register(r.u32()? as usize),
1880
+ Register(r.u32()? as usize),
1881
+ r.str()?,
1882
+ )),
1883
+ 21 => Ok(IrInstruction::AllocBuffer(
1884
+ Register(r.u32()? as usize),
1885
+ Register(r.u32()? as usize),
1886
+ )),
1887
+ 22 => Ok(IrInstruction::StoreByte(
1888
+ Register(r.u32()? as usize),
1889
+ Register(r.u32()? as usize),
1890
+ Register(r.u32()? as usize),
1891
+ )),
1892
+ 23 => Ok(IrInstruction::LoadByte(
1893
+ Register(r.u32()? as usize),
1894
+ Register(r.u32()? as usize),
1895
+ Register(r.u32()? as usize),
1896
+ )),
1897
+ _ => Err(PolyError::msg("E0716", "invalid VM instruction tag")),
1898
+ }
1899
+ }
1900
+
1901
+ fn decode_binop(v: u8) -> Result<IrBinOp, PolyError> {
1902
+ match v {
1903
+ x if x == IrBinOp::Add as u8 => Ok(IrBinOp::Add),
1904
+ x if x == IrBinOp::Sub as u8 => Ok(IrBinOp::Sub),
1905
+ x if x == IrBinOp::Mul as u8 => Ok(IrBinOp::Mul),
1906
+ x if x == IrBinOp::Div as u8 => Ok(IrBinOp::Div),
1907
+ x if x == IrBinOp::FloorDiv as u8 => Ok(IrBinOp::FloorDiv),
1908
+ x if x == IrBinOp::Mod as u8 => Ok(IrBinOp::Mod),
1909
+ x if x == IrBinOp::Eq as u8 => Ok(IrBinOp::Eq),
1910
+ x if x == IrBinOp::Ne as u8 => Ok(IrBinOp::Ne),
1911
+ x if x == IrBinOp::Lt as u8 => Ok(IrBinOp::Lt),
1912
+ x if x == IrBinOp::Le as u8 => Ok(IrBinOp::Le),
1913
+ x if x == IrBinOp::Gt as u8 => Ok(IrBinOp::Gt),
1914
+ x if x == IrBinOp::Ge as u8 => Ok(IrBinOp::Ge),
1915
+ x if x == IrBinOp::And as u8 => Ok(IrBinOp::And),
1916
+ x if x == IrBinOp::Or as u8 => Ok(IrBinOp::Or),
1917
+ x if x == IrBinOp::BitAnd as u8 => Ok(IrBinOp::BitAnd),
1918
+ x if x == IrBinOp::BitOr as u8 => Ok(IrBinOp::BitOr),
1919
+ x if x == IrBinOp::BitXor as u8 => Ok(IrBinOp::BitXor),
1920
+ x if x == IrBinOp::Shl as u8 => Ok(IrBinOp::Shl),
1921
+ x if x == IrBinOp::Shr as u8 => Ok(IrBinOp::Shr),
1922
+ _ => Err(PolyError::msg("E0716", "invalid BinOp tag")),
1923
+ }
1924
+ }
1925
+
1926
+ fn decode_unaryop(v: u8) -> Result<IrUnaryOp, PolyError> {
1927
+ match v {
1928
+ x if x == IrUnaryOp::Neg as u8 => Ok(IrUnaryOp::Neg),
1929
+ x if x == IrUnaryOp::Not as u8 => Ok(IrUnaryOp::Not),
1930
+ x if x == IrUnaryOp::BitNot as u8 => Ok(IrUnaryOp::BitNot),
1931
+ x if x == IrUnaryOp::BitsToF64 as u8 => Ok(IrUnaryOp::BitsToF64),
1932
+ _ => Err(PolyError::msg("E0716", "invalid UnaryOp tag")),
1933
+ }
1934
+ }
1935
+
1936
+ fn decode_builtin(v: u32) -> Result<BuiltinId, PolyError> {
1937
+ match v {
1938
+ x if x == BuiltinId::Print as u32 => Ok(BuiltinId::Print),
1939
+ x if x == BuiltinId::Println as u32 => Ok(BuiltinId::Println),
1940
+ x if x == BuiltinId::Printf as u32 => Ok(BuiltinId::Printf),
1941
+ x if x == BuiltinId::Len as u32 => Ok(BuiltinId::Len),
1942
+ x if x == BuiltinId::Str as u32 => Ok(BuiltinId::Str),
1943
+ x if x == BuiltinId::Int as u32 => Ok(BuiltinId::Int),
1944
+ x if x == BuiltinId::Float as u32 => Ok(BuiltinId::Float),
1945
+ x if x == BuiltinId::Bool as u32 => Ok(BuiltinId::Bool),
1946
+ x if x == BuiltinId::Abs as u32 => Ok(BuiltinId::Abs),
1947
+ x if x == BuiltinId::Min as u32 => Ok(BuiltinId::Min),
1948
+ x if x == BuiltinId::Max as u32 => Ok(BuiltinId::Max),
1949
+ x if x == BuiltinId::Sqrt as u32 => Ok(BuiltinId::Sqrt),
1950
+ x if x == BuiltinId::Pow as u32 => Ok(BuiltinId::Pow),
1951
+ x if x == BuiltinId::Push as u32 => Ok(BuiltinId::Push),
1952
+ x if x == BuiltinId::Pop as u32 => Ok(BuiltinId::Pop),
1953
+ x if x == BuiltinId::TypeOf as u32 => Ok(BuiltinId::TypeOf),
1954
+ x if x == BuiltinId::AllocBuf as u32 => Ok(BuiltinId::AllocBuf),
1955
+ x if x == BuiltinId::ReadU8 as u32 => Ok(BuiltinId::ReadU8),
1956
+ x if x == BuiltinId::WriteU8 as u32 => Ok(BuiltinId::WriteU8),
1957
+ x if x == BuiltinId::BufLen as u32 => Ok(BuiltinId::BufLen),
1958
+ x if x == BuiltinId::ClockMs as u32 => Ok(BuiltinId::ClockMs),
1959
+ x if x == BuiltinId::Assert as u32 => Ok(BuiltinId::Assert),
1960
+ _ => Err(PolyError::msg("E0716", "invalid BuiltinId tag")),
1961
+ }
1962
+ }
1963
+
1964
+ // ============================================================================
1965
+ // Armored POLYX003 Parser
1966
+ // ============================================================================
1967
+
1968
+ struct ParsedArmored {
1969
+ canonical_header: String,
1970
+ kdf_mode: u8,
1971
+ obfuscated: bool,
1972
+ flags: u8,
1973
+ pubkey_bytes: [u8; 32],
1974
+ origin_fp: [u8; 32],
1975
+ salt: [u8; 16],
1976
+ nonce: [u8; 24],
1977
+ ciphertext: Vec<u8>,
1978
+ sig_bytes: [u8; 64],
1979
+ sig_msg: Vec<u8>,
1980
+ }
1981
+
1982
+ fn parse_armored_polyx(text: &str) -> Result<ParsedArmored, PolyError> {
1983
+ let trimmed = text.trim();
1984
+ let after_begin = trimmed
1985
+ .strip_prefix(ARMOR_BEGIN)
1986
+ .ok_or_else(|| PolyError::msg("E0707", "missing POLYX begin armor"))?
1987
+ .strip_prefix('\n')
1988
+ .ok_or_else(|| PolyError::msg("E0707", "malformed POLYX armor header"))?;
1989
+
1990
+ let (canonical_header, rest) = after_begin
1991
+ .split_once("\n\n")
1992
+ .ok_or_else(|| PolyError::msg("E0707", "missing header/payload separator in POLYX"))?;
1993
+
1994
+ let (b64_part, tail) = rest
1995
+ .split_once(&format!("\n{ARMOR_END}"))
1996
+ .ok_or_else(|| PolyError::msg("E0707", "missing POLYX end armor"))?;
1997
+
1998
+ let sig_line = tail
1999
+ .trim()
2000
+ .strip_prefix("Signature:")
2001
+ .ok_or_else(|| PolyError::msg("E0712", "missing Ed25519 Signature line in POLYX"))?
2002
+ .trim();
2003
+ let sig_bytes = decode_hex_64(sig_line)
2004
+ .ok_or_else(|| PolyError::msg("E0712", "malformed 64-byte hex Ed25519 signature"))?;
2005
+
2006
+ let mut fmt_ok = false;
2007
+ let mut ver_ok = false;
2008
+ let mut obfuscated = false;
2009
+ let mut kdf_mode = 0u8;
2010
+ let mut pubkey_bytes = None;
2011
+ let mut origin_fp = None;
2012
+ let mut salt = None;
2013
+ let mut nonce = None;
2014
+
2015
+ for line in canonical_header.lines() {
2016
+ let Some((k, v)) = line.split_once(':') else {
2017
+ return Err(PolyError::msg("E0707", "malformed POLYX header line"));
2018
+ };
2019
+ let k = k.trim();
2020
+ let v = v.trim();
2021
+ match k {
2022
+ "Format" => fmt_ok = v == "POLYX003",
2023
+ "Version" => ver_ok = v == "3",
2024
+ "Obfuscated" => {
2025
+ obfuscated = match v {
2026
+ "true" => true,
2027
+ "false" => false,
2028
+ _ => return Err(PolyError::msg("E0707", "invalid Obfuscated flag")),
2029
+ };
2030
+ }
2031
+ "Encrypted" => {
2032
+ if v != "true" {
2033
+ return Err(PolyError::msg("E0707", "POLYX Encrypted must be true"));
2034
+ }
2035
+ }
2036
+ "KDF" => {
2037
+ kdf_mode = match v {
2038
+ "vm-sealed" => KDF_VM_SEALED,
2039
+ "argon2id" => KDF_ARGON2ID,
2040
+ "blake3-raw" => KDF_RAW_BLAKE3,
2041
+ _ => return Err(PolyError::msg("E0715", "unknown KDF in POLYX header")),
2042
+ };
2043
+ }
2044
+ "Signer" => pubkey_bytes = decode_hex_32(v),
2045
+ "Origin" => origin_fp = decode_hex_32(v),
2046
+ "Salt" => salt = decode_hex_16(v),
2047
+ "Nonce" => nonce = decode_hex_24(v),
2048
+ "Payload-Encoding" => {
2049
+ if v != "base64" {
2050
+ return Err(PolyError::msg("E0707", "unsupported POLYX payload encoding"));
2051
+ }
2052
+ }
2053
+ _ => {}
2054
+ }
2055
+ }
2056
+
2057
+ if !fmt_ok || !ver_ok {
2058
+ return Err(PolyError::msg("E0708", "invalid or unsupported POLYX format/version"));
2059
+ }
2060
+ let pubkey_bytes = pubkey_bytes.ok_or_else(|| PolyError::msg("E0710", "missing Signer"))?;
2061
+ let origin_fp = origin_fp.ok_or_else(|| PolyError::msg("E0709", "missing Origin"))?;
2062
+ let salt = salt.ok_or_else(|| PolyError::msg("E0707", "missing Salt"))?;
2063
+ let nonce = nonce.ok_or_else(|| PolyError::msg("E0707", "missing Nonce"))?;
2064
+ let flags = FLAG_ENCRYPTED | if obfuscated { FLAG_OBFUSCATED } else { 0 };
2065
+
2066
+ let ciphertext = base64_decode(b64_part)?;
2067
+ let mut sig_msg =
2068
+ Vec::with_capacity(VERIFY_DOMAIN.len() + canonical_header.len() + 2 + ciphertext.len());
2069
+ sig_msg.extend_from_slice(VERIFY_DOMAIN);
2070
+ sig_msg.extend_from_slice(canonical_header.as_bytes());
2071
+ sig_msg.extend_from_slice(b"\n\n");
2072
+ sig_msg.extend_from_slice(&ciphertext);
2073
+
2074
+ Ok(ParsedArmored {
2075
+ canonical_header: canonical_header.to_string(),
2076
+ kdf_mode,
2077
+ obfuscated,
2078
+ flags,
2079
+ pubkey_bytes,
2080
+ origin_fp,
2081
+ salt,
2082
+ nonce,
2083
+ ciphertext,
2084
+ sig_bytes,
2085
+ sig_msg,
2086
+ })
2087
+ }
2088
+
2089
+ // ============================================================================
2090
+ // Pure UTF-8 Human-Readable IR Formatter & Parser (POLYIR03)
2091
+ // ============================================================================
2092
+
2093
+ struct PlainSigInfo {
2094
+ salt: [u8; 16],
2095
+ pubkey_bytes: [u8; 32],
2096
+ origin_fp: [u8; 32],
2097
+ sig_bytes: [u8; 64],
2098
+ }
2099
+
2100
+ struct ParsedPlainEnvelope {
2101
+ bundle: IrBundle,
2102
+ ir_body: String,
2103
+ sig_info: Option<PlainSigInfo>,
2104
+ }
2105
+
2106
+ fn format_plain_meta(
2107
+ bundle: &IrBundle,
2108
+ salt: &[u8; 16],
2109
+ pubkey: &[u8; 32],
2110
+ origin_fp: &[u8; 32],
2111
+ ) -> String {
2112
+ format!(
2113
+ "POLYIR03\nv={FORMAT_VERSION}\nentry={} {}\ninits={}\nexports={}\nsalt={}\nsigner={}\norigin={}\n",
2114
+ bundle.entry_fn.0,
2115
+ escape_str(&bundle.entry_name),
2116
+ format_fn_id_list(&bundle.init_fns),
2117
+ format_exports_list(&bundle.exports),
2118
+ encode_hex(salt),
2119
+ encode_hex(pubkey),
2120
+ encode_hex(origin_fp),
2121
+ )
2122
+ }
2123
+
2124
+ fn format_fn_id_list(ids: &[FnId]) -> String {
2125
+ let items: Vec<String> = ids.iter().map(|i| i.0.to_string()).collect();
2126
+ format!("[{}]", items.join(", "))
2127
+ }
2128
+
2129
+ fn format_exports_list(exports: &[(String, FnId)]) -> String {
2130
+ let items: Vec<String> = exports
2131
+ .iter()
2132
+ .map(|(n, id)| format!("{}={}", escape_str(n), id.0))
2133
+ .collect();
2134
+ format!("[{}]", items.join(", "))
2135
+ }
2136
+
2137
+ fn format_ir_body(bundle: &IrBundle) -> String {
2138
+ let mut out = String::new();
2139
+ for f in &bundle.functions {
2140
+ let params: Vec<String> = f
2141
+ .params
2142
+ .iter()
2143
+ .map(|(r, t)| format!("r{}:{}", r.0, ir_type_name(*t)))
2144
+ .collect();
2145
+ let regs: Vec<&'static str> = f
2146
+ .register_types
2147
+ .iter()
2148
+ .map(|t| ir_type_name(*t))
2149
+ .collect();
2150
+ let _ = writeln!(
2151
+ out,
2152
+ "fn #{} {} mod={} ret={} params=[{}] {{",
2153
+ f.id.0,
2154
+ escape_str(&f.qualified_name),
2155
+ f.module_id,
2156
+ ir_type_name(f.return_type),
2157
+ params.join(", ")
2158
+ );
2159
+ let _ = writeln!(out, " regs: [{}]", regs.join(", "));
2160
+ for bb in &f.blocks {
2161
+ let _ = writeln!(out, " bb{}:", bb.id.0);
2162
+ for instr in &bb.instructions {
2163
+ out.push_str(" ");
2164
+ format_instr(&mut out, instr);
2165
+ out.push('\n');
2166
+ }
2167
+ }
2168
+ out.push_str("}\n");
2169
+ }
2170
+ out
2171
+ }
2172
+
2173
+ fn parse_plain_polyir_envelope(text: &str) -> Result<ParsedPlainEnvelope, PolyError> {
2174
+ let mut entry_fn: Option<FnId> = None;
2175
+ let mut entry_name: Option<String> = None;
2176
+ let mut init_fns = Vec::new();
2177
+ let mut exports = Vec::new();
2178
+ let mut salt: Option<[u8; 16]> = None;
2179
+ let mut signer: Option<[u8; 32]> = None;
2180
+ let mut origin: Option<[u8; 32]> = None;
2181
+ let mut signature: Option<[u8; 64]> = None;
2182
+
2183
+ let (header_part, body_and_end) = if let Some((h, rest)) = text.split_once(PLAIN_BEGIN_IR) {
2184
+ let rest = rest.strip_prefix('\n').unwrap_or(rest);
2185
+ let ir_body = if let Some((b, _)) = rest.split_once(PLAIN_END_IR) {
2186
+ b.to_string()
2187
+ } else {
2188
+ rest.to_string()
2189
+ };
2190
+ (h, ir_body)
2191
+ } else {
2192
+ ("", text.to_string())
2193
+ };
2194
+
2195
+ for line in header_part.lines() {
2196
+ let t = line.trim();
2197
+ let Some(comment) = t.strip_prefix(';') else {
2198
+ continue;
2199
+ };
2200
+ let comment = comment.trim();
2201
+ if let Some(v) = comment.strip_prefix("format:") {
2202
+ if v.trim() != "POLYIR03" {
2203
+ return Err(PolyError::msg("E0708", "unsupported POLYIR format"));
2204
+ }
2205
+ } else if let Some(v) = comment.strip_prefix("version:") {
2206
+ if v.trim() != "3" {
2207
+ return Err(PolyError::msg("E0708", "unsupported POLYIR version"));
2208
+ }
2209
+ } else if let Some(v) = comment.strip_prefix("entry:") {
2210
+ let (id, name) = parse_entry_meta(v.trim())?;
2211
+ entry_fn = Some(id);
2212
+ entry_name = Some(name);
2213
+ } else if let Some(v) = comment.strip_prefix("inits:") {
2214
+ init_fns = parse_fn_id_list(v.trim())?;
2215
+ } else if let Some(v) = comment.strip_prefix("exports:") {
2216
+ exports = parse_exports_list(v.trim())?;
2217
+ } else if let Some(v) = comment.strip_prefix("salt:") {
2218
+ salt = decode_hex_16(v.trim());
2219
+ } else if let Some(v) = comment.strip_prefix("signer:") {
2220
+ signer = decode_hex_32(v.trim());
2221
+ } else if let Some(v) = comment.strip_prefix("origin:") {
2222
+ origin = decode_hex_32(v.trim());
2223
+ } else if let Some(v) = comment.strip_prefix("signature:") {
2224
+ signature = decode_hex_64(v.trim());
2225
+ }
2226
+ }
2227
+
2228
+ let functions = parse_ir_functions(&body_and_end)?;
2229
+ if functions.is_empty() {
2230
+ return Err(PolyError::msg("E0716", "IR container contains 0 functions"));
2231
+ }
2232
+
2233
+ let final_entry_fn = entry_fn.unwrap_or(functions[0].id);
2234
+ let final_entry_name = entry_name.unwrap_or_else(|| "main".to_string());
2235
+ if exports.is_empty() {
2236
+ exports.push((final_entry_name.clone(), final_entry_fn));
2237
+ }
2238
+
2239
+ let sig_info = match (salt, signer, origin, signature) {
2240
+ (Some(s), Some(p), Some(o), Some(sig)) => Some(PlainSigInfo {
2241
+ salt: s,
2242
+ pubkey_bytes: p,
2243
+ origin_fp: o,
2244
+ sig_bytes: sig,
2245
+ }),
2246
+ _ => None,
2247
+ };
2248
+
2249
+ Ok(ParsedPlainEnvelope {
2250
+ bundle: IrBundle {
2251
+ entry_fn: final_entry_fn,
2252
+ entry_name: final_entry_name,
2253
+ init_fns,
2254
+ exports,
2255
+ functions,
2256
+ },
2257
+ ir_body: body_and_end,
2258
+ sig_info,
2259
+ })
2260
+ }
2261
+
2262
+ fn parse_entry_meta(s: &str) -> Result<(FnId, String), PolyError> {
2263
+ let s = s.trim();
2264
+ let Some((num_part, str_part)) = s.split_once(' ') else {
2265
+ return Err(PolyError::msg("E0716", "invalid entry metadata"));
2266
+ };
2267
+ let id: u32 = num_part
2268
+ .trim()
2269
+ .parse()
2270
+ .map_err(|_| PolyError::msg("E0716", "invalid entry fn id"))?;
2271
+ let (name, _) = parse_escaped_str(str_part.trim())?;
2272
+ Ok((FnId(id), name))
2273
+ }
2274
+
2275
+ fn parse_fn_id_list(s: &str) -> Result<Vec<FnId>, PolyError> {
2276
+ let inner = s
2277
+ .trim()
2278
+ .strip_prefix('[')
2279
+ .and_then(|x| x.strip_suffix(']'))
2280
+ .ok_or_else(|| PolyError::msg("E0716", "expected [...] id list"))?
2281
+ .trim();
2282
+ if inner.is_empty() {
2283
+ return Ok(Vec::new());
2284
+ }
2285
+ let mut out = Vec::new();
2286
+ for p in inner.split(',') {
2287
+ let id: u32 = p
2288
+ .trim()
2289
+ .parse()
2290
+ .map_err(|_| PolyError::msg("E0716", "invalid FnId in list"))?;
2291
+ out.push(FnId(id));
2292
+ }
2293
+ Ok(out)
2294
+ }
2295
+
2296
+ fn parse_exports_list(s: &str) -> Result<Vec<(String, FnId)>, PolyError> {
2297
+ let mut p = s
2298
+ .trim()
2299
+ .strip_prefix('[')
2300
+ .and_then(|x| x.strip_suffix(']'))
2301
+ .ok_or_else(|| PolyError::msg("E0716", "expected [...] exports list"))?
2302
+ .trim();
2303
+ let mut out = Vec::new();
2304
+ while !p.is_empty() {
2305
+ let (name, rest) = parse_escaped_str(p)?;
2306
+ let rest = rest
2307
+ .trim_start()
2308
+ .strip_prefix('=')
2309
+ .ok_or_else(|| PolyError::msg("E0716", "expected '=' in export entry"))?
2310
+ .trim_start();
2311
+ let end_num = rest
2312
+ .find(|c: char| !c.is_ascii_digit())
2313
+ .unwrap_or(rest.len());
2314
+ let id: u32 = rest[..end_num]
2315
+ .parse()
2316
+ .map_err(|_| PolyError::msg("E0716", "invalid export FnId"))?;
2317
+ out.push((name, FnId(id)));
2318
+ p = rest[end_num..].trim_start();
2319
+ if let Some(after_comma) = p.strip_prefix(',') {
2320
+ p = after_comma.trim_start();
2321
+ } else {
2322
+ break;
2323
+ }
2324
+ }
2325
+ Ok(out)
2326
+ }
2327
+
2328
+ fn parse_ir_functions(body: &str) -> Result<Vec<IrFunction>, PolyError> {
2329
+ let mut funcs = Vec::new();
2330
+ let lines: Vec<&str> = body.lines().collect();
2331
+ let mut i = 0usize;
2332
+
2333
+ while i < lines.len() {
2334
+ let line = lines[i].trim();
2335
+ if line.is_empty() || line.starts_with(';') {
2336
+ i += 1;
2337
+ continue;
2338
+ }
2339
+ if !line.starts_with("fn ") {
2340
+ return Err(PolyError::msg(
2341
+ "E0716",
2342
+ format!("unexpected top-level IR line: {line}"),
2343
+ ));
2344
+ }
2345
+
2346
+ let rest = line.strip_prefix("fn ").unwrap().trim();
2347
+ let (fn_id_tok, rest) = split_ws_tok(rest)?;
2348
+ let fn_id = parse_fn_hash(fn_id_tok)?;
2349
+ let (qualified_name, rest) = parse_escaped_str(rest.trim_start())?;
2350
+ let rest = rest.trim();
2351
+
2352
+ let (mod_tok, rest) = split_ws_tok(rest)?;
2353
+ let module_id: usize = mod_tok
2354
+ .strip_prefix("mod=")
2355
+ .ok_or_else(|| PolyError::msg("E0716", "missing mod= in fn header"))?
2356
+ .parse()
2357
+ .map_err(|_| PolyError::msg("E0716", "invalid mod= integer"))?;
2358
+
2359
+ let (ret_tok, rest) = split_ws_tok(rest)?;
2360
+ let return_type = parse_ir_type_name(
2361
+ ret_tok
2362
+ .strip_prefix("ret=")
2363
+ .ok_or_else(|| PolyError::msg("E0716", "missing ret= in fn header"))?,
2364
+ )?;
2365
+
2366
+ let params_part = rest
2367
+ .trim()
2368
+ .strip_prefix("params=")
2369
+ .and_then(|s| s.strip_suffix('{'))
2370
+ .ok_or_else(|| PolyError::msg("E0716", "expected params=[...] {"))?
2371
+ .trim();
2372
+ let params = parse_params_list(params_part)?;
2373
+
2374
+ i += 1;
2375
+ let mut register_types = Vec::new();
2376
+ let mut blocks = Vec::new();
2377
+ let mut current_bb: Option<BasicBlock> = None;
2378
+
2379
+ while i < lines.len() {
2380
+ let bline = lines[i].trim();
2381
+ i += 1;
2382
+ if bline.is_empty() || bline.starts_with(';') {
2383
+ continue;
2384
+ }
2385
+ if bline == "}" {
2386
+ if let Some(bb) = current_bb.take() {
2387
+ blocks.push(bb);
2388
+ }
2389
+ break;
2390
+ }
2391
+ if let Some(regs_raw) = bline.strip_prefix("regs:") {
2392
+ let inner = regs_raw
2393
+ .trim()
2394
+ .strip_prefix('[')
2395
+ .and_then(|s| s.strip_suffix(']'))
2396
+ .ok_or_else(|| PolyError::msg("E0716", "expected regs: [...]"))?
2397
+ .trim();
2398
+ if !inner.is_empty() {
2399
+ for rt in inner.split(',') {
2400
+ register_types.push(parse_ir_type_name(rt.trim())?);
2401
+ }
2402
+ }
2403
+ continue;
2404
+ }
2405
+ if let Some(bb_str) = bline.strip_suffix(':')
2406
+ && let Some(num) = bb_str.strip_prefix("bb")
2407
+ {
2408
+ if let Some(prev) = current_bb.take() {
2409
+ blocks.push(prev);
2410
+ }
2411
+ let bbid: usize = num
2412
+ .parse()
2413
+ .map_err(|_| PolyError::msg("E0716", "invalid basic block id"))?;
2414
+ current_bb = Some(BasicBlock {
2415
+ id: BasicBlockId(bbid),
2416
+ instructions: Vec::new(),
2417
+ });
2418
+ continue;
2419
+ }
2420
+ let instr = parse_instr_line(bline)?;
2421
+ let bb = current_bb.as_mut().ok_or_else(|| {
2422
+ PolyError::msg("E0716", "instruction found outside basic block")
2423
+ })?;
2424
+ bb.instructions.push(instr);
2425
+ }
2426
+
2427
+ funcs.push(IrFunction {
2428
+ id: fn_id,
2429
+ module_id,
2430
+ qualified_name,
2431
+ params,
2432
+ return_type,
2433
+ register_types,
2434
+ blocks,
2435
+ });
2436
+ }
2437
+
2438
+ Ok(funcs)
2439
+ }
2440
+
2441
+ fn parse_params_list(s: &str) -> Result<Vec<(Register, IrType)>, PolyError> {
2442
+ let inner = s
2443
+ .trim()
2444
+ .strip_prefix('[')
2445
+ .and_then(|x| x.strip_suffix(']'))
2446
+ .ok_or_else(|| PolyError::msg("E0716", "expected [...] params"))?
2447
+ .trim();
2448
+ if inner.is_empty() {
2449
+ return Ok(Vec::new());
2450
+ }
2451
+ let mut out = Vec::new();
2452
+ for item in inner.split(',') {
2453
+ let (r_str, t_str) = item
2454
+ .trim()
2455
+ .split_once(':')
2456
+ .ok_or_else(|| PolyError::msg("E0716", "expected rN:Type in params"))?;
2457
+ out.push((parse_reg(r_str)?, parse_ir_type_name(t_str)?));
2458
+ }
2459
+ Ok(out)
2460
+ }
2461
+
2462
+ fn format_reg_list(regs: &[Register]) -> String {
2463
+ let items: Vec<String> = regs.iter().map(|r| format!("r{}", r.0)).collect();
2464
+ format!("[{}]", items.join(", "))
2465
+ }
2466
+
2467
+ fn format_instr(out: &mut String, instr: &IrInstruction) {
2468
+ match instr {
2469
+ IrInstruction::LoadConst(d, c) => match c {
2470
+ Constant::Nil => {
2471
+ let _ = write!(out, "load_const r{} nil", d.0);
2472
+ }
2473
+ Constant::Bool(b) => {
2474
+ let _ = write!(out, "load_const r{} bool {b}", d.0);
2475
+ }
2476
+ Constant::Int(i) => {
2477
+ let _ = write!(out, "load_const r{} int {i}", d.0);
2478
+ }
2479
+ Constant::Float(f) => {
2480
+ let s = f.to_string();
2481
+ if !f.is_nan()
2482
+ && !f.is_infinite()
2483
+ && !(*f == 0.0 && f.is_sign_negative())
2484
+ && s.parse::<f64>().map(|x| x.to_bits()) == Ok(f.to_bits())
2485
+ {
2486
+ let _ = write!(out, "load_const r{} float {s}", d.0);
2487
+ } else {
2488
+ let _ = write!(out, "load_const r{} float_bits 0x{:016x}", d.0, f.to_bits());
2489
+ }
2490
+ }
2491
+ Constant::String(s) => {
2492
+ let _ = write!(out, "load_const r{} str {}", d.0, escape_str(s));
2493
+ }
2494
+ },
2495
+ IrInstruction::Move(d, s) => {
2496
+ let _ = write!(out, "move r{} r{}", d.0, s.0);
2497
+ }
2498
+ IrInstruction::Cast(d, ty, s) => {
2499
+ let _ = write!(out, "cast r{} {} r{}", d.0, ir_type_name(*ty), s.0);
2500
+ }
2501
+ IrInstruction::BinOp(op, d, l, r) => {
2502
+ let _ = write!(out, "binop {} r{} r{} r{}", binop_name(*op), d.0, l.0, r.0);
2503
+ }
2504
+ IrInstruction::UnaryOp(op, d, s) => {
2505
+ let _ = write!(out, "unary {} r{} r{}", unary_name(*op), d.0, s.0);
2506
+ }
2507
+ IrInstruction::CallLazy(d, site, args) => {
2508
+ let _ = write!(out, "call_lazy r{} #{} {}", d.0, site.0, format_reg_list(args));
2509
+ }
2510
+ IrInstruction::CallFn(d, fn_id, args) => {
2511
+ let _ = write!(out, "call_fn r{} #{} {}", d.0, fn_id.0, format_reg_list(args));
2512
+ }
2513
+ IrInstruction::CallIndirect(d, f, args) => {
2514
+ let _ = write!(
2515
+ out,
2516
+ "call_indirect r{} r{} {}",
2517
+ d.0,
2518
+ f.0,
2519
+ format_reg_list(args)
2520
+ );
2521
+ }
2522
+ IrInstruction::CallBuiltin(d, b, args) => {
2523
+ let _ = write!(
2524
+ out,
2525
+ "call_builtin r{} {} {}",
2526
+ d.0,
2527
+ builtin_name(*b),
2528
+ format_reg_list(args)
2529
+ );
2530
+ }
2531
+ IrInstruction::ResolveFn(d, site) => {
2532
+ let _ = write!(out, "resolve_fn r{} #{}", d.0, site.0);
2533
+ }
2534
+ IrInstruction::LoadFnRef(d, fn_id) => {
2535
+ let _ = write!(out, "load_fn_ref r{} #{}", d.0, fn_id.0);
2536
+ }
2537
+ IrInstruction::Return(None) => out.push_str("return"),
2538
+ IrInstruction::Return(Some(r)) => {
2539
+ let _ = write!(out, "return r{}", r.0);
2540
+ }
2541
+ IrInstruction::BranchIf(c, t, f) => {
2542
+ let _ = write!(out, "branch_if r{} bb{} bb{}", c.0, t.0, f.0);
2543
+ }
2544
+ IrInstruction::Jump(t) => {
2545
+ let _ = write!(out, "jump bb{}", t.0);
2546
+ }
2547
+ IrInstruction::CreateArray(d, items) => {
2548
+ let _ = write!(out, "create_array r{} {}", d.0, format_reg_list(items));
2549
+ }
2550
+ IrInstruction::GetIndex(d, o, i) => {
2551
+ let _ = write!(out, "get_index r{} r{} r{}", d.0, o.0, i.0);
2552
+ }
2553
+ IrInstruction::SetIndex(o, i, v) => {
2554
+ let _ = write!(out, "set_index r{} r{} r{}", o.0, i.0, v.0);
2555
+ }
2556
+ IrInstruction::CreateObject(d, cname) => {
2557
+ let _ = write!(out, "create_object r{} {}", d.0, escape_str(cname));
2558
+ }
2559
+ IrInstruction::SetField(o, field, v) => {
2560
+ let _ = write!(out, "set_field r{} {} r{}", o.0, escape_str(field), v.0);
2561
+ }
2562
+ IrInstruction::GetField(d, o, field) => {
2563
+ let _ = write!(out, "get_field r{} r{} {}", d.0, o.0, escape_str(field));
2564
+ }
2565
+ IrInstruction::AllocBuffer(d, s) => {
2566
+ let _ = write!(out, "alloc_buf r{} r{}", d.0, s.0);
2567
+ }
2568
+ IrInstruction::StoreByte(b, o, v) => {
2569
+ let _ = write!(out, "store_byte r{} r{} r{}", b.0, o.0, v.0);
2570
+ }
2571
+ IrInstruction::LoadByte(d, b, o) => {
2572
+ let _ = write!(out, "load_byte r{} r{} r{}", d.0, b.0, o.0);
2573
+ }
2574
+ }
2575
+ }
2576
+
2577
+ fn parse_instr_line(line: &str) -> Result<IrInstruction, PolyError> {
2578
+ let (op, rest) = match line.split_once(' ') {
2579
+ Some((a, b)) => (a.trim(), b.trim()),
2580
+ None => (line.trim(), ""),
2581
+ };
2582
+ match op {
2583
+ "load_const" => {
2584
+ let (d_tok, rest) = split_ws_tok(rest)?;
2585
+ let dst = parse_reg(d_tok)?;
2586
+ let (kind, val_str) = match rest.split_once(' ') {
2587
+ Some((k, v)) => (k.trim(), v.trim()),
2588
+ None => (rest.trim(), ""),
2589
+ };
2590
+ let c = match kind {
2591
+ "nil" => Constant::Nil,
2592
+ "bool" => Constant::Bool(match val_str {
2593
+ "true" => true,
2594
+ "false" => false,
2595
+ _ => return Err(PolyError::msg("E0716", "invalid bool constant")),
2596
+ }),
2597
+ "int" => Constant::Int(
2598
+ val_str
2599
+ .parse()
2600
+ .map_err(|_| PolyError::msg("E0716", "invalid int constant"))?,
2601
+ ),
2602
+ "float" => Constant::Float(
2603
+ val_str
2604
+ .parse()
2605
+ .map_err(|_| PolyError::msg("E0716", "invalid float constant"))?,
2606
+ ),
2607
+ "float_bits" => {
2608
+ let hex = val_str.strip_prefix("0x").unwrap_or(val_str);
2609
+ let bits = u64::from_str_radix(hex, 16)
2610
+ .map_err(|_| PolyError::msg("E0716", "invalid float_bits constant"))?;
2611
+ Constant::Float(f64::from_bits(bits))
2612
+ }
2613
+ "str" => Constant::String(parse_escaped_str(val_str)?.0),
2614
+ _ => return Err(PolyError::msg("E0716", format!("unknown constant kind '{kind}'"))),
2615
+ };
2616
+ Ok(IrInstruction::LoadConst(dst, c))
2617
+ }
2618
+ "move" => {
2619
+ let (a, r) = split_ws_tok(rest)?;
2620
+ Ok(IrInstruction::Move(parse_reg(a)?, parse_reg(r)?))
2621
+ }
2622
+ "cast" => {
2623
+ let (d, r1) = split_ws_tok(rest)?;
2624
+ let (t, s) = split_ws_tok(r1)?;
2625
+ Ok(IrInstruction::Cast(
2626
+ parse_reg(d)?,
2627
+ parse_ir_type_name(t)?,
2628
+ parse_reg(s)?,
2629
+ ))
2630
+ }
2631
+ "binop" => {
2632
+ let (bop, r1) = split_ws_tok(rest)?;
2633
+ let (d, r2) = split_ws_tok(r1)?;
2634
+ let (l, r) = split_ws_tok(r2)?;
2635
+ Ok(IrInstruction::BinOp(
2636
+ parse_binop_name(bop)?,
2637
+ parse_reg(d)?,
2638
+ parse_reg(l)?,
2639
+ parse_reg(r)?,
2640
+ ))
2641
+ }
2642
+ "unary" => {
2643
+ let (uop, r1) = split_ws_tok(rest)?;
2644
+ let (d, s) = split_ws_tok(r1)?;
2645
+ Ok(IrInstruction::UnaryOp(
2646
+ parse_unary_name(uop)?,
2647
+ parse_reg(d)?,
2648
+ parse_reg(s)?,
2649
+ ))
2650
+ }
2651
+ "call_lazy" => {
2652
+ let (d, r1) = split_ws_tok(rest)?;
2653
+ let (id_tok, args_tok) = split_ws_tok(r1)?;
2654
+ Ok(IrInstruction::CallLazy(
2655
+ parse_reg(d)?,
2656
+ CallSiteId(parse_hash_u32(id_tok)?),
2657
+ parse_reg_list(args_tok)?,
2658
+ ))
2659
+ }
2660
+ "call_fn" => {
2661
+ let (d, r1) = split_ws_tok(rest)?;
2662
+ let (id_tok, args_tok) = split_ws_tok(r1)?;
2663
+ Ok(IrInstruction::CallFn(
2664
+ parse_reg(d)?,
2665
+ parse_fn_hash(id_tok)?,
2666
+ parse_reg_list(args_tok)?,
2667
+ ))
2668
+ }
2669
+ "call_indirect" => {
2670
+ let (d, r1) = split_ws_tok(rest)?;
2671
+ let (f, args_tok) = split_ws_tok(r1)?;
2672
+ Ok(IrInstruction::CallIndirect(
2673
+ parse_reg(d)?,
2674
+ parse_reg(f)?,
2675
+ parse_reg_list(args_tok)?,
2676
+ ))
2677
+ }
2678
+ "call_builtin" => {
2679
+ let (d, r1) = split_ws_tok(rest)?;
2680
+ let (b_tok, args_tok) = split_ws_tok(r1)?;
2681
+ Ok(IrInstruction::CallBuiltin(
2682
+ parse_reg(d)?,
2683
+ parse_builtin_name(b_tok)?,
2684
+ parse_reg_list(args_tok)?,
2685
+ ))
2686
+ }
2687
+ "resolve_fn" => {
2688
+ let (d, id_tok) = split_ws_tok(rest)?;
2689
+ Ok(IrInstruction::ResolveFn(
2690
+ parse_reg(d)?,
2691
+ CallSiteId(parse_hash_u32(id_tok)?),
2692
+ ))
2693
+ }
2694
+ "load_fn_ref" => {
2695
+ let (d, id_tok) = split_ws_tok(rest)?;
2696
+ Ok(IrInstruction::LoadFnRef(parse_reg(d)?, parse_fn_hash(id_tok)?))
2697
+ }
2698
+ "return" => {
2699
+ if rest.is_empty() {
2700
+ Ok(IrInstruction::Return(None))
2701
+ } else {
2702
+ Ok(IrInstruction::Return(Some(parse_reg(rest)?)))
2703
+ }
2704
+ }
2705
+ "branch_if" => {
2706
+ let (c, r1) = split_ws_tok(rest)?;
2707
+ let (t, f) = split_ws_tok(r1)?;
2708
+ Ok(IrInstruction::BranchIf(
2709
+ parse_reg(c)?,
2710
+ parse_bb(t)?,
2711
+ parse_bb(f)?,
2712
+ ))
2713
+ }
2714
+ "jump" => Ok(IrInstruction::Jump(parse_bb(rest)?)),
2715
+ "create_array" => {
2716
+ let (d, items) = split_ws_tok(rest)?;
2717
+ Ok(IrInstruction::CreateArray(
2718
+ parse_reg(d)?,
2719
+ parse_reg_list(items)?,
2720
+ ))
2721
+ }
2722
+ "get_index" => {
2723
+ let (d, r1) = split_ws_tok(rest)?;
2724
+ let (o, idx) = split_ws_tok(r1)?;
2725
+ Ok(IrInstruction::GetIndex(
2726
+ parse_reg(d)?,
2727
+ parse_reg(o)?,
2728
+ parse_reg(idx)?,
2729
+ ))
2730
+ }
2731
+ "set_index" => {
2732
+ let (o, r1) = split_ws_tok(rest)?;
2733
+ let (idx, v) = split_ws_tok(r1)?;
2734
+ Ok(IrInstruction::SetIndex(
2735
+ parse_reg(o)?,
2736
+ parse_reg(idx)?,
2737
+ parse_reg(v)?,
2738
+ ))
2739
+ }
2740
+ "create_object" => {
2741
+ let (d, r1) = split_ws_tok(rest)?;
2742
+ let (cname, _) = parse_escaped_str(r1)?;
2743
+ Ok(IrInstruction::CreateObject(parse_reg(d)?, cname))
2744
+ }
2745
+ "set_field" => {
2746
+ let (o, r1) = split_ws_tok(rest)?;
2747
+ let (fname, r2) = parse_escaped_str(r1)?;
2748
+ Ok(IrInstruction::SetField(
2749
+ parse_reg(o)?,
2750
+ fname,
2751
+ parse_reg(r2.trim())?,
2752
+ ))
2753
+ }
2754
+ "get_field" => {
2755
+ let (d, r1) = split_ws_tok(rest)?;
2756
+ let (o, r2) = split_ws_tok(r1)?;
2757
+ let (fname, _) = parse_escaped_str(r2)?;
2758
+ Ok(IrInstruction::GetField(parse_reg(d)?, parse_reg(o)?, fname))
2759
+ }
2760
+ "alloc_buf" => {
2761
+ let (d, s) = split_ws_tok(rest)?;
2762
+ Ok(IrInstruction::AllocBuffer(parse_reg(d)?, parse_reg(s)?))
2763
+ }
2764
+ "store_byte" => {
2765
+ let (b, r1) = split_ws_tok(rest)?;
2766
+ let (o, v) = split_ws_tok(r1)?;
2767
+ Ok(IrInstruction::StoreByte(
2768
+ parse_reg(b)?,
2769
+ parse_reg(o)?,
2770
+ parse_reg(v)?,
2771
+ ))
2772
+ }
2773
+ "load_byte" => {
2774
+ let (d, r1) = split_ws_tok(rest)?;
2775
+ let (b, o) = split_ws_tok(r1)?;
2776
+ Ok(IrInstruction::LoadByte(
2777
+ parse_reg(d)?,
2778
+ parse_reg(b)?,
2779
+ parse_reg(o)?,
2780
+ ))
2781
+ }
2782
+ other => Err(PolyError::msg(
2783
+ "E0716",
2784
+ format!("unknown IR opcode '{other}'"),
2785
+ )),
2786
+ }
2787
+ }
2788
+
2789
+ fn split_ws_tok(s: &str) -> Result<(&str, &str), PolyError> {
2790
+ let s = s.trim_start();
2791
+ if s.is_empty() {
2792
+ return Err(PolyError::msg("E0716", "unexpected end of IR instruction"));
2793
+ }
2794
+ match s.find(char::is_whitespace) {
2795
+ Some(idx) => Ok((&s[..idx], s[idx..].trim_start())),
2796
+ None => Ok((s, "")),
2797
+ }
2798
+ }
2799
+
2800
+ fn parse_reg(s: &str) -> Result<Register, PolyError> {
2801
+ let num = s
2802
+ .trim()
2803
+ .strip_prefix('r')
2804
+ .ok_or_else(|| PolyError::msg("E0716", format!("expected register rN, got '{s}'")))?;
2805
+ let idx: usize = num
2806
+ .parse()
2807
+ .map_err(|_| PolyError::msg("E0716", format!("invalid register '{s}'")))?;
2808
+ Ok(Register(idx))
2809
+ }
2810
+
2811
+ fn parse_bb(s: &str) -> Result<BasicBlockId, PolyError> {
2812
+ let num = s
2813
+ .trim()
2814
+ .strip_prefix("bb")
2815
+ .ok_or_else(|| PolyError::msg("E0716", format!("expected bbN, got '{s}'")))?;
2816
+ let idx: usize = num
2817
+ .parse()
2818
+ .map_err(|_| PolyError::msg("E0716", format!("invalid block id '{s}'")))?;
2819
+ Ok(BasicBlockId(idx))
2820
+ }
2821
+
2822
+ fn parse_hash_u32(s: &str) -> Result<u32, PolyError> {
2823
+ let num = s
2824
+ .trim()
2825
+ .strip_prefix('#')
2826
+ .ok_or_else(|| PolyError::msg("E0716", format!("expected #N, got '{s}'")))?;
2827
+ num.parse()
2828
+ .map_err(|_| PolyError::msg("E0716", format!("invalid id '{s}'")))
2829
+ }
2830
+
2831
+ fn parse_fn_hash(s: &str) -> Result<FnId, PolyError> {
2832
+ Ok(FnId(parse_hash_u32(s)?))
2833
+ }
2834
+
2835
+ fn parse_reg_list(s: &str) -> Result<Vec<Register>, PolyError> {
2836
+ let inner = s
2837
+ .trim()
2838
+ .strip_prefix('[')
2839
+ .and_then(|x| x.strip_suffix(']'))
2840
+ .ok_or_else(|| PolyError::msg("E0716", format!("expected [r...], got '{s}'")))?
2841
+ .trim();
2842
+ if inner.is_empty() {
2843
+ return Ok(Vec::new());
2844
+ }
2845
+ inner.split(',').map(parse_reg).collect()
2846
+ }
2847
+
2848
+ fn escape_str(s: &str) -> String {
2849
+ let mut out = String::with_capacity(s.len() + 2);
2850
+ out.push('"');
2851
+ for ch in s.chars() {
2852
+ match ch {
2853
+ '"' => out.push_str("\\\""),
2854
+ '\\' => out.push_str("\\\\"),
2855
+ '\n' => out.push_str("\\n"),
2856
+ '\r' => out.push_str("\\r"),
2857
+ '\t' => out.push_str("\\t"),
2858
+ '\0' => out.push_str("\\0"),
2859
+ c if (c as u32) < 0x20 || c as u32 == 0x7f => {
2860
+ let _ = write!(out, "\\u{{{:x}}}", c as u32);
2861
+ }
2862
+ c => out.push(c),
2863
+ }
2864
+ }
2865
+ out.push('"');
2866
+ out
2867
+ }
2868
+
2869
+ fn parse_escaped_str(s: &str) -> Result<(String, &str), PolyError> {
2870
+ let s = s.trim_start();
2871
+ let rest = s
2872
+ .strip_prefix('"')
2873
+ .ok_or_else(|| PolyError::msg("E0716", format!("expected quoted string near '{s}'")))?;
2874
+ let mut out = String::new();
2875
+ let mut chars = rest.char_indices();
2876
+ while let Some((idx, ch)) = chars.next() {
2877
+ match ch {
2878
+ '"' => return Ok((out, &rest[idx + 1..])),
2879
+ '\\' => match chars.next() {
2880
+ Some((_, '"')) => out.push('"'),
2881
+ Some((_, '\\')) => out.push('\\'),
2882
+ Some((_, 'n')) => out.push('\n'),
2883
+ Some((_, 'r')) => out.push('\r'),
2884
+ Some((_, 't')) => out.push('\t'),
2885
+ Some((_, '0')) => out.push('\0'),
2886
+ Some((_, 'u')) => {
2887
+ if !matches!(chars.next(), Some((_, '{'))) {
2888
+ return Err(PolyError::msg("E0716", "invalid \\u escape"));
2889
+ }
2890
+ let mut hex = String::new();
2891
+ let mut closed = false;
2892
+ for (_, hc) in chars.by_ref() {
2893
+ if hc == '}' {
2894
+ closed = true;
2895
+ break;
2896
+ }
2897
+ hex.push(hc);
2898
+ }
2899
+ if !closed {
2900
+ return Err(PolyError::msg("E0716", "unterminated \\u{...} escape"));
2901
+ }
2902
+ let code = u32::from_str_radix(&hex, 16)
2903
+ .ok()
2904
+ .and_then(char::from_u32)
2905
+ .ok_or_else(|| PolyError::msg("E0716", "invalid unicode scalar in escape"))?;
2906
+ out.push(code);
2907
+ }
2908
+ _ => return Err(PolyError::msg("E0716", "invalid escape in IR string")),
2909
+ },
2910
+ c => out.push(c),
2911
+ }
2912
+ }
2913
+ Err(PolyError::msg("E0716", "unterminated string in IR"))
2914
+ }
2915
+
2916
+ fn ir_type_name(t: IrType) -> &'static str {
2917
+ match t {
2918
+ IrType::Dynamic => "Dynamic",
2919
+ IrType::Void => "Void",
2920
+ IrType::Bool => "Bool",
2921
+ IrType::I64 => "I64",
2922
+ IrType::F64 => "F64",
2923
+ IrType::Str => "Str",
2924
+ }
2925
+ }
2926
+
2927
+ fn parse_ir_type_name(s: &str) -> Result<IrType, PolyError> {
2928
+ match s.trim() {
2929
+ "Dynamic" => Ok(IrType::Dynamic),
2930
+ "Void" => Ok(IrType::Void),
2931
+ "Bool" => Ok(IrType::Bool),
2932
+ "I64" => Ok(IrType::I64),
2933
+ "F64" => Ok(IrType::F64),
2934
+ "Str" => Ok(IrType::Str),
2935
+ other => Err(PolyError::msg("E0716", format!("unknown IrType '{other}'"))),
2936
+ }
2937
+ }
2938
+
2939
+ fn binop_name(op: IrBinOp) -> &'static str {
2940
+ match op {
2941
+ IrBinOp::Add => "Add",
2942
+ IrBinOp::Sub => "Sub",
2943
+ IrBinOp::Mul => "Mul",
2944
+ IrBinOp::Div => "Div",
2945
+ IrBinOp::FloorDiv => "FloorDiv",
2946
+ IrBinOp::Mod => "Mod",
2947
+ IrBinOp::Eq => "Eq",
2948
+ IrBinOp::Ne => "Ne",
2949
+ IrBinOp::Lt => "Lt",
2950
+ IrBinOp::Le => "Le",
2951
+ IrBinOp::Gt => "Gt",
2952
+ IrBinOp::Ge => "Ge",
2953
+ IrBinOp::And => "And",
2954
+ IrBinOp::Or => "Or",
2955
+ IrBinOp::BitAnd => "BitAnd",
2956
+ IrBinOp::BitOr => "BitOr",
2957
+ IrBinOp::BitXor => "BitXor",
2958
+ IrBinOp::Shl => "Shl",
2959
+ IrBinOp::Shr => "Shr",
2960
+ }
2961
+ }
2962
+
2963
+ fn parse_binop_name(s: &str) -> Result<IrBinOp, PolyError> {
2964
+ match s.trim() {
2965
+ "Add" => Ok(IrBinOp::Add),
2966
+ "Sub" => Ok(IrBinOp::Sub),
2967
+ "Mul" => Ok(IrBinOp::Mul),
2968
+ "Div" => Ok(IrBinOp::Div),
2969
+ "FloorDiv" => Ok(IrBinOp::FloorDiv),
2970
+ "Mod" => Ok(IrBinOp::Mod),
2971
+ "Eq" => Ok(IrBinOp::Eq),
2972
+ "Ne" => Ok(IrBinOp::Ne),
2973
+ "Lt" => Ok(IrBinOp::Lt),
2974
+ "Le" => Ok(IrBinOp::Le),
2975
+ "Gt" => Ok(IrBinOp::Gt),
2976
+ "Ge" => Ok(IrBinOp::Ge),
2977
+ "And" => Ok(IrBinOp::And),
2978
+ "Or" => Ok(IrBinOp::Or),
2979
+ "BitAnd" => Ok(IrBinOp::BitAnd),
2980
+ "BitOr" => Ok(IrBinOp::BitOr),
2981
+ "BitXor" => Ok(IrBinOp::BitXor),
2982
+ "Shl" => Ok(IrBinOp::Shl),
2983
+ "Shr" => Ok(IrBinOp::Shr),
2984
+ other => Err(PolyError::msg("E0716", format!("unknown BinOp '{other}'"))),
2985
+ }
2986
+ }
2987
+
2988
+ fn unary_name(op: IrUnaryOp) -> &'static str {
2989
+ match op {
2990
+ IrUnaryOp::Neg => "Neg",
2991
+ IrUnaryOp::Not => "Not",
2992
+ IrUnaryOp::BitNot => "BitNot",
2993
+ IrUnaryOp::BitsToF64 => "BitsToF64",
2994
+ }
2995
+ }
2996
+
2997
+ fn parse_unary_name(s: &str) -> Result<IrUnaryOp, PolyError> {
2998
+ match s.trim() {
2999
+ "Neg" => Ok(IrUnaryOp::Neg),
3000
+ "Not" => Ok(IrUnaryOp::Not),
3001
+ "BitNot" => Ok(IrUnaryOp::BitNot),
3002
+ "BitsToF64" => Ok(IrUnaryOp::BitsToF64),
3003
+ other => Err(PolyError::msg("E0716", format!("unknown UnaryOp '{other}'"))),
3004
+ }
3005
+ }
3006
+
3007
+ fn builtin_name(b: BuiltinId) -> &'static str {
3008
+ match b {
3009
+ BuiltinId::Print => "Print",
3010
+ BuiltinId::Println => "Println",
3011
+ BuiltinId::Printf => "Printf",
3012
+ BuiltinId::Len => "Len",
3013
+ BuiltinId::Str => "Str",
3014
+ BuiltinId::Int => "Int",
3015
+ BuiltinId::Float => "Float",
3016
+ BuiltinId::Bool => "Bool",
3017
+ BuiltinId::Abs => "Abs",
3018
+ BuiltinId::Min => "Min",
3019
+ BuiltinId::Max => "Max",
3020
+ BuiltinId::Sqrt => "Sqrt",
3021
+ BuiltinId::Pow => "Pow",
3022
+ BuiltinId::Push => "Push",
3023
+ BuiltinId::Pop => "Pop",
3024
+ BuiltinId::TypeOf => "TypeOf",
3025
+ BuiltinId::AllocBuf => "AllocBuf",
3026
+ BuiltinId::ReadU8 => "ReadU8",
3027
+ BuiltinId::WriteU8 => "WriteU8",
3028
+ BuiltinId::BufLen => "BufLen",
3029
+ BuiltinId::ClockMs => "ClockMs",
3030
+ BuiltinId::Assert => "Assert",
3031
+ }
3032
+ }
3033
+
3034
+ fn parse_builtin_name(s: &str) -> Result<BuiltinId, PolyError> {
3035
+ match s.trim() {
3036
+ "Print" => Ok(BuiltinId::Print),
3037
+ "Println" => Ok(BuiltinId::Println),
3038
+ "Printf" => Ok(BuiltinId::Printf),
3039
+ "Len" => Ok(BuiltinId::Len),
3040
+ "Str" => Ok(BuiltinId::Str),
3041
+ "Int" => Ok(BuiltinId::Int),
3042
+ "Float" => Ok(BuiltinId::Float),
3043
+ "Bool" => Ok(BuiltinId::Bool),
3044
+ "Abs" => Ok(BuiltinId::Abs),
3045
+ "Min" => Ok(BuiltinId::Min),
3046
+ "Max" => Ok(BuiltinId::Max),
3047
+ "Sqrt" => Ok(BuiltinId::Sqrt),
3048
+ "Pow" => Ok(BuiltinId::Pow),
3049
+ "Push" => Ok(BuiltinId::Push),
3050
+ "Pop" => Ok(BuiltinId::Pop),
3051
+ "TypeOf" => Ok(BuiltinId::TypeOf),
3052
+ "AllocBuf" => Ok(BuiltinId::AllocBuf),
3053
+ "ReadU8" => Ok(BuiltinId::ReadU8),
3054
+ "WriteU8" => Ok(BuiltinId::WriteU8),
3055
+ "BufLen" => Ok(BuiltinId::BufLen),
3056
+ "ClockMs" => Ok(BuiltinId::ClockMs),
3057
+ "Assert" => Ok(BuiltinId::Assert),
3058
+ other => Err(PolyError::msg("E0716", format!("unknown BuiltinId '{other}'"))),
3059
+ }
3060
+ }
3061
+
3062
+ // ============================================================================
3063
+ // Pure-Rust RFC 4648 Base64 + Hex Utilities
3064
+ // ============================================================================
3065
+
3066
+ const B64_TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3067
+
3068
+ fn base64_encode_wrapped(data: &[u8], line_width: usize) -> String {
3069
+ let mut raw = String::with_capacity(data.len().div_ceil(3) * 4);
3070
+ for chunk in data.chunks(3) {
3071
+ let b0 = chunk[0];
3072
+ let b1 = *chunk.get(1).unwrap_or(&0);
3073
+ let b2 = *chunk.get(2).unwrap_or(&0);
3074
+ let triple = (u32::from(b0) << 16) | (u32::from(b1) << 8) | u32::from(b2);
3075
+ raw.push(B64_TABLE[((triple >> 18) & 0x3f) as usize] as char);
3076
+ raw.push(B64_TABLE[((triple >> 12) & 0x3f) as usize] as char);
3077
+ raw.push(if chunk.len() > 1 {
3078
+ B64_TABLE[((triple >> 6) & 0x3f) as usize] as char
3079
+ } else {
3080
+ '='
3081
+ });
3082
+ raw.push(if chunk.len() > 2 {
3083
+ B64_TABLE[(triple & 0x3f) as usize] as char
3084
+ } else {
3085
+ '='
3086
+ });
3087
+ }
3088
+ if line_width == 0 || raw.len() <= line_width {
3089
+ return raw;
3090
+ }
3091
+ let mut wrapped = String::with_capacity(raw.len() + raw.len() / line_width + 2);
3092
+ for (idx, ch) in raw.bytes().enumerate() {
3093
+ if idx > 0 && idx % line_width == 0 {
3094
+ wrapped.push('\n');
3095
+ }
3096
+ wrapped.push(ch as char);
3097
+ }
3098
+ wrapped
3099
+ }
3100
+
3101
+ fn base64_decode(input: &str) -> Result<Vec<u8>, PolyError> {
3102
+ let clean: Vec<u8> = input
3103
+ .bytes()
3104
+ .filter(|b| !b.is_ascii_whitespace())
3105
+ .collect();
3106
+ if clean.is_empty() || clean.len() % 4 != 0 {
3107
+ return Err(PolyError::msg("E0707", "invalid base64 payload length"));
3108
+ }
3109
+ let mut out = Vec::with_capacity((clean.len() / 4) * 3);
3110
+ for (idx, chunk) in clean.chunks_exact(4).enumerate() {
3111
+ let is_last = idx + 1 == clean.len() / 4;
3112
+ let a = b64_val(chunk[0])?;
3113
+ let b = b64_val(chunk[1])?;
3114
+ let pad_c = chunk[2] == b'=';
3115
+ let pad_d = chunk[3] == b'=';
3116
+ if (pad_c || pad_d) && !is_last {
3117
+ return Err(PolyError::msg("E0707", "invalid base64 padding"));
3118
+ }
3119
+ if pad_c && !pad_d {
3120
+ return Err(PolyError::msg("E0707", "invalid base64 padding"));
3121
+ }
3122
+ let c = if pad_c { 0 } else { b64_val(chunk[2])? };
3123
+ let d = if pad_d { 0 } else { b64_val(chunk[3])? };
3124
+ let triple = (u32::from(a) << 18)
3125
+ | (u32::from(b) << 12)
3126
+ | (u32::from(c) << 6)
3127
+ | u32::from(d);
3128
+ out.push(((triple >> 16) & 0xff) as u8);
3129
+ if !pad_c {
3130
+ out.push(((triple >> 8) & 0xff) as u8);
3131
+ }
3132
+ if !pad_d {
3133
+ out.push((triple & 0xff) as u8);
3134
+ }
3135
+ }
3136
+ Ok(out)
3137
+ }
3138
+
3139
+ fn b64_val(b: u8) -> Result<u8, PolyError> {
3140
+ match b {
3141
+ b'A'..=b'Z' => Ok(b - b'A'),
3142
+ b'a'..=b'z' => Ok(b - b'a' + 26),
3143
+ b'0'..=b'9' => Ok(b - b'0' + 52),
3144
+ b'+' => Ok(62),
3145
+ b'/' => Ok(63),
3146
+ _ => Err(PolyError::msg("E0707", "invalid base64 character in POLYX")),
3147
+ }
3148
+ }
3149
+
3150
+ pub fn encode_hex(bytes: &[u8]) -> String {
3151
+ let mut s = String::with_capacity(bytes.len() * 2);
3152
+ for b in bytes {
3153
+ let _ = write!(s, "{b:02x}");
3154
+ }
3155
+ s
3156
+ }
3157
+
3158
+ fn decode_hex_exact<const N: usize>(hex: &str) -> Option<[u8; N]> {
3159
+ if hex.len() != N * 2 {
3160
+ return None;
3161
+ }
3162
+ let mut out = [0u8; N];
3163
+ for (i, slot) in out.iter_mut().enumerate() {
3164
+ *slot = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).ok()?;
3165
+ }
3166
+ Some(out)
3167
+ }
3168
+
3169
+ pub fn decode_hex_16(hex: &str) -> Option<[u8; 16]> {
3170
+ decode_hex_exact::<16>(hex)
3171
+ }
3172
+ pub fn decode_hex_24(hex: &str) -> Option<[u8; 24]> {
3173
+ decode_hex_exact::<24>(hex)
3174
+ }
3175
+ pub fn decode_hex_32(hex: &str) -> Option<[u8; 32]> {
3176
+ decode_hex_exact::<32>(hex)
3177
+ }
3178
+ pub fn decode_hex_64(hex: &str) -> Option<[u8; 64]> {
3179
+ decode_hex_exact::<64>(hex)
3180
+ }