circuits

package
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 3, 2026 License: AGPL-3.0 Imports: 39 Imported by: 0

Documentation

Overview

Package circuits provides functionality for working with zero-knowledge proof circuits and their associated artifacts (circuit definitions, proving keys, and verification keys). It includes utilities for loading, downloading, and verifying the integrity of these artifacts.

Index

Constants

View Source
const (
	BallotModeSerializedLen    = 8
	EncryptionKeySerializedLen = 2

	KeyProcessID     = 0x00
	KeyBallotMode    = 0x02
	KeyEncryptionKey = 0x03
	KeyResultsAdd    = 0x04
	KeyResultsSub    = 0x05
	KeyCensusOrigin  = 0x06

	// ReservedKeysOffset is used to prevent collisions in edge cases
	// where a VoteID or Address is near zero (e.g. in badly designed tests)
	ReservedKeysOffset = 0x10
)
View Source
const BallotProofNPubInputs = 3

BallotProofNPubInputs is the number of public inputs for the ballot proof circom circuit.

Variables

View Source
var BaseDir string

BaseDir is the path where the artifact cache is expected to be found. If the artifacts are not found there, they will be downloaded and stored. It can be set to a different path if needed from other packages. Defaults to the env var DAVINCI_ARTIFACTS_DIR or the user home directory.

View Source
var Poseidon377Domain = poseidon377.DomainFromLEBytes([]byte("/davinci/"))

Poseidon377Domain is the domain used for Poseidon377 hashing

View Source
var Poseidon377DomainVar frontend.Variable

Poseidon377DomainVar is the domain as a frontend.Variable for use in circuits

Functions

func BallotHash

func BallotHash(
	api frontend.API,
	process Process[frontend.Variable],
	vote Vote[frontend.Variable],
) []frontend.Variable

BallotHash returns the inputs hashed for BallotHash in this order:

Process.ID
Process.BallotMode
Process.EncryptionKey (in Twisted Edwards format)
Vote.Address
Vote.VoteID
Vote.Ballot (in Twisted Edwards format)
Vote.UserWeight

func BigIntArrayToN

func BigIntArrayToN(arr []*big.Int, n int) []*big.Int

BigIntArrayToN pads the big.Int array to n elements, if needed, with zeros.

func BigIntArrayToNInternal

func BigIntArrayToNInternal(arr []*big.Int, n int) []*types.BigInt

BigIntArrayToNInternal pads the types.BigInt array to n elements, if needed, with zeros.

func BigIntArrayToStringArray

func BigIntArrayToStringArray(arr []*big.Int, n int) []string

BigIntArrayToStringArray converts the big.Int array to a string array.

func BoolToBigInt

func BoolToBigInt(b bool) *big.Int

BoolToBigInt returns 1 when b is true or 0 otherwise

func FrontendError

func FrontendError(api frontend.API, msg string, trace error)

FrontendError function is an in-circuit function to print an error message and an error trace, making the circuit fail.

func NextK

NextK uses the Poseidon hasher to generate a new k starting from the provided k.

func RandK

func RandK() (*big.Int, error)

RandK function generates a random k value for encryption, inside the scalar field of the BallotProof curve

func StoreConstraintSystem

func StoreConstraintSystem(cs constraint.ConstraintSystem, filepath string) error

StoreConstraintSystem stores the constraint system in a file.

func StoreProof

func StoreProof(proof groth16.Proof, filepath string) error

StoreProof stores the proof in a file.

func StoreVerificationKey

func StoreVerificationKey(vkey groth16.VerifyingKey, filepath string) error

StoreVerificationKey stores the verification key in a file.

func StoreWitness

func StoreWitness(witness witness.Witness, filepath string) error

StoreWitness stores the witness in a file.

func VoteID

func VoteID(processID types.ProcessID, address common.Address, k *types.BigInt) (*types.BigInt, error)

VoteID calculates the vote ID, which is the poseidon hash of: the process ID, voter's address and a secret value k. This is truncated to the least significant 64 bits. The vote ID is used to identify a vote in the system. The function transforms the inputs to safe values of ballot proof curve scalar field, then hashes them using iden3 poseidon. The resulting vote ID is a hex byte array. If something goes wrong during the hashing process, it returns an error.

Types

type Artifact

type Artifact struct {
	Name      string
	RemoteURL string
	Hash      []byte
	Content   []byte
}

Artifact is a struct that holds the remote URL, the hash of the content and the content itself. It provides a method to load the content from the local cache or download it from the remote URL provided. It also checks the hash of the content to ensure its integrity.

func (*Artifact) Download

func (k *Artifact) Download(ctx context.Context) error

Download method downloads the content of the artifact from the remote URL, checks the hash of the content and stores it locally. It returns an error if the remote URL is not provided or the content cannot be downloaded, or if the hash of the content does not match. If the content is already loaded, it will return.

