Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add SafeLessThan template to comparators with range checks over inputs #86

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions circuits/comparators.circom
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,23 @@ template LessThan(n) {
out <== 1-n2b.out[n];
}

// Do Range checks on the inputs to avoid overflow
template SafeLessThan(n) {
assert(n <= 252);
signal input in[2];
signal output out;

component aInRange = Num2Bits(252);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can save some constraints by restricting to n bits instead. It will always be safe since n <= 252 anyway. Also, that way we can interpret SafeLessThan(n) as meaning "safely compare two n-bit numbers." This makes it easier to understand why in[0]+ (1<<n) - in[1] should be an n+1 bit number.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the comment. Good point. Added to the PR.

aInRange.in <== in[0];
component bInRange = Num2Bits(252);
bInRange.in <== in[1];

component n2b = Num2Bits(n+1);

n2b.in <== in[0]+ (1<<n) - in[1];

out <== 1-n2b.out[n];

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps we could use a normal LessThan component here to avoid code reuse. It makes it clearer what the difference between LessThan and SafeLessThan is, and if LessThan changes in the future we don't risk two difference implementations.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree, applied change in this commit

}


// N is the number of bits the input have.
Expand Down