Longfellow ZK 0290cb32

Loading...
Searching...
No Matches
utility.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_ALGEBRA_UTILITY_H_
16#define PRIVACY_PROOFS_ZK_LIB_ALGEBRA_UTILITY_H_
17
18#include <stddef.h>
19
20#include <cstdint>
21
22 namespace proofs {
23 template <class Field>
24 class AlgebraUtil {
25 public:
26 using Elt = typename Field::Elt;
27
28 // a[i*da] = inverse(b[i*db]), via Montgomery batch inversion
29 static void batch_invert(size_t n, Elt a[/*n with stride da*/], size_t da,
30 const Elt b[/*n with stride db*/], size_t db,
31 const Field& F) {
32 Elt p = F.one();
33
34 // a[i] \gets \prod_{j<i] b[j]
35 for (size_t i = 0; i < n; ++i) {
36 Elt bi = b[i * db];
37 a[i * da] = p;
38 F.mul(p, bi);
39 }
40
41 // now p = \prod_{j<n] b[j]
42 F.invert(p);
43
44 for (size_t i = n; i-- > 0;) {
45 F.mul(a[i * da], p);
46 F.mul(p, b[i * db]);
47 }
48 }
49
50 // a[i] = 1/i, with a[0]=0
51 static void batch_inverse_arithmetic(size_t n, Elt a[/*n*/], const Field& F) {
52 a[0] = F.zero();
53 // this is essentially batch_inverse with b[i]=bi
54
55 Elt p = F.one();
56 Elt bi = F.zero();
57
58 for (size_t i = 1; i < n; ++i) {
59 F.add(bi, F.one());
60 a[i] = p;
61 F.mul(p, bi);
62 }
63
64 // now p = \prod_{j<n] b[j]
65 F.invert(p);
66
67 for (size_t i = n; i-- > 0;) {
68 F.mul(a[i], p);
69 F.mul(p, bi);
70 F.sub(bi, F.one());
71 }
72 }
73
74 static Elt factorial(uint64_t n, const Field& F) {
75 auto p = F.one();
76 auto fi = F.one();
77 for (uint64_t i = 1; i <= n; ++i) {
78 F.mul(p, fi);
79 F.add(fi, F.one());
80 }
81 return p;
82 }
83};
84} // namespace proofs
85
86#endif // PRIVACY_PROOFS_ZK_LIB_ALGEBRA_UTILITY_H_
proofs::AlgebraUtil
Definition utility.h:24
proofs::GF2_128::Elt
Definition gf2_128.h:63