1use alloc::vec;
6use alloc::vec::Vec;
7use core::iter::repeat_n;
8use hekate_core::config::{Config, FoldShape, MIN_PRODUCTION_BITS};
9use hekate_core::errors::Error;
10use hekate_core::poly::PolyVariant;
11use hekate_core::trace::{ColumnType, Trace, TraceColumn, TraceCompatibleField};
12use hekate_core::utils::{compute_split_vars, support_floor_vars};
13use hekate_math::{
14 Bit, Block8, Block16, Block32, Block64, Block128, Flat, HardwareField, TowerField,
15};
16
17pub const RING_BLIND_BITS: usize = 128;
18
19#[derive(Clone, Copy, Debug)]
21pub enum ExpansionEntry {
22 ExpandBits {
23 count: usize,
24 storage: ColumnType,
25 },
26 PassThrough {
27 count: usize,
28 storage: ColumnType,
29 },
30 ControlBits {
31 count: usize,
32 },
33 ReusePassThrough {
34 phy_col_start: usize,
35 count: usize,
36 storage: ColumnType,
37 },
38 ReuseExpandBits {
39 phy_col_start: usize,
40 count: usize,
41 storage: ColumnType,
42 },
43}
44
45#[derive(Clone, Copy, Debug)]
47enum EntryKind {
48 ExpandBits { count: usize, storage: ColumnType },
51
52 PassThrough { count: usize, storage: ColumnType },
55
56 ControlBits { count: usize },
59}
60
61impl EntryKind {
62 fn count(&self) -> usize {
63 match self {
64 Self::ExpandBits { count, .. }
65 | Self::PassThrough { count, .. }
66 | Self::ControlBits { count } => *count,
67 }
68 }
69
70 fn storage(&self) -> ColumnType {
71 match self {
72 Self::ExpandBits { storage, .. } | Self::PassThrough { storage, .. } => *storage,
73 Self::ControlBits { .. } => ColumnType::Bit,
74 }
75 }
76}
77
78#[derive(Clone, Copy, Debug)]
81struct CompiledEntry {
82 phy_col_start: usize,
85
86 byte_offset: usize,
88 kind: EntryKind,
89
90 reuse: bool,
93}
94
95#[derive(Clone, Debug)]
103pub struct VirtualExpander {
104 entries: Vec<CompiledEntry>,
105 num_virtual: usize,
106 num_physical: usize,
107 physical_row_bytes: usize,
108 virtual_layout: Vec<ColumnType>,
109 error: Option<Error>,
110}
111
112impl VirtualExpander {
113 pub fn new() -> Self {
114 Self {
115 entries: Vec::new(),
116 num_virtual: 0,
117 num_physical: 0,
118 physical_row_bytes: 0,
119 virtual_layout: Vec::new(),
120 error: None,
121 }
122 }
123
124 pub fn build(self) -> Result<Self, Error> {
127 match self.error {
128 Some(e) => Err(e),
129 None => Ok(self),
130 }
131 }
132
133 pub fn expand_bits(mut self, count: usize, storage: ColumnType) -> Self {
136 if self.error.is_some() {
137 return self;
138 }
139
140 let bits_per = match expand_bit_width(storage) {
141 Ok(v) => v,
142 Err(e) => {
143 self.error = Some(e);
144 return self;
145 }
146 };
147
148 let byte_offset = self.physical_row_bytes;
149 let phy_col_start = self.num_physical;
150
151 self.entries.push(CompiledEntry {
152 phy_col_start,
153 byte_offset,
154 kind: EntryKind::ExpandBits { count, storage },
155 reuse: false,
156 });
157
158 let virt_count = count * bits_per;
159 self.virtual_layout
160 .extend(repeat_n(ColumnType::Bit, virt_count));
161
162 self.num_virtual += virt_count;
163 self.num_physical += count;
164 self.physical_row_bytes += count * storage.byte_size();
165
166 self
167 }
168
169 pub fn pass_through(mut self, count: usize, storage: ColumnType) -> Self {
172 let byte_offset = self.physical_row_bytes;
173 let phy_col_start = self.num_physical;
174
175 self.entries.push(CompiledEntry {
176 phy_col_start,
177 byte_offset,
178 kind: EntryKind::PassThrough { count, storage },
179 reuse: false,
180 });
181
182 self.virtual_layout.extend(repeat_n(storage, count));
183
184 self.num_virtual += count;
185 self.num_physical += count;
186 self.physical_row_bytes += count * storage.byte_size();
187
188 self
189 }
190
191 pub fn control_bits(mut self, count: usize) -> Self {
193 let byte_offset = self.physical_row_bytes;
194 let phy_col_start = self.num_physical;
195
196 self.entries.push(CompiledEntry {
197 phy_col_start,
198 byte_offset,
199 kind: EntryKind::ControlBits { count },
200 reuse: false,
201 });
202
203 self.virtual_layout.extend(repeat_n(ColumnType::Bit, count));
204
205 self.num_virtual += count;
206 self.num_physical += count;
207 self.physical_row_bytes += count;
208
209 self
210 }
211
212 pub fn reuse_pass_through(mut self, phy_col_start: usize, count: usize) -> Self {
216 if self.error.is_some() {
217 return self;
218 }
219
220 if phy_col_start + count > self.num_physical {
221 self.error = Some(Error::Protocol {
222 protocol: "virtual_expand",
223 message: "reuse_pass_through: range exceeds declared physical columns",
224 });
225 return self;
226 }
227
228 let (byte_offset, storage) = match self.find_phy_source(phy_col_start, count) {
229 Ok(v) => v,
230 Err(e) => {
231 self.error = Some(e);
232 return self;
233 }
234 };
235
236 self.entries.push(CompiledEntry {
237 phy_col_start,
238 byte_offset,
239 kind: EntryKind::PassThrough { count, storage },
240 reuse: true,
241 });
242
243 self.virtual_layout.extend(repeat_n(storage, count));
244
245 self.num_virtual += count;
246
247 self
248 }
249
250 pub fn reuse_expand_bits(mut self, phy_col_start: usize, count: usize) -> Self {
254 if self.error.is_some() {
255 return self;
256 }
257
258 if phy_col_start + count > self.num_physical {
259 self.error = Some(Error::Protocol {
260 protocol: "virtual_expand",
261 message: "reuse_expand_bits: range exceeds declared physical columns",
262 });
263 return self;
264 }
265
266 let (byte_offset, storage) = match self.find_phy_source(phy_col_start, count) {
267 Ok(v) => v,
268 Err(e) => {
269 self.error = Some(e);
270 return self;
271 }
272 };
273
274 let bits_per = match expand_bit_width(storage) {
275 Ok(v) => v,
276 Err(e) => {
277 self.error = Some(e);
278 return self;
279 }
280 };
281
282 self.entries.push(CompiledEntry {
283 phy_col_start,
284 byte_offset,
285 kind: EntryKind::ExpandBits { count, storage },
286 reuse: true,
287 });
288
289 let virt_count = count * bits_per;
290 self.virtual_layout
291 .extend(repeat_n(ColumnType::Bit, virt_count));
292
293 self.num_virtual += virt_count;
294
295 self
296 }
297
298 pub fn append(mut self, other: &VirtualExpander) -> Self {
302 if self.error.is_some() {
303 return self;
304 }
305
306 if let Some(e) = &other.error {
307 self.error = Some(*e);
308 return self;
309 }
310
311 let phy_shift = self.num_physical;
312 let byte_shift = self.physical_row_bytes;
313
314 for entry in &other.entries {
315 self.entries.push(CompiledEntry {
316 phy_col_start: entry.phy_col_start + phy_shift,
317 byte_offset: entry.byte_offset + byte_shift,
318 kind: entry.kind,
319 reuse: entry.reuse,
320 });
321 }
322
323 self.virtual_layout.extend_from_slice(&other.virtual_layout);
324
325 self.num_virtual += other.num_virtual;
326 self.num_physical += other.num_physical;
327 self.physical_row_bytes += other.physical_row_bytes;
328
329 self
330 }
331
332 #[inline]
333 pub fn num_virtual_columns(&self) -> usize {
334 self.num_virtual
335 }
336
337 #[inline]
338 pub fn num_physical_columns(&self) -> usize {
339 self.num_physical
340 }
341
342 #[inline]
343 pub fn physical_row_bytes(&self) -> usize {
344 self.physical_row_bytes
345 }
346
347 #[inline]
348 pub fn virtual_layout(&self) -> &[ColumnType] {
349 &self.virtual_layout
350 }
351
352 pub fn parse_row<F: TraceCompatibleField>(
356 &self,
357 bytes: &[u8],
358 res: &mut Vec<Flat<F>>,
359 ) -> Result<(), Error> {
360 if bytes.len() != self.physical_row_bytes {
361 return Err(Error::Protocol {
362 protocol: "virtual_expand",
363 message: "parse_row: byte slice length mismatch",
364 });
365 }
366
367 res.reserve(self.num_virtual);
368
369 for entry in &self.entries {
370 let off = entry.byte_offset;
371 match entry.kind {
372 EntryKind::ExpandBits { count, storage } => {
373 let bsz = storage.byte_size();
374 let bits = expand_bit_width(storage)?;
375
376 for i in 0..count {
377 let start = off + i * bsz;
378 for bit_idx in 0..bits {
379 let bit = parse_tower_bit(storage, &bytes[start..start + bsz], bit_idx);
380 res.push(Flat::from_raw(F::from(Bit::from(bit))));
381 }
382 }
383 }
384 EntryKind::PassThrough { count, storage } => {
385 let bsz = storage.byte_size();
386 for i in 0..count {
387 let start = off + i * bsz;
388 res.push(storage.parse_from_bytes(&bytes[start..start + bsz]));
389 }
390 }
391 EntryKind::ControlBits { count } => {
392 for i in 0..count {
393 res.push(Flat::from_raw(F::from(Bit::from(bytes[off + i] & 1))));
394 }
395 }
396 }
397 }
398
399 Ok(())
400 }
401
402 pub fn expand_variants<'a, F, T: Trace + ?Sized>(
406 &self,
407 trace: &'a T,
408 phy_start_idx: usize,
409 ) -> Result<Vec<PolyVariant<'a, F>>, Error>
410 where
411 F: TraceCompatibleField + 'static,
412 {
413 let columns = trace.columns();
414
415 let mut variants = Vec::with_capacity(self.num_virtual);
416 for entry in &self.entries {
417 let base = phy_start_idx + entry.phy_col_start;
418 match entry.kind {
419 EntryKind::ExpandBits { count, storage } => {
420 let bits = expand_bit_width(storage)?;
421 for i in 0..count {
422 let col = columns.get(base + i).ok_or(Error::Protocol {
423 protocol: "virtual_expand",
424 message: "missing physical column for ExpandBits",
425 })?;
426
427 for bit_idx in 0..bits {
428 variants.push(expand_packed_bit(col, storage, bit_idx)?);
429 }
430 }
431 }
432 EntryKind::PassThrough { count, storage } => {
433 for i in 0..count {
434 let col = columns.get(base + i).ok_or(Error::Protocol {
435 protocol: "virtual_expand",
436 message: "missing physical column for PassThrough",
437 })?;
438
439 variants.push(expand_pass_through(col, storage)?);
440 }
441 }
442 EntryKind::ControlBits { count } => {
443 for i in 0..count {
444 let col = columns.get(base + i).ok_or(Error::Protocol {
445 protocol: "virtual_expand",
446 message: "missing physical column for ControlBits",
447 })?;
448 let data = col.as_bit_slice().ok_or(Error::Protocol {
449 protocol: "virtual_expand",
450 message: "control column must be Bit",
451 })?;
452
453 variants.push(PolyVariant::BitSlice(data));
454 }
455 }
456 }
457 }
458
459 Ok(variants)
460 }
461
462 pub fn expansion_entries(&self) -> Vec<ExpansionEntry> {
464 self.entries
465 .iter()
466 .map(|e| match (e.kind, e.reuse) {
467 (EntryKind::PassThrough { count, storage }, true) => {
468 ExpansionEntry::ReusePassThrough {
469 phy_col_start: e.phy_col_start,
470 count,
471 storage,
472 }
473 }
474 (EntryKind::ExpandBits { count, storage }, true) => {
475 ExpansionEntry::ReuseExpandBits {
476 phy_col_start: e.phy_col_start,
477 count,
478 storage,
479 }
480 }
481 (EntryKind::ExpandBits { count, storage }, false) => {
482 ExpansionEntry::ExpandBits { count, storage }
483 }
484 (EntryKind::PassThrough { count, storage }, false) => {
485 ExpansionEntry::PassThrough { count, storage }
486 }
487 (EntryKind::ControlBits { count }, _) => ExpansionEntry::ControlBits { count },
488 })
489 .collect()
490 }
491
492 fn find_phy_source(
495 &self,
496 target_start: usize,
497 target_count: usize,
498 ) -> Result<(usize, ColumnType), Error> {
499 let mut running_phy = 0usize;
500 for entry in &self.entries {
501 if entry.phy_col_start != running_phy {
502 continue;
503 }
504
505 let entry_count = entry.kind.count();
506 let entry_end = running_phy + entry_count;
507
508 if target_start >= running_phy && target_start + target_count <= entry_end {
509 let storage = entry.kind.storage();
510 let offset_in_entry = target_start - running_phy;
511
512 return Ok((
513 entry.byte_offset + offset_in_entry * storage.byte_size(),
514 storage,
515 ));
516 }
517
518 running_phy = entry_end;
519 }
520
521 Err(Error::Protocol {
522 protocol: "virtual_expand",
523 message: "reuse: source columns not found in any single fresh entry",
524 })
525 }
526}
527
528impl Default for VirtualExpander {
529 fn default() -> Self {
530 Self::new()
531 }
532}
533
534pub struct RingSwitchPlan {
539 pub num_units: usize,
540 pub units: Vec<(bool, usize)>,
541 pub phys_rs: Vec<ColumnType>,
542 pub blind_slots: usize,
543 pub h_cols: usize,
544
545 phys_bit: Vec<Vec<usize>>,
546 phys_whole: Vec<Vec<usize>>,
547 h_whole: Vec<usize>,
548}
549
550impl RingSwitchPlan {
551 pub fn new(
552 layout: &[ColumnType],
553 entries: Option<&[ExpansionEntry]>,
554 num_blind: usize,
555 num_h: usize,
556 ) -> Result<Self, Error> {
557 let num_phys = layout.len();
558 let total = num_phys + num_blind;
559
560 let mut phys_bit = vec![Vec::new(); total];
561 let mut phys_whole = vec![Vec::new(); total];
562 let mut units: Vec<(bool, usize)> = Vec::new();
563
564 let mut phys_rs: Vec<ColumnType> = layout.iter().map(|ct| ct.rs_field()).collect();
565 phys_rs.extend((0..num_blind).map(|_| ColumnType::B128));
566
567 let bounds = |upper: usize| -> Result<(), Error> {
568 if upper > num_phys {
569 return Err(Error::Protocol {
570 protocol: "ring_switch_plan",
571 message: "expansion entry exceeds the physical column layout",
572 });
573 }
574
575 Ok(())
576 };
577
578 match entries {
579 Some(entries) => {
580 let mut running = 0usize;
581 for e in entries {
582 match *e {
583 ExpansionEntry::ExpandBits { count, storage } => {
584 let bits = expand_bit_width(storage)?;
585
586 bounds(running + count)?;
587
588 for j in 0..count {
589 phys_bit[running + j].push(units.len());
590 units.push((true, bits));
591 }
592
593 running += count;
594 }
595 ExpansionEntry::PassThrough { count, .. }
596 | ExpansionEntry::ControlBits { count } => {
597 bounds(running + count)?;
598
599 for j in 0..count {
600 phys_whole[running + j].push(units.len());
601 units.push((false, 1));
602 }
603
604 running += count;
605 }
606 ExpansionEntry::ReusePassThrough {
607 phy_col_start,
608 count,
609 ..
610 } => {
611 bounds(phy_col_start + count)?;
612
613 for j in 0..count {
614 phys_whole[phy_col_start + j].push(units.len());
615 units.push((false, 1));
616 }
617 }
618 ExpansionEntry::ReuseExpandBits {
619 phy_col_start,
620 count,
621 storage,
622 } => {
623 let bits = expand_bit_width(storage)?;
624
625 bounds(phy_col_start + count)?;
626
627 for j in 0..count {
628 phys_bit[phy_col_start + j].push(units.len());
629 units.push((true, bits));
630 }
631 }
632 }
633 }
634
635 if running != num_phys {
636 return Err(Error::Protocol {
637 protocol: "ring_switch_plan",
638 message: "expansion entries do not cover the physical column layout",
639 });
640 }
641 }
642 None => {
643 for pw in phys_whole.iter_mut().take(num_phys) {
644 pw.push(units.len());
645 units.push((false, 1));
646 }
647 }
648 }
649
650 let has_ring = units.iter().any(|(is_ring, _)| *is_ring);
651
652 for b in 0..num_blind {
653 phys_whole[num_phys + b].push(units.len());
654 units.push((false, 1));
655 }
656
657 let mut blind_slots = num_blind;
658
659 if has_ring && num_blind > 0 {
661 phys_bit.push(vec![units.len()]);
662 phys_whole.push(Vec::new());
663 phys_rs.push(ColumnType::B128);
664 units.push((true, RING_BLIND_BITS));
665 blind_slots += 1;
666 }
667
668 let mut h_whole = Vec::with_capacity(num_h);
669 for _ in 0..num_h {
670 h_whole.push(units.len());
671 units.push((false, 1));
672 }
673
674 let num_units = units.len();
675
676 Ok(Self {
677 units,
678 phys_bit,
679 phys_whole,
680 h_whole,
681 phys_rs,
682 blind_slots,
683 h_cols: num_h,
684 num_units,
685 })
686 }
687
688 pub fn has_ring(&self) -> bool {
689 self.units.iter().any(|(is_ring, _)| *is_ring)
690 }
691
692 pub fn has_ring_blind(&self) -> bool {
693 self.blind_slots > 0 && self.has_ring()
694 }
695
696 pub fn total_claims(&self) -> usize {
697 self.units.iter().map(|(_, n)| n).sum()
698 }
699
700 pub fn leaf_row_bytes(&self) -> usize {
701 self.phys_rs.iter().map(|ct| ct.byte_size()).sum()
702 }
703
704 pub fn h_leaf_row_bytes(&self) -> usize {
705 self.h_cols * ColumnType::B128.byte_size()
706 }
707
708 pub fn opened_row_bytes(&self) -> usize {
709 self.leaf_row_bytes() + self.h_leaf_row_bytes()
710 }
711
712 pub fn split_vars(&self, num_vars: usize, field_bits: usize, config: &Config) -> usize {
716 let split = compute_split_vars(
717 num_vars,
718 config.num_queries,
719 config.ldt_support_size,
720 self.opened_row_bytes(),
721 );
722
723 let floor = support_floor_vars(config.ldt_support_size)
724 .clamp(1, num_vars.max(1))
725 .min(split);
726
727 let bits = |c: usize| {
728 config.estimated_security_bits(
729 field_bits,
730 FoldShape {
731 grid_cols: 1 << c,
732 grid_rows: 1 << (num_vars - c),
733 units: self.num_units,
734 },
735 )
736 };
737
738 (floor..=split)
741 .rev()
742 .find(|&c| bits(c) >= MIN_PRODUCTION_BITS)
743 .unwrap_or(split)
744 }
745
746 pub fn column_coeffs<F>(&self, eta: Flat<F>) -> (Vec<Flat<F>>, Vec<Flat<F>>, Flat<F>)
750 where
751 F: HardwareField,
752 {
753 let mut eta_pows = Vec::with_capacity(self.num_units + 1);
754 let mut e = Flat::from_raw(F::ONE);
755
756 for _ in 0..=self.num_units {
757 eta_pows.push(e);
758 e *= eta;
759 }
760
761 let num_phys = self.phys_rs.len();
762 let total = num_phys + self.h_cols;
763
764 let mut coeff_bit = vec![Flat::from_raw(F::ZERO); total];
765 let mut coeff_whole = vec![Flat::from_raw(F::ZERO); total];
766
767 for p in 0..num_phys {
768 for &u in &self.phys_bit[p] {
769 coeff_bit[p] += eta_pows[u];
770 }
771
772 for &u in &self.phys_whole[p] {
773 coeff_whole[p] += eta_pows[u];
774 }
775 }
776
777 for (p, &u) in self.h_whole.iter().enumerate() {
778 coeff_whole[num_phys + p] += eta_pows[u];
779 }
780
781 (coeff_bit, coeff_whole, eta_pows[self.num_units])
782 }
783}
784
785fn expand_bit_width(storage: ColumnType) -> Result<usize, Error> {
786 match storage {
787 ColumnType::B8 => Ok(8),
788 ColumnType::B16 => Ok(16),
789 ColumnType::B32 => Ok(32),
790 ColumnType::B64 => Ok(64),
791 _ => Err(Error::Protocol {
792 protocol: "virtual_expand",
793 message: "ExpandBits requires B8/B16/B32/B64",
794 }),
795 }
796}
797
798fn parse_tower_bit(storage: ColumnType, bytes: &[u8], bit_idx: usize) -> u8 {
800 match storage {
801 ColumnType::B8 => Flat::from_raw(Block8(bytes[0])).tower_bit(bit_idx),
802 ColumnType::B16 => {
803 let mut arr = [0u8; 2];
804 arr.copy_from_slice(bytes);
805
806 Flat::from_raw(Block16(u16::from_le_bytes(arr))).tower_bit(bit_idx)
807 }
808 ColumnType::B32 => {
809 let mut arr = [0u8; 4];
810 arr.copy_from_slice(bytes);
811
812 Flat::from_raw(Block32(u32::from_le_bytes(arr))).tower_bit(bit_idx)
813 }
814 ColumnType::B64 => {
815 let mut arr = [0u8; 8];
816 arr.copy_from_slice(bytes);
817
818 Flat::from_raw(Block64(u64::from_le_bytes(arr))).tower_bit(bit_idx)
819 }
820 _ => unreachable!(),
821 }
822}
823
824fn expand_packed_bit<F: TraceCompatibleField + 'static>(
825 col: &'_ TraceColumn,
826 storage: ColumnType,
827 bit_idx: usize,
828) -> Result<PolyVariant<'_, F>, Error> {
829 match storage {
830 ColumnType::B8 => {
831 let data = col.as_b8_slice().ok_or(Error::Protocol {
832 protocol: "virtual_expand",
833 message: "ExpandBits B8: column type mismatch",
834 })?;
835
836 Ok(PolyVariant::PackedBitB8 { data, bit_idx })
837 }
838 ColumnType::B16 => {
839 let data = col.as_b16_slice().ok_or(Error::Protocol {
840 protocol: "virtual_expand",
841 message: "ExpandBits B16: column type mismatch",
842 })?;
843
844 Ok(PolyVariant::PackedBitB16 { data, bit_idx })
845 }
846 ColumnType::B32 => {
847 let data = col.as_b32_slice().ok_or(Error::Protocol {
848 protocol: "virtual_expand",
849 message: "ExpandBits B32: column type mismatch",
850 })?;
851
852 Ok(PolyVariant::PackedBitB32 { data, bit_idx })
853 }
854 ColumnType::B64 => {
855 let data = col.as_b64_slice().ok_or(Error::Protocol {
856 protocol: "virtual_expand",
857 message: "ExpandBits B64: column type mismatch",
858 })?;
859
860 Ok(PolyVariant::PackedBitB64 { data, bit_idx })
861 }
862 _ => unreachable!(),
863 }
864}
865
866fn expand_pass_through<F: TraceCompatibleField + 'static>(
867 col: &TraceColumn,
868 storage: ColumnType,
869) -> Result<PolyVariant<'_, F>, Error> {
870 match storage {
871 ColumnType::Bit => {
872 let data = col.as_bit_slice().ok_or(Error::Protocol {
873 protocol: "virtual_expand",
874 message: "PassThrough Bit: column type mismatch",
875 })?;
876
877 Ok(PolyVariant::BitSlice(data))
878 }
879 ColumnType::B8 => {
880 let data = col.as_b8_slice().ok_or(Error::Protocol {
881 protocol: "virtual_expand",
882 message: "PassThrough B8: column type mismatch",
883 })?;
884
885 Ok(PolyVariant::B8Slice(data))
886 }
887 ColumnType::B16 => {
888 let data = col.as_b16_slice().ok_or(Error::Protocol {
889 protocol: "virtual_expand",
890 message: "PassThrough B16: column type mismatch",
891 })?;
892
893 Ok(PolyVariant::B16Slice(data))
894 }
895 ColumnType::B32 => {
896 let data = col.as_b32_slice().ok_or(Error::Protocol {
897 protocol: "virtual_expand",
898 message: "PassThrough B32: column type mismatch",
899 })?;
900
901 Ok(PolyVariant::B32Slice(data))
902 }
903 ColumnType::B64 => {
904 let data = col.as_b64_slice().ok_or(Error::Protocol {
905 protocol: "virtual_expand",
906 message: "PassThrough B64: column type mismatch",
907 })?;
908
909 Ok(PolyVariant::B64Slice(data))
910 }
911 ColumnType::B128 => {
912 let data = col.as_b128_slice().ok_or(Error::Protocol {
913 protocol: "virtual_expand",
914 message: "PassThrough B128: column type mismatch",
915 })?;
916
917 Ok(PolyVariant::B128Slice(data))
918 }
919 }
920}
921
922pub fn eq_tensor_b(r: &[Block128]) -> Vec<Block128> {
923 let mut t = vec![Block128::ONE];
924 for &ri in r {
925 let len = t.len();
926 let mut nt = Vec::with_capacity(len * 2);
927
928 for &v in &t {
929 nt.push(v * (Block128::ONE + ri));
930 }
931
932 for &v in &t {
933 nt.push(v * ri);
934 }
935
936 t = nt;
937 }
938
939 t
940}
941
942pub fn ring_batch_b(bit_claims: &[Block128], eq_mix: &[Block128]) -> Block128 {
944 let mut acc = Block128::ZERO;
945 for (u, &m) in eq_mix.iter().enumerate() {
946 let mut shat = 0u128;
947 for (v, cv) in bit_claims.iter().enumerate() {
948 shat |= ((cv.0 >> u) & 1) << v;
949 }
950
951 acc += m * Block128(shat);
952 }
953
954 acc
955}
956
957pub fn ring_target<F>(
961 plan: &RingSwitchPlan,
962 claims: &[Flat<F>],
963 eta_tower: F,
964 r_mix: &[Block128],
965 shifted_claims: bool,
966) -> Block128
967where
968 F: HardwareField + Into<Block128>,
969{
970 let claim_halves = if shifted_claims { 2 } else { 1 };
971 let half = claims.len() / claim_halves;
972 let eq_mix = eq_tensor_b(r_mix);
973 let eta: Block128 = eta_tower.into();
974
975 let mut eta_pows = Vec::with_capacity(plan.num_units + 1);
976 let mut e = Block128::ONE;
977
978 for _ in 0..=plan.num_units {
979 eta_pows.push(e);
980 e *= eta;
981 }
982
983 let eta_shift = eta_pows[plan.num_units];
984
985 let base = [(0usize, Block128::ONE)];
986 let base_and_shift = [(0usize, Block128::ONE), (half, eta_shift)];
987 let offsets: &[(usize, Block128)] = if shifted_claims {
988 &base_and_shift
989 } else {
990 &base
991 };
992
993 let mut target = Block128::ZERO;
994 for &(offset, shift_mul) in offsets {
995 let half_claims = &claims[offset..offset + half];
996
997 let mut ci = 0usize;
998 for (unit_idx, &(is_ring, num_claims)) in plan.units.iter().enumerate() {
999 let weight = eta_pows[unit_idx] * shift_mul;
1000 if is_ring {
1001 let bits: Vec<Block128> = half_claims[ci..ci + num_claims]
1002 .iter()
1003 .map(|f| f.to_tower().into())
1004 .collect();
1005
1006 target += weight * ring_batch_b(&bits, &eq_mix);
1007 } else {
1008 let c: Block128 = half_claims[ci].to_tower().into();
1009 target += weight * c;
1010 }
1011
1012 ci += num_claims;
1013 }
1014 }
1015
1016 target
1017}
1018
1019pub fn claim_weights<F>(
1023 plan: &RingSwitchPlan,
1024 eta_tower: F,
1025 shifted_claims: bool,
1026) -> Vec<(bool, Block128)>
1027where
1028 F: HardwareField + Into<Block128>,
1029{
1030 let eta: Block128 = eta_tower.into();
1031
1032 let mut eta_pows = Vec::with_capacity(plan.num_units + 1);
1033 let mut e = Block128::ONE;
1034
1035 for _ in 0..=plan.num_units {
1036 eta_pows.push(e);
1037 e *= eta;
1038 }
1039
1040 let shifts: &[Block128] = if shifted_claims {
1041 &[Block128::ONE, eta_pows[plan.num_units]]
1042 } else {
1043 &[Block128::ONE]
1044 };
1045
1046 let mut weights = Vec::with_capacity(plan.total_claims() * shifts.len());
1047 for &shift_mul in shifts {
1048 for (unit_idx, &(is_ring, num_claims)) in plan.units.iter().enumerate() {
1049 let weight = eta_pows[unit_idx] * shift_mul;
1050 for v in 0..num_claims {
1051 let basis = if is_ring {
1052 Block128(1u128 << v)
1053 } else {
1054 Block128::ONE
1055 };
1056
1057 weights.push((is_ring, weight * basis));
1058 }
1059 }
1060 }
1061
1062 weights
1063}
1064
1065#[cfg(test)]
1066mod tests {
1067 use super::*;
1068 use hekate_core::trace::TraceBuilder;
1069 use hekate_math::{Block128, TowerField};
1070
1071 fn keccak_expander() -> VirtualExpander {
1072 VirtualExpander::new()
1073 .expand_bits(25, ColumnType::B64)
1074 .expand_bits(1, ColumnType::B64)
1075 .reuse_pass_through(0, 25)
1076 .control_bits(2)
1077 .build()
1078 .unwrap()
1079 }
1080
1081 fn keccak_physical_layout() -> Vec<ColumnType> {
1082 let mut layout = vec![ColumnType::B64; 26];
1083 layout.extend(repeat_n(ColumnType::Bit, 2));
1084
1085 layout
1086 }
1087
1088 fn plan_of(cols: usize) -> RingSwitchPlan {
1089 RingSwitchPlan::new(&vec![ColumnType::B128; cols], None, 1, 1).unwrap()
1090 }
1091
1092 #[test]
1093 fn ram_layout() {
1094 let e = VirtualExpander::new()
1095 .expand_bits(2, ColumnType::B32)
1096 .pass_through(13, ColumnType::B32)
1097 .pass_through(1, ColumnType::B128)
1098 .control_bits(4)
1099 .build()
1100 .unwrap();
1101
1102 assert_eq!(e.num_virtual_columns(), 82);
1103 assert_eq!(e.num_physical_columns(), 20);
1104 assert_eq!(e.physical_row_bytes(), 80);
1105
1106 let layout = e.virtual_layout();
1107
1108 assert_eq!(layout.len(), 82);
1109 assert!(layout[..64].iter().all(|&t| t == ColumnType::Bit));
1110 assert!(layout[64..77].iter().all(|&t| t == ColumnType::B32));
1111 assert_eq!(layout[77], ColumnType::B128);
1112 assert!(layout[78..82].iter().all(|&t| t == ColumnType::Bit));
1113 }
1114
1115 #[test]
1116 fn keccak_layout() {
1117 let e = VirtualExpander::new()
1118 .expand_bits(25, ColumnType::B64)
1119 .expand_bits(1, ColumnType::B64)
1120 .reuse_pass_through(0, 25)
1121 .control_bits(2)
1122 .build()
1123 .unwrap();
1124
1125 assert_eq!(e.num_virtual_columns(), 1691);
1126 assert_eq!(e.num_physical_columns(), 28);
1127 assert_eq!(e.physical_row_bytes(), 210);
1128
1129 let layout = e.virtual_layout();
1130
1131 assert_eq!(layout.len(), 1691);
1132 assert!(layout[..1600].iter().all(|&t| t == ColumnType::Bit));
1133 assert!(layout[1600..1664].iter().all(|&t| t == ColumnType::Bit));
1134 assert!(layout[1664..1689].iter().all(|&t| t == ColumnType::B64));
1135 assert!(layout[1689..1691].iter().all(|&t| t == ColumnType::Bit));
1136 }
1137
1138 #[test]
1139 fn ring_switch_plan_rejects_uncovered_columns() {
1140 let expander = keccak_expander();
1141 let entries = expander.expansion_entries();
1142
1143 let mut layout = keccak_physical_layout();
1144
1145 assert_eq!(expander.num_physical_columns(), layout.len());
1146 assert!(RingSwitchPlan::new(&layout, Some(&entries), 0, 0).is_ok());
1147
1148 layout.push(ColumnType::B64);
1149
1150 assert!(RingSwitchPlan::new(&layout, Some(&entries), 0, 0).is_err());
1151 }
1152
1153 #[test]
1154 fn ring_switch_plan_folds_every_committed_column() {
1155 let entries = keccak_expander().expansion_entries();
1156 let layout = keccak_physical_layout();
1157
1158 let plan = RingSwitchPlan::new(&layout, Some(&entries), 2, 0).unwrap();
1159
1160 let zero = Flat::from_raw(Block128::ZERO);
1161 let eta = Block128(0x2545F4914F6CDD1D_517CC1B727220A95).to_hardware();
1162 let (coeff_bit, coeff_whole, _) = plan.column_coeffs::<Block128>(eta);
1163
1164 for p in 0..plan.phys_rs.len() {
1165 assert!(
1166 coeff_bit[p] != zero || coeff_whole[p] != zero,
1167 "committed column {p} enters no master fold"
1168 );
1169 }
1170 }
1171
1172 #[test]
1173 fn h_units_trail_ring_blind() {
1174 let layout = [ColumnType::B32, ColumnType::B64];
1175 let expander = VirtualExpander::new()
1176 .expand_bits(1, ColumnType::B32)
1177 .pass_through(1, ColumnType::B64)
1178 .build()
1179 .unwrap();
1180 let entries = expander.expansion_entries();
1181
1182 let bare = RingSwitchPlan::new(&layout, Some(&entries), 1, 0).unwrap();
1183 let plan = RingSwitchPlan::new(&layout, Some(&entries), 1, 2).unwrap();
1184
1185 assert_eq!(plan.h_cols, 2);
1186 assert_eq!(plan.phys_rs, bare.phys_rs);
1187 assert_eq!(plan.total_claims(), bare.total_claims() + 2);
1188 assert_eq!(&plan.units[plan.num_units - 2..], &[(false, 1), (false, 1)]);
1189 assert_eq!(plan.units[plan.num_units - 3], (true, RING_BLIND_BITS));
1190 assert_eq!(plan.leaf_row_bytes(), bare.opened_row_bytes());
1191 assert_eq!(plan.opened_row_bytes(), bare.opened_row_bytes() + 32);
1192
1193 let eta = Block128::from(0x9E37_79B9u128).to_hardware();
1194 let (coeff_bit, coeff_whole, eta_shift) = plan.column_coeffs::<Block128>(eta);
1195 let n = plan.phys_rs.len();
1196
1197 let mut first_h = Flat::from_raw(Block128::ONE);
1198 for _ in 0..plan.num_units - 2 {
1199 first_h *= eta;
1200 }
1201
1202 assert_eq!(coeff_whole.len(), n + 2);
1203 assert_eq!(coeff_bit[n..], [Flat::from_raw(Block128::ZERO); 2]);
1204 assert_eq!(coeff_whole[n], first_h);
1205 assert_eq!(coeff_whole[n + 1], first_h * eta);
1206 assert_eq!(eta_shift, first_h * eta * eta);
1207 }
1208
1209 #[test]
1210 fn blinded_ring_plan_ends_in_ring_blind_unit() {
1211 let entries = keccak_expander().expansion_entries();
1212 let layout = keccak_physical_layout();
1213
1214 let raw = RingSwitchPlan::new(&layout, Some(&entries), 0, 0).unwrap();
1215 let blinded = RingSwitchPlan::new(&layout, Some(&entries), 2, 0).unwrap();
1216 let whole_only = RingSwitchPlan::new(&[ColumnType::B32; 3], None, 2, 0).unwrap();
1217
1218 assert_eq!(raw.blind_slots, 0);
1219 assert_eq!(raw.phys_rs.len(), layout.len());
1220
1221 assert_eq!(blinded.blind_slots, 3);
1222 assert_eq!(blinded.phys_rs.len(), layout.len() + 3);
1223 assert_eq!(blinded.units.last(), Some(&(true, RING_BLIND_BITS)));
1224 assert_eq!(
1225 blinded.total_claims(),
1226 raw.total_claims() + 2 + RING_BLIND_BITS
1227 );
1228
1229 assert_eq!(whole_only.blind_slots, 2);
1230 assert_eq!(whole_only.units.last(), Some(&(false, 1)));
1231
1232 let eta = Block128(0x2545F4914F6CDD1D_517CC1B727220A95).to_hardware();
1233 let (coeff_bit, coeff_whole, _) = blinded.column_coeffs::<Block128>(eta);
1234 let last = blinded.phys_rs.len() - 1;
1235
1236 assert_ne!(coeff_bit[last], Flat::from_raw(Block128::ZERO));
1237 assert_eq!(coeff_whole[last], Flat::from_raw(Block128::ZERO));
1238 }
1239
1240 #[test]
1241 fn reuse_partial_range() {
1242 let e = VirtualExpander::new()
1243 .expand_bits(10, ColumnType::B32)
1244 .reuse_pass_through(3, 4)
1245 .build()
1246 .unwrap();
1247
1248 assert_eq!(e.num_virtual_columns(), 324);
1249 assert_eq!(e.num_physical_columns(), 10);
1250 assert_eq!(e.physical_row_bytes(), 40);
1251
1252 let layout = e.virtual_layout();
1253
1254 assert_eq!(layout[320..324].len(), 4);
1255 assert!(layout[320..324].iter().all(|&t| t == ColumnType::B32));
1256 }
1257
1258 #[test]
1259 fn reuse_exceeds_declared() {
1260 let result = VirtualExpander::new()
1261 .expand_bits(5, ColumnType::B32)
1262 .reuse_pass_through(3, 5)
1263 .build();
1264
1265 assert!(result.is_err());
1266 }
1267
1268 #[test]
1269 fn reuse_expand_bits_from_pass_through() {
1270 let e = VirtualExpander::new()
1271 .pass_through(4, ColumnType::B64)
1272 .reuse_expand_bits(0, 4)
1273 .build()
1274 .unwrap();
1275
1276 assert_eq!(e.num_physical_columns(), 4);
1277 assert_eq!(e.physical_row_bytes(), 32);
1278 assert_eq!(e.num_virtual_columns(), 4 + 256);
1279
1280 let layout = e.virtual_layout();
1281
1282 assert!(layout[0..4].iter().all(|&t| t == ColumnType::B64));
1283 assert!(layout[4..260].iter().all(|&t| t == ColumnType::Bit));
1284 }
1285
1286 #[test]
1287 fn reuse_expand_bits_exceeds_declared() {
1288 let result = VirtualExpander::new()
1289 .pass_through(4, ColumnType::B64)
1290 .reuse_expand_bits(2, 4)
1291 .build();
1292
1293 assert!(result.is_err());
1294 }
1295
1296 #[test]
1297 fn reuse_expand_bits_rejects_b128_source() {
1298 let result = VirtualExpander::new()
1299 .pass_through(1, ColumnType::B128)
1300 .reuse_expand_bits(0, 1)
1301 .build();
1302
1303 assert!(result.is_err());
1304 }
1305
1306 #[test]
1307 fn expand_rejects_bit() {
1308 let result = VirtualExpander::new()
1309 .expand_bits(1, ColumnType::Bit)
1310 .build();
1311
1312 assert!(result.is_err());
1313 }
1314
1315 #[test]
1316 fn expand_rejects_b128() {
1317 let result = VirtualExpander::new()
1318 .expand_bits(1, ColumnType::B128)
1319 .build();
1320
1321 assert!(result.is_err());
1322 }
1323
1324 #[test]
1325 fn empty_expander() {
1326 let e = VirtualExpander::new();
1327 assert_eq!(e.num_virtual_columns(), 0);
1328 assert_eq!(e.num_physical_columns(), 0);
1329 assert_eq!(e.physical_row_bytes(), 0);
1330 assert!(e.virtual_layout().is_empty());
1331 }
1332
1333 #[test]
1334 fn parse_row_b32_roundtrip() {
1335 let expander = VirtualExpander::new()
1336 .expand_bits(1, ColumnType::B32)
1337 .pass_through(1, ColumnType::B32)
1338 .control_bits(1)
1339 .build()
1340 .unwrap();
1341
1342 let val: u32 = 0xDEAD_BEEF;
1343 let pass_val: u32 = 0x1234_5678;
1344
1345 let mut bytes = Vec::new();
1346 bytes.extend_from_slice(&val.to_le_bytes());
1347 bytes.extend_from_slice(&pass_val.to_le_bytes());
1348 bytes.push(1);
1349
1350 let mut res: Vec<Flat<Block128>> = Vec::new();
1351 expander.parse_row(&bytes, &mut res).unwrap();
1352
1353 assert_eq!(res.len(), 34);
1354
1355 for (bit_idx, elem) in res.iter().enumerate().take(32) {
1356 let expected = Flat::from_raw(Block32(val)).tower_bit(bit_idx);
1357 let got = elem.tower_bit(0);
1358 assert_eq!(got, expected, "bit {bit_idx} mismatch");
1359 }
1360
1361 let pass = res[32];
1362 assert_eq!(
1363 pass,
1364 <Block128 as hekate_math::FlatPromote<Block32>>::promote_flat(Flat::from_raw(Block32(
1365 pass_val
1366 )))
1367 );
1368
1369 let ctrl = res[33].tower_bit(0);
1370 assert_eq!(ctrl, 1);
1371 }
1372
1373 #[test]
1374 fn expand_variants_b32() {
1375 let expander = VirtualExpander::new()
1376 .expand_bits(1, ColumnType::B32)
1377 .pass_through(1, ColumnType::B32)
1378 .control_bits(1)
1379 .build()
1380 .unwrap();
1381
1382 let layout = [ColumnType::B32, ColumnType::B32, ColumnType::Bit];
1383 let num_vars = 2;
1384
1385 let mut tb = TraceBuilder::new(&layout, num_vars).unwrap();
1386 tb.set_b32(0, 0, Block32(0xAAAA_BBBB)).unwrap();
1387 tb.set_b32(1, 0, Block32(0x1111_2222)).unwrap();
1388 tb.set_bit(2, 0, Bit::ONE).unwrap();
1389
1390 let trace = tb.build();
1391
1392 let variants: Vec<PolyVariant<'_, Block128>> = expander.expand_variants(&trace, 0).unwrap();
1393
1394 assert_eq!(variants.len(), 34);
1395
1396 for (i, v) in variants.iter().enumerate().take(32) {
1397 assert!(matches!(v, PolyVariant::PackedBitB32 { bit_idx, .. } if *bit_idx == i));
1398 }
1399
1400 assert!(matches!(variants[32], PolyVariant::B32Slice(_)));
1401 assert!(matches!(variants[33], PolyVariant::BitSlice(_)));
1402 }
1403
1404 #[test]
1405 fn claim_weights_reproduce_ring_target() {
1406 let layout = [
1407 ColumnType::B32,
1408 ColumnType::B32,
1409 ColumnType::B64,
1410 ColumnType::Bit,
1411 ];
1412
1413 let expander = VirtualExpander::new()
1414 .expand_bits(2, ColumnType::B32)
1415 .pass_through(1, ColumnType::B64)
1416 .control_bits(1)
1417 .build()
1418 .unwrap();
1419
1420 let entries = expander.expansion_entries();
1421 let plan = RingSwitchPlan::new(&layout, Some(&entries), 2, 0).unwrap();
1422
1423 let mut state = 0x9e37_79b9_7f4a_7c15_0123_4567_89ab_cdefu128;
1424 let mut next = || {
1425 state ^= state << 13;
1426 state ^= state >> 7;
1427 state ^= state << 17;
1428
1429 Block128(state)
1430 };
1431
1432 let claims: Vec<Block128> = (0..2 * plan.total_claims()).map(|_| next()).collect();
1433 let eta = next();
1434 let r_mix: Vec<Block128> = (0..7).map(|_| next()).collect();
1435 let eq_mix = eq_tensor_b(&r_mix);
1436
1437 let flat: Vec<Flat<Block128>> = claims.iter().map(|c| c.to_hardware()).collect();
1438 let target = ring_target::<Block128>(&plan, &flat, eta, &r_mix, true);
1439
1440 let mut sum = Block128::ZERO;
1441 for ((is_ring, weight), claim) in claim_weights::<Block128>(&plan, eta, true)
1442 .into_iter()
1443 .zip(&claims)
1444 {
1445 let value = match is_ring {
1446 true => ring_batch_b(&[*claim], &eq_mix),
1447 false => *claim,
1448 };
1449
1450 sum += weight * value;
1451 }
1452
1453 assert_eq!(sum, target);
1454 }
1455
1456 #[test]
1460 fn adaptive_split_clears_floor_whenever_any_split_can() {
1461 let config = Config::prod();
1462
1463 let mut stepped_down = 0;
1464 for cols in [1usize, 4, 16, 64, 128] {
1465 let plan = plan_of(cols);
1466 for num_vars in 10usize..=30 {
1467 let chosen = plan.split_vars(num_vars, 128, &config);
1468 let bits = |c: usize| {
1469 config.estimated_security_bits(
1470 128,
1471 FoldShape {
1472 grid_cols: 1 << c,
1473 grid_rows: 1 << (num_vars - c),
1474 units: plan.num_units,
1475 },
1476 )
1477 };
1478
1479 let optimal = compute_split_vars(
1480 num_vars,
1481 config.num_queries,
1482 config.ldt_support_size,
1483 plan.opened_row_bytes(),
1484 );
1485
1486 assert!(chosen <= optimal, "cols={cols} n={num_vars}: stepped up");
1487 assert!(
1488 chosen >= support_floor_vars(config.ldt_support_size).min(optimal),
1489 "cols={cols} n={num_vars}: below the support floor"
1490 );
1491
1492 if chosen < optimal {
1493 stepped_down += 1;
1494 }
1495
1496 let best = (1..=optimal).map(bits).max().unwrap();
1497
1498 if best >= MIN_PRODUCTION_BITS {
1499 assert!(
1500 bits(chosen) >= MIN_PRODUCTION_BITS,
1501 "cols={cols} n={num_vars}: chose {chosen} at {} bits, \
1502 but some split reaches {best}",
1503 bits(chosen),
1504 );
1505 }
1506 }
1507 }
1508
1509 assert!(stepped_down > 0, "the adaptive walk never fired");
1510 }
1511}