Skip to content

Commit

Permalink
Merge pull request #16 from reilabs/wz/4844-endpoints
Browse files Browse the repository at this point in the history
Adjust web API to 4844
  • Loading branch information
wzmuda authored Jun 29, 2024
2 parents e3341d2 + 4b79235 commit cd49443
Show file tree
Hide file tree
Showing 8 changed files with 408 additions and 159 deletions.
19 changes: 12 additions & 7 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,6 @@ func main() {
params.MerkleProofs[i] = tree.Update(i, params.IdComms[i])
}
params.PostRoot = tree.Root()
params.ComputeInputHashInsertion()
r, err = json.Marshal(&params)
} else if mode == server.DeletionMode {
params := prover.DeletionParameters{}
Expand Down Expand Up @@ -335,31 +334,37 @@ func main() {
return err
}

var proof *prover.Proof
var r []byte
if mode == server.InsertionMode {
var params prover.InsertionParameters
err = json.Unmarshal(bytes, &params)
if err != nil {
return err
}
logging.Logger().Info().Msg("params read successfully")
proof, err = ps.ProveInsertion(&params)
var response *prover.InsertionResponse
response, err = ps.ProveInsertion(&params)
r, err = json.Marshal(&response)
if err != nil {
return err
}
} else if mode == server.DeletionMode {
var params prover.DeletionParameters
err = json.Unmarshal(bytes, &params)
if err != nil {
return err
}
logging.Logger().Info().Msg("params read successfully")
var proof *prover.Proof
proof, err = ps.ProveDeletion(&params)
r, err = json.Marshal(&proof)
if err != nil {
return err
}
} else {
return fmt.Errorf("Invalid mode: %s", mode)
}

if err != nil {
return err
}
r, _ := json.Marshal(&proof)
fmt.Println(string(r))
return nil
},
Expand Down
44 changes: 41 additions & 3 deletions integration_test.go → main_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
package main_test

