Skip to main content

hekate_program/
expander.rs

1// SPDX-FileCopyrightText: 2026 Andrei Kochergin <andrei@oumuamua.dev>
2// SPDX-FileCopyrightText: 2026 Oumuamua Labs <info@oumuamua.dev>
3// SPDX-License-Identifier: AGPL-3.0-only
4
5use alloc::vec;
6use alloc::vec::Vec;
7use core::iter::repeat_n;
8use hekate_core::config::Config;
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;
13use hekate_math::{
14    Bit, Block8, Block16, Block32, Block64, Block128, Flat, HardwareField, TowerField,
15};
16
17pub const RING_BLIND_BITS: usize = 128;
18
19/// Serializable expansion step descriptor.
20#[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/// Physical-to-virtual column mapping rule.
46#[derive(Clone, Copy, Debug)]
47enum EntryKind {
48    /// N physical columns to N ×
49    /// bit_width virtual Bit columns.
50    ExpandBits { count: usize, storage: ColumnType },
51
52    /// N physical columns to N virtual
53    /// columns of the same type.
54    PassThrough { count: usize, storage: ColumnType },
55
56    /// N physical Bit columns
57    /// to N virtual Bit columns.
58    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/// Pre-computed expansion entry
79/// with frozen byte/column offsets.
80#[derive(Clone, Copy, Debug)]
81struct CompiledEntry {
82    /// Physical column index,
83    /// relative to `phy_start_idx`.
84    phy_col_start: usize,
85
86    /// Byte offset in the committed row.
87    byte_offset: usize,
88    kind: EntryKind,
89
90    /// True if this entry reuses physical
91    /// columns declared by a prior entry.
92    reuse: bool,
93}
94
95/// Declarative physical->virtual
96/// column expander for chiplets.
97///
98/// Built once per chiplet, generates
99/// `virtual_layout()`, `parse_row()`,
100/// and `expand_variants()` from the
101/// same packing specification.
102#[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    /// Finalize the builder. Returns `Err` if any
125    /// builder step recorded a validation error.
126    pub fn build(self) -> Result<Self, Error> {
127        match self.error {
128            Some(e) => Err(e),
129            None => Ok(self),
130        }
131    }
132
133    /// N physical columns of `storage` type
134    /// to N × bit_width virtual Bit columns.
135    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    /// N physical columns pass through
170    /// 1:1 as virtual columns.
171    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    /// N physical Bit columns pass through 1:1.
192    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    /// Emit pass-through for columns already
213    /// declared by a prior fresh entry.
214    /// Does not advance the physical cursor.
215    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    /// Emit bit-expansion for columns already
251    /// declared by a prior fresh entry.
252    /// Does not advance the physical cursor.
253    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    /// Append another expander's entries after this
299    /// one's, shifting its physical references onto
300    /// this expander's coordinate space.
301    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    /// Verifier-side:
353    /// parse committed physical row bytes
354    /// into virtual field elements.
355    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    /// Prover-side:
403    /// expand physical `ColumnTrace`
404    /// into virtual `PolyVariant`s.
405    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    /// Wire-format serialization descriptor.
463    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    // Fresh entries have phy_col_start == running_phy;
493    // reuse entries point backward.
494    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
534/// Maps the claimed virtual evals and the committed columns
535/// onto ring-switch binding units. `eta^k` runs once per
536/// unit (in claim order); a bit-expanded physical column
537/// is one Ring unit consuming its `bits` claims.
538pub 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
544    phys_bit: Vec<Vec<usize>>,
545    phys_whole: Vec<Vec<usize>>,
546}
547
548impl RingSwitchPlan {
549    pub fn new(
550        layout: &[ColumnType],
551        entries: Option<&[ExpansionEntry]>,
552        num_blind: usize,
553    ) -> Result<Self, Error> {
554        let num_phys = layout.len();
555        let total = num_phys + num_blind;
556
557        let mut phys_bit = vec![Vec::new(); total];
558        let mut phys_whole = vec![Vec::new(); total];
559        let mut units: Vec<(bool, usize)> = Vec::new();
560
561        let mut phys_rs: Vec<ColumnType> = layout.iter().map(|ct| ct.rs_field()).collect();
562        phys_rs.extend((0..num_blind).map(|_| ColumnType::B128));
563
564        let bounds = |upper: usize| -> Result<(), Error> {
565            if upper > num_phys {
566                return Err(Error::Protocol {
567                    protocol: "ring_switch_plan",
568                    message: "expansion entry exceeds the physical column layout",
569                });
570            }
571
572            Ok(())
573        };
574
575        match entries {
576            Some(entries) => {
577                let mut running = 0usize;
578                for e in entries {
579                    match *e {
580                        ExpansionEntry::ExpandBits { count, storage } => {
581                            let bits = expand_bit_width(storage)?;
582
583                            bounds(running + count)?;
584
585                            for j in 0..count {
586                                phys_bit[running + j].push(units.len());
587                                units.push((true, bits));
588                            }
589
590                            running += count;
591                        }
592                        ExpansionEntry::PassThrough { count, .. }
593                        | ExpansionEntry::ControlBits { count } => {
594                            bounds(running + count)?;
595
596                            for j in 0..count {
597                                phys_whole[running + j].push(units.len());
598                                units.push((false, 1));
599                            }
600
601                            running += count;
602                        }
603                        ExpansionEntry::ReusePassThrough {
604                            phy_col_start,
605                            count,
606                            ..
607                        } => {
608                            bounds(phy_col_start + count)?;
609
610                            for j in 0..count {
611                                phys_whole[phy_col_start + j].push(units.len());
612                                units.push((false, 1));
613                            }
614                        }
615                        ExpansionEntry::ReuseExpandBits {
616                            phy_col_start,
617                            count,
618                            storage,
619                        } => {
620                            let bits = expand_bit_width(storage)?;
621
622                            bounds(phy_col_start + count)?;
623
624                            for j in 0..count {
625                                phys_bit[phy_col_start + j].push(units.len());
626                                units.push((true, bits));
627                            }
628                        }
629                    }
630                }
631
632                if running != num_phys {
633                    return Err(Error::Protocol {
634                        protocol: "ring_switch_plan",
635                        message: "expansion entries do not cover the physical column layout",
636                    });
637                }
638            }
639            None => {
640                for pw in phys_whole.iter_mut().take(num_phys) {
641                    pw.push(units.len());
642                    units.push((false, 1));
643                }
644            }
645        }
646
647        let has_ring = units.iter().any(|(is_ring, _)| *is_ring);
648
649        for b in 0..num_blind {
650            phys_whole[num_phys + b].push(units.len());
651            units.push((false, 1));
652        }
653
654        let mut blind_slots = num_blind;
655
656        // A uniform L-valued unit
657        if has_ring && num_blind > 0 {
658            phys_bit.push(vec![units.len()]);
659            phys_whole.push(Vec::new());
660            phys_rs.push(ColumnType::B128);
661            units.push((true, RING_BLIND_BITS));
662            blind_slots += 1;
663        }
664
665        let num_units = units.len();
666
667        Ok(Self {
668            units,
669            phys_bit,
670            phys_whole,
671            phys_rs,
672            blind_slots,
673            num_units,
674        })
675    }
676
677    pub fn has_ring(&self) -> bool {
678        self.units.iter().any(|(is_ring, _)| *is_ring)
679    }
680
681    pub fn has_ring_blind(&self) -> bool {
682        self.blind_slots > 0 && self.has_ring()
683    }
684
685    pub fn total_claims(&self) -> usize {
686        self.units.iter().map(|(_, n)| n).sum()
687    }
688
689    pub fn opened_row_bytes(&self) -> usize {
690        self.phys_rs.iter().map(|ct| ct.byte_size()).sum()
691    }
692
693    pub fn num_master_vectors(&self) -> usize {
694        1 + usize::from(self.has_ring())
695    }
696
697    pub fn split_vars(&self, num_vars: usize, config: &Config) -> usize {
698        compute_split_vars(
699            num_vars,
700            config.num_queries,
701            config.ldt_support_size,
702            self.opened_row_bytes(),
703            self.num_master_vectors(),
704        )
705    }
706
707    /// Per committed column:
708    /// its base `eta` coefficients in the ring and whole
709    /// masters, plus `eta^U` (the next-row shift multiplier).
710    pub fn column_coeffs<F>(&self, eta: Flat<F>) -> (Vec<Flat<F>>, Vec<Flat<F>>, Flat<F>)
711    where
712        F: HardwareField,
713    {
714        let mut eta_pows = Vec::with_capacity(self.num_units + 1);
715        let mut e = Flat::from_raw(F::ONE);
716
717        for _ in 0..=self.num_units {
718            eta_pows.push(e);
719            e *= eta;
720        }
721
722        let total = self.phys_rs.len();
723
724        let mut coeff_bit = vec![Flat::from_raw(F::ZERO); total];
725        let mut coeff_whole = vec![Flat::from_raw(F::ZERO); total];
726
727        for p in 0..total {
728            for &u in &self.phys_bit[p] {
729                coeff_bit[p] += eta_pows[u];
730            }
731
732            for &u in &self.phys_whole[p] {
733                coeff_whole[p] += eta_pows[u];
734            }
735        }
736
737        (coeff_bit, coeff_whole, eta_pows[self.num_units])
738    }
739}
740
741fn expand_bit_width(storage: ColumnType) -> Result<usize, Error> {
742    match storage {
743        ColumnType::B8 => Ok(8),
744        ColumnType::B16 => Ok(16),
745        ColumnType::B32 => Ok(32),
746        ColumnType::B64 => Ok(64),
747        _ => Err(Error::Protocol {
748            protocol: "virtual_expand",
749            message: "ExpandBits requires B8/B16/B32/B64",
750        }),
751    }
752}
753
754/// Tower-basis bit extraction from LE bytes.
755fn parse_tower_bit(storage: ColumnType, bytes: &[u8], bit_idx: usize) -> u8 {
756    match storage {
757        ColumnType::B8 => Flat::from_raw(Block8(bytes[0])).tower_bit(bit_idx),
758        ColumnType::B16 => {
759            let mut arr = [0u8; 2];
760            arr.copy_from_slice(bytes);
761
762            Flat::from_raw(Block16(u16::from_le_bytes(arr))).tower_bit(bit_idx)
763        }
764        ColumnType::B32 => {
765            let mut arr = [0u8; 4];
766            arr.copy_from_slice(bytes);
767
768            Flat::from_raw(Block32(u32::from_le_bytes(arr))).tower_bit(bit_idx)
769        }
770        ColumnType::B64 => {
771            let mut arr = [0u8; 8];
772            arr.copy_from_slice(bytes);
773
774            Flat::from_raw(Block64(u64::from_le_bytes(arr))).tower_bit(bit_idx)
775        }
776        _ => unreachable!(),
777    }
778}
779
780fn expand_packed_bit<F: TraceCompatibleField + 'static>(
781    col: &'_ TraceColumn,
782    storage: ColumnType,
783    bit_idx: usize,
784) -> Result<PolyVariant<'_, F>, Error> {
785    match storage {
786        ColumnType::B8 => {
787            let data = col.as_b8_slice().ok_or(Error::Protocol {
788                protocol: "virtual_expand",
789                message: "ExpandBits B8: column type mismatch",
790            })?;
791
792            Ok(PolyVariant::PackedBitB8 { data, bit_idx })
793        }
794        ColumnType::B16 => {
795            let data = col.as_b16_slice().ok_or(Error::Protocol {
796                protocol: "virtual_expand",
797                message: "ExpandBits B16: column type mismatch",
798            })?;
799
800            Ok(PolyVariant::PackedBitB16 { data, bit_idx })
801        }
802        ColumnType::B32 => {
803            let data = col.as_b32_slice().ok_or(Error::Protocol {
804                protocol: "virtual_expand",
805                message: "ExpandBits B32: column type mismatch",
806            })?;
807
808            Ok(PolyVariant::PackedBitB32 { data, bit_idx })
809        }
810        ColumnType::B64 => {
811            let data = col.as_b64_slice().ok_or(Error::Protocol {
812                protocol: "virtual_expand",
813                message: "ExpandBits B64: column type mismatch",
814            })?;
815
816            Ok(PolyVariant::PackedBitB64 { data, bit_idx })
817        }
818        _ => unreachable!(),
819    }
820}
821
822fn expand_pass_through<F: TraceCompatibleField + 'static>(
823    col: &TraceColumn,
824    storage: ColumnType,
825) -> Result<PolyVariant<'_, F>, Error> {
826    match storage {
827        ColumnType::Bit => {
828            let data = col.as_bit_slice().ok_or(Error::Protocol {
829                protocol: "virtual_expand",
830                message: "PassThrough Bit: column type mismatch",
831            })?;
832
833            Ok(PolyVariant::BitSlice(data))
834        }
835        ColumnType::B8 => {
836            let data = col.as_b8_slice().ok_or(Error::Protocol {
837                protocol: "virtual_expand",
838                message: "PassThrough B8: column type mismatch",
839            })?;
840
841            Ok(PolyVariant::B8Slice(data))
842        }
843        ColumnType::B16 => {
844            let data = col.as_b16_slice().ok_or(Error::Protocol {
845                protocol: "virtual_expand",
846                message: "PassThrough B16: column type mismatch",
847            })?;
848
849            Ok(PolyVariant::B16Slice(data))
850        }
851        ColumnType::B32 => {
852            let data = col.as_b32_slice().ok_or(Error::Protocol {
853                protocol: "virtual_expand",
854                message: "PassThrough B32: column type mismatch",
855            })?;
856
857            Ok(PolyVariant::B32Slice(data))
858        }
859        ColumnType::B64 => {
860            let data = col.as_b64_slice().ok_or(Error::Protocol {
861                protocol: "virtual_expand",
862                message: "PassThrough B64: column type mismatch",
863            })?;
864
865            Ok(PolyVariant::B64Slice(data))
866        }
867        ColumnType::B128 => {
868            let data = col.as_b128_slice().ok_or(Error::Protocol {
869                protocol: "virtual_expand",
870                message: "PassThrough B128: column type mismatch",
871            })?;
872
873            Ok(PolyVariant::B128Slice(data))
874        }
875    }
876}
877
878pub fn eq_tensor_b(r: &[Block128]) -> Vec<Block128> {
879    let mut t = vec![Block128::ONE];
880    for &ri in r {
881        let len = t.len();
882        let mut nt = Vec::with_capacity(len * 2);
883
884        for &v in &t {
885            nt.push(v * (Block128::ONE + ri));
886        }
887
888        for &v in &t {
889            nt.push(v * ri);
890        }
891
892        t = nt;
893    }
894
895    t
896}
897
898/// Σ_u eq(r'',u)·ŝ_u for one ring unit, ŝ_u = Σ_v bit_u(c_v)·2^v.
899pub fn ring_batch_b(bit_claims: &[Block128], eq_mix: &[Block128]) -> Block128 {
900    let mut acc = Block128::ZERO;
901    for (u, &m) in eq_mix.iter().enumerate() {
902        let mut shat = 0u128;
903        for (v, cv) in bit_claims.iter().enumerate() {
904            shat |= ((cv.0 >> u) & 1) << v;
905        }
906
907        acc += m * Block128(shat);
908    }
909
910    acc
911}
912
913/// Reconstructs the sumcheck's initial claim from the claimed
914/// virtual evals, in the tower basis. Ring units contribute
915/// `eta·Σ_u eq(r'',u) ŝ_u`; whole units contribute `eta·c'`.
916pub fn ring_target<F>(
917    plan: &RingSwitchPlan,
918    claims: &[Flat<F>],
919    eta_tower: F,
920    r_mix: &[Block128],
921    shifted_claims: bool,
922) -> Block128
923where
924    F: HardwareField + Into<Block128>,
925{
926    let claim_halves = if shifted_claims { 2 } else { 1 };
927    let half = claims.len() / claim_halves;
928    let eq_mix = eq_tensor_b(r_mix);
929    let eta: Block128 = eta_tower.into();
930
931    let mut eta_pows = Vec::with_capacity(plan.num_units + 1);
932    let mut e = Block128::ONE;
933
934    for _ in 0..=plan.num_units {
935        eta_pows.push(e);
936        e *= eta;
937    }
938
939    let eta_shift = eta_pows[plan.num_units];
940
941    let base = [(0usize, Block128::ONE)];
942    let base_and_shift = [(0usize, Block128::ONE), (half, eta_shift)];
943    let offsets: &[(usize, Block128)] = if shifted_claims {
944        &base_and_shift
945    } else {
946        &base
947    };
948
949    let mut target = Block128::ZERO;
950    for &(offset, shift_mul) in offsets {
951        let half_claims = &claims[offset..offset + half];
952
953        let mut ci = 0usize;
954        for (unit_idx, &(is_ring, num_claims)) in plan.units.iter().enumerate() {
955            let weight = eta_pows[unit_idx] * shift_mul;
956            if is_ring {
957                let bits: Vec<Block128> = half_claims[ci..ci + num_claims]
958                    .iter()
959                    .map(|f| f.to_tower().into())
960                    .collect();
961
962                target += weight * ring_batch_b(&bits, &eq_mix);
963            } else {
964                let c: Block128 = half_claims[ci].to_tower().into();
965                target += weight * c;
966            }
967
968            ci += num_claims;
969        }
970    }
971
972    target
973}
974
975/// Per-claim weight `a_c` such that
976/// `ring_target = Σ_c a_c · (ring ? φ_{r''}(c_c) : c_c)`,
977/// with `φ_{r''}(x) = Σ_u eq(r'',u)·bit_u(x)`.
978pub fn claim_weights<F>(
979    plan: &RingSwitchPlan,
980    eta_tower: F,
981    shifted_claims: bool,
982) -> Vec<(bool, Block128)>
983where
984    F: HardwareField + Into<Block128>,
985{
986    let eta: Block128 = eta_tower.into();
987
988    let mut eta_pows = Vec::with_capacity(plan.num_units + 1);
989    let mut e = Block128::ONE;
990
991    for _ in 0..=plan.num_units {
992        eta_pows.push(e);
993        e *= eta;
994    }
995
996    let shifts: &[Block128] = if shifted_claims {
997        &[Block128::ONE, eta_pows[plan.num_units]]
998    } else {
999        &[Block128::ONE]
1000    };
1001
1002    let mut weights = Vec::with_capacity(plan.total_claims() * shifts.len());
1003    for &shift_mul in shifts {
1004        for (unit_idx, &(is_ring, num_claims)) in plan.units.iter().enumerate() {
1005            let weight = eta_pows[unit_idx] * shift_mul;
1006            for v in 0..num_claims {
1007                let basis = if is_ring {
1008                    Block128(1u128 << v)
1009                } else {
1010                    Block128::ONE
1011                };
1012
1013                weights.push((is_ring, weight * basis));
1014            }
1015        }
1016    }
1017
1018    weights
1019}
1020
1021#[cfg(test)]
1022mod tests {
1023    use super::*;
1024    use hekate_core::trace::TraceBuilder;
1025    use hekate_math::{Block128, TowerField};
1026
1027    fn keccak_expander() -> VirtualExpander {
1028        VirtualExpander::new()
1029            .expand_bits(25, ColumnType::B64)
1030            .expand_bits(1, ColumnType::B64)
1031            .reuse_pass_through(0, 25)
1032            .control_bits(2)
1033            .build()
1034            .unwrap()
1035    }
1036
1037    fn keccak_physical_layout() -> Vec<ColumnType> {
1038        let mut layout = vec![ColumnType::B64; 26];
1039        layout.extend(repeat_n(ColumnType::Bit, 2));
1040
1041        layout
1042    }
1043
1044    #[test]
1045    fn ram_layout() {
1046        let e = VirtualExpander::new()
1047            .expand_bits(2, ColumnType::B32)
1048            .pass_through(13, ColumnType::B32)
1049            .pass_through(1, ColumnType::B128)
1050            .control_bits(4)
1051            .build()
1052            .unwrap();
1053
1054        assert_eq!(e.num_virtual_columns(), 82);
1055        assert_eq!(e.num_physical_columns(), 20);
1056        assert_eq!(e.physical_row_bytes(), 80);
1057
1058        let layout = e.virtual_layout();
1059
1060        assert_eq!(layout.len(), 82);
1061        assert!(layout[..64].iter().all(|&t| t == ColumnType::Bit));
1062        assert!(layout[64..77].iter().all(|&t| t == ColumnType::B32));
1063        assert_eq!(layout[77], ColumnType::B128);
1064        assert!(layout[78..82].iter().all(|&t| t == ColumnType::Bit));
1065    }
1066
1067    #[test]
1068    fn keccak_layout() {
1069        let e = VirtualExpander::new()
1070            .expand_bits(25, ColumnType::B64)
1071            .expand_bits(1, ColumnType::B64)
1072            .reuse_pass_through(0, 25)
1073            .control_bits(2)
1074            .build()
1075            .unwrap();
1076
1077        assert_eq!(e.num_virtual_columns(), 1691);
1078        assert_eq!(e.num_physical_columns(), 28);
1079        assert_eq!(e.physical_row_bytes(), 210);
1080
1081        let layout = e.virtual_layout();
1082
1083        assert_eq!(layout.len(), 1691);
1084        assert!(layout[..1600].iter().all(|&t| t == ColumnType::Bit));
1085        assert!(layout[1600..1664].iter().all(|&t| t == ColumnType::Bit));
1086        assert!(layout[1664..1689].iter().all(|&t| t == ColumnType::B64));
1087        assert!(layout[1689..1691].iter().all(|&t| t == ColumnType::Bit));
1088    }
1089
1090    #[test]
1091    fn ring_switch_plan_rejects_uncovered_columns() {
1092        let expander = keccak_expander();
1093        let entries = expander.expansion_entries();
1094
1095        let mut layout = keccak_physical_layout();
1096
1097        assert_eq!(expander.num_physical_columns(), layout.len());
1098        assert!(RingSwitchPlan::new(&layout, Some(&entries), 0).is_ok());
1099
1100        layout.push(ColumnType::B64);
1101
1102        assert!(RingSwitchPlan::new(&layout, Some(&entries), 0).is_err());
1103    }
1104
1105    #[test]
1106    fn ring_switch_plan_folds_every_committed_column() {
1107        let entries = keccak_expander().expansion_entries();
1108        let layout = keccak_physical_layout();
1109
1110        let plan = RingSwitchPlan::new(&layout, Some(&entries), 2).unwrap();
1111
1112        let zero = Flat::from_raw(Block128::ZERO);
1113        let eta = Block128(0x2545F4914F6CDD1D_517CC1B727220A95).to_hardware();
1114        let (coeff_bit, coeff_whole, _) = plan.column_coeffs::<Block128>(eta);
1115
1116        for p in 0..plan.phys_rs.len() {
1117            assert!(
1118                coeff_bit[p] != zero || coeff_whole[p] != zero,
1119                "committed column {p} enters no master fold"
1120            );
1121        }
1122    }
1123
1124    #[test]
1125    fn blinded_ring_plan_ends_in_ring_blind_unit() {
1126        let entries = keccak_expander().expansion_entries();
1127        let layout = keccak_physical_layout();
1128
1129        let raw = RingSwitchPlan::new(&layout, Some(&entries), 0).unwrap();
1130        let blinded = RingSwitchPlan::new(&layout, Some(&entries), 2).unwrap();
1131        let whole_only = RingSwitchPlan::new(&[ColumnType::B32; 3], None, 2).unwrap();
1132
1133        assert_eq!(raw.blind_slots, 0);
1134        assert_eq!(raw.phys_rs.len(), layout.len());
1135
1136        assert_eq!(blinded.blind_slots, 3);
1137        assert_eq!(blinded.phys_rs.len(), layout.len() + 3);
1138        assert_eq!(blinded.units.last(), Some(&(true, RING_BLIND_BITS)));
1139        assert_eq!(
1140            blinded.total_claims(),
1141            raw.total_claims() + 2 + RING_BLIND_BITS
1142        );
1143
1144        assert_eq!(whole_only.blind_slots, 2);
1145        assert_eq!(whole_only.units.last(), Some(&(false, 1)));
1146
1147        let eta = Block128(0x2545F4914F6CDD1D_517CC1B727220A95).to_hardware();
1148        let (coeff_bit, coeff_whole, _) = blinded.column_coeffs::<Block128>(eta);
1149        let last = blinded.phys_rs.len() - 1;
1150
1151        assert_ne!(coeff_bit[last], Flat::from_raw(Block128::ZERO));
1152        assert_eq!(coeff_whole[last], Flat::from_raw(Block128::ZERO));
1153    }
1154
1155    #[test]
1156    fn reuse_partial_range() {
1157        let e = VirtualExpander::new()
1158            .expand_bits(10, ColumnType::B32)
1159            .reuse_pass_through(3, 4)
1160            .build()
1161            .unwrap();
1162
1163        assert_eq!(e.num_virtual_columns(), 324);
1164        assert_eq!(e.num_physical_columns(), 10);
1165        assert_eq!(e.physical_row_bytes(), 40);
1166
1167        let layout = e.virtual_layout();
1168
1169        assert_eq!(layout[320..324].len(), 4);
1170        assert!(layout[320..324].iter().all(|&t| t == ColumnType::B32));
1171    }
1172
1173    #[test]
1174    fn reuse_exceeds_declared() {
1175        let result = VirtualExpander::new()
1176            .expand_bits(5, ColumnType::B32)
1177            .reuse_pass_through(3, 5)
1178            .build();
1179
1180        assert!(result.is_err());
1181    }
1182
1183    #[test]
1184    fn reuse_expand_bits_from_pass_through() {
1185        let e = VirtualExpander::new()
1186            .pass_through(4, ColumnType::B64)
1187            .reuse_expand_bits(0, 4)
1188            .build()
1189            .unwrap();
1190
1191        assert_eq!(e.num_physical_columns(), 4);
1192        assert_eq!(e.physical_row_bytes(), 32);
1193        assert_eq!(e.num_virtual_columns(), 4 + 256);
1194
1195        let layout = e.virtual_layout();
1196
1197        assert!(layout[0..4].iter().all(|&t| t == ColumnType::B64));
1198        assert!(layout[4..260].iter().all(|&t| t == ColumnType::Bit));
1199    }
1200
1201    #[test]
1202    fn reuse_expand_bits_exceeds_declared() {
1203        let result = VirtualExpander::new()
1204            .pass_through(4, ColumnType::B64)
1205            .reuse_expand_bits(2, 4)
1206            .build();
1207
1208        assert!(result.is_err());
1209    }
1210
1211    #[test]
1212    fn reuse_expand_bits_rejects_b128_source() {
1213        let result = VirtualExpander::new()
1214            .pass_through(1, ColumnType::B128)
1215            .reuse_expand_bits(0, 1)
1216            .build();
1217
1218        assert!(result.is_err());
1219    }
1220
1221    #[test]
1222    fn expand_rejects_bit() {
1223        let result = VirtualExpander::new()
1224            .expand_bits(1, ColumnType::Bit)
1225            .build();
1226
1227        assert!(result.is_err());
1228    }
1229
1230    #[test]
1231    fn expand_rejects_b128() {
1232        let result = VirtualExpander::new()
1233            .expand_bits(1, ColumnType::B128)
1234            .build();
1235
1236        assert!(result.is_err());
1237    }
1238
1239    #[test]
1240    fn empty_expander() {
1241        let e = VirtualExpander::new();
1242        assert_eq!(e.num_virtual_columns(), 0);
1243        assert_eq!(e.num_physical_columns(), 0);
1244        assert_eq!(e.physical_row_bytes(), 0);
1245        assert!(e.virtual_layout().is_empty());
1246    }
1247
1248    #[test]
1249    fn parse_row_b32_roundtrip() {
1250        let expander = VirtualExpander::new()
1251            .expand_bits(1, ColumnType::B32)
1252            .pass_through(1, ColumnType::B32)
1253            .control_bits(1)
1254            .build()
1255            .unwrap();
1256
1257        let val: u32 = 0xDEAD_BEEF;
1258        let pass_val: u32 = 0x1234_5678;
1259
1260        let mut bytes = Vec::new();
1261        bytes.extend_from_slice(&val.to_le_bytes());
1262        bytes.extend_from_slice(&pass_val.to_le_bytes());
1263        bytes.push(1);
1264
1265        let mut res: Vec<Flat<Block128>> = Vec::new();
1266        expander.parse_row(&bytes, &mut res).unwrap();
1267
1268        assert_eq!(res.len(), 34);
1269
1270        for (bit_idx, elem) in res.iter().enumerate().take(32) {
1271            let expected = Flat::from_raw(Block32(val)).tower_bit(bit_idx);
1272            let got = elem.tower_bit(0);
1273            assert_eq!(got, expected, "bit {bit_idx} mismatch");
1274        }
1275
1276        let pass = res[32];
1277        assert_eq!(
1278            pass,
1279            <Block128 as hekate_math::FlatPromote<Block32>>::promote_flat(Flat::from_raw(Block32(
1280                pass_val
1281            )))
1282        );
1283
1284        let ctrl = res[33].tower_bit(0);
1285        assert_eq!(ctrl, 1);
1286    }
1287
1288    #[test]
1289    fn expand_variants_b32() {
1290        let expander = VirtualExpander::new()
1291            .expand_bits(1, ColumnType::B32)
1292            .pass_through(1, ColumnType::B32)
1293            .control_bits(1)
1294            .build()
1295            .unwrap();
1296
1297        let layout = [ColumnType::B32, ColumnType::B32, ColumnType::Bit];
1298        let num_vars = 2;
1299
1300        let mut tb = TraceBuilder::new(&layout, num_vars).unwrap();
1301        tb.set_b32(0, 0, Block32(0xAAAA_BBBB)).unwrap();
1302        tb.set_b32(1, 0, Block32(0x1111_2222)).unwrap();
1303        tb.set_bit(2, 0, Bit::ONE).unwrap();
1304
1305        let trace = tb.build();
1306
1307        let variants: Vec<PolyVariant<'_, Block128>> = expander.expand_variants(&trace, 0).unwrap();
1308
1309        assert_eq!(variants.len(), 34);
1310
1311        for (i, v) in variants.iter().enumerate().take(32) {
1312            assert!(matches!(v, PolyVariant::PackedBitB32 { bit_idx, .. } if *bit_idx == i));
1313        }
1314
1315        assert!(matches!(variants[32], PolyVariant::B32Slice(_)));
1316        assert!(matches!(variants[33], PolyVariant::BitSlice(_)));
1317    }
1318
1319    #[test]
1320    fn claim_weights_reproduce_ring_target() {
1321        let layout = [
1322            ColumnType::B32,
1323            ColumnType::B32,
1324            ColumnType::B64,
1325            ColumnType::Bit,
1326        ];
1327
1328        let expander = VirtualExpander::new()
1329            .expand_bits(2, ColumnType::B32)
1330            .pass_through(1, ColumnType::B64)
1331            .control_bits(1)
1332            .build()
1333            .unwrap();
1334
1335        let entries = expander.expansion_entries();
1336        let plan = RingSwitchPlan::new(&layout, Some(&entries), 2).unwrap();
1337
1338        let mut state = 0x9e37_79b9_7f4a_7c15_0123_4567_89ab_cdefu128;
1339        let mut next = || {
1340            state ^= state << 13;
1341            state ^= state >> 7;
1342            state ^= state << 17;
1343
1344            Block128(state)
1345        };
1346
1347        let claims: Vec<Block128> = (0..2 * plan.total_claims()).map(|_| next()).collect();
1348        let eta = next();
1349        let r_mix: Vec<Block128> = (0..7).map(|_| next()).collect();
1350        let eq_mix = eq_tensor_b(&r_mix);
1351
1352        let flat: Vec<Flat<Block128>> = claims.iter().map(|c| c.to_hardware()).collect();
1353        let target = ring_target::<Block128>(&plan, &flat, eta, &r_mix, true);
1354
1355        let mut sum = Block128::ZERO;
1356        for ((is_ring, weight), claim) in claim_weights::<Block128>(&plan, eta, true)
1357            .into_iter()
1358            .zip(&claims)
1359        {
1360            let value = match is_ring {
1361                true => ring_batch_b(&[*claim], &eq_mix),
1362                false => *claim,
1363            };
1364
1365            sum += weight * value;
1366        }
1367
1368        assert_eq!(sum, target);
1369    }
1370}