# immudb and Gnark: Creating Immutable and Verifiable Databases with Zero-Knowledge Proof

### A simple example of integrating gnark with immudb

In recent years, zero-knowledge proof (ZKP) systems have become increasingly popular due to their ability to provide privacy and security in various applications. Gnark is one such system that has been gaining traction in the ZKP space. It allows developers to build circuits and generate proofs that can be used to verify certain computations without revealing any sensitive information. If you are new to ZK Proofs, read my article on the introduction to this topic.

However, building a secure and scalable infrastructure to store and manage these proofs can be a challenge. This is where immudb, a lightweight and immutable database, comes in. In this article, we will explore how to integrate Gnark with immudb to securely store and verify circuit proofs.

## What is immudb?

immudb is a general purpose immutable database that provides a tamper-proof and auditable ledger with the help of cryptographic proofs. It uses a Merkle tree structure to ensure that every change made to the database is cryptographically verifiable. This makes immudb ideal for storing sensitive information that needs to be audited and secured. You can learn more about immudb here.

https://immudb.io/

Every record that is added to immudb is given a unique hash, which is used to construct a Merkle tree. This hash provides a cryptographic proof that the record has not been tampered with.

## What is Gnark?

Gnark is a zero-knowledge proof (ZKP) system that allows developers to build circuits and generate proofs that can be used to verify certain computations without revealing any sensitive information. It uses a circuit-based approach to build proofs, which means that developers can build circuits that represent a specific computation and generate a proof that can be used to verify the result of that computation. If you are interested in learning more about GNARK, refer to my article here.

Let's take a simple example to illustrate how to build a circuit using Gnark. Suppose we want to create a circuit that verifies whether a given number x is equal to 42. We can express this as a Boolean constraint using the following equation:

`x**3 + x + 5 = y`

To build this circuit using Gnark, we can write the following Go code:

```
package main
import (
"github.com/consensys/gnark-crypto/ecc"
"github.com/consensys/gnark/backend/groth16"
"github.com/consensys/gnark/frontend"
"github.com/consensys/gnark/frontend/cs/r1cs"
)
// CubicCircuit defines a simple circuit
// x**3 + x + 5 == y
type CubicCircuit struct {
// struct tags on a variable is optional
// default uses variable name and secret visibility.
X frontend.Variable `gnark:"x"`
Y frontend.Variable `gnark:",public"`
}
// Define declares the circuit constraints
// x**3 + x + 5 == y
func (circuit *CubicCircuit) Define(api frontend.API) error {
x3 := api.Mul(circuit.X, circuit.X, circuit.X)
api.AssertIsEqual(circuit.Y, api.Add(x3, circuit.X, 5))
return nil
}
func main() {
// compiles our circuit into a R1CS
var circuit CubicCircuit
ccs, _ := frontend.Compile(ecc.BN254.ScalarField(), r1cs.NewBuilder, &circuit)
// groth16 zkSNARK: Setup
pk, vk, _ := groth16.Setup(ccs)
// witness definition
assignment := CubicCircuit{X: 3, Y: 35}
witness, _ := frontend.NewWitness(&assignment, ecc.BN254.ScalarField())
publicWitness, _ := witness.Public()
// groth16: Prove & Verify
proof, _ := groth16.Prove(ccs, pk, witness)
groth16.Verify(proof, vk, publicWitness)
}
```

In this example, we define a circuit using the `frontend`

package provided by Gnark. We then define an input variable `x`

and set its value to 3. We define the constraints using the `AssertIsEqual`

method, which checks whether the expression `x**3 + x + 5 = y`

is true.

We then compile the circuit into a rank-1 constraint system (R1CS) using the `ToR1CS`

method. We generate the proving and verification keys using the `Groth16Setup`

method. We create a proof using the `Groth16Prove`