import (
gnarkLogger "github.com/consensys/gnark/logger"
"encoding/json"
"io"
"net/http"
"strings"
"testing"

"github.com/consensys/gnark-crypto/ecc"
"github.com/consensys/gnark/backend/groth16"
"github.com/consensys/gnark/frontend"
gnarkLogger "github.com/consensys/gnark/logger"

"worldcoin/gnark-mbu/logging"
"worldcoin/gnark-mbu/prover"
"worldcoin/gnark-mbu/server"
Expand All @@ -15,11 +21,13 @@ const ProverAddress = "localhost:8080"
const MetricsAddress = "localhost:9999"

var mode string
var ps *prover.ProvingSystem

func TestMain(m *testing.M) {
gnarkLogger.Set(*logging.Logger())
logging.Logger().Info().Msg("Setting up the prover")
ps, err := prover.SetupInsertion(3, 2)
var err error
ps, err = prover.SetupInsertion(3, 2)
if err != nil {
panic(err)
}
Expand Down Expand Up @@ -64,7 +72,6 @@ func TestInsertionHappyPath(t *testing.T) {
return
}
body := `{
"inputHash":"0x5057a31740d54d42ac70c05e0768fb770c682cb2c559bdd03fe4099f7e584e4f",
"startIndex":0,
"preRoot":"0x18f43331537ee2af2e3d758d50f72106467c6eea50371dd528d57eb2b856d238",
"postRoot":"0x2267bee7aae8ed55eb9aecff101145335ed1dd0a5a276a2b7eb3ae7d20e232d8",
Expand All @@ -80,6 +87,37 @@ func TestInsertionHappyPath(t *testing.T) {
if response.StatusCode != http.StatusOK {
t.Fatalf("Expected status code %d, got %d", http.StatusOK, response.StatusCode)
}

responseBody, err := io.ReadAll(response.Body)
if err != nil {
t.Fatal(err)
}

var ir prover.InsertionResponse
if err = json.Unmarshal(responseBody, &ir); err != nil {
t.Fatal(err)
}

var params prover.InsertionParameters
if err = json.Unmarshal([]byte(body), &params); err != nil {
t.Fatal(err)
}

publicWitness, err := frontend.NewWitness(&prover.InsertionMbuCircuit{
InputHash: ir.InputHash,
ExpectedEvaluation: ir.ExpectedEvaluation[:],
Commitment4844: ir.Commitment4844[:],
StartIndex: params.StartIndex,
PreRoot: params.PreRoot,
PostRoot: params.PostRoot,
}, ecc.BN254.ScalarField(), frontend.PublicOnly())
if err != nil {
t.Fatal(err)
}

if err = groth16.Verify(ir.Proof.Proof, ps.VerifyingKey, publicWitness); err != nil {
t.Fatal(err)
}
}

func TestDeletionHappyPath(t *testing.T) {
Expand Down
52 changes: 52 additions & 0 deletions prover/circuit_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,15 @@ package prover
import (
"fmt"
"io"
"math"
"math/big"
"os"
"strconv"

bn254fr "github.com/consensys/gnark-crypto/ecc/bn254/fr"
gokzg4844 "github.com/crate-crypto/go-kzg-4844"
"github.com/iden3/go-iden3-crypto/keccak256"

"worldcoin/gnark-mbu/logging"
"worldcoin/gnark-mbu/prover/poseidon"

Expand Down Expand Up @@ -300,3 +306,49 @@ func toBytesLE(b []byte) []byte {
func (ps *ProvingSystem) ExportSolidity(writer io.Writer) error {
return ps.VerifyingKey.ExportSolidity(writer)
}

// identitiesToBlob converts a slice of big.Int into a KZG 4844 Blob.
func identitiesToBlob(ids []big.Int) *gokzg4844.Blob {
if len(ids) > gokzg4844.ScalarsPerBlob {
panic("too many identities for a blob")
}
var blob gokzg4844.Blob
for i, id := range ids {
startByte := i * 32
id.FillBytes(blob[startByte : startByte+32])
}
return &blob
}

// bytesToBn254BigInt converts a slice of bytes to a *big.Int and reduces it by BN254 modulus
func bytesToBn254BigInt(b []byte) *big.Int {
n := new(big.Int).SetBytes(b)
modulus := bn254fr.Modulus()
return n.Mod(n, modulus)
}

// bigIntsToChallenge converts input bit.Ints to a challenge for a proof of knowledge of a polynomial.
// The challenge is defined as a gokzg4844.Scalar of a keccak256 hash of all input big.Ints reduced
// by BN254 modulus.
func bigIntsToChallenge(input []big.Int) (challenge gokzg4844.Scalar) {
var inputBytes []byte
for _, i := range input {
temp := make([]byte, 32)
inputBytes = append(inputBytes, i.FillBytes(temp)...)
}

// Reduce keccak because gokzg4844 API expects that
hashBytes := bytesToBn254BigInt(keccak256.Hash(inputBytes)).Bytes()

copy(challenge[:], hashBytes)
return challenge
}

// treeDepth calculates the depth of a binary tree containing the given number of leaves
func treeDepth(leavesCount int) (height int) {
if leavesCount <= 0 {
return 0
}
height = int(math.Ceil(math.Log2(float64(leavesCount))))
return
}
48 changes: 0 additions & 48 deletions prover/insertion_circuit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package prover

import (
"crypto/rand"
"math"
"math/big"
"testing"

Expand All @@ -12,7 +11,6 @@ import (
"github.com/consensys/gnark/frontend"
"github.com/consensys/gnark/test"
gokzg4844 "github.com/crate-crypto/go-kzg-4844"
"github.com/iden3/go-iden3-crypto/keccak256"
"github.com/stretchr/testify/require"

poseidon "worldcoin/gnark-mbu/poseidon_native"
Expand Down Expand Up @@ -104,49 +102,3 @@ func generateRandomIdentities(count int) []big.Int {
}
return ids
}

// identitiesToBlob converts a slice of big.Int into a KZG 4844 Blob.
func identitiesToBlob(ids []big.Int) *gokzg4844.Blob {
if len(ids) > gokzg4844.ScalarsPerBlob {
panic("too many identities for a blob")
}
var blob gokzg4844.Blob
for i, id := range ids {
startByte := i * 32
id.FillBytes(blob[startByte : startByte+32])
}
return &blob
}

// bytesToBn254BigInt converts a slice of bytes to a *big.Int and reduces it by BN254 modulus
func bytesToBn254BigInt(b []byte) *big.Int {
n := new(big.Int).SetBytes(b)
modulus := bn254fr.Modulus()
return n.Mod(n, modulus)
}

// bigIntsToChallenge converts input bit.Ints to a challenge for a proof of knowledge of a polynomial.
// The challenge is defined as a gokzg4844.Scalar of a keccak256 hash of all input big.Ints reduced
// by BN254 modulus.
func bigIntsToChallenge(input []big.Int) (challenge gokzg4844.Scalar) {
var inputBytes []byte
for _, i := range input {
temp := make([]byte, 32)
inputBytes = append(inputBytes, i.FillBytes(temp)...)
}

// Reduce keccak because gokzg4844 API expects that
hashBytes := bytesToBn254BigInt(keccak256.Hash(inputBytes)).Bytes()

copy(challenge[:], hashBytes)
return challenge
}

// treeDepth calculates the depth of a binary tree containing the given number of leaves
func treeDepth(leavesCount int) (height int) {
if leavesCount <= 0 {
return 0
}
height = int(math.Ceil(math.Log2(float64(leavesCount))))
return
}
Loading

0 comments on commit cd49443

Please sign in to comment.