hyperplonk/hyperplonk/src/witness.rs
hyperplonk/src/witness.rsRaw
1// Copyright (c) 2023 Espresso Systems (espressosys.com)
2// This file is part of the HyperPlonk library.
3
4// You should have received a copy of the MIT License
5// along with the HyperPlonk library. If not, see <https://mit-license.org/>.
6
7use crate::{build_mle, errors::HyperPlonkErrors};
8use ark_ff::PrimeField;
9use ark_poly::DenseMultilinearExtension;
10use ark_std::log2;
11use std::sync::Arc;
12
13/// A row of witnesses of width `#wires`
14#[derive(Debug, Clone)]
15pub struct WitnessRow<F: PrimeField>(pub(crate) Vec<F>);
16
17/// A column of witnesses of length `#constraints`
18#[derive(Debug, Clone, Default)]
19pub struct WitnessColumn<F: PrimeField>(pub(crate) Vec<F>);
20
21impl<F: PrimeField> WitnessColumn<F> {
22 /// the number of variables of the multilinear polynomial that presents a
23 /// column.
24 pub fn get_nv(&self) -> usize {
25 log2(self.0.len()) as usize
26 }
27
28 /// Append a new element to the witness column
29 pub fn append(&mut self, new_element: F) {
30 self.0.push(new_element)
31 }
32
33 /// Build witness columns from rows
34 pub fn from_witness_rows(
35 witness_rows: &[WitnessRow<F>],
36 ) -> Result<Vec<Self>, HyperPlonkErrors> {
37 if witness_rows.is_empty() {
38 return Err(HyperPlonkErrors::InvalidParameters(
39 "empty witness rows".to_string(),
40 ));
41 }
42
43 let mut res = Vec::with_capacity(witness_rows.len());
44 let num_columns = witness_rows[0].0.len();
45
46 for i in 0..num_columns {
47 let mut cur_column = Vec::new();
48 for row in witness_rows.iter() {
49 cur_column.push(row.0[i])
50 }
51 res.push(Self(cur_column))
52 }
53
54 Ok(res)
55 }
56
57 pub fn coeff_ref(&self) -> &[F] {
58 self.0.as_ref()
59 }
60}
61
62impl<F: PrimeField> From<&WitnessColumn<F>> for DenseMultilinearExtension<F> {
63 fn from(witness: &WitnessColumn<F>) -> Self {
64 let nv = witness.get_nv();
65 Self::from_evaluations_slice(nv, witness.0.as_ref())
66 }
67}
68
69impl<F: PrimeField> WitnessRow<F> {
70 /// Build MLE from matrix of witnesses.
71 ///
72 /// Given a matrix := [row1, row2, ...] where
73 /// row1:= (a1, a2, ...)
74 /// row2:= (b1, b2, ...)
75 /// row3:= (c1, c2, ...)
76 ///
77 /// output mle(a1,b1,c1, ...), mle(a2,b2,c2, ...), ...
78 pub fn build_mles(
79 matrix: &[Self],
80 ) -> Result<Vec<Arc<DenseMultilinearExtension<F>>>, HyperPlonkErrors> {
81 build_mle!(matrix)
82 }
83}