Barretenberg
The ZK-SNARK library at the core of Aztec
Loading...
Searching...
No Matches
affine_element.test.cpp
Go to the documentation of this file.
2
13
14#include "gmock/gmock.h"
15#include <algorithm>
16#include <fstream>
17#include <gtest/gtest.h>
18#include <iterator>
19#include <tuple>
20
21using ::testing::Each;
22using ::testing::ElementsAreArray;
23using ::testing::Eq;
24using ::testing::Property;
25
26using namespace bb;
27
28namespace {
29template <typename G1> class TestAffineElement : public testing::Test {
30 using element = typename G1::element;
31 using affine_element = typename G1::affine_element;
32 using Fr = typename G1::Fr;
33
34 public:
35 static void test_read_write_buffer()
36 {
37 // a generic point
38 {
39 affine_element P = affine_element(element::random_element());
40 affine_element R;
41
42 std::vector<uint8_t> v(64);
43 uint8_t* ptr = v.data();
44 affine_element::serialize_to_buffer(P, ptr);
45
46 R = affine_element::serialize_from_buffer(ptr);
47 ASSERT_TRUE(R.on_curve());
48 ASSERT_TRUE(P == R);
49 }
50
51 // point at infinity
52 {
53 affine_element P = affine_element(element::random_element());
54 P.self_set_infinity();
55 affine_element R;
56
57 std::vector<uint8_t> v(64);
58 uint8_t* ptr = v.data();
59 affine_element::serialize_to_buffer(P, ptr);
60
61 R = affine_element::serialize_from_buffer(ptr);
62 ASSERT_TRUE(R.is_point_at_infinity());
63 ASSERT_TRUE(P == R);
64 }
65 }
66
67 // Verify that serialize_from_buffer rejects off-curve bytes by throwing.
68 static void test_deserialize_off_curve_throws()
69 {
70 using Fq = typename G1::Fq;
71 // Take a valid on-curve point and corrupt its y-coordinate.
72 // P.y + 1 satisfies (y+1)^2 != y^2 (i.e. off-curve) unless 2y + 1 = 0 (prob ~1/p).
73 affine_element P = affine_element(element::random_element());
74 affine_element off_curve;
75 off_curve.x = P.x;
76 off_curve.y = P.y + Fq::one();
77
78 std::vector<uint8_t> v(sizeof(affine_element));
79 uint8_t* ptr = v.data();
80 affine_element::serialize_to_buffer(off_curve, ptr);
81
82 if (!off_curve.on_curve()) {
83#ifndef __wasm__
84 EXPECT_THROW_OR_ABORT(affine_element::serialize_from_buffer(ptr), "not on the curve");
85#endif
86 }
87 }
88
89 static void test_read_and_write()
90 {
91 // a generic point
92 {
93 affine_element P = affine_element(element::random_element());
94 [[maybe_unused]] affine_element R;
95
96 std::vector<uint8_t> v(sizeof(R));
97 uint8_t* ptr = v.data();
98 write(ptr, P);
99 ASSERT_TRUE(P.on_curve());
100
101 // // Reset to start?
102 // ptr = v.data();
103
104 const uint8_t* read_ptr = v.data();
105 // good read
106 read(read_ptr, R);
107 ASSERT_TRUE(R.on_curve());
108 ASSERT_TRUE(P == R);
109 }
110 }
111
112 static void test_msgpack_serialization()
113 {
114 // a generic point
115 {
116 affine_element P = affine_element(element::random_element());
117
118 // Serialize using msgpack
119 msgpack::sbuffer sbuf;
120 msgpack::pack(sbuf, P);
121
122 // Deserialize using msgpack
123 msgpack::object_handle oh = msgpack::unpack(sbuf.data(), sbuf.size());
124 msgpack::object deserialized = oh.get();
125
126 affine_element R;
127 deserialized.convert(R);
128
129 ASSERT_TRUE(R.on_curve() && !R.is_point_at_infinity());
130 ASSERT_TRUE(P == R);
131 }
132
133 // point at infinity
134 {
135 affine_element P = affine_element(element::random_element());
136 P.self_set_infinity();
137
138 // Serialize using msgpack
139 msgpack::sbuffer sbuf;
140 msgpack::pack(sbuf, P);
141
142 // Deserialize using msgpack
143 msgpack::object_handle oh = msgpack::unpack(sbuf.data(), sbuf.size());
144 msgpack::object deserialized = oh.get();
145
146 affine_element R;
147 deserialized.convert(R);
148
149 ASSERT_TRUE(R.is_point_at_infinity());
150 ASSERT_TRUE(P == R);
151 }
152 }
153
154 static void test_point_compression()
155 {
156 for (size_t i = 0; i < 10; i++) {
157 affine_element P = affine_element(element::random_element());
158 uint256_t compressed = uint256_t(P.x);
159 if (uint256_t(P.y).get_bit(0)) {
160 compressed.data[3] |= group_elements::UINT256_TOP_LIMB_MSB;
161 }
162 affine_element Q = affine_element::from_compressed(compressed);
163 EXPECT_EQ(P, Q);
164 }
165 }
166
167 static void test_point_compression_unsafe()
168 {
169 for (size_t i = 0; i < 100; i++) {
170 affine_element P = affine_element(element::random_element());
171 uint256_t compressed = uint256_t(P.x);
172
173 // Note that we do not check the point Q_points[1] because its highly unlikely to hit a point P on the curve
174 // such that r < P.x < q.
175 std::array<affine_element, 2> Q_points = affine_element::from_compressed_unsafe(compressed);
176 EXPECT_EQ(P, Q_points[0]);
177 }
178 }
179
180 static void test_add_affine()
181 {
182 element lhs = element::random_element();
183 affine_element lhs_affine(lhs);
184
185 element rhs = element::random_element();
186 affine_element rhs_affine(rhs);
187
188 element expected = lhs + rhs;
189 affine_element result = lhs_affine + rhs_affine;
190 EXPECT_EQ(element(result) == expected, true);
191 }
192
193 // Regression test for the large-modulus mixed-addition path: element +/- affine_element must
194 // detect when the affine operand is the infinity sentinel (x = modulus, y = 0). Previously the
195 // operator only checked whether `*this` was infinity, so adding the infinity sentinel to a
196 // normal point fell through to the arithmetic and produced an off-curve garbage result.
197 // operator-=(affine) inherits the bug via its `to_add{other.x, -other.y}` delegation.
198 static void test_mixed_add_infinity_regression()
199 {
200 const element P = element::random_element();
201 const affine_element Q_inf = affine_element::infinity();
202
203 // P (+/-) infinity == P, both as out-of-place and compound-assignment.
204 EXPECT_EQ(P + Q_inf, P);
205 EXPECT_EQ(P - Q_inf, P);
206 {
207 element acc = P;
208 acc += Q_inf;
209 EXPECT_EQ(acc, P);
210 }
211 {
212 element acc = P;
213 acc -= Q_inf;
214 EXPECT_EQ(acc, P);
215 }
216
217 // infinity (+/-) P == +/-P
218 EXPECT_EQ(Q_inf + P, P);
219 EXPECT_EQ(Q_inf - P, -P);
220
221 // *this = infinity, other = infinity must remain infinity (not become {modulus, 0, 1}).
222 element inf_elem = element::zero();
223 ASSERT_TRUE(inf_elem.is_point_at_infinity());
224 EXPECT_TRUE((inf_elem + Q_inf).is_point_at_infinity());
225 EXPECT_TRUE((inf_elem - Q_inf).is_point_at_infinity());
226
227 // The result of mixing a normal point with the infinity sentinel must remain on-curve.
228 EXPECT_TRUE((P + Q_inf).on_curve());
229 EXPECT_TRUE((P - Q_inf).on_curve());
230 }
231
232 // Regression test to ensure that the point at infinity is not equal to its coordinate-wise reduction, which may lie
233 // on the curve, depending on the y-coordinate.
234 static void test_infinity_regression()
235 {
236 affine_element P;
237 P.self_set_infinity();
238 affine_element R(0, P.y);
239 ASSERT_FALSE(P == R);
240 }
241 static void test_infinity_ordering_regression()
242 {
243 affine_element P(0, 1);
244 affine_element Q(0, 1);
245
246 P.self_set_infinity();
247 EXPECT_NE(P < Q, Q < P);
248 }
249
250 // Verify that from_compressed with an x that has no y on the curve returns the (0,0) sentinel.
251 static void test_point_compression_invalid_x()
252 {
253 using Fq = typename G1::Fq;
254 size_t invalid_count = 0;
255 for (size_t i = 0; i < 20; ++i) {
256 affine_element result = affine_element::from_compressed(uint256_t(Fq::random_element()));
257 if (!result.on_curve()) {
258 ++invalid_count;
259 // from_compressed returns (0, 0) when x has no valid y
260 EXPECT_EQ(result.x, Fq::zero());
261 EXPECT_EQ(result.y, Fq::zero());
262 }
263 }
264 // With 20 trials ~10 should have no valid y, so we almost certainly exercise this path
265 EXPECT_GT(invalid_count, 0U);
266 }
267
272 static void test_batch_endomorphism_by_minus_one()
273 {
274 constexpr size_t num_points = 2;
275 std::vector<affine_element> affine_points(num_points, affine_element::one());
276
278 element::batch_mul_with_endomorphism(affine_points, -affine_element::Fr::one());
279
280 for (size_t i = 0; i < num_points; i++) {
281 EXPECT_EQ(affine_points[i], -result[i]);
282 }
283 }
284
289 static void test_fixed_point_at_infinity()
290 {
291 using Fq = affine_element::Fq;
292 affine_element P = affine_element::infinity();
293 affine_element Q(Fq::zero(), Fq::zero());
294 Q.x.self_set_msb();
295 affine_element R = affine_element(element::random_element());
296 EXPECT_EQ(P, Q);
297 EXPECT_NE(P, R);
298 }
299
300 static void test_infinity_mul_by_scalar_is_infinity()
301 {
302 auto result = affine_element::infinity() * Fr::random_element();
303 EXPECT_TRUE(result.is_point_at_infinity());
304 }
305
306 static void test_batch_mul_matches_non_batch_mul()
307 {
308 constexpr size_t num_points = 512;
309 std::vector<affine_element> affine_points(num_points - 1, affine_element::infinity());
310 affine_points.push_back(affine_element::infinity());
311 Fr exponent = Fr::random_element();
313 std::transform(affine_points.begin(),
314 affine_points.end(),
315 std::back_inserter(expected),
316 [exponent](const auto& el) { return el * exponent; });
317 std::vector<affine_element> result = element::batch_mul_with_endomorphism(affine_points, exponent);
318 EXPECT_THAT(result, ElementsAreArray(expected));
319 }
320
321 static void test_infinity_batch_mul_by_scalar_is_infinity()
322 {
323 constexpr size_t num_points = 1024;
324 std::vector<affine_element> affine_points(num_points, affine_element::infinity());
325 std::vector<affine_element> result = element::batch_mul_with_endomorphism(affine_points, Fr::random_element());
326 EXPECT_THAT(result, Each(Property(&affine_element::is_point_at_infinity, Eq(true))));
327 }
328
329 static void test_batch_mul_endomorphism_even_scalars()
330 {
331 const affine_element P = affine_element::one();
332 const std::vector<affine_element> points(4, P);
333 for (const Fr scalar : { Fr(0), Fr(2), Fr(4), Fr(6) }) {
334 const auto result = element::batch_mul_with_endomorphism(points, scalar);
335 const affine_element expected(element(P) * scalar);
336 for (size_t i = 0; i < points.size(); ++i) {
337 EXPECT_EQ(result[i], expected);
338 }
339 }
340 }
341
342 static void test_frc_codec_round_trip()
343 {
344 using FrField = FrCodec::DataType;
345 affine_element point = affine_element::random_element();
348 affine_element::PUBLIC_INPUTS_SIZE);
349 auto reconstructed = FrCodec::deserialize_from_fields<affine_element>(limbs);
350 EXPECT_EQ(reconstructed, point);
351 }
352
353 // The point at infinity, the generator, and any scalar multiple of the generator must all be
354 // recognized as members of the prime-order subgroup.
355 static void test_is_in_prime_subgroup_accepts_subgroup_points()
356 {
357 EXPECT_TRUE(affine_element::infinity().is_in_prime_subgroup());
358 EXPECT_TRUE(affine_element::one().is_in_prime_subgroup());
359
360 for (size_t i = 0; i < 8; ++i) {
361 affine_element P = affine_element(element::random_element());
362 EXPECT_TRUE(P.is_in_prime_subgroup());
363 }
364 }
365};
366
367// using TestTypes = testing::Types<bb::g1>;
368using TestTypes = testing::Types<bb::g1, grumpkin::g1, secp256k1::g1, secp256r1::g1>;
369} // namespace
370
371TYPED_TEST_SUITE(TestAffineElement, TestTypes);
372
373TYPED_TEST(TestAffineElement, AddAffine)
374{
375 TestFixture::test_add_affine();
376}
377
378// Regression test for `element +/- affine_element` when the affine operand is the infinity sentinel.
379// Exercises both the large-modulus and small-modulus branches of `element::operator+=(affine)`.
380TYPED_TEST(TestAffineElement, MixedAddInfinityRegression)
381{
382 TestFixture::test_mixed_add_infinity_regression();
383}
384
385TYPED_TEST(TestAffineElement, ReadWrite)
386{
387 TestFixture::test_read_and_write();
388}
389
390TYPED_TEST(TestAffineElement, ReadWriteBuffer)
391{
392 TestFixture::test_read_write_buffer();
393 TestFixture::test_msgpack_serialization();
394}
395
396TYPED_TEST(TestAffineElement, PointCompression)
397{
398 if constexpr (TypeParam::Fq::modulus.data[3] >= MODULUS_TOP_LIMB_LARGE_THRESHOLD) {
399 GTEST_SKIP();
400 } else {
401 TestFixture::test_point_compression();
402 }
403}
404
405TYPED_TEST(TestAffineElement, FixedInfinityPoint)
406{
407 if constexpr (TypeParam::Fq::modulus.data[3] >= MODULUS_TOP_LIMB_LARGE_THRESHOLD) {
408 GTEST_SKIP();
409 } else {
410 TestFixture::test_fixed_point_at_infinity();
411 }
412}
413
414TYPED_TEST(TestAffineElement, PointCompressionUnsafe)
415{
416 if constexpr (TypeParam::Fq::modulus.data[3] >= MODULUS_TOP_LIMB_LARGE_THRESHOLD) {
417 TestFixture::test_point_compression_unsafe();
418 } else {
419 GTEST_SKIP();
420 }
421}
422
423TYPED_TEST(TestAffineElement, InfinityOrderingRegression)
424{
425 TestFixture::test_infinity_ordering_regression();
426}
427
428namespace bb::group_elements {
429// mul_with_endomorphism and mul_without_endomorphism are private in affine_element.
430// We could make those public to test or create other public utilities, but to keep the API intact we
431// instead mark TestElementPrivate as a friend class so that our test functions can have access.
433 public:
434 template <typename Element, typename Scalar>
435 static Element mul_without_endomorphism(const Element& element, const Scalar& scalar)
436 {
437 return element.mul_without_endomorphism(scalar);
438 }
439 template <typename Element, typename Scalar>
440 static Element mul_with_endomorphism(const Element& element, const Scalar& scalar)
441 {
442 return element.mul_with_endomorphism(scalar);
443 }
444};
445} // namespace bb::group_elements
446
447// Our endomorphism-specialized multiplication should match our generic multiplication.
448// Previously only tested on Grumpkin; now runs on every curve that has USE_ENDOMORPHISM.
449TYPED_TEST(TestAffineElement, MulWithEndomorphismMatchesMulWithoutEndomorphism)
450{
451 if constexpr (!TypeParam::USE_ENDOMORPHISM) {
452 GTEST_SKIP();
453 } else {
454 using element_t = typename TypeParam::element;
455 using Fr = typename TypeParam::Fr;
456 for (int i = 0; i < 100; i++) {
457 element_t x1(element_t::random_element());
458 Fr f1 = Fr::random_element();
461 EXPECT_EQ(r1, r2);
462 }
463 }
464}
465
466// mul_const_time must agree with operator* on every input, including edge cases (0, 1, n-1, low and
467// high Hamming weight).
468TYPED_TEST(TestAffineElement, MulConstTimeMatchesOperatorMul)
469{
470 using element_t = typename TypeParam::element;
471 using Fr = typename TypeParam::Fr;
472 element_t G(element_t::random_element());
473
474 // Edge-case scalars
475 for (Fr s : { Fr::zero(), Fr::one(), -Fr::one(), Fr(2), Fr(uint256_t(1) << 128) }) {
476 EXPECT_EQ(G.mul_const_time(s), G * s);
477 }
478 // Random scalars
479 for (int i = 0; i < 50; ++i) {
481 EXPECT_EQ(G.mul_const_time(s), G * s);
482 }
483}
484
485// FrCodec is defined only for BN254 and Grumpkin (the two curves whose points appear in transcripts).
486TYPED_TEST(TestAffineElement, FrCodecRoundTrip)
487{
489 TestFixture::test_frc_codec_round_trip();
490 } else {
491 GTEST_SKIP();
492 }
493}
494
495// Verify that batch_mul_with_endomorphism gives correct results for even scalars (where k1 or k2 in the
496// GLV decomposition is even), exercising the skew-correction path that uses affine_element::operator+.
497// Scalar 0 gives k1 = k2 = 0 (both skews), and even scalars like 2 and 4 trigger the k1-skew path.
498// These are regression tests for the operator+ fix: reverting to add_chunked would abort when the
499// accumulated result happens to equal ±P during the skew correction.
500TYPED_TEST(TestAffineElement, BatchMulEndomorphismEvenScalars)
501{
502 if constexpr (!TypeParam::USE_ENDOMORPHISM) {
503 GTEST_SKIP();
504 } else {
505 TestFixture::test_batch_mul_endomorphism_even_scalars();
506 }
507}
508
509// Multiplication of a point at infinity by a scalar should be a point at infinity
510TYPED_TEST(TestAffineElement, InfinityMulByScalarIsInfinity)
511{
512 TestFixture::test_infinity_mul_by_scalar_is_infinity();
513}
514
515// Batched multiplication of points should match non-batched multiplication
516TYPED_TEST(TestAffineElement, BatchMulMatchesNonBatchMul)
517{
518 if constexpr (!TypeParam::USE_ENDOMORPHISM) {
519 GTEST_SKIP();
520 } else {
521 TestFixture::test_batch_mul_matches_non_batch_mul();
522 }
523}
524
525// Batched multiplication of a point at infinity by a scalar should result in points at infinity
526TYPED_TEST(TestAffineElement, InfinityBatchMulByScalarIsInfinity)
527{
528 if constexpr (!TypeParam::USE_ENDOMORPHISM) {
529 GTEST_SKIP();
530 } else {
531 TestFixture::test_infinity_batch_mul_by_scalar_is_infinity();
532 }
533}
534
535TYPED_TEST(TestAffineElement, BatchEndomoprhismByMinusOne)
536{
537 if constexpr (TypeParam::USE_ENDOMORPHISM) {
538 TestFixture::test_batch_endomorphism_by_minus_one();
539 } else {
540 GTEST_SKIP();
541 }
542}
543
544// Verify that serialize_from_buffer rejects off-curve bytes by throwing (tests the invalid-curve attack fix).
545TYPED_TEST(TestAffineElement, DeserializeOffCurveThrows)
546{
547 TestFixture::test_deserialize_off_curve_throws();
548}
549
550// Verify is_in_prime_subgroup accepts known prime-order subgroup points
551TYPED_TEST(TestAffineElement, IsInPrimeSubgroupAcceptsSubgroupPoints)
552{
553 TestFixture::test_is_in_prime_subgroup_accepts_subgroup_points();
554}
555
556// Verify that from_compressed returns the (0,0) sentinel for x values with no valid y.
557TYPED_TEST(TestAffineElement, PointCompressionInvalidX)
558{
559 if constexpr (TypeParam::Fq::modulus.data[3] >= MODULUS_TOP_LIMB_LARGE_THRESHOLD) {
560 GTEST_SKIP(); // from_compressed is not used on large-modulus curves
561 } else {
562 TestFixture::test_point_compression_invalid_x();
563 }
564}
565
566TEST(AffineElement, HashToCurve)
567{
569 test_vectors.emplace_back(std::vector<uint8_t>(),
571 fr(uint256_t("24c4cb9c1206ab5470592f237f1698abe684dadf0ab4d7a132c32b2134e2c12e")),
572 fr(uint256_t("0668b8d61a317fb34ccad55c930b3554f1828a0e5530479ecab4defe6bbc0b2e"))));
573
574 test_vectors.emplace_back(std::vector<uint8_t>{ 1 },
576 fr(uint256_t("107f1b633c6113f3222f39f6256f0546b41a4880918c86864b06471afb410454")),
577 fr(uint256_t("050cd3823d0c01590b6a50adcc85d2ee4098668fd28805578aa05a423ea938c6"))));
578
579 // "hello world"
580 test_vectors.emplace_back(std::vector<uint8_t>{ 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64 },
582 fr(uint256_t("037c5c229ae495f6e8d1b4bf7723fafb2b198b51e27602feb8a4d1053d685093")),
583 fr(uint256_t("10cf9596c5b2515692d930efa2cf3817607e4796856a79f6af40c949b066969f"))));
584
585 for (std::tuple<std::vector<uint8_t>, grumpkin::g1::affine_element> test_case : test_vectors) {
586 auto result = grumpkin::g1::affine_element::hash_to_curve(std::get<0>(test_case), 0);
587 auto expected_result = std::get<1>(test_case);
588 std::cout << result << std::endl;
589 EXPECT_TRUE(result == expected_result);
590 }
591}
#define EXPECT_THROW_OR_ABORT(statement, matcher)
Definition assert.hpp:192
static std::vector< fr > serialize_to_fields(const T &val)
Conversion from transcript values to bb::frs.
static Element mul_without_endomorphism(const Element &element, const Scalar &scalar)
static Element mul_with_endomorphism(const Element &element, const Scalar &scalar)
element class. Implements ecc group arithmetic using Jacobian coordinates See https://hyperelliptic....
Definition element.hpp:35
element mul_with_endomorphism(const Fr &scalar) const noexcept
element mul_without_endomorphism(const Fr &scalar) const noexcept
group_elements::affine_element< Fq, Fr, Params > affine_element
Definition group.hpp:44
constexpr bool get_bit(uint64_t bit_index) const
bool expected_result
#define G(r, i, a, b, c, d)
Definition blake2s.cpp:116
test_vector test_vectors[]
bb::curve::BN254::Element Element
const size_t num_points
AffineElement * rhs
std::conditional_t< IsGoblinBigGroup< C, Fq, Fr, G >, element_goblin::goblin_element< C, goblin_field< C >, Fr, G >, element_default::element< C, Fq, Fr, G > > element
element wraps either element_default::element or element_goblin::goblin_element depending on parametr...
Entry point for Barretenberg command-line interface.
Definition api.hpp:5
void read(B &it, field2< base_field, Params > &value)
TYPED_TEST_SUITE(CommitmentKeyTest, Curves)
field< Bn254FrParams > fr
Definition fr.hpp:155
void write(B &buf, field2< base_field, Params > const &value)
TYPED_TEST(CommitmentKeyTest, CommitToZeroPoly)
TEST(BoomerangMegaCircuitBuilder, BasicCircuit)
constexpr decltype(auto) get(::tuplet::tuple< T... > &&t) noexcept
Definition tuple.hpp:13
testing::Types< VKTestParams< UltraFlavor, stdlib::recursion::honk::DefaultIO< UltraCircuitBuilder > >, VKTestParams< UltraFlavor, stdlib::recursion::honk::RollupIO >, VKTestParams< UltraKeccakFlavor, stdlib::recursion::honk::DefaultIO< UltraCircuitBuilder > >, VKTestParams< MegaFlavor, stdlib::recursion::honk::DefaultIO< MegaCircuitBuilder > > > TestTypes
Curve::ScalarField Fr
static constexpr field one()
static field random_element(numeric::RNG *engine=nullptr) noexcept
static constexpr field zero()