Longfellow ZK 0290cb32

Loading...
Searching...
No Matches
polynomial.h
1// Copyright 2025 Google LLC.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifndef PRIVACY_PROOFS_ZK_LIB_CIRCUITS_LOGIC_POLYNOMIAL_H_
16#define PRIVACY_PROOFS_ZK_LIB_CIRCUITS_LOGIC_POLYNOMIAL_H_
17
18#include <stddef.h>
19
20#include <array>
21
22#include "algebra/poly.h"
23#include "util/ceildiv.h"
24
25 namespace proofs {
26 template <class Logic>
27 class Polynomial {
28 public:
29 using Field = typename Logic::Field;
30 using BitW = typename Logic::BitW;
31 using EltW = typename Logic::EltW;
32 const Logic& l_;
33
34 explicit Polynomial(const Logic& l) : l_(l) {}
35
36 void powers_of_x(size_t n, EltW xi[/*n*/], const EltW& x) const {
37 const Logic& L = l_; // shorthand
38
39 if (n > 0) {
40 xi[0] = L.konst(1);
41 if (n > 1) {
42 xi[1] = x;
43 // invariant: xi[i] = x**i for i < k.
44 // Extend inductively to k = n.
45 for (size_t k = 2; k < n; ++k) {
46 xi[k] = L.mul(&xi[k - k / 2], xi[k / 2]);
47 }
48 }
49 }
50 }
51
52 // Evaluation via dot product with coefficients
53 template <size_t N>
54 EltW eval(const Poly<N, Field>& coef, const EltW& x) const {
55 const Logic& L = l_; // shorthand
56
57 std::array<EltW, N> xi;
58 powers_of_x(N, xi.data(), x);
59
60 // dot product with coefficients
61 EltW r = L.konst(0);
62 for (size_t i = 0; i < N; ++i) {
63 auto cxi = L.mul(coef[i], xi[i]);
64 r = L.add(&r, cxi);
65 }
66 return r;
67 }
68
69 // Evaluation via parallel Horner's rule
70 template <size_t N>
71 EltW eval_horner(const Poly<N, Field>& coef, EltW x) const {
72 const Logic& L = l_; // shorthand
73
74 std::array<EltW, N> c;
75 for (size_t i = 0; i < N; ++i) {
76 c[i] = L.konst(coef[i]);
77 }
78
79 for (size_t n = N; n > 1; n = ceildiv<size_t>(n, 2)) {
80 for (size_t i = 0; 2 * i < n; ++i) {
81 c[i] = c[2 * i];
82 if (2 * i + 1 < n) {
83 auto cxi = L.mul(&x, c[2 * i + 1]);
84 c[i] = L.add(&c[i], cxi);
85 }
86 }
87 x = L.mul(&x, x);
88 }
89 return c[0];
90 }
91};
92} // namespace proofs
93
94#endif // PRIVACY_PROOFS_ZK_LIB_CIRCUITS_LOGIC_POLYNOMIAL_H_
proofs::Logic
Definition logic.h:38
proofs::Poly
Definition poly.h:30
proofs::Logic::BitW
Definition logic.h:130