func (*Artifact) Load

func (k *Artifact) Load() error

Load method checks if the artifact content is already loaded, if not, it will try to load it from the local storage. It also checks the hash of the content to ensure its integrity. It returns an error if the artifact is already loaded but the hash is not set or it does not match with the content.

type Ballot

func NewBallot

func NewBallot() *Ballot

func (*Ballot) Add

func (z *Ballot) Add(api frontend.API, x, y *Ballot) *Ballot

Add sets z to the sum x+y and returns z.

Panics if twistededwards curve init fails.

func (*Ballot) AssertDecrypt

func (z *Ballot) AssertDecrypt(api frontend.API, privKey frontend.Variable, originals [params.FieldsPerBallot]frontend.Variable)

AssertDecrypt checks that the ballot can be decrypted with the provided private key and the original values. It uses the elgamal.Ciphertext's AssertDecrypt method for each ciphertext in the ballot.

func (*Ballot) AssertIsEqual

func (z *Ballot) AssertIsEqual(api frontend.API, x *Ballot)

AssertIsEqual fails if any of the fields differ between z and x

func (*Ballot) Encrypt

Encrypt encrypts the ballot using the provided encryption key and messages. It uses the Poseidon hasher to generate a new k for each ciphertext starting from the provided k.

func (*Ballot) EncryptedZero

func (b *Ballot) EncryptedZero(api frontend.API, encKey EncryptionKey[frontend.Variable], k frontend.Variable) *Ballot

EncryptedZero returns a new ballot with all fields set to the encrypted zero point using the provided encryption key and k.

func (*Ballot) IsEqual

func (z *Ballot) IsEqual(api frontend.API, x *Ballot) frontend.Variable

func (*Ballot) Reencrypt

Reencrypt re-encrypts the ballot using the provided encryption key and the provided k. To re-encrypt the ballot, it uses the encrypted zero point with the inputs provided and them adds it to the original ballot. It uses the Poseidon hasher to generate a new k for each ciphertext starting from the provided k.

func (*Ballot) Select

func (z *Ballot) Select(api frontend.API, b frontend.Variable, i1 *Ballot, i2 *Ballot) *Ballot

Select if b is true, sets z = i1, else z = i2, and returns z

func (*Ballot) Serialize

func (z *Ballot) Serialize(api frontend.API) []emulated.Element[sw_bn254.ScalarField]

Serialize returns a slice with the C1.X, C1.Y, C2.X, C2.Y in order

func (*Ballot) SerializeVars

func (z *Ballot) SerializeVars() []frontend.Variable

Serialize returns a slice with the C1.X, C1.Y, C2.X, C2.Y in order

func (*Ballot) ToEmulatedBallot

func (z *Ballot) ToEmulatedBallot(api frontend.API) EmulatedBallot[sw_bn254.ScalarField]

type BallotMode

type BallotMode[T any] struct {
	NumFields      T
	UniqueValues   T
	MaxValue       T
	MinValue       T
	MaxValueSum    T
	MinValueSum    T
	CostExponent   T
	CostFromWeight T
}

BallotMode is a struct that contains the common inputs for all the voters. The values of this struct should be the same for all the voters in the same process. Is a generic struct that can be used with any type of circuit input.

func BallotModeToCircuit

func BallotModeToCircuit(b *types.BallotMode) BallotMode[*big.Int]

BallotModeToCircuit converts a BallotMode to a circuit BallotMode which can be implemented with different base types. Before calling this function, the BallotMode must be validated.

func DeserializeBallotMode

func DeserializeBallotMode(data []byte) (BallotMode[*big.Int], error)

DeserializeBallotMode reconstructs a BallotMode from a slice of bytes. The input must be of len 8*32 bytes (otherwise it returns an error), representing 8 big.Ints as little-endian.

func (BallotMode[T]) BigIntsToEmulatedElementBN254

func (bm BallotMode[T]) BigIntsToEmulatedElementBN254() BallotMode[emulated.Element[sw_bn254.ScalarField]]

BigIntsToEmulatedElementBN254 casts BallotMode[*big.Int] into a BallotMode[emulated.Element[sw_bn254.ScalarField]]

func (BallotMode[T]) Bytes

func (bm BallotMode[T]) Bytes() []byte

Bytes returns 8*32 bytes representing BallotMode components. Returns an empty slice if T is not *big.Int.

func (BallotMode[T]) Deserialize

func (bm BallotMode[T]) Deserialize(values []T) (BallotMode[T], error)

func (BallotMode[T]) Serialize

func (bm BallotMode[T]) Serialize() []T

func (BallotMode[T]) VarsToEmulatedElementBN254

