Skip to content

Commit

Permalink
bigint assert less than or equal
Browse files Browse the repository at this point in the history
  • Loading branch information
mitschabaude committed Mar 27, 2024
1 parent 9c6fa34 commit e274fcd
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
28 changes: 26 additions & 2 deletions src/lib/provable/gadgets/foreign-field.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ const ForeignField = {
assertAlmostReduced,

assertLessThan,
assertLessThanOrEqual,

equals,
};
Expand Down Expand Up @@ -712,8 +713,10 @@ class Sum {
// Field3 comparison

function assertLessThan(x: Field3, y: bigint | Field3) {
if (typeof y === 'bigint')
assert(y > 0n, 'assertLessThan: upper bound must be positive');
assert(
typeof y !== 'bigint' || y > 0n,
'assertLessThan: upper bound must be positive'
);
let y_ = Field3.from(y);

// constant case
Expand Down Expand Up @@ -747,3 +750,24 @@ function assertLessThan(x: Field3, y: bigint | Field3) {
// z = y - x - 1 - 0*(o1 + o2) for some overflows o1, o2
sum([y_, x, Field3.from(1n)], [-1n, -1n], 0n);
}

function assertLessThanOrEqual(x: Field3, y: bigint | Field3) {
assert(
typeof y !== 'bigint' || y >= 0n,
'assertLessThanOrEqual: upper bound must be positive'
);
let y_ = Field3.from(y);

// constant case
if (Field3.isConstant(x) && Field3.isConstant(y_)) {
assert(
Field3.toBigint(x) <= Field3.toBigint(y_),
'assertLessThan: got x > y'
);
return;
}

// provable case
// we compute z = y - x and check that z \in [0, 2^3l), which implies x <= y
sum([y_, x], [-1n], 0n);
}
9 changes: 9 additions & 0 deletions src/lib/provable/gadgets/gadgets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -764,6 +764,15 @@ const Gadgets = {
assertLessThan(x: Field3, f: bigint | Field3) {
ForeignField.assertLessThan(x, f);
},

/**
* Prove that x <= f for any constant f < 2^264, or for another `Field3` f.
*
* See {@link ForeignField.assertLessThan} for details and usage examples.
*/
assertLessThanOrEqual(x: Field3, f: bigint | Field3) {
ForeignField.assertLessThanOrEqual(x, f);
},
},

/**
Expand Down

0 comments on commit e274fcd

Please sign in to comment.