Skip to main content

hekate_core/
trace.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 crate::errors;
6use crate::poly::variant::PolyVariant;
7use alloc::vec;
8use alloc::vec::Vec;
9use core::any::TypeId;
10use core::fmt;
11use core::mem::transmute;
12use hekate_math::{
13    BinaryFieldExtras, Bit, Block8, Block16, Block32, Block64, Block128, CanonicalSerialize, Flat,
14    FlatPromote, HardwareField, PackableField, TowerField,
15};
16use zeroize::Zeroize;
17#[cfg(feature = "secure-memory")]
18use zeroize::ZeroizeOnDrop;
19
20/// Bound for the proving field `F`:
21/// it must losslessly represent every `ColumnType`
22/// used by the trace (Bit, B8, B16, B32, B64, B128)
23/// and carry the additive-FFT substrate the
24/// Reed-Solomon codes encode over.
25pub trait TraceCompatibleField:
26    TowerField
27    + HardwareField
28    + PackableField
29    + BinaryFieldExtras
30    + FlatPromote<Block8>
31    + FlatPromote<Block16>
32    + FlatPromote<Block32>
33    + FlatPromote<Block64>
34    + FlatPromote<Block128>
35    + From<Bit>
36    + From<Block8>
37    + From<Block16>
38    + From<Block32>
39    + From<Block64>
40    + From<Block128>
41    + Send
42    + Sync
43{
44}
45
46impl<T> TraceCompatibleField for T where
47    T: TowerField
48        + HardwareField
49        + PackableField
50        + BinaryFieldExtras
51        + FlatPromote<Block8>
52        + FlatPromote<Block16>
53        + FlatPromote<Block32>
54        + FlatPromote<Block64>
55        + FlatPromote<Block128>
56        + From<Bit>
57        + From<Block8>
58        + From<Block16>
59        + From<Block32>
60        + From<Block64>
61        + From<Block128>
62        + Send
63        + Sync
64{
65}
66
67#[derive(Clone, Copy, Debug, Eq, PartialEq)]
68pub enum Error {
69    InvalidParameters {
70        message: &'static str,
71    },
72    ColumnLengthMismatch {
73        expected_len: usize,
74        got_len: usize,
75    },
76    ColumnIndexOutOfBounds {
77        col_idx: usize,
78        num_cols: usize,
79    },
80    RowIndexOutOfBounds {
81        row_idx: usize,
82        num_rows: usize,
83    },
84    PointDimensionMismatch {
85        expected_len: usize,
86        got_len: usize,
87    },
88    ColumnTypeMismatch {
89        col_idx: usize,
90        expected: &'static str,
91        got: &'static str,
92    },
93}
94
95impl fmt::Display for Error {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        match self {
98            Self::InvalidParameters { message } => {
99                write!(f, "Trace invalid parameters: {message}")
100            }
101            Self::ColumnLengthMismatch {
102                expected_len,
103                got_len,
104            } => write!(
105                f,
106                "Trace column length mismatch: expected {expected_len}, got {got_len}",
107            ),
108            Self::ColumnIndexOutOfBounds { col_idx, num_cols } => write!(
109                f,
110                "Trace column index out of bounds: col_idx={col_idx}, num_cols={num_cols}",
111            ),
112            Self::RowIndexOutOfBounds { row_idx, num_rows } => write!(
113                f,
114                "Trace row index out of bounds: row_idx={row_idx}, num_rows={num_rows}",
115            ),
116            Self::PointDimensionMismatch {
117                expected_len,
118                got_len,
119            } => write!(
120                f,
121                "Trace evaluation point dimension mismatch: expected {expected_len}, got {got_len}",
122            ),
123            Self::ColumnTypeMismatch {
124                col_idx,
125                expected,
126                got,
127            } => write!(
128                f,
129                "Trace column type mismatch at col_idx={col_idx}: expected {expected}, got {got}",
130            ),
131        }
132    }
133}
134
135// =========================================================
136// TRACE TRAIT DEFINITION
137// =========================================================
138
139/// Execution-trace interface. Separates physical
140/// storage (`TraceColumn`) from the virtual
141/// polynomial view consumed by Sumcheck.
142pub trait Trace: Send + Sync {
143    /// `log2` of the trace height.
144    fn num_vars(&self) -> usize;
145
146    fn columns(&self) -> &[TraceColumn];
147
148    /// `2^num_vars`.
149    fn num_rows(&self) -> errors::Result<usize> {
150        num_rows_from_num_vars(self.num_vars())
151    }
152
153    fn num_cols(&self) -> usize {
154        self.columns().len()
155    }
156
157    fn column_layout(&self) -> Vec<ColumnType> {
158        self.columns().iter().map(|col| col.column_type()).collect()
159    }
160
161    /// Read a single trace cell and lift
162    /// it into `F` in the flat/hardware basis.
163    fn get_element<F: TraceCompatibleField>(
164        &self,
165        col_idx: usize,
166        row_idx: usize,
167    ) -> errors::Result<Flat<F>> {
168        let cols = self.columns();
169        let num_cols = self.num_cols();
170
171        if col_idx >= num_cols {
172            return Err(Error::ColumnIndexOutOfBounds { col_idx, num_cols }.into());
173        }
174
175        let num_rows = self.num_rows()?;
176        if row_idx >= num_rows {
177            return Err(Error::RowIndexOutOfBounds { row_idx, num_rows }.into());
178        }
179
180        match &cols[col_idx] {
181            TraceColumn::Bit(v) => Ok(Flat::from_raw(F::from(v[row_idx]))),
182            TraceColumn::B8(v) => Ok(F::promote_flat(v[row_idx])),
183            TraceColumn::B16(v) => Ok(F::promote_flat(v[row_idx])),
184            TraceColumn::B32(v) => Ok(F::promote_flat(v[row_idx])),
185            TraceColumn::B64(v) => Ok(F::promote_flat(v[row_idx])),
186            TraceColumn::B128(v) => Ok(F::promote_flat(v[row_idx])),
187        }
188    }
189
190    /// Zero-copy typed slice over a column.
191    /// Fails if `F` does not match
192    /// the column's storage type.
193    fn get_column_slice<F: 'static>(&self, col_idx: usize) -> errors::Result<&[F]> {
194        let cols = self.columns();
195        let num_cols = self.num_cols();
196
197        if col_idx >= num_cols {
198            return Err(Error::ColumnIndexOutOfBounds { col_idx, num_cols }.into());
199        }
200
201        let got = core::any::type_name::<F>();
202
203        match &cols[col_idx] {
204            TraceColumn::Bit(vec) => {
205                if TypeId::of::<F>() != TypeId::of::<Bit>() {
206                    return Err(Error::ColumnTypeMismatch {
207                        col_idx,
208                        expected: "Bit",
209                        got,
210                    }
211                    .into());
212                }
213
214                // SAFETY:
215                // The TypeId check guarantees F == Bit.
216                Ok(unsafe { transmute::<&[Bit], &[F]>(vec.as_slice()) })
217            }
218            TraceColumn::B8(vec) => {
219                if TypeId::of::<F>() != TypeId::of::<Flat<Block8>>() {
220                    return Err(Error::ColumnTypeMismatch {
221                        col_idx,
222                        expected: "Flat<Block8>",
223                        got,
224                    }
225                    .into());
226                }
227                Ok(unsafe { transmute::<&[Flat<Block8>], &[F]>(vec.as_slice()) })
228            }
229            TraceColumn::B16(vec) => {
230                if TypeId::of::<F>() != TypeId::of::<Flat<Block16>>() {
231                    return Err(Error::ColumnTypeMismatch {
232                        col_idx,
233                        expected: "Flat<Block16>",
234                        got,
235                    }
236                    .into());
237                }
238                Ok(unsafe { transmute::<&[Flat<Block16>], &[F]>(vec.as_slice()) })
239            }
240            TraceColumn::B32(vec) => {
241                if TypeId::of::<F>() != TypeId::of::<Flat<Block32>>() {
242                    return Err(Error::ColumnTypeMismatch {
243                        col_idx,
244                        expected: "Flat<Block32>",
245                        got,
246                    }
247                    .into());
248                }
249                Ok(unsafe { transmute::<&[Flat<Block32>], &[F]>(vec.as_slice()) })
250            }
251            TraceColumn::B64(vec) => {
252                if TypeId::of::<F>() != TypeId::of::<Flat<Block64>>() {
253                    return Err(Error::ColumnTypeMismatch {
254                        col_idx,
255                        expected: "Flat<Block64>",
256                        got,
257                    }
258                    .into());
259                }
260                Ok(unsafe { transmute::<&[Flat<Block64>], &[F]>(vec.as_slice()) })
261            }
262            TraceColumn::B128(vec) => {
263                if TypeId::of::<F>() != TypeId::of::<Flat<Block128>>() {
264                    return Err(Error::ColumnTypeMismatch {
265                        col_idx,
266                        expected: "Flat<Block128>",
267                        got,
268                    }
269                    .into());
270                }
271                Ok(unsafe { transmute::<&[Flat<Block128>], &[F]>(vec.as_slice()) })
272            }
273        }
274    }
275
276    /// Map physical columns to the `PolyVariant`s
277    /// consumed by Sumcheck. Default is a 1:1
278    /// `BitSlice` / `B{N}Slice` mapping; chiplets
279    /// that pack data (e.g. Keccak) override this
280    /// to expose virtual bit-columns.
281    fn get_poly_variants<F>(&'_ self) -> errors::Result<Vec<PolyVariant<'_, F>>>
282    where
283        F: TraceCompatibleField + 'static,
284    {
285        let cols = self.columns();
286        let mut variants = Vec::with_capacity(cols.len());
287
288        for (i, col) in cols.iter().enumerate() {
289            if i >= self.num_cols() {
290                return Err(errors::Error::Protocol {
291                    protocol: "air",
292                    message: "trace has fewer columns than required by AIR",
293                });
294            }
295
296            let variant = if let Some(s) = col.as_bit_slice() {
297                PolyVariant::BitSlice(s)
298            } else if let Some(s) = col.as_b8_slice() {
299                PolyVariant::B8Slice(s)
300            } else if let Some(s) = col.as_b16_slice() {
301                PolyVariant::B16Slice(s)
302            } else if let Some(s) = col.as_b32_slice() {
303                PolyVariant::B32Slice(s)
304            } else if let Some(s) = col.as_b64_slice() {
305                PolyVariant::B64Slice(s)
306            } else if let Some(s) = col.as_b128_slice() {
307                PolyVariant::B128Slice(s)
308            } else {
309                return Err(errors::Error::Protocol {
310                    protocol: "air",
311                    message: "unsupported trace column variant",
312                });
313            };
314
315            variants.push(variant);
316        }
317
318        Ok(variants)
319    }
320}
321
322// =========================================================
323// COLUMN LAYOUT METADATA
324// =========================================================
325
326/// A column's field. The commitment binds every cell to it;
327/// an AIR needs no constraint to keep a cell in range.
328#[derive(Clone, Copy, Debug, PartialEq, Eq)]
329pub enum ColumnType {
330    Bit,
331    B8,
332    B16,
333    B32,
334    B64,
335    B128,
336}
337
338impl ColumnType {
339    #[inline]
340    pub const fn byte_size(&self) -> usize {
341        match self {
342            Self::Bit => 1,
343            Self::B8 => 1,
344            Self::B16 => 2,
345            Self::B32 => 4,
346            Self::B64 => 8,
347            Self::B128 => 16,
348        }
349    }
350
351    /// Returns the narrowest code field type holding
352    /// the column's cells: Bit, B8 and B16 widen to B32.
353    #[inline]
354    pub const fn rs_field(&self) -> Self {
355        match self {
356            Self::Bit | Self::B8 | Self::B16 => Self::B32,
357            other => *other,
358        }
359    }
360
361    /// Parse a field element from its on-wire
362    /// bytes (little-endian, hardware basis)
363    /// without intermediate allocation.
364    pub fn parse_from_bytes<F>(&self, bytes: &[u8]) -> Flat<F>
365    where
366        F: TraceCompatibleField,
367    {
368        match self {
369            Self::Bit => Flat::from_raw(F::from(Bit::new(bytes[0]))),
370            Self::B8 => F::promote_flat(Flat::from_raw(Block8(bytes[0]))),
371            Self::B16 => {
372                let mut buf = [0u8; 2];
373                buf.copy_from_slice(&bytes[0..2]);
374
375                F::promote_flat(Flat::from_raw(Block16(u16::from_le_bytes(buf))))
376            }
377            Self::B32 => {
378                let mut buf = [0u8; 4];
379                buf.copy_from_slice(&bytes[0..4]);
380
381                F::promote_flat(Flat::from_raw(Block32(u32::from_le_bytes(buf))))
382            }
383            Self::B64 => {
384                let mut buf = [0u8; 8];
385                buf.copy_from_slice(&bytes[0..8]);
386
387                F::promote_flat(Flat::from_raw(Block64(u64::from_le_bytes(buf))))
388            }
389            Self::B128 => {
390                let mut buf = [0u8; 16];
391                buf.copy_from_slice(&bytes[0..16]);
392
393                F::promote_flat(Flat::from_raw(Block128(u128::from_le_bytes(buf))))
394            }
395        }
396    }
397}
398
399/// One typed column of the execution trace.
400/// Stored in hardware (flat) basis for all
401/// non-`Bit` variants.
402#[derive(Clone, Debug, Zeroize)]
403#[cfg_attr(feature = "secure-memory", derive(ZeroizeOnDrop))]
404pub enum TraceColumn {
405    Bit(Vec<Bit>),
406    B8(Vec<Flat<Block8>>),
407    B16(Vec<Flat<Block16>>),
408    B32(Vec<Flat<Block32>>),
409    B64(Vec<Flat<Block64>>),
410    B128(Vec<Flat<Block128>>),
411}
412
413impl TraceColumn {
414    /// Narrow a vector of `Block128` into a column
415    /// of `target_type` by truncating to the low bytes.
416    pub fn from_data(data: Vec<Block128>, target_type: ColumnType) -> Self {
417        match target_type {
418            ColumnType::Bit => {
419                let converted: Vec<Bit> = data
420                    .iter()
421                    .map(|val| {
422                        let bytes = val.to_bytes();
423                        Bit::from(bytes[0] & 1)
424                    })
425                    .collect();
426                TraceColumn::Bit(converted)
427            }
428            ColumnType::B8 => {
429                let converted: Vec<Flat<Block8>> = data
430                    .iter()
431                    .map(|val| {
432                        let bytes = val.to_bytes();
433                        Block8::from(bytes[0]).to_hardware()
434                    })
435                    .collect();
436                TraceColumn::B8(converted)
437            }
438            ColumnType::B16 => {
439                let converted: Vec<Flat<Block16>> = data
440                    .iter()
441                    .map(|val| {
442                        let bytes = val.to_bytes();
443                        let mut chunk = [0u8; 2];
444                        chunk.copy_from_slice(&bytes[0..2]);
445
446                        Block16::from(u16::from_le_bytes(chunk)).to_hardware()
447                    })
448                    .collect();
449                TraceColumn::B16(converted)
450            }
451            ColumnType::B32 => {
452                let converted: Vec<Flat<Block32>> = data
453                    .iter()
454                    .map(|val| {
455                        let bytes = val.to_bytes();
456                        let mut chunk = [0u8; 4];
457                        chunk.copy_from_slice(&bytes[0..4]);
458
459                        Block32::from(u32::from_le_bytes(chunk)).to_hardware()
460                    })
461                    .collect();
462                TraceColumn::B32(converted)
463            }
464            ColumnType::B64 => {
465                let converted: Vec<Flat<Block64>> = data
466                    .iter()
467                    .map(|val| {
468                        let bytes = val.to_bytes();
469                        let mut chunk = [0u8; 8];
470                        chunk.copy_from_slice(&bytes[0..8]);
471
472                        Block64::from(u64::from_le_bytes(chunk)).to_hardware()
473                    })
474                    .collect();
475                TraceColumn::B64(converted)
476            }
477            ColumnType::B128 => {
478                TraceColumn::B128(data.into_iter().map(|value| value.to_hardware()).collect())
479            }
480        }
481    }
482
483    pub fn len(&self) -> usize {
484        match self {
485            Self::Bit(v) => v.len(),
486            Self::B8(v) => v.len(),
487            Self::B16(v) => v.len(),
488            Self::B32(v) => v.len(),
489            Self::B64(v) => v.len(),
490            Self::B128(v) => v.len(),
491        }
492    }
493
494    pub fn is_empty(&self) -> bool {
495        self.len() == 0
496    }
497
498    pub fn is_all_zeros(&self) -> bool {
499        match self {
500            Self::Bit(v) => v.iter().all(|x| x.get() == 0),
501            Self::B8(v) => v.iter().all(|x| x.into_raw().0 == 0),
502            Self::B16(v) => v.iter().all(|x| x.into_raw().0 == 0),
503            Self::B32(v) => v.iter().all(|x| x.into_raw().0 == 0),
504            Self::B64(v) => v.iter().all(|x| x.into_raw().0 == 0),
505            Self::B128(v) => v.iter().all(|x| x.into_raw() == Block128::ZERO),
506        }
507    }
508
509    /// The `ColumnType` tag matching this variant.
510    pub fn column_type(&self) -> ColumnType {
511        match self {
512            Self::Bit(_) => ColumnType::Bit,
513            Self::B8(_) => ColumnType::B8,
514            Self::B16(_) => ColumnType::B16,
515            Self::B32(_) => ColumnType::B32,
516            Self::B64(_) => ColumnType::B64,
517            Self::B128(_) => ColumnType::B128,
518        }
519    }
520
521    // ===========================================
522    // Typed slice accessors
523    // ===========================================
524
525    pub fn as_bit_slice(&self) -> Option<&[Bit]> {
526        if let Self::Bit(v) = self {
527            Some(v)
528        } else {
529            None
530        }
531    }
532
533    pub fn as_b8_slice(&self) -> Option<&[Flat<Block8>]> {
534        if let Self::B8(v) = self {
535            Some(v)
536        } else {
537            None
538        }
539    }
540
541    pub fn as_b16_slice(&self) -> Option<&[Flat<Block16>]> {
542        if let Self::B16(v) = self {
543            Some(v)
544        } else {
545            None
546        }
547    }
548
549    pub fn as_b32_slice(&self) -> Option<&[Flat<Block32>]> {
550        if let Self::B32(v) = self {
551            Some(v)
552        } else {
553            None
554        }
555    }
556
557    pub fn as_b64_slice(&self) -> Option<&[Flat<Block64>]> {
558        if let Self::B64(v) = self {
559            Some(v)
560        } else {
561            None
562        }
563    }
564
565    pub fn as_b128_slice(&self) -> Option<&[Flat<Block128>]> {
566        if let Self::B128(v) = self {
567            Some(v)
568        } else {
569            None
570        }
571    }
572}
573
574/// A concrete implementation of
575/// Trace using column-major storage.
576#[derive(Clone, Debug, Zeroize)]
577pub struct ColumnTrace {
578    pub columns: Vec<TraceColumn>,
579    pub num_vars: usize,
580
581    #[zeroize(skip)]
582    secret: bool,
583}
584
585impl Drop for ColumnTrace {
586    fn drop(&mut self) {
587        if self.secret || cfg!(feature = "secure-memory") {
588            self.columns.zeroize();
589        }
590    }
591}
592
593#[cfg(feature = "secure-memory")]
594impl ZeroizeOnDrop for ColumnTrace {}
595
596impl Trace for ColumnTrace {
597    fn num_vars(&self) -> usize {
598        self.num_vars
599    }
600
601    fn columns(&self) -> &[TraceColumn] {
602        &self.columns
603    }
604}
605
606impl ColumnTrace {
607    pub fn new(num_vars: usize) -> errors::Result<Self> {
608        let num_rows = num_rows_from_num_vars(num_vars)?;
609        if num_rows == 0 {
610            return Err(Error::InvalidParameters {
611                message: "trace height is zero",
612            }
613            .into());
614        }
615
616        Ok(Self {
617            num_vars,
618            columns: Vec::new(),
619            secret: false,
620        })
621    }
622
623    /// An empty trace whose columns zeroize on drop.
624    pub fn new_secret(num_vars: usize) -> errors::Result<Self> {
625        let mut trace = Self::new(num_vars)?;
626        trace.secret = true;
627
628        Ok(trace)
629    }
630
631    /// Consume the trace and return its owned column storage.
632    pub fn into_columns(mut self) -> Vec<TraceColumn> {
633        core::mem::take(&mut self.columns)
634    }
635
636    pub fn add_column(&mut self, col: TraceColumn) -> errors::Result<()> {
637        let expected_len = self.num_rows()?;
638        let got_len = col.len();
639
640        if got_len != expected_len {
641            return Err(Error::ColumnLengthMismatch {
642                expected_len,
643                got_len,
644            }
645            .into());
646        }
647
648        self.columns.push(col);
649
650        Ok(())
651    }
652}
653
654pub trait IntoTraceColumn {
655    fn into_trace_column(self) -> TraceColumn;
656}
657
658impl IntoTraceColumn for Vec<Bit> {
659    fn into_trace_column(self) -> TraceColumn {
660        TraceColumn::Bit(self)
661    }
662}
663
664impl IntoTraceColumn for Vec<Block8> {
665    fn into_trace_column(self) -> TraceColumn {
666        TraceColumn::B8(self.into_iter().map(|value| value.to_hardware()).collect())
667    }
668}
669
670impl IntoTraceColumn for Vec<Block16> {
671    fn into_trace_column(self) -> TraceColumn {
672        TraceColumn::B16(self.into_iter().map(|value| value.to_hardware()).collect())
673    }
674}
675
676impl IntoTraceColumn for Vec<Block32> {
677    fn into_trace_column(self) -> TraceColumn {
678        TraceColumn::B32(self.into_iter().map(|value| value.to_hardware()).collect())
679    }
680}
681
682impl IntoTraceColumn for Vec<Block64> {
683    fn into_trace_column(self) -> TraceColumn {
684        TraceColumn::B64(self.into_iter().map(|value| value.to_hardware()).collect())
685    }
686}
687
688impl IntoTraceColumn for Vec<Block128> {
689    fn into_trace_column(self) -> TraceColumn {
690        TraceColumn::B128(self.into_iter().map(|value| value.to_hardware()).collect())
691    }
692}
693
694impl IntoTraceColumn for Vec<Flat<Block8>> {
695    fn into_trace_column(self) -> TraceColumn {
696        TraceColumn::B8(self)
697    }
698}
699
700impl IntoTraceColumn for Vec<Flat<Block16>> {
701    fn into_trace_column(self) -> TraceColumn {
702        TraceColumn::B16(self)
703    }
704}
705
706impl IntoTraceColumn for Vec<Flat<Block32>> {
707    fn into_trace_column(self) -> TraceColumn {
708        TraceColumn::B32(self)
709    }
710}
711
712impl IntoTraceColumn for Vec<Flat<Block64>> {
713    fn into_trace_column(self) -> TraceColumn {
714        TraceColumn::B64(self)
715    }
716}
717
718impl IntoTraceColumn for Vec<Flat<Block128>> {
719    fn into_trace_column(self) -> TraceColumn {
720        TraceColumn::B128(self)
721    }
722}
723
724/// Zero-copy byte views `(ptr, elem_width)` for every column in a trace.
725/// Centralizes the `#[repr(transparent)]`-dependent pointer casts.
726pub fn get_col_views(columns: &[TraceColumn]) -> Vec<(&[u8], usize)> {
727    columns
728        .iter()
729        .map(|col| match col {
730            TraceColumn::Bit(v) => (
731                unsafe { core::slice::from_raw_parts(v.as_ptr() as *const u8, v.len()) },
732                1,
733            ),
734            TraceColumn::B8(v) => (
735                unsafe { core::slice::from_raw_parts(v.as_ptr() as *const u8, v.len()) },
736                1,
737            ),
738            TraceColumn::B16(v) => (
739                unsafe { core::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 2) },
740                2,
741            ),
742            TraceColumn::B32(v) => (
743                unsafe { core::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 4) },
744                4,
745            ),
746            TraceColumn::B64(v) => (
747                unsafe { core::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 8) },
748                8,
749            ),
750            TraceColumn::B128(v) => (
751                unsafe { core::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 16) },
752                16,
753            ),
754        })
755        .collect()
756}
757
758// =========================================================
759// TRACE BUILDER
760// =========================================================
761
762macro_rules! impl_width_writes {
763    (
764        $(
765            $block:ty {
766                set: $set:ident,
767                set_array: $set_array:ident,
768                push: $push:ident,
769                set_flat: $set_flat:ident,
770                set_array_flat: $set_array_flat:ident,
771                column: $expect:ident,
772            }
773        )*
774    ) => {
775        $(
776            #[inline]
777            pub fn $set(&mut self, col: usize, row: usize, val: $block) -> errors::Result<()> {
778                self.$set_flat(col, row, val.to_hardware())
779            }
780
781            #[inline]
782            pub fn $set_flat(
783                &mut self,
784                col: usize,
785                row: usize,
786                val: Flat<$block>,
787            ) -> errors::Result<()> {
788                let num_rows = self.num_rows;
789                let data = self.$expect(col)?;
790                let slot = data.get_mut(row).ok_or(Error::RowIndexOutOfBounds {
791                    row_idx: row,
792                    num_rows,
793                })?;
794
795                *slot = val;
796
797                Ok(())
798            }
799
800            #[inline]
801            pub fn $push(&mut self, col: usize, val: $block) -> errors::Result<()> {
802                let row = self.cursor(col)?;
803                self.$set(col, row, val)?;
804
805                self.cursors[col] = row + 1;
806
807                Ok(())
808            }
809
810            pub fn $set_array(
811                &mut self,
812                base: usize,
813                row: usize,
814                values: &[$block],
815            ) -> errors::Result<()> {
816                for (i, &val) in values.iter().enumerate() {
817                    self.$set(base + i, row, val)?;
818                }
819
820                Ok(())
821            }
822
823            pub fn $set_array_flat(
824                &mut self,
825                base: usize,
826                row: usize,
827                values: &[Flat<$block>],
828            ) -> errors::Result<()> {
829                for (i, &val) in values.iter().enumerate() {
830                    self.$set_flat(base + i, row, val)?;
831                }
832
833                Ok(())
834            }
835        )*
836    };
837}
838
839/// Schema-driven builder. Every column
840/// is allocated zero-filled from the layout;
841/// unfilled rows stay zero, so padding is implicit.
842pub struct TraceBuilder {
843    columns: Vec<TraceColumn>,
844    num_vars: usize,
845    num_rows: usize,
846    cursors: Vec<usize>,
847    secret: bool,
848}
849
850impl Drop for TraceBuilder {
851    fn drop(&mut self) {
852        if self.secret || cfg!(feature = "secure-memory") {
853            self.columns.zeroize();
854        }
855    }
856}
857
858impl TraceBuilder {
859    pub fn new(layout: &[ColumnType], num_vars: usize) -> errors::Result<Self> {
860        Self::with_secrecy(layout, num_vars, false)
861    }
862
863    /// A builder whose columns and the trace it builds
864    /// zeroize on drop: for witnesses that carry secrets.
865    pub fn new_secret(layout: &[ColumnType], num_vars: usize) -> errors::Result<Self> {
866        Self::with_secrecy(layout, num_vars, true)
867    }
868
869    fn with_secrecy(layout: &[ColumnType], num_vars: usize, secret: bool) -> errors::Result<Self> {
870        let num_rows = num_rows_from_num_vars(num_vars)?;
871        let columns = layout
872            .iter()
873            .map(|ct| match ct {
874                ColumnType::Bit => TraceColumn::Bit(vec![Bit::ZERO; num_rows]),
875                ColumnType::B8 => TraceColumn::B8(vec![Block8::ZERO.to_hardware(); num_rows]),
876                ColumnType::B16 => TraceColumn::B16(vec![Block16::ZERO.to_hardware(); num_rows]),
877                ColumnType::B32 => TraceColumn::B32(vec![Block32::ZERO.to_hardware(); num_rows]),
878                ColumnType::B64 => TraceColumn::B64(vec![Block64::ZERO.to_hardware(); num_rows]),
879                ColumnType::B128 => TraceColumn::B128(vec![Block128::ZERO.to_hardware(); num_rows]),
880            })
881            .collect();
882
883        Ok(Self {
884            columns,
885            num_vars,
886            num_rows,
887            cursors: vec![0; layout.len()],
888            secret,
889        })
890    }
891
892    /// `2^num_vars`.
893    #[inline]
894    pub fn num_rows(&self) -> usize {
895        self.num_rows
896    }
897
898    // =========================================================
899    // Column writes: indexed, cursor-push, array
900    // =========================================================
901
902    #[inline]
903    pub fn set_bit(&mut self, col: usize, row: usize, val: Bit) -> errors::Result<()> {
904        let num_rows = self.num_rows;
905        let data = self.expect_bit_col(col)?;
906        let slot = data.get_mut(row).ok_or(Error::RowIndexOutOfBounds {
907            row_idx: row,
908            num_rows,
909        })?;
910
911        *slot = val;
912
913        Ok(())
914    }
915
916    pub fn set_bit_array(&mut self, base: usize, row: usize, values: &[Bit]) -> errors::Result<()> {
917        for (i, &val) in values.iter().enumerate() {
918            self.set_bit(base + i, row, val)?;
919        }
920
921        Ok(())
922    }
923
924    #[inline]
925    pub fn push_bit(&mut self, col: usize, val: Bit) -> errors::Result<()> {
926        let row = self.cursor(col)?;
927        self.set_bit(col, row, val)?;
928
929        self.cursors[col] = row + 1;
930
931        Ok(())
932    }
933
934    impl_width_writes! {
935        Block8 {
936            set: set_b8,
937            set_array: set_b8_array,
938            push: push_b8,
939            set_flat: set_b8_flat,
940            set_array_flat: set_b8_array_flat,
941            column: expect_b8_col,
942        }
943
944        Block16 {
945            set: set_b16,
946            set_array: set_b16_array,
947            push: push_b16,
948            set_flat: set_b16_flat,
949            set_array_flat: set_b16_array_flat,
950            column: expect_b16_col,
951        }
952
953        Block32 {
954            set: set_b32,
955            set_array: set_b32_array,
956            push: push_b32,
957            set_flat: set_b32_flat,
958            set_array_flat: set_b32_array_flat,
959            column: expect_b32_col,
960        }
961
962        Block64 {
963            set: set_b64,
964            set_array: set_b64_array,
965            push: push_b64,
966            set_flat: set_b64_flat,
967            set_array_flat: set_b64_array_flat,
968            column: expect_b64_col,
969        }
970
971        Block128 {
972            set: set_b128,
973            set_array: set_b128_array,
974            push: push_b128,
975            set_flat: set_b128_flat,
976            set_array_flat: set_b128_array_flat,
977            column: expect_b128_col,
978        }
979    }
980
981    // =========================================================
982    // Selector helpers
983    // =========================================================
984
985    /// Write `ONE` into rows `[0, active_rows)`
986    /// of a `Bit` column. The tail stays zero from allocation.
987    pub fn fill_selector(&mut self, col: usize, active_rows: usize) -> errors::Result<()> {
988        let limit = active_rows.min(self.num_rows);
989        let data = self.expect_bit_col(col)?;
990
991        for slot in data.iter_mut().take(limit) {
992            *slot = Bit::ONE;
993        }
994
995        Ok(())
996    }
997
998    // =========================================================
999    // Finalization
1000    // =========================================================
1001
1002    /// Consume the builder and return a `ColumnTrace`.
1003    /// Column order matches the schema passed to `new`.
1004    pub fn build(mut self) -> ColumnTrace {
1005        ColumnTrace {
1006            columns: core::mem::take(&mut self.columns),
1007            num_vars: self.num_vars,
1008            secret: self.secret,
1009        }
1010    }
1011
1012    // =========================================================
1013    // Internal helpers
1014    // =========================================================
1015
1016    #[inline]
1017    fn cursor(&self, col: usize) -> errors::Result<usize> {
1018        self.cursors.get(col).copied().ok_or_else(|| {
1019            Error::ColumnIndexOutOfBounds {
1020                col_idx: col,
1021                num_cols: self.columns.len(),
1022            }
1023            .into()
1024        })
1025    }
1026
1027    #[inline]
1028    fn expect_bit_col(&mut self, col: usize) -> errors::Result<&mut Vec<Bit>> {
1029        let num_cols = self.columns.len();
1030        let tc = self
1031            .columns
1032            .get_mut(col)
1033            .ok_or(Error::ColumnIndexOutOfBounds {
1034                col_idx: col,
1035                num_cols,
1036            })?;
1037
1038        match tc {
1039            TraceColumn::Bit(data) => Ok(data),
1040            other => Err(Error::ColumnTypeMismatch {
1041                col_idx: col,
1042                expected: "Bit",
1043                got: other.column_type_name(),
1044            }
1045            .into()),
1046        }
1047    }
1048
1049    #[inline]
1050    fn expect_b8_col(&mut self, col: usize) -> errors::Result<&mut Vec<Flat<Block8>>> {
1051        let num_cols = self.columns.len();
1052        let tc = self
1053            .columns
1054            .get_mut(col)
1055            .ok_or(Error::ColumnIndexOutOfBounds {
1056                col_idx: col,
1057                num_cols,
1058            })?;
1059
1060        match tc {
1061            TraceColumn::B8(data) => Ok(data),
1062            other => Err(Error::ColumnTypeMismatch {
1063                col_idx: col,
1064                expected: "B8",
1065                got: other.column_type_name(),
1066            }
1067            .into()),
1068        }
1069    }
1070
1071    #[inline]
1072    fn expect_b16_col(&mut self, col: usize) -> errors::Result<&mut Vec<Flat<Block16>>> {
1073        let num_cols = self.columns.len();
1074        let tc = self
1075            .columns
1076            .get_mut(col)
1077            .ok_or(Error::ColumnIndexOutOfBounds {
1078                col_idx: col,
1079                num_cols,
1080            })?;
1081
1082        match tc {
1083            TraceColumn::B16(data) => Ok(data),
1084            other => Err(Error::ColumnTypeMismatch {
1085                col_idx: col,
1086                expected: "B16",
1087                got: other.column_type_name(),
1088            }
1089            .into()),
1090        }
1091    }
1092
1093    #[inline]
1094    fn expect_b32_col(&mut self, col: usize) -> errors::Result<&mut Vec<Flat<Block32>>> {
1095        let num_cols = self.columns.len();
1096        let tc = self
1097            .columns
1098            .get_mut(col)
1099            .ok_or(Error::ColumnIndexOutOfBounds {
1100                col_idx: col,
1101                num_cols,
1102            })?;
1103
1104        match tc {
1105            TraceColumn::B32(data) => Ok(data),
1106            other => Err(Error::ColumnTypeMismatch {
1107                col_idx: col,
1108                expected: "B32",
1109                got: other.column_type_name(),
1110            }
1111            .into()),
1112        }
1113    }
1114
1115    #[inline]
1116    fn expect_b64_col(&mut self, col: usize) -> errors::Result<&mut Vec<Flat<Block64>>> {
1117        let num_cols = self.columns.len();
1118        let tc = self
1119            .columns
1120            .get_mut(col)
1121            .ok_or(Error::ColumnIndexOutOfBounds {
1122                col_idx: col,
1123                num_cols,
1124            })?;
1125
1126        match tc {
1127            TraceColumn::B64(data) => Ok(data),
1128            other => Err(Error::ColumnTypeMismatch {
1129                col_idx: col,
1130                expected: "B64",
1131                got: other.column_type_name(),
1132            }
1133            .into()),
1134        }
1135    }
1136
1137    #[inline]
1138    fn expect_b128_col(&mut self, col: usize) -> errors::Result<&mut Vec<Flat<Block128>>> {
1139        let num_cols = self.columns.len();
1140        let tc = self
1141            .columns
1142            .get_mut(col)
1143            .ok_or(Error::ColumnIndexOutOfBounds {
1144                col_idx: col,
1145                num_cols,
1146            })?;
1147
1148        match tc {
1149            TraceColumn::B128(data) => Ok(data),
1150            other => Err(Error::ColumnTypeMismatch {
1151                col_idx: col,
1152                expected: "B128",
1153                got: other.column_type_name(),
1154            }
1155            .into()),
1156        }
1157    }
1158}
1159
1160impl TraceColumn {
1161    fn column_type_name(&self) -> &'static str {
1162        match self {
1163            Self::Bit(_) => "Bit",
1164            Self::B8(_) => "B8",
1165            Self::B16(_) => "B16",
1166            Self::B32(_) => "B32",
1167            Self::B64(_) => "B64",
1168            Self::B128(_) => "B128",
1169        }
1170    }
1171}
1172
1173fn num_rows_from_num_vars(num_vars: usize) -> errors::Result<usize> {
1174    let num_vars_u32 = match u32::try_from(num_vars) {
1175        Ok(v) => v,
1176        Err(_) => {
1177            return Err(Error::InvalidParameters {
1178                message: "num_vars too large",
1179            }
1180            .into());
1181        }
1182    };
1183
1184    let Some(num_rows) = 1usize.checked_shl(num_vars_u32) else {
1185        return Err(Error::InvalidParameters {
1186            message: "num_rows overflow",
1187        }
1188        .into());
1189    };
1190
1191    if num_rows == 0 {
1192        return Err(Error::InvalidParameters {
1193            message: "num_rows is zero",
1194        }
1195        .into());
1196    }
1197
1198    Ok(num_rows)
1199}
1200
1201// =================================================================
1202// UNIT TESTS
1203// =================================================================
1204
1205#[cfg(test)]
1206mod tests {
1207    use super::*;
1208    use crate::errors;
1209    use hekate_math::HardwareField;
1210
1211    fn create_mock_trace(num_vars: usize) -> ColumnTrace {
1212        ColumnTrace::new(num_vars).unwrap()
1213    }
1214
1215    #[test]
1216    fn trace_construction_basic() {
1217        let num_vars = 3;
1218        let mut trace = create_mock_trace(num_vars);
1219
1220        let col_data = vec![Block128::from(1u8); 8];
1221        trace.add_column(col_data.into_trace_column()).unwrap();
1222
1223        assert_eq!(trace.num_rows().unwrap(), 8);
1224        assert_eq!(trace.num_cols(), 1);
1225        assert_eq!(trace.num_vars, 3);
1226    }
1227
1228    #[test]
1229    fn trace_add_column_wrong_len() {
1230        let num_vars = 2;
1231        let mut trace = create_mock_trace(num_vars);
1232
1233        let col_data = vec![Block128::ZERO; 5];
1234        let err = trace
1235            .add_column(col_data.into_trace_column())
1236            .expect_err("Expected length mismatch error");
1237
1238        assert!(matches!(
1239            err,
1240            errors::Error::Trace(Error::ColumnLengthMismatch { .. })
1241        ));
1242    }
1243
1244    #[test]
1245    fn trace_get_element_mixed_types() {
1246        let num_vars = 1;
1247        let mut trace = create_mock_trace(num_vars);
1248
1249        trace
1250            .add_column(TraceColumn::Bit(vec![Bit::new(0), Bit::new(1)]))
1251            .unwrap();
1252        trace
1253            .add_column(vec![Block32::from(10u32), Block32::from(20u32)].into_trace_column())
1254            .unwrap();
1255
1256        let val0_r0: Flat<Block128> = trace.get_element(0, 0).unwrap();
1257        let val0_r1: Flat<Block128> = trace.get_element(0, 1).unwrap();
1258        let val1_r0: Flat<Block128> = trace.get_element(1, 0).unwrap();
1259        let val1_r1: Flat<Block128> = trace.get_element(1, 1).unwrap();
1260
1261        assert_eq!(val0_r0.into_raw(), Block128::ZERO);
1262        assert_eq!(val0_r1.into_raw(), Block128::ONE);
1263
1264        let expected_10 = Block128::promote_flat(Block32::from(10u32).to_hardware()).into_raw();
1265        let expected_20 = Block128::promote_flat(Block32::from(20u32).to_hardware()).into_raw();
1266
1267        assert_eq!(val1_r0.into_raw(), expected_10);
1268        assert_eq!(val1_r1.into_raw(), expected_20);
1269    }
1270
1271    #[test]
1272    fn get_element_oob_row() {
1273        let mut trace = create_mock_trace(1);
1274        trace
1275            .add_column(TraceColumn::Bit(vec![Bit::ZERO; 2]))
1276            .unwrap();
1277        trace
1278            .get_element::<Block128>(0, 2)
1279            .expect_err("Expected out-of-bounds row error");
1280    }
1281
1282    #[test]
1283    fn get_element_oob_col() {
1284        let trace = create_mock_trace(1);
1285        trace
1286            .get_element::<Block128>(0, 0)
1287            .expect_err("Expected out-of-bounds column error");
1288    }
1289
1290    // ===========================================
1291    // SAFETY & SLICE TESTS
1292    // ===========================================
1293
1294    #[test]
1295    fn get_column_slice_correct_type() {
1296        let mut trace = create_mock_trace(2);
1297        let data = vec![
1298            Block32::from(1u32),
1299            Block32::from(2u32),
1300            Block32::from(3u32),
1301            Block32::from(4u32),
1302        ];
1303        trace.add_column(data.clone().into_trace_column()).unwrap();
1304
1305        let expected_hw: Vec<Flat<Block32>> = data.into_iter().map(|x| x.to_hardware()).collect();
1306
1307        let slice: &[Flat<Block32>] = trace.get_column_slice(0).unwrap();
1308        assert_eq!(slice, expected_hw.as_slice());
1309    }
1310
1311    #[test]
1312    fn get_column_slice_wrong_type() {
1313        let mut trace = create_mock_trace(1);
1314        trace
1315            .add_column(vec![Block128::ZERO; 2].into_trace_column())
1316            .unwrap();
1317
1318        trace
1319            .get_column_slice::<Flat<Block32>>(0)
1320            .expect_err("Expected column type mismatch error");
1321    }
1322
1323    #[test]
1324    fn trace_stores_hardware_basis() {
1325        let mut trace = create_mock_trace(2);
1326
1327        let tower_data = vec![
1328            Block32::from(42u32),
1329            Block32::from(13u32),
1330            Block32::from(255u32),
1331            Block32::from(1u32),
1332        ];
1333
1334        let expected_hardware: Vec<Block32> = tower_data
1335            .iter()
1336            .map(|x| x.to_hardware().into_raw())
1337            .collect();
1338
1339        trace.add_column(tower_data.into_trace_column()).unwrap();
1340
1341        let stored: &[Flat<Block32>] = trace.get_column_slice(0).unwrap();
1342
1343        for (i, (&stored_val, &expected_val)) in
1344            stored.iter().zip(expected_hardware.iter()).enumerate()
1345        {
1346            assert_eq!(
1347                stored_val.into_raw(),
1348                expected_val,
1349                "Row {}: stored value {:?} != expected hardware {:?}",
1350                i,
1351                stored_val,
1352                expected_val
1353            );
1354        }
1355    }
1356
1357    #[test]
1358    fn trace_hardware_basis_homomorphism() {
1359        let mut trace = create_mock_trace(3);
1360
1361        let a_tower = vec![Block32::from(5u32); 8];
1362        let b_tower = vec![Block32::from(7u32); 8];
1363
1364        trace
1365            .add_column(a_tower.clone().into_trace_column())
1366            .unwrap();
1367        trace
1368            .add_column(b_tower.clone().into_trace_column())
1369            .unwrap();
1370
1371        let a_stored: &[Flat<Block32>] = trace.get_column_slice(0).unwrap();
1372        let b_stored: &[Flat<Block32>] = trace.get_column_slice(1).unwrap();
1373
1374        let a_hw_expected = a_tower[0].to_hardware().into_raw();
1375        let b_hw_expected = b_tower[0].to_hardware().into_raw();
1376
1377        assert_eq!(a_stored[0].into_raw(), a_hw_expected);
1378        assert_eq!(b_stored[0].into_raw(), b_hw_expected);
1379
1380        let product_hw = a_stored[0] * b_stored[0];
1381        let product_expected = (a_tower[0] * b_tower[0]).to_hardware().into_raw();
1382
1383        assert_eq!(product_hw.into_raw(), product_expected);
1384    }
1385
1386    // =========================================================
1387    // TRACE BUILDER TESTS
1388    // =========================================================
1389
1390    #[test]
1391    fn trace_builder_construction_and_auto_padding() {
1392        let layout = &[ColumnType::B32, ColumnType::Bit];
1393        let tb = TraceBuilder::new(layout, 2).unwrap(); // 4 rows
1394        assert_eq!(tb.num_rows(), 4);
1395
1396        let trace = tb.build();
1397        assert_eq!(trace.num_cols(), 2);
1398        assert_eq!(trace.num_rows().unwrap(), 4);
1399
1400        // All values should be zero (auto-padding)
1401        assert!(trace.columns[0].is_all_zeros());
1402        assert!(trace.columns[1].is_all_zeros());
1403    }
1404
1405    #[test]
1406    fn trace_builder_set_b32_stores_hardware_basis() {
1407        let layout = &[ColumnType::B32];
1408        let mut tb = TraceBuilder::new(layout, 1).unwrap(); // 2 rows
1409
1410        tb.set_b32(0, 0, Block32::from(42u32)).unwrap();
1411        tb.set_b32(0, 1, Block32::from(13u32)).unwrap();
1412
1413        let trace = tb.build();
1414        let stored: &[Flat<Block32>] = trace.get_column_slice(0).unwrap();
1415
1416        assert_eq!(stored[0], Block32::from(42u32).to_hardware());
1417        assert_eq!(stored[1], Block32::from(13u32).to_hardware());
1418    }
1419
1420    #[test]
1421    fn trace_builder_column_ordering_matches_schema() {
1422        let layout = &[ColumnType::Bit, ColumnType::B32, ColumnType::B128];
1423        let mut tb = TraceBuilder::new(layout, 1).unwrap();
1424
1425        tb.set_bit(0, 0, Bit::ONE).unwrap();
1426        tb.set_b32(1, 0, Block32::from(99u32)).unwrap();
1427        tb.set_b128(2, 0, Block128::from(7u8)).unwrap();
1428
1429        let trace = tb.build();
1430        assert_eq!(trace.columns[0].column_type(), ColumnType::Bit);
1431        assert_eq!(trace.columns[1].column_type(), ColumnType::B32);
1432        assert_eq!(trace.columns[2].column_type(), ColumnType::B128);
1433    }
1434
1435    #[test]
1436    fn trace_builder_type_mismatch_returns_error() {
1437        let layout = &[ColumnType::Bit];
1438        let mut tb = TraceBuilder::new(layout, 1).unwrap();
1439
1440        let err = tb.set_b32(0, 0, Block32::ZERO);
1441        assert!(err.is_err());
1442    }
1443
1444    #[test]
1445    fn trace_builder_row_out_of_bounds_returns_error() {
1446        let layout = &[ColumnType::B32];
1447        let mut tb = TraceBuilder::new(layout, 1).unwrap(); // 2 rows
1448
1449        let err = tb.set_b32(0, 2, Block32::ZERO);
1450        assert!(err.is_err());
1451    }
1452
1453    #[test]
1454    fn trace_builder_col_out_of_bounds_returns_error() {
1455        let layout = &[ColumnType::B32];
1456        let mut tb = TraceBuilder::new(layout, 1).unwrap();
1457
1458        let err = tb.set_b32(1, 0, Block32::ZERO);
1459        assert!(err.is_err());
1460    }
1461
1462    #[test]
1463    fn trace_builder_fill_selector() {
1464        let layout = &[ColumnType::Bit];
1465        let mut tb = TraceBuilder::new(layout, 2).unwrap(); // 4 rows
1466
1467        tb.fill_selector(0, 3).unwrap(); // rows 0,1,2 = ONE
1468
1469        let trace = tb.build();
1470        let bits = trace.columns[0].as_bit_slice().unwrap();
1471        assert_eq!(bits[0], Bit::ONE);
1472        assert_eq!(bits[1], Bit::ONE);
1473        assert_eq!(bits[2], Bit::ONE);
1474        assert_eq!(bits[3], Bit::ZERO); // padding
1475    }
1476
1477    #[test]
1478    fn trace_builder_push_mode() {
1479        let layout = &[ColumnType::B32, ColumnType::Bit];
1480        let mut tb = TraceBuilder::new(layout, 1).unwrap(); // 2 rows
1481
1482        tb.push_b32(0, Block32::from(10u32)).unwrap();
1483        tb.push_b32(0, Block32::from(20u32)).unwrap();
1484        tb.push_bit(1, Bit::ONE).unwrap();
1485        // row 1 of col 1 stays zero (auto-pad)
1486
1487        let trace = tb.build();
1488        let b32s: &[Flat<Block32>] = trace.get_column_slice(0).unwrap();
1489        assert_eq!(b32s[0], Block32::from(10u32).to_hardware());
1490        assert_eq!(b32s[1], Block32::from(20u32).to_hardware());
1491
1492        let bits = trace.columns[1].as_bit_slice().unwrap();
1493        assert_eq!(bits[0], Bit::ONE);
1494        assert_eq!(bits[1], Bit::ZERO);
1495    }
1496
1497    #[test]
1498    fn trace_builder_set_b32_array() {
1499        let layout = &[ColumnType::B32, ColumnType::B32, ColumnType::B32];
1500        let mut tb = TraceBuilder::new(layout, 1).unwrap(); // 2 rows
1501
1502        let vals = [
1503            Block32::from(1u32),
1504            Block32::from(2u32),
1505            Block32::from(3u32),
1506        ];
1507        tb.set_b32_array(0, 0, &vals).unwrap();
1508
1509        let trace = tb.build();
1510        for (i, &expected) in vals.iter().enumerate() {
1511            let stored: &[Flat<Block32>] = trace.get_column_slice(i).unwrap();
1512            assert_eq!(stored[0], expected.to_hardware());
1513        }
1514    }
1515
1516    #[test]
1517    fn trace_builder_set_b8() {
1518        let layout = &[ColumnType::B8];
1519        let mut tb = TraceBuilder::new(layout, 1).unwrap();
1520
1521        tb.set_b8(0, 0, Block8(0xAB)).unwrap();
1522        tb.set_b8(0, 1, Block8(0xCD)).unwrap();
1523
1524        let trace = tb.build();
1525        let stored: &[Flat<Block8>] = trace.get_column_slice(0).unwrap();
1526        assert_eq!(stored[0], Block8(0xAB).to_hardware());
1527        assert_eq!(stored[1], Block8(0xCD).to_hardware());
1528    }
1529
1530    #[test]
1531    fn trace_builder_set_b16() {
1532        let layout = &[ColumnType::B16];
1533        let mut tb = TraceBuilder::new(layout, 1).unwrap();
1534
1535        tb.set_b16(0, 0, Block16(1000)).unwrap();
1536        tb.set_b16(0, 1, Block16(2000)).unwrap();
1537
1538        let trace = tb.build();
1539        let stored: &[Flat<Block16>] = trace.get_column_slice(0).unwrap();
1540        assert_eq!(stored[0], Block16(1000).to_hardware());
1541        assert_eq!(stored[1], Block16(2000).to_hardware());
1542    }
1543
1544    #[test]
1545    fn trace_builder_set_b64() {
1546        let layout = &[ColumnType::B64];
1547        let mut tb = TraceBuilder::new(layout, 1).unwrap();
1548
1549        tb.set_b64(0, 0, Block64(0xDEADBEEF_CAFEBABE)).unwrap();
1550
1551        let trace = tb.build();
1552        let stored: &[Flat<Block64>] = trace.get_column_slice(0).unwrap();
1553        assert_eq!(stored[0], Block64(0xDEADBEEF_CAFEBABE).to_hardware());
1554        assert_eq!(stored[1], Block64::ZERO.to_hardware()); // auto-padding
1555    }
1556
1557    #[test]
1558    fn trace_builder_set_b128() {
1559        let layout = &[ColumnType::B128];
1560        let mut tb = TraceBuilder::new(layout, 1).unwrap();
1561
1562        let val = Block128::from(0xFFu8);
1563        tb.set_b128(0, 0, val).unwrap();
1564
1565        let trace = tb.build();
1566        let stored: &[Flat<Block128>] = trace.get_column_slice(0).unwrap();
1567        assert_eq!(stored[0], val.to_hardware());
1568    }
1569
1570    #[test]
1571    fn trace_builder_push_all_types() {
1572        let layout = &[
1573            ColumnType::Bit,
1574            ColumnType::B8,
1575            ColumnType::B16,
1576            ColumnType::B32,
1577            ColumnType::B64,
1578            ColumnType::B128,
1579        ];
1580        let mut tb = TraceBuilder::new(layout, 1).unwrap(); // 2 rows
1581
1582        tb.push_bit(0, Bit::ONE).unwrap();
1583        tb.push_b8(1, Block8(0x42)).unwrap();
1584        tb.push_b16(2, Block16(1234)).unwrap();
1585        tb.push_b32(3, Block32::from(5678u32)).unwrap();
1586        tb.push_b64(4, Block64(9999)).unwrap();
1587        tb.push_b128(5, Block128::from(77u8)).unwrap();
1588
1589        let trace = tb.build();
1590        assert_eq!(trace.num_cols(), 6);
1591
1592        let bits = trace.columns[0].as_bit_slice().unwrap();
1593        assert_eq!(bits[0], Bit::ONE);
1594        assert_eq!(bits[1], Bit::ZERO); // auto-pad
1595
1596        let b8s: &[Flat<Block8>] = trace.get_column_slice(1).unwrap();
1597        assert_eq!(b8s[0], Block8(0x42).to_hardware());
1598
1599        let b16s: &[Flat<Block16>] = trace.get_column_slice(2).unwrap();
1600        assert_eq!(b16s[0], Block16(1234).to_hardware());
1601
1602        let b32s: &[Flat<Block32>] = trace.get_column_slice(3).unwrap();
1603        assert_eq!(b32s[0], Block32::from(5678u32).to_hardware());
1604
1605        let b64s: &[Flat<Block64>] = trace.get_column_slice(4).unwrap();
1606        assert_eq!(b64s[0], Block64(9999).to_hardware());
1607
1608        let b128s: &[Flat<Block128>] = trace.get_column_slice(5).unwrap();
1609        assert_eq!(b128s[0], Block128::from(77u8).to_hardware());
1610    }
1611
1612    #[test]
1613    fn trace_builder_type_mismatch_all_setters() {
1614        // B32 column, every non-B32 setter should fail
1615        let layout = &[ColumnType::B32];
1616        let mut tb = TraceBuilder::new(layout, 1).unwrap();
1617
1618        assert!(tb.set_bit(0, 0, Bit::ONE).is_err());
1619        assert!(tb.set_b8(0, 0, Block8(1)).is_err());
1620        assert!(tb.set_b16(0, 0, Block16(1)).is_err());
1621        assert!(tb.set_b64(0, 0, Block64(1)).is_err());
1622        assert!(tb.set_b128(0, 0, Block128::ONE).is_err());
1623
1624        // Correct type succeeds
1625        assert!(tb.set_b32(0, 0, Block32::ONE).is_ok());
1626    }
1627
1628    #[test]
1629    fn trace_builder_array_setters_all_types() {
1630        let layout = &[
1631            ColumnType::Bit,
1632            ColumnType::Bit,
1633            ColumnType::B8,
1634            ColumnType::B8,
1635            ColumnType::B64,
1636            ColumnType::B64,
1637            ColumnType::B128,
1638            ColumnType::B128,
1639        ];
1640        let mut tb = TraceBuilder::new(layout, 1).unwrap();
1641
1642        tb.set_bit_array(0, 0, &[Bit::ONE, Bit::ZERO]).unwrap();
1643        tb.set_b8_array(2, 0, &[Block8(10), Block8(20)]).unwrap();
1644        tb.set_b64_array(4, 0, &[Block64(100), Block64(200)])
1645            .unwrap();
1646        tb.set_b128_array(6, 0, &[Block128::ONE, Block128::from(2u8)])
1647            .unwrap();
1648
1649        let trace = tb.build();
1650
1651        let bits = trace.columns[0].as_bit_slice().unwrap();
1652        assert_eq!(bits[0], Bit::ONE);
1653
1654        let bits1 = trace.columns[1].as_bit_slice().unwrap();
1655        assert_eq!(bits1[0], Bit::ZERO);
1656
1657        let b8s: &[Flat<Block8>] = trace.get_column_slice(2).unwrap();
1658        assert_eq!(b8s[0], Block8(10).to_hardware());
1659
1660        let b8s1: &[Flat<Block8>] = trace.get_column_slice(3).unwrap();
1661        assert_eq!(b8s1[0], Block8(20).to_hardware());
1662    }
1663
1664    #[test]
1665    fn trace_builder_invalid_num_vars() {
1666        let layout = &[ColumnType::B32];
1667        // num_vars too large to shift
1668        assert!(TraceBuilder::new(layout, 128).is_err());
1669    }
1670}