func (bm BallotMode[T]) VarsToEmulatedElementBN254(api frontend.API) BallotMode[emulated.Element[sw_bn254.ScalarField]]

VarsToEmulatedElementBN254 casts BallotMode[frontend.Variable] into a BallotMode[emulated.Element[sw_bn254.ScalarField]]

type CircuitArtifacts

type CircuitArtifacts struct {
	// contains filtered or unexported fields
}

CircuitArtifacts is a struct that holds the artifacts of a zkSNARK circuit (definition, proving and verification key). It provides a method to load the keys from the local cache or download them from the remote URLs provided.

func NewCircuitArtifacts

func NewCircuitArtifacts(curve ecc.ID, circuit, provingKey, verifyingKey *Artifact) *CircuitArtifacts

NewCircuitArtifacts creates a new CircuitArtifacts struct with the circuit artifacts provided. It returns the struct with the artifacts set.

func (*CircuitArtifacts) CircuitDefinition

func (ca *CircuitArtifacts) CircuitDefinition() (constraint.ConstraintSystem, error)

CircuitDefinition returns the content of the circuit definition as constraint.ConstraintSystem. If the circuit definition is not loaded, it returns nil.

func (*CircuitArtifacts) DownloadAll

func (ca *CircuitArtifacts) DownloadAll(ctx context.Context) error

DownloadAll method downloads the circuit artifacts with the provided context. It returns an error if any of the artifacts cannot be downloaded.

func (*CircuitArtifacts) LoadAll

func (ca *CircuitArtifacts) LoadAll() error

LoadAll method loads the circuit artifacts into memory.

func (*CircuitArtifacts) ProvingKey

func (ca *CircuitArtifacts) ProvingKey() (groth16.ProvingKey, error)

ProvingKey returns the content of the proving key as groth16.ProvingKey. If the proving key is not loaded or cannot be read, it returns an error.

func (*CircuitArtifacts) RawProvingKey

func (ca *CircuitArtifacts) RawProvingKey() types.HexBytes

RawProvingKey returns the content of the proving key as types.HexBytes. If the proving key is not loaded, it returns nil.

func (*CircuitArtifacts) RawVerifyingKey

func (ca *CircuitArtifacts) RawVerifyingKey() []byte

RawVerifyingKey returns the content of the verifying key as types.HexBytes. If the verifying key is not loaded, it returns nil.

func (*CircuitArtifacts) VerifyingKey

func (ca *CircuitArtifacts) VerifyingKey() (groth16.VerifyingKey, error)

VerifyingKey returns the content of the verifying key as groth16.VerifyingKey. If the proving key is not loaded or cannot be read, it returns an error.

type EmulatedBallot

EmulatedBallot is a copy of the Ballot struct, but using the EmulatedCiphertext type

func NewEmulatedBallot

func NewEmulatedBallot[F emulated.FieldParams]() *EmulatedBallot[F]

NewEmulatedBallot returns a new EmulatedBallot with all fields with both points to zero point (0, 1).

func (*EmulatedBallot[F]) Serialize

func (z *EmulatedBallot[F]) Serialize() []emulated.Element[F]

Serialize returns a slice with the C1.X, C1.Y, C2.X, C2.Y in order

func (*EmulatedBallot[F]) SerializeAsTE

func (zt *EmulatedBallot[F]) SerializeAsTE(api frontend.API) []emulated.Element[sw_bn254.ScalarField]

SerializeAsTE returns a slice with the C1.X, C1.Y, C2.X, C2.Y in order, in Twisted Edwards format (rather than Reduced Twisted Edwards)

type EmulatedCiphertext

type EmulatedCiphertext[F emulated.FieldParams] struct {
	C1, C2 EmulatedPoint[F]
}

EmulatedCiphertext struct is a copy of the elgamal.Ciphertext struct, but using the EmulatedPoint type

type EmulatedPoint

type EmulatedPoint[F emulated.FieldParams] struct {
	X, Y emulated.Element[F]
}

EmulatedPoint struct is a copy of the elgamal.Point struct, but using the emulated.Element type

type EmulatedVote

type EmulatedVote[F emulated.FieldParams] struct {
	Address    emulated.Element[F]
	VoteID     emulated.Element[F]
	Ballot     EmulatedBallot[F]
	VoteWeight emulated.Element[F]
}

EmulatedVote is a copy of the Vote struct, but using the emulated.Element type as generic type for the Address, VoteID fields and the EmulatedBallot type for the Ballot field.

func (*EmulatedVote[F]) Serialize

func (z *EmulatedVote[F]) Serialize() []emulated.Element[F]

Serialize returns a slice with the vote parameters in order

EmulatedVote.Address
EmulatedVote.VoteID
EmulatedVote.UserWeight
EmulatedVote.Ballot

