Barretenberg
The ZK-SNARK library at the core of Aztec
Loading...
Searching...
No Matches
field_gt.cpp
Go to the documentation of this file.
2
5
6namespace bb::avm2::simulation {
7
8namespace {
9
10LimbsComparisonWitness limb_gt_witness(const U256Decomposition& a, const U256Decomposition& b, bool allow_eq)
11{
12 bool borrow = allow_eq ? (a.lo < b.lo) : (a.lo <= b.lo);
13 // No need to add borrow * TWO_POW_128 since uint128_t will wrap in the way we need
14 uint128_t x_lo = a.lo - b.lo - (allow_eq ? 0 : 1);
15 uint128_t x_hi = a.hi - b.hi - (borrow ? 1 : 0);
16 return { x_lo, x_hi, borrow };
17}
18
19LimbsComparisonWitness canonical_decomposition(const U256Decomposition& x_limbs, RangeCheckInterface& range_check)
20{
21 static auto p_limbs = decompose(FF::modulus);
22
23 range_check.assert_range(x_limbs.lo, 128);
24 range_check.assert_range(x_limbs.hi, 128);
25
26 auto p_sub_x_witness = limb_gt_witness(p_limbs, x_limbs, false);
27 range_check.assert_range(p_sub_x_witness.lo, 128);
28 range_check.assert_range(p_sub_x_witness.hi, 128);
29
30 return p_sub_x_witness;
31}
32
33} // namespace
34
35bool FieldGreaterThan::ff_gt(const FF& a, const FF& b)
36{
37 const uint256_t a_integer(a);
38 const uint256_t b_integer(b);
39 const auto a_limbs = decompose(a_integer);
40 const auto b_limbs = decompose(b_integer);
41
42 const auto p_sub_a_witness = canonical_decomposition(a_limbs, range_check);
43 const auto p_sub_b_witness = canonical_decomposition(b_limbs, range_check);
44
45 const bool result = a_integer > b_integer;
46
47 const auto res_witness =
48 result ? limb_gt_witness(a_limbs, b_limbs, false) : limb_gt_witness(b_limbs, a_limbs, true);
49 range_check.assert_range(res_witness.lo, 128);
50 range_check.assert_range(res_witness.hi, 128);
51
52 events.emit({
54 .a = a,
55 .b = b,
56 .a_limbs = a_limbs,
57 .p_sub_a_witness = p_sub_a_witness,
58 .b_limbs = b_limbs,
59 .p_sub_b_witness = p_sub_b_witness,
60 .res_witness = res_witness,
61 .gt_result = result,
62 });
63 return result;
64}
65
67{
68 const auto a_limbs = decompose(static_cast<uint256_t>(a));
69 const auto p_sub_a_witness = canonical_decomposition(a_limbs, range_check);
70
71 events.emit({
73 .a = a,
74 .a_limbs = a_limbs,
75 .p_sub_a_witness = p_sub_a_witness,
76 });
77
78 return a_limbs;
79}
80
81} // namespace bb::avm2::simulation
U256Decomposition canon_dec(const FF &a) override
Definition field_gt.cpp:66
EventEmitterInterface< FieldGreaterThanEvent > & events
Definition field_gt.hpp:29
bool ff_gt(const FF &a, const FF &b) override
Definition field_gt.cpp:35
void assert_range(uint128_t value, uint8_t num_bits) override
RangeCheck range_check
FF a
FF b
U256Decomposition decompose(const uint256_t &x)
AvmFlavorSettings::FF FF
Definition field.hpp:10
unsigned __int128 uint128_t
Definition serialize.hpp:44
static constexpr uint256_t modulus