method and verify it using the `Groth16Verify

## Why use ZK Proofs with immudb?

* Firstly*, immudb's immutable nature makes it ideal for storing the state of the circuit. The circuit's state is an essential part of zero-knowledge proof systems, and immutability guarantees that the state cannot be changed after it has been committed to the database. This is a critical requirement for any system that needs to provide tamper-evident data storage.

* Secondly*, immudb provides efficient storage and retrieval of key-value pairs, which is the data structure used by gnark to store the circuit's public inputs and proofs. The integration of gnark and immudb allows for efficient and secure storage and retrieval of these key-value pairs.

* Thirdly*, immudb's support for cryptographic authentication and authorization mechanisms ensures that only authorized parties can access the circuit's data. This provides an additional layer of security and trust in the zero-knowledge proof system.

* Lastly*, immudb's easy-to-use API and seamless integration with gnark make it a great choice for implementing zero-knowledge proof systems. With immudb, developers can focus on building and verifying the circuit while immudb takes care of secure and tamper-evident storage.

Hence integration of gnark with immudb provides an efficient and secure solution for building and verifying zero-knowledge proof circuits. Immudb's immutable storage, efficient key-value store, cryptographic authentication and authorization mechanisms, and easy-to-use API make it an excellent choice for developers looking to build robust zero-knowledge proof systems.

## Integrating Gnark with immudb

Now that we have a basic understanding of immudb and Gnark, let's dive into how we can integrate these two systems to store and verify circuit proofs.

#### Step 1: Set up immudb

The first step is to set up immudb. You can download the immudb binary from the official website here and install it on your system. Once installed, you can start immudb by running the following command:

```
wget https://github.com/codenotary/immudb/releases/download/v1.4.1/immudb-v1.4.1-linux-amd64
mv immudb-v1.4.1-linux-amd64 immudb
chmod +x immudb
# run immudb in the foreground to see all output
./immudb
# or run immudb in the background
./immudb -d
```

This will start the immudb server on the default port 3322. You can also specify a custom port by passing the `--port`

flag.

#### Step 2: Set up Gnark

Next, we need to set up Gnark. You can install Gnark by running the following command:

`go get -u github.com/consensys/gnark/...`

This will install Gnark and its dependencies on your system.

#### Step 3: Build a Circuit and Generate a Proof

Once Gnark is installed, we can start building circuits and generating proofs. In this example, we will build a simple circuit that adds two numbers and generate a proof that can be used to verify the result of the computation.

Import the necessary packages in your Go program:

`package main import ( "context" "encoding/json" "fmt" "github.com/codenotary/immudb/pkg/client" "github.com/consensys/gnark-crypto/ecc" "github.com/consensys/gnark/backend/groth16" "github.com/consensys/gnark/frontend" "github.com/consensys/gnark/frontend/cs/r1cs" )`

Define the circuit you want to store in immudb. For example, let's say you want to create a circuit that verifies the multiplication of two numbers:

`// Define the circuit struct type RollupCircuit struct { BatchTransaction BatchTransaction `gnark:",public"` } // Define declares the circuit constraints func (circuit *RollupCircuit) Define(api frontend.API) error { return nil }`

Generate the proving and verification keys for the circuit:

`// Use gnark to generate a ZK proof that proves the validity of the batch transaction var pk groth16.ProvingKey var vk groth16.VerifyingKey // Define the circuit, generate the proving key and verifying key, and generate the proof var circuit RollupCircuit circuit.BatchTransaction = batch // Generate the proving key and verifying key const ( nbConstraints = 1 << 10 pkFile = "rollup.pk" vkFile = "rollup.vk" ) // groth16 zkSNARK: Setup ccs, _ := frontend.Compile(ecc.BN254.ScalarField(), r1cs.NewBuilder, &circuit) pk, vk, _ = groth16.Setup(ccs) // witness definition with some transaction assignment := RollupCircuit{} witness, _ := frontend.NewWitness(&assignment, ecc.BN254.ScalarField()) publicWitness, _ := witness.Public() // groth16: Prove & Verify proof, _ := groth16.Prove(ccs, pk, witness) groth16.Verify(proof, vk, publicWitness)`

Connect to immudb and store the keys and circuit:

`// connect to immudb options := client.DefaultOptions().WithAddress("127.0.0.1").WithPort(3322) client, err := client.NewImmuClient(options) if err != nil { log.Fatal(err) } // Serialize the batch transaction and ZK proof batchBytes, err := json.Marshal(batch) if err != nil { panic(err) } proofBytes, err := json.Marshal(proof) if err != nil { panic(err) } // Store the batch transaction and ZK proof in immudb _, err = client.Set(context.Background(), []byte("batch"), batchBytes) if err != nil { panic(err) } _, err = client.Set(context.Background(), []byte("proof"), proofBytes) if err != nil { panic(err) }`

Retrieve the keys and circuit from immudb:

`// retrieve the keys and circuit from immudb pkBytes, err := client.Get(context.Background(), []byte("proof")) if err != nil { log.Fatal(err) }`

That's it! Now you can use the keys and circuit to generate and verify proofs with the circuit stored in immudb in an immutable format.