func (*EmulatedVote[F]) SerializeForBallotProof

func (zt *EmulatedVote[F]) SerializeForBallotProof(api frontend.API) []emulated.Element[sw_bn254.ScalarField]

SerializeForBallotProof returns a slice with the vote parameters in order

	EmulatedVote.Address
	EmulatedVote.VoteID
	EmulatedVote.Ballot (in Twisted Edwards format)
 EmulatedVote.UserWeight

type EncryptionKey

type EncryptionKey[T any] struct {
	PubKey [2]T
}

func DeserializeEncryptionKey

func DeserializeEncryptionKey(data []byte) (EncryptionKey[*big.Int], error)

DeserializeEncryptionKey reconstructs a EncryptionKey from a slice of bytes. The input must be of len 2*32 bytes (otherwise it returns an error), representing 2 big.Ints as little-endian.

func EncryptionKeyFromECCPoint

func EncryptionKeyFromECCPoint(p ecc.Point) EncryptionKey[*big.Int]

func EncryptionKeyToCircuit

func EncryptionKeyToCircuit(k types.EncryptionKey) EncryptionKey[*big.Int]

func (EncryptionKey[T]) AsVar

AsVar returns the EncryptionKey as a different type. Returns an empty EncryptionKey if T is not *big.Int.

func (EncryptionKey[T]) BigIntsToEmulatedElementBN254

func (k EncryptionKey[T]) BigIntsToEmulatedElementBN254() EncryptionKey[emulated.Element[sw_bn254.ScalarField]]

BigIntsToEmulatedElementBN254 returns the EncryptionKey as a different type. Returns an empty EncryptionKey if T is not *big.Int.

func (EncryptionKey[T]) Bytes

func (k EncryptionKey[T]) Bytes() []byte

Bytes returns 2*32 bytes representing PubKey components. Returns an empty slice if T is not *big.Int.

func (EncryptionKey[T]) Deserialize

func (k EncryptionKey[T]) Deserialize(values []T) (EncryptionKey[T], error)

func (EncryptionKey[T]) Serialize

func (k EncryptionKey[T]) Serialize() []T

func (EncryptionKey[T]) SerializeAsTE

func (kt EncryptionKey[T]) SerializeAsTE(api frontend.API) []emulated.Element[sw_bn254.ScalarField]

SerializeAsTE returns the EncryptionKey in Twisted Edwards format

func (EncryptionKey[T]) VarsToEmulatedElementBN254

func (k EncryptionKey[T]) VarsToEmulatedElementBN254(api frontend.API) EncryptionKey[emulated.Element[sw_bn254.ScalarField]]

VarsToEmulatedElementBN254 returns the EncryptionKey as a different type. Returns an empty EncryptionKey if T is not frontend.Variable

type Process

type Process[T any] struct {
	ID            T
	CensusOrigin  T
	BallotMode    BallotMode[T]
	EncryptionKey EncryptionKey[T]
}

Process is a struct that contains the common inputs for a process. Is a generic struct that can be used with any type of circuit input.

func (Process[T]) Serialize

func (p Process[T]) Serialize() []T

Serialize returns a slice with the process parameters in order

Process.ID
Process.CensusOrigin
Process.BallotMode
Process.EncryptionKey

func (Process[T]) SerializeForBallotProof

func (pt Process[T]) SerializeForBallotProof(api frontend.API) []emulated.Element[sw_bn254.ScalarField]

SerializeForBallotProof returns a slice with the process parameters in order

Process.ID
Process.BallotMode
Process.EncryptionKey (in Twisted Edwards format)

func (Process[T]) VarsToEmulatedElementBN254

func (p Process[T]) VarsToEmulatedElementBN254(api frontend.API) Process[emulated.Element[sw_bn254.ScalarField]]

type Vote

type Vote[T any] struct {
	Ballot     Ballot
	VoteID     T
	Address    T
	VoteWeight T
}

Vote is a struct that contains all data related to a vote. Is a generic struct that can be used with any type of circuit input.

func (Vote[T]) SerializeAsVars

func (v Vote[T]) SerializeAsVars() []frontend.Variable

func (Vote[T]) ToEmulated

func (v Vote[T]) ToEmulated(api frontend.API) EmulatedVote[sw_bn254.ScalarField]

Directories

Path Synopsis
aggregator package contains the Gnark circuit defiinition that aggregates some votes and proves the validity of the aggregation.
aggregator package contains the Gnark circuit defiinition that aggregates some votes and proves the validity of the aggregation.
voteverifier package contains the Gnark circuit definition that verifies a vote package to be aggregated by the vote aggregator and included in a new state transition.
voteverifier package contains the Gnark circuit definition that verifies a vote package to be aggregated by the vote aggregator and included in a new state transition.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL