### KZG Setup and Commitment Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/COMPLETION_SUMMARY.txt Demonstrates generating a KZG SRS (Setup), and then creating a commitment to a polynomial. ```go package main import ( "fmt" "log" "github.com/consensys/gnark-crypto/ecc/bn254/fr" "github.com/consensys/gnark-crypto/kzg" ) func main() { // Define polynomial degree degree := uint64(10) // Generate SRS (Setup) s// This can be time-consuming and requires a trusted setup. // For testing, a small SRS can be generated quickly. s// In production, use pre-generated SRS or a secure multi-party computation. ssrs, err := kzg.NewSRS(degree) if err != nil { log.Fatal(err) } // Define a polynomial (e.g., p(x) = 3x^2 + 2x + 1) // Coefficients are in little-endian order: [c0, c1, c2, ...] polyCoeffs := []fr.Element{ *fr.NewElement(1), *fr.NewElement(2), *fr.NewElement(3), } // Create a commitment to the polynomial commitment, err := kzg.Commit(polyCoeffs, ssrs) if err != nil { log.Fatal(err) } fmt.Printf("KZG Commitment: %v\n", commitment) } ``` -------------------------------- ### Complete Hash Function Usage Example Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/hash-functions.md A full example demonstrating how to create, use, and verify the availability of hash functions like Poseidon2 and MiMC. ```go package main import ( "fmt" "github.com/consensys/gnark-crypto/hash" _ "github.com/consensys/gnark-crypto/hash/all" // Register all hash functions ) func main() { // Create hash h := hash.POSEIDON2_BN254.New() // Hash data message := []byte("confidential message") h.Write(message) digest := h.Sum(nil) fmt.Printf("Digest: %x\n", digest) fmt.Printf("Size: %d bytes\n", h.Size()) // Verify availability if hash.MIMC_BLS12_381.Available() { h2 := hash.MIMC_BLS12_381.New() h2.Write(message) digest2 := h2.Sum(nil) fmt.Printf("MiMC digest: %x\n", digest2) } } ``` -------------------------------- ### Example: Add Two G1Affine Points Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/elliptic-curve-operations.md Demonstrates adding two G1Affine points. ```go var p, a, b ecc.bn254.G1Affine p.Add(&a, &b) ``` -------------------------------- ### Example: Set G1Affine Point to Infinity Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/elliptic-curve-operations.md Demonstrates setting a G1Affine point to the point at infinity. ```go var p ecc.bn254.G1Affine p.SetInfinity() ``` -------------------------------- ### Install gnark-crypto Source: https://github.com/consensys/gnark-crypto/blob/master/README.md Install the gnark-crypto library using go get. Ensure correct casing for the module path in go.mod if using Go modules. ```bash go get github.com/consensys/gnark-crypto ``` -------------------------------- ### How to Use This Reference - Step 4 Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/README.md Copy example patterns provided in the documentation for common operations. ```APIDOC 4. **Copy example patterns** for common operations ``` -------------------------------- ### Fiat-Shamir Protocol Setup Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/INDEX.md Illustrates the initialization and usage of the Fiat-Shamir transcript for generating challenges. Requires a hash function and commitments. ```go t := fiat_shamir.NewTranscript(sha256.New(), "alpha", "beta") t.Bind("alpha", commitment1) alpha, _ := t.ComputeChallenge("alpha") t.Bind("beta", commitment2) beta, _ := t.ComputeChallenge("beta") ``` -------------------------------- ### Install and Build gnark-crypto Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/overview.md Commands to install the gnark-crypto library, regenerate its code, run tests, and execute benchmarks. ```bash # Install go get github.com/consensys/gnark-crypto # Regenerate generated code go generate ./... # Run tests (short mode recommended during development) go test -short ./... # Run benchmarks go test -benchmem -count=4 -bench= ./ecc/bn254/... ``` -------------------------------- ### How to Use This Reference - Step 1 Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/README.md The first step in using this reference is to start with `INDEX.md` to locate your topic of interest. ```APIDOC ## How to Use This Reference 1. **Start with INDEX.md** to find your topic ``` -------------------------------- ### Example: Double a G1Affine Point Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/elliptic-curve-operations.md Demonstrates doubling a G1Affine point. ```go var p, a ecc.bn254.G1Affine p.Double(&a) ``` -------------------------------- ### Simple Sigma Protocol Example (Prover and Verifier) Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/fiat-shamir-transcript.md Demonstrates a basic sigma protocol flow using the Fiat-Shamir transcript. The prover computes a commitment, challenge, and response, while the verifier recomputes and verifies the challenge and response. ```go import ( "crypto/sha256" "github.com/consensys/gnark-crypto/fiat-shamir" ) // Prover side func proveStatement(secretValue *big.Int) ([]byte, []byte, []byte, error) { hash := sha256.New() transcript := fiat_shamir.NewTranscript(hash, "challenge") // Round 1: Compute and send commitment commitment := computeCommitment(secretValue) // Round 2: Derive challenge from commitment if err := transcript.Bind("challenge", commitment); err != nil { return nil, nil, nil, err } challenge, err := transcript.ComputeChallenge("challenge") if err != nil { return nil, nil, nil, err } // Round 3: Compute response response := computeResponse(secretValue, challenge) return commitment, challenge, response, nil } // Verifier side func verifyStatement(commitment, challenge, response []byte) (bool, error) { hash := sha256.New() transcript := fiat_shamir.NewTranscript(hash, "challenge") // Recompute challenge from commitment if err := transcript.Bind("challenge", commitment); err != nil { return false, err } recomputedChallenge, err := transcript.ComputeChallenge("challenge") if err != nil { return false, err } // Verify challenge matches if !bytes.Equal(challenge, recomputedChallenge) { return false, nil } // Verify response satisfies statement return verifyResponse(commitment, challenge, response), nil } ``` -------------------------------- ### Compressor Usage Example Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/hash-functions.md Illustrates how to use the Compressor interface to compress two byte slices into a single output. Ensure inputs match the BlockSize. ```go compressor, _ := mimc.NewCompressor() left := make([]byte, compressor.BlockSize()) right := make([]byte, compressor.BlockSize()) // Fill left and right... compressed, err := compressor.Compress(left, right) if err != nil { return err } ``` -------------------------------- ### Multi-Round Protocol Example Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/fiat-shamir-transcript.md Illustrates setting up and using a Fiat-Shamir transcript for a multi-round protocol. It shows how to initialize the transcript with multiple challenge names and sequentially bind commitments and compute challenges for each round. ```go // Create transcript with multiple challenges transcript := fiat_shamir.NewTranscript( sha256.New(), "round1_challenge", "round2_challenge", "round3_challenge", ) // Round 1 commitment1 := proveRound1() if err := transcript.Bind("round1_challenge", commitment1); err != nil { return err } challenge1, err := transcript.ComputeChallenge("round1_challenge") if err != nil { return err } // Round 2 (depends on round1_challenge) commitment2 := proveRound2(challenge1) if err := transcript.Bind("round2_challenge", commitment2); err != nil { return err } challenge2, err := transcript.ComputeChallenge("round2_challenge") if err != nil { return err } // Round 3 (depends on round2_challenge) commitment3 := proveRound3(challenge2) if err := transcript.Bind("round3_challenge", commitment3); err != nil { return err } challenge3, err := transcript.ComputeChallenge("round3_challenge") if err != nil { return err } ``` -------------------------------- ### Point Addition Example Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/INDEX.md Shows how to add two points on the curve. The result is stored in the first point variable. ```go var p, a, b G1Affine p.Add(&a, &b) ``` -------------------------------- ### Complete Field Arithmetic Usage Example Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/field-arithmetic.md Demonstrates a comprehensive set of field arithmetic operations including addition, multiplication, subtraction, division, exponentiation, conversion to big.Int, and comparisons. This example uses the BN254 scalar field (fr.Element). ```go package main import ( "fmt" "github.com/consensys/gnark-crypto/ecc/bn254/fr" "math/big" ) func main() { // Create elements var x, y, z fr.Element // Set values x.SetUint64(17) y.SetUint64(3) // Arithmetic z.Add(&x, &y) fmt.Printf("%v + %v = %v\n", x, y, z) z.Mul(&x, &y) fmt.Printf("%v * %v = %v\n", x, y, z) z.Sub(&x, &y) fmt.Printf("%v - %v = %v\n", x, y, z) // Division (multiply by inverse) z.Div(&x, &y) fmt.Printf("%v / %v = %v\n", x, y, z) // Inverse z.Inverse(&x) fmt.Printf("1/%v = %v\n", x, z) // Exponentiation exp := big.NewInt(100) z.ExpBigInt(&x, exp) fmt.Printf("%v^100 = %v\n", x, z) // Conversion bigInt := z.ToBigInt() fmt.Printf("As big.Int: %v\n", bigInt) // Comparison var a, b fr.Element a.SetUint64(42) b.SetUint64(42) if a.Equal(&b) { fmt.Println("a equals b") } if !a.IsZero() { fmt.Println("a is not zero") } } ``` -------------------------------- ### Complete EdDSA Example in Go Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/digital-signatures-eddsa.md This snippet demonstrates the full lifecycle of EdDSA signatures: key generation, signing a message, verifying the signature, and serializing/deserializing keys. It uses Blake2b as the hash function. Ensure the necessary packages are imported. ```go package main import ( "crypto/rand" "fmt" "golang.org/x/crypto/blake2b" "github.com/consensys/gnark-crypto/ecc/bn254/twistededwards/eddsa" ) func main() { // Key generation privKey, err := eddsa.GenerateKey(rand.Reader) if err != nil { panic(err) } pubKey := privKey.Public().(*eddsa.PublicKey) // Signing message := []byte("Hello, EdDSA!") hashFunc := blake2b.New512() sig, err := privKey.Sign(message, hashFunc) if err != nil { panic(err) } fmt.Printf("Signature (%d bytes): %x\n", len(sig), sig) // Verification hashFunc.Reset() valid, err := pubKey.Verify(sig, message, hashFunc) if err != nil { panic(err) } if valid { fmt.Println("Signature verified!") } // Serialization pubKeyBytes := pubKey.Bytes() privKeyBytes := privKey.Bytes() fmt.Printf("Public key size: %d bytes\n", len(pubKeyBytes)) fmt.Printf("Private key size: %d bytes\n", len(privKeyBytes)) // Deserialization var recoveredPub eddsa.PublicKey if _, err := recoveredPub.SetBytes(pubKeyBytes); err != nil { panic(err) } if !recoveredPub.Equal(pubKey) { panic("Recovered key does not match") } } ``` -------------------------------- ### StateStorer Usage Example Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/hash-functions.md Demonstrates how to use the StateStorer interface to save and restore hash state, useful in interactive protocols. ```go h := hash.MIMC_BN254.New().(hash.StateStorer) h.Write([]byte("part1")) state := h.State() // Save state h.Write([]byte("part2")) digest1 := h.Sum(nil) // Restore state and continue differently h.SetState(state) h.Write([]byte("different_part2")) digest2 := h.Sum(nil) ``` -------------------------------- ### Example: Scalar Multiplication of G1Affine Point Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/elliptic-curve-operations.md Demonstrates multiplying a G1Affine point by a scalar using ScalarMultiplication. ```go var p, a ecc.bn254.G1Affine var scalar big.Int scalar.SetInt64(42) p.ScalarMultiplication(&a, &scalar) ``` -------------------------------- ### Example: Copy G1Affine Point Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/elliptic-curve-operations.md Demonstrates copying the coordinates of one G1Affine point to another. ```go var p, q ecc.bn254.G1Affine p.Set(&q) // p = q ``` -------------------------------- ### Example: Scalar Multiplication of G1Affine Base Point Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/elliptic-curve-operations.md Demonstrates multiplying the base point by a scalar using ScalarMultiplicationBase. ```go var p ecc.bn254.G1Affine var scalar big.Int scalar.SetInt64(12345) p.ScalarMultiplicationBase(&scalar) ``` -------------------------------- ### Example: Check if G1Affine Point is on Curve Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/elliptic-curve-operations.md Demonstrates checking if a G1Affine point lies on the curve. ```go var p ecc.bn254.G1Affine if !p.IsOnCurve() { return fmt.Errorf("point not on curve") } ``` -------------------------------- ### Scalar Multiplication Example Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/INDEX.md Demonstrates scalar multiplication of a point on the curve. Ensure G1Affine and big.Int are properly initialized. ```go var p, g G1Affine var scalar big.Int scalar.SetInt64(42) p.ScalarMultiplication(&g, &scalar) ``` -------------------------------- ### Parallel Multi-Exponentiation Example Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/parallel-execution.md Performs multi-exponentiation in parallel using the gnark-crypto library. It distributes the scalar multiplication and addition operations across multiple goroutines for efficiency, then combines the results sequentially. ```go package main import ( "fmt" "github.com/consensys/gnark-crypto/ecc/bn254" "github.com/consensys/gnark-crypto/parallel" "math/big" ) func multiExpParallel( scalars []*big.Int, points []*bn254.G1Affine, ) bn254.G1Affine { if len(scalars) != len(points) { panic("mismatched lengths") } n := len(scalars) // Distribute computation across goroutines results := make([]bn254.G1Affine, parallel.Chunks(n, 8)) chunkIdx := 0 parallel.Execute(n, func(start, end int) { // Each worker sums its range var acc bn254.G1Affine acc.SetInfinity() for i := start; i < end; i++ { var p bn254.G1Affine p.ScalarMultiplication(&points[i], scalars[i]) acc.Add(&acc, &p) } results[chunkIdx] = acc chunkIdx++ }, 8) // Combine results (sequential) var result bn254.G1Affine result.SetInfinity() for _, r := range results { result.Add(&result, &r) } return result } func main() { // Example usage scalars := make([]*big.Int, 1000) points := make([]*bn254.G1Affine, 1000) for i := range scalars { scalars[i] = big.NewInt(int64(i + 1)) points[i] = &bn254.G1Affine{} // Initialize points... } result := multiExpParallel(scalars, points) fmt.Printf("Result: %v\n", result) } ``` -------------------------------- ### Fiat-Shamir Transcript Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/README.md API reference for the Fiat-Shamir transform, covering challenge generation, protocol binding, and multi-round setup. ```APIDOC ## Fiat-Shamir Transcript ### Description Provides the API for implementing the Fiat-Shamir transform, including generating challenges, binding protocols, and managing multi-round interaction setups. ### Module fiat-shamir ### Operations - **Challenge Generation**: Create challenges within a transcript. - **Protocol Binding**: Securely bind protocol messages to challenges. - **Multi-Round Setup**: Manage transcripts across multiple rounds of interaction. ### Examples Refer to the `fiat-shamir-transcript.md` document for detailed usage examples. ``` -------------------------------- ### Blocking Synchronization Example Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/parallel-execution.md Demonstrates that Execute and ExecuteAligned calls are blocking and synchronize on completion via sync.WaitGroup. The code after the parallel execution will only run once all workers have finished. ```go // This waits for all workers to finish parallel.Execute(n, work) fmt.Println("All workers done") ``` -------------------------------- ### KZG Polynomial Commitments Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/COMPLETION_SUMMARY.txt Manages the setup (SRS) for KZG polynomial commitments and provides methods for reading and writing commitment data. ```APIDOC ## KZG Polynomial Commitments ### Description Handles the setup and management of the Structured Reference String (SRS) for KZG commitments. ### Methods - NewSRS(degree) - ReadFrom(reader) - WriteTo(writer) - WriteDump(filePath) - ReadDump(filePath) ### Parameters - `degree`: The degree of the polynomial. - `reader`: An io.Reader for reading SRS data. - `writer`: An io.Writer for writing SRS data. - `filePath`: Path to the SRS dump file. ### Response - SRS object or file operation status. ``` -------------------------------- ### Quick Reference - API Lookup Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/README.md Provides a quick reference for API lookup within the documentation. Users can start with `INDEX.md` and navigate to the module table to find specific documents. ```APIDOC ### Quick Reference **API lookup**: INDEX.md → Module table → Specific document ``` -------------------------------- ### Get Chunk Ranges for Manual Distribution Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/parallel-execution.md Returns pre-computed chunk ranges (start, end pairs) for a given number of iterations and optional maximum CPUs. This allows for manual work distribution, debugging, or profiling. ```go func Chunks(nbIterations int, maxCpus ...int) [][2]int ``` ```go chunks := parallel.Chunks(10000, 4) fmt.Println("Chunks to process:") for i, chunk := range chunks { fmt.Printf(" Goroutine %d: [%d, %d)\n", i, chunk[0], chunk[1]) } // Manually distribute work for _, chunk := range chunks { go processRange(chunk[0], chunk[1]) } ``` -------------------------------- ### Get Curve ID String Representation Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/INDEX.md Returns the string representation of a curve ID. ```go curveName := curveID.String() ``` -------------------------------- ### How to Use This Reference - Step 5 Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/README.md Refer to the performance tips section for guidance on optimizing operations. ```APIDOC 5. **Check performance tips** section for optimization ``` -------------------------------- ### Typical KZG Workflow with SRS Loading Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/kzg-polynomial-commitment.md Illustrates a standard workflow for initializing, loading, and preparing a KZG SRS for use. This includes creating an SRS for a specific curve, reading data from a reader, and serializing the SRS for later use. Ensure to handle potential errors during I/O operations. ```go package main import ( "bytes" "github.com/consensys/gnark-crypto/ecc" "github.com/consensys/gnark-crypto/kzg" ) func main() { // Step 1: Create empty SRS for curve srs := kzg.NewSRS(ecc.BN254) // Step 2: Load SRS from storage srsData := []byte{/* ... trusted SRS bytes ... */} n, err := srs.ReadFrom(bytes.NewReader(srsData)) if err != nil { panic(err) } // Step 3: Use SRS for curve-specific operations // (Implementation depends on specific curve package) // Step 4: Serialize for later use var buf bytes.Buffer if _, err := srs.WriteTo(&buf); err != nil { panic(err) } // buf.Bytes() now contains serialized SRS } ``` -------------------------------- ### Complete Merkle Tree Proof Workflow Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/merkle-tree-accumulator.md Demonstrates the full lifecycle of creating a Merkle tree, generating a proof for a specific leaf, verifying the proof, and testing with tampered data. Ensure the same hash function is used for tree construction and verification. ```go package main import ( "crypto/sha256" "fmt" "github.com/consensys/gnark-crypto/accumulator/merkletree" ) func main() { // Step 1: Create and populate tree tree := merkletree.New(sha256.New()) leaves := [][]byte{ []byte("alice"), []byte("bob"), []byte("charlie"), []byte("diana"), } for _, leaf := range leaves { if err := tree.Push(leaf); err != nil { panic(err) } } // Step 2: Generate proof for leaf at index 2 tree.SetIndex(2) root, proofSet, index, numLeaves := tree.Prove() fmt.Printf("Leaf: %s (index %d)\n", leaves[2], index) fmt.Printf("Root: %x\n", root) fmt.Printf("Proof size: %d hashes\n", len(proofSet)) // Step 3: Verify proof valid, err := merkletree.VerifyProof( sha256.New(), root, leaves[2], index, proofSet, numLeaves, ) if err != nil { panic(err) } if valid { fmt.Println("✓ Proof verified!") } else { fmt.Println("✗ Proof invalid!") } // Step 4: Test tampered data tampered := []byte("CHARLIE") valid, _ = merkletree.VerifyProof( sha256.New(), root, tampered, index, proofSet, numLeaves, ) if !valid { fmt.Println("✓ Tampered data correctly rejected!") } } ``` -------------------------------- ### Fiat-Shamir Transcript Builder Usage Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/COMPLETION_SUMMARY.txt Illustrates how to use the Fiat-Shamir transcript builder to bind data and compute challenges. ```go package main import ( "fmt" "log" "github.com/consensys/gnark-crypto/fiat-shamir" "github.com/consensys/gnark-crypto/fiat-shamir/transcript/bn254" ) func main() { // Initialize a new transcript var t transcript.Transcript t = transcript.NewTranscript(nil, "my_protocol_label") // Bind data to the transcript data1 := []byte("some data") t.Bind(data1) // Compute a challenge challenge, err := t.ComputeChallenge(nil) if err != nil { log.Fatal(err) } fmt.Printf("Computed challenge: %x\n", challenge) } ``` -------------------------------- ### Get Base Field of a Curve Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/INDEX.md Retrieves the base field (a big.Int) associated with a given curve ID. ```go baseField := curveID.BaseField() ``` -------------------------------- ### Get Scalar Field of a Curve Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/INDEX.md Retrieves the scalar field (a big.Int) associated with a given curve ID. ```go scalarField := curveID.ScalarField() ``` -------------------------------- ### How to Use This Reference - Step 3 Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/README.md Use the provided type and function signatures as a direct reference for implementation. ```APIDOC 3. **Use type/function signatures** as direct reference ``` -------------------------------- ### Registering Hash Functions (All) Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/hash-functions.md Demonstrates the bulk import method to register all available hash functions provided by the Gnark Crypto library. ```go import _ "github.com/consensys/gnark-crypto/hash/all" ``` -------------------------------- ### Standard Hash Interface Implementation Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/hash-functions.md Demonstrates the usage pattern for hash functions, adhering to Go's standard `hash.Hash` interface. Includes writing data, summing the digest, and resetting the hash state for reuse. ```go import ( "crypto/sha256" "github.com/consensys/gnark-crypto/hash" ) // Standard usage h := hash.MIMC_BN254.New() h.Write([]byte("hello")) h.Write([]byte(" world")) digest := h.Sum(nil) // digest is 32 bytes for BN254 // Reset and reuse h.Reset() h.Write([]byte("different message")) digest2 := h.Sum(nil) ``` -------------------------------- ### Merkle Tree Proof Generation and Verification Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/INDEX.md Shows how to build a Merkle tree, push leaves, generate a proof for a specific leaf, and verify that proof against the root. Uses SHA-256. ```go tree := merkletree.New(sha256.New()) tree.Push(leaf1) tree.Push(leaf2) tree.SetIndex(0) root, proof, idx, total := tree.Prove() valid, _ := merkletree.VerifyProof(sha256.New(), root, leaf1, idx, proof, total) ``` -------------------------------- ### Registering Hash Functions (Individual) Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/hash-functions.md Shows how to import specific curve packages to register individual hash functions like MiMC or Poseidon2. ```go import _ "github.com/consensys/gnark-crypto/ecc/bn254/fr/mimc" import _ "github.com/consensys/gnark-crypto/ecc/bn254/fr/poseidon2" ``` -------------------------------- ### Get Curve ID from String Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/INDEX.md Converts a string representation to a curve ID. Returns an error for unsupported curve names. ```go curveID := ecc.IDFromString("bn254") ``` -------------------------------- ### Quick Reference - Import Paths Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/README.md Information on how to find import paths. All documents include the "Package:" information at the top. ```APIDOC **Import paths**: All documents have "Package:" at top ``` -------------------------------- ### Get Hash Function Name Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/hash-functions.md Returns the string representation of a hash function enum value. Useful for logging or debugging. ```go func (m Hash) String() string // Example: name := hash.MIMC_BN254.String() // "MIMC_BN254" ``` -------------------------------- ### Get Curve Name as String Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/ecc-curves.md Converts a curve ID to its lowercase string representation. Useful for logging or display purposes. ```go curveName := ecc.BN254.String() // "bn254" fmt.Println(curveName) ``` -------------------------------- ### How to Use This Reference - Step 2 Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/README.md After finding your topic in `INDEX.md`, navigate to the relevant document. Use overview documents for context and specific documents for API details. ```APIDOC 2. **Go to relevant document** (overview for context, specific doc for API details) ``` -------------------------------- ### Parallel Execution of Tasks Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/COMPLETION_SUMMARY.txt Demonstrates using the parallel execution utilities to run multiple tasks concurrently. ```go package main import ( "fmt" "time" "github.com/consensys/gnark-crypto/parallel" ) func main() { // Define a task function task := func(id int) { fmt.Printf("Task %d started\n", id) time.Sleep(1 * time.Second) fmt.Printf("Task %d finished\n", id) } // Number of tasks nTasks := 5 // Execute tasks in parallel parallel.Run(0, nTasks-1, func(i int) { task(i) }) fmt.Println("All tasks completed") } ``` -------------------------------- ### Generic Signature Verification using Interface Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/digital-signatures-eddsa.md Demonstrates how to verify a signature using the generic `signature.Signer` interface. This allows for polymorphic handling of different signature schemes. ```go func verifySignature(signer signature.Signer, message, sig []byte, h hash.Hash) (bool, error) { pub := signer.Public() return pub.Verify(sig, message, h) } ``` -------------------------------- ### Get Hash Digest Size Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/hash-functions.md Returns the size of the hash digest in bytes for a given hash function. This is useful for pre-allocating buffers. ```go func (m Hash) Size() int // Example: size := hash.MIMC_BN254.Size() // 32 ``` -------------------------------- ### Get Scalar Field Modulus Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/ecc-curves.md Retrieves the scalar field modulus (order of the prime subgroup) for a given curve. This is a large prime number. ```go scalar := ecc.BN254.ScalarField() fmt.Println(scalar.String()) ``` -------------------------------- ### Standard Go Import Paths for Gnark-Crypto Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/README.md Demonstrates the standard Go import paths used for various modules within the gnark-crypto library. Ensure these paths are correctly used when importing functionalities. ```Go import ( "github.com/consensys/gnark-crypto/ecc" bn254 "github.com/consensys/gnark-crypto/ecc/bn254" "github.com/consensys/gnark-crypto/ecc/bn254/fr" "github.com/consensys/gnark-crypto/fiat-shamir" "github.com/consensys/gnark-crypto/hash" "github.com/consensys/gnark-crypto/signature" "github.com/consensys/gnark-crypto/accumulator/merkletree" "github.com/consensys/gnark-crypto/kzg" "github.com/consensys/gnark-crypto/parallel" ) ``` -------------------------------- ### Get Base Field Modulus Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/ecc-curves.md Retrieves the base field modulus (prime of the field for curve points) for a given curve. This is a large prime number. ```go baseField := ecc.BLS12_381.BaseField() fmt.Println(baseField.String()) ``` -------------------------------- ### Create Settings with New Transcript and Hash Function Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/fiat-shamir-transcript.md Use this function to create settings for a new transcript based on a provided hash function. It accepts the hash function and optional base challenges. ```go func WithHash(hash hash.Hash, baseChallenges ...[]byte) Settings ``` ```go hash := sha256.New() settings := fiat_shamir.WithHash(hash, initialChallenge) ``` -------------------------------- ### String Representation of Field Element Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/field-arithmetic.md Provides a method to get the hexadecimal string representation of a field element. This is useful for debugging and logging, and can be used directly with fmt.Printf. ```go // Hex string representation func (z *Element) String() string ``` ```go // Use in fmt fmt.Printf("Element: %v\n", element) ``` -------------------------------- ### CPU Detection with GOMAXPROCS Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/parallel-execution.md Shows how to detect the number of available CPUs using `runtime.NumCPU()` and how to limit the number of goroutines using the `GOMAXPROCS` environment variable. ```go numCPU := runtime.NumCPU() // Default to NumCPU unless maxCpus specified ``` ```bash GOMAXPROCS=4 go run program.go # Will use at most 4 goroutines ``` -------------------------------- ### Verify Proof with Error Handling Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/merkle-tree-accumulator.md Demonstrates how to verify a Merkle proof and handle potential errors. It's recommended to check both the boolean validity and the error return value. ```go valid, err := merkletree.VerifyProof(...) if err != nil { log.Printf("verification error: %v", err) return false } return valid // True only if no error AND proof valid ``` -------------------------------- ### Define Field Element Representation Source: https://github.com/consensys/gnark-crypto/blob/master/CLAUDE.md Illustrates the representation of field elements using fixed-size arrays, specifically the Montgomery representation. This example shows a 4-limb array for a 254-bit field. ```go // Field elements are fixed-size arrays (Montgomery representation) type Element [4]uint64 // bn254/fr - 4 limbs for 254-bit field ``` -------------------------------- ### Hash Function Registry Usage Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/COMPLETION_SUMMARY.txt Shows how to create a hash object using the registry and register custom hash functions. ```go package main import ( "fmt" "github.com/consensys/gnark-crypto/hash" ) func main() { // Get a hash object from the registry (e.g., SHA2_256) h := hash.New(hash.SHA2_256) // Hash some data data := []byte("hello world") h.Write(data) digest := h.Sum(nil) fmt.Printf("SHA2_256 digest: %x\n", digest) // Register a custom hash function (example using a placeholder) // In a real scenario, this would be a valid hash implementation. // hash.RegisterCustomHash("MY_HASH", func() hash.Hash { return &myCustomHash{} }) // myCustomHash := hash.New(hash.MY_HASH) // fmt.Printf("Custom hash digest: %x\n", myCustomHash.Sum(nil)) } ``` -------------------------------- ### Configure Parallel Multi-Exponentiation Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/ecc-curves.md Sets up configuration for parallel multi-exponentiation, specifying the number of goroutines for execution. This configuration is used in curve-specific MultiExp calls. ```go cfg := ecc.MultiExpConfig{ NbTasks: 8, // Use 8 goroutines } // Used in curve-specific MultiExp calls ``` -------------------------------- ### Create Settings with Existing Transcript Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/fiat-shamir-transcript.md Use this function to create settings when reusing an existing transcript. It takes the transcript, a prefix for challenge names, and optional base challenges. ```go func WithTranscript(transcript *Transcript, prefix string, baseChallenges ...[]byte) Settings ``` ```go settings := fiat_shamir.WithTranscript(myTranscript, "round1_", baseChallenge1, baseChallenge2) ``` -------------------------------- ### NewTranscript Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/fiat-shamir-transcript.md Creates a new Fiat-Shamir transcript. It requires a hash function and a list of challenge names that will be computed in order. Panics if duplicate challenge names are provided. ```APIDOC ## NewTranscript ### Description Creates a new Fiat-Shamir transcript with pre-registered challenge names. The order of challenge names determines the computation sequence. ### Method `NewTranscript` ### Parameters #### Arguments - **h** (hash.Hash) - Required - The hash function to use for computations (e.g., sha256.New()). - **challengesID** (...string) - Optional - A variadic list of strings representing the names of the challenges in the order they will be computed. ### Returns - `*Transcript` - A pointer to the newly created Transcript instance. ### Panics - If duplicate challenge names are provided in `challengesID`. ### Example ```go import ( "crypto/sha256" "github.com/consensys/gnark-crypto/fiat-shamir" ) hash := sha256.New() transcript := fiat_shamir.NewTranscript(hash, "challenge1", "challenge2", "challenge3") ``` ``` -------------------------------- ### Type Safety Example: Field Element Assignment Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/field-arithmetic.md Illustrates the strong typing of field elements in Gnark Crypto. It shows that elements from different field types (e.g., fr.Element and fp.Element) cannot be implicitly converted, preventing type-related errors. ```go var x fr.Element // BN254 scalar field var y fp.Element // BN254 base field // x = y // COMPILER ERROR: cannot use y (type fp.Element) as type fr.Element var z fr.Element z = x // OK: same type ``` -------------------------------- ### Import Patterns Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/README.md Demonstrates the standard Go import paths used for various modules within the gnark-crypto library, such as ECC, signature schemes, hash functions, and accumulators. ```APIDOC ## Import Patterns All APIs use standard Go import paths. Example: ```go import ( "github.com/consensys/gnark-crypto/ecc" bn254 "github.com/consensys/gnark-crypto/ecc/bn254" "github.com/consensys/gnark-crypto/ecc/bn254/fr" "github.com/consensys/gnark-crypto/fiat-shamir" "github.com/consensys/gnark-crypto/hash" "github.com/consensys/gnark-crypto/signature" "github.com/consensys/gnark-crypto/accumulator/merkletree" "github.com/consensys/gnark-crypto/kzg" "github.com/consensys/gnark-crypto/parallel" ) ``` ``` -------------------------------- ### Finding Information - Merkle Proofs Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/README.md Details on how to find documentation for Merkle proofs and accumulators. The `Tree.Prove` and `VerifyProof` methods are available in `merkle-tree-accumulator.md`. ```APIDOC ### Search Locations - **Merkle proofs**: merkle-tree-accumulator.md → Tree.Prove, VerifyProof ``` -------------------------------- ### Curve-Specific SRS and Commitment Operations (BN254) Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/kzg-polynomial-commitment.md Demonstrates how to use curve-specific KZG packages for operations like reading the SRS, committing to a polynomial, opening a commitment, and verifying a proof. Requires importing the specific curve's KZG package. ```go import ( kzg_bn254 "github.com/consensys/gnark-crypto/ecc/bn254/fr/kzg" ) // Curve-specific SRS operations srs := &kzg_bn254.SRS{} srs.ReadFrom(reader) // Polynomial commitment operations commit, _ := srs.Commit(polynomialCoefficients) proof, _ := srs.Open(polynomialCoefficients, evaluationPoint) valid, _ := srs.Verify(commit, proof, evaluationPoint, evaluationValue) ``` -------------------------------- ### Import Poseidon2 Hash Field Variants Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/field-arithmetic.md Imports dedicated fields optimized for Poseidon2 hashing. These include variants for Koalabear, Babybear, and Goldilocks fields. ```go // Koalabear field with Poseidon2 import "github.com/consensys/gnark-crypto/field/koalabear/poseidon2" ``` ```go // Babybear field with Poseidon2 import "github.com/consensys/gnark-crypto/field/babybear/poseidon2" ``` ```go // Goldilocks field with Poseidon2 import "github.com/consensys/gnark-crypto/field/goldilocks/poseidon2" ``` -------------------------------- ### EdDSA Key Generation, Signing, and Verification Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/COMPLETION_SUMMARY.txt Demonstrates generating an EdDSA key pair, signing a message, and verifying the signature using one of the supported curves. ```go package main import ( "fmt" "log" "github.com/consensys/gnark-crypto/ecc/bn254/native/eddsa" ) func main() { // Generate EdDSA private and public key privateKey, publicKey := eddsa.NewKey(eddsa.NewEdDSASetup()) // Message to sign message := []byte("this is my message") // Sign the message signature, err := eddsa.Sign(privateKey, message) if err != nil { log.Fatal(err) } // Verify the signature isValid, err := eddsa.Verify(publicKey, message, signature) if err != nil { log.Fatal(err) } if !isValid { fmt.Println("Signature is invalid") } else { fmt.Println("Signature is valid") } } ``` -------------------------------- ### Hash Functions Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/README.md Documentation for hash function implementations, including MiMC and Poseidon2, covering registration, usage, and state preservation. ```APIDOC ## Hash Functions ### Description Reference for hash function implementations, including MiMC and Poseidon2. Covers registration, usage patterns, and state management for hashing operations. ### Module hash ### Functions - **MiMC**: Documentation for the MiMC hash function. - **Poseidon2**: Documentation for the Poseidon2 hash function. - **Registration**: How to register custom hash functions. - **State Preservation**: Techniques for preserving hash state across operations. ### Examples Refer to the `hash-functions.md` document for detailed usage examples. ``` -------------------------------- ### Utility Functions for Bit Reversal and Slice Operations Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/types-and-interfaces.md Provides utility functions for bit reversal on uint64 values and reversing the order of elements in a slice. These are general-purpose utilities. ```go import "github.com/consensys/gnark-crypto/utils" // Bit reversal utilities func BitReverse(a uint64, nbBits int) uint64 // Slice operations func SliceReverse(slice []interface{}) ``` -------------------------------- ### Run Tests with Short Flag Source: https://github.com/consensys/gnark-crypto/blob/master/CLAUDE.md Execute all tests in the project. Use the '-short' flag to skip lengthy tests, which is recommended for faster feedback during development. ```bash go test -short ./... ``` -------------------------------- ### Fiat-Shamir Transcript and Settings Types Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/types-and-interfaces.md Defines the structure for a Fiat-Shamir transcript builder and its associated configuration settings. The transcript manages challenges and their positions, while settings allow for pre-defined base challenges and hash functions. ```Go // Fiat-Shamir transcript builder type Transcript struct { h hash.Hash challenges []challenge nameToChallengePos map[string]int } // Configuration helper type Settings struct { Transcript *Transcript Prefix string BaseChallenges [][]byte Hash hash.Hash } ``` -------------------------------- ### Create New Hash Instance Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/hash-functions.md Instantiates a new hash object for a given hash function type. This object implements Go's standard `hash.Hash` interface. Ensure the corresponding package for the hash function is imported. ```go func (m Hash) New() hash.Hash // Example: h := hash.MIMC_BN254.New() h.Write([]byte("message")) digest := h.Sum(nil) ``` -------------------------------- ### Optimized vs. Contended Parallel Execution Patterns Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/parallel-execution.md Demonstrates an optimized pattern for parallel accumulation where workers use independent result buffers, contrasting it with a slow pattern that uses a contended mutex. The optimized pattern avoids lock contention. ```go // Good: Workers accumulate independently results := make([]bn254.G1Jac, numWorkers) parallel.Execute(n, func(start, end int) { workerIdx := /* ... get worker index ... */ for i := start; i < end; i++ { results[workerIdx].Add(&results[workerIdx], &data[i]) } }) // Bad: Contended mutex in worker var mutex sync.Mutex var result bn254.G1Affine parallel.Execute(n, func(start, end int) { for i := start; i < end; i++ { // SLOW: Lock contention! mutex.Lock() result.Add(&result, &data[i]) mutex.Unlock() } }) ``` -------------------------------- ### Bind Method Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/fiat-shamir-transcript.md Binds a byte value to a specific challenge within the transcript. Use this to associate data with a challenge before it's computed. Multiple values can be bound to the same challenge, and their order matters. ```go func (t *Transcript) Bind(challengeID string, bValue []byte) error ``` ```go // Bind commitment to challenge commitment := []byte{1, 2, 3} if err := transcript.Bind("alpha", commitment); err != nil { return err } // Bind multiple values to same challenge (order matters) if err := transcript.Bind("alpha", []byte{4, 5, 6}); err != nil { return err } ``` -------------------------------- ### Multi-Exponentiation for G1 Affine Points Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/elliptic-curve-operations.md Computes a multi-exponentiation of the form ∑[sᵢ]Pᵢ for G1 affine points. Supports parallel execution by specifying NbTasks in MultiExpConfig. ```go scalars := []*big.Int{&s1, &s2, &s3} points := []*G1Affine{&p1, &p2, &p3} result, err := bn254.MultiExp(scalars, points, ecc.MultiExpConfig{NbTasks: 4}) if err != nil { return err } ``` -------------------------------- ### NewTranscript Function Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/fiat-shamir-transcript.md Creates a new Fiat-Shamir transcript. Use this to initialize a transcript with a specific hash function and pre-registered challenge names. ```go func NewTranscript(h hash.Hash, challengesID ...string) *Transcript ``` ```go import ( "crypto/sha256" "github.com/consensys/gnark-crypto/fiat-shamir" ) hash := sha256.New() transcript := fiat_shamir.NewTranscript(hash, "challenge1", "challenge2", "challenge3") ``` -------------------------------- ### NewChallenge Method Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/fiat-shamir-transcript.md Dynamically adds a new challenge to the transcript sequence. Use this if a challenge name was not known at initialization. ```go func (t *Transcript) NewChallenge(challengeID string) error ``` ```go if err := transcript.NewChallenge("round2_challenge"); err != nil { return err // Challenge already exists } ``` -------------------------------- ### Settings Struct for Transcript Initialization Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/fiat-shamir-transcript.md Defines the configuration structure for initializing a Fiat-Shamir transcript. Use this struct to manage transcript reuse, prefixes, base challenges, and hash functions. ```go type Settings struct { Transcript *Transcript Prefix string BaseChallenges [][]byte Hash hash.Hash } ``` -------------------------------- ### Configure Multi-Exponentiation Tasks Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/INDEX.md Defines the number of concurrent tasks for multi-exponentiation operations. ```go config := ecc.MultiExpConfig{NbTasks: 10} ``` -------------------------------- ### Hash.New() Source: https://github.com/consensys/gnark-crypto/blob/master/_autodocs/hash-functions.md Creates a new hash instance for the selected hash function. This instance implements the standard Go `hash.Hash` interface. ```APIDOC ## Hash.New() ### Description Creates a new hash instance. ### Method func (m Hash) New() hash.Hash ### Returns `hash.Hash` - Instance implementing standard Go hash.Hash interface ### Panics If hash function not registered (must import corresponding package) ### Example ```go h := hash.MIMC_BN254.New() h.Write([]byte("message")) digest := h.Sum(nil) ``` ```