Skip to content

Commit

Permalink
Merge pull request #233 from ConsenSys/feat/api_cmp
Browse files Browse the repository at this point in the history
feat: addition of Cmp in the API
  • Loading branch information
ThomasPiellard authored Jan 20, 2022
2 parents 58758e8 + 3e3b1c6 commit d3eb384
Show file tree
Hide file tree
Showing 6 changed files with 257 additions and 124 deletions.
9 changes: 6 additions & 3 deletions frontend/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,12 @@ type API interface {
// Add returns res = i1+i2+...in
Add(i1, i2 Variable, in ...Variable) Variable

// Sub returns res = i1 - i2 - ...in
Sub(i1, i2 Variable, in ...Variable) Variable

// Neg returns -i
Neg(i1 Variable) Variable

// Sub returns res = i1 - i2 - ...in
Sub(i1, i2 Variable, in ...Variable) Variable

// Mul returns res = i1 * i2 * ... in
Mul(i1, i2 Variable, in ...Variable) Variable

Expand Down Expand Up @@ -89,6 +89,9 @@ type API interface {
// IsZero returns 1 if a is zero, 0 otherwise
IsZero(i1 Variable) Variable

// Cmp returns 1 if i1>i2, 0 if i1=i2, -1 if i1<i2
Cmp(i1, i2 Variable) Variable

// ---------------------------------------------------------------------------------------------
// Assertions

Expand Down
26 changes: 26 additions & 0 deletions frontend/cs/plonk/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,32 @@ func (system *sparseR1CS) IsZero(i1 frontend.Variable) frontend.Variable {
return m
}

// Cmp returns 1 if i1>i2, 0 if i1=i2, -1 if i1<i2
func (system *sparseR1CS) Cmp(i1, i2 frontend.Variable) frontend.Variable {

bi1 := system.ToBinary(i1, system.BitLen())
bi2 := system.ToBinary(i2, system.BitLen())

var res frontend.Variable
res = 0

for i := system.BitLen() - 1; i >= 0; i-- {

iszeroi1 := system.IsZero(bi1[i])
iszeroi2 := system.IsZero(bi2[i])

i1i2 := system.And(bi1[i], iszeroi2)
i2i1 := system.And(bi2[i], iszeroi1)

n := system.Select(i2i1, -1, 0)
m := system.Select(i1i2, 1, n)

res = system.Select(system.IsZero(res), m, res)

}
return res
}

// Println behaves like fmt.Println but accepts Variable as parameter
// whose value will be resolved at runtime when computed by the solver
// Println enables circuit debugging and behaves almost like fmt.Println()
Expand Down
Loading

0 comments on commit d3eb384

Please sign in to comment.