api

package
v0.0.0-...-d051a58 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2025 License: AGPL-3.0 Imports: 38 Imported by: 0

README

API Documentation

This document describes the HTTP API endpoints for the Vocdoni Z Sandbox API server.

Table of Contents

Base URL

All endpoints are relative to the base URL of the API server.

Response Format

All responses are returned as JSON objects. Successful responses will have a 200 OK status code unless otherwise specified. Error responses will include an error message and code.

Error Handling

API errors are returned with appropriate HTTP status codes and a JSON body with error details:

{
  "error": "error message",
  "code": 40001
}
Error Codes
Code HTTP Status Description
40001 404 Resource not found
40004 400 Malformed JSON body
40005 400 Invalid signature
40006 400 Malformed process ID
40007 404 Process not found
40008 400 Invalid census proof
40009 400 Invalid ballot proof
40010 400 Invalid census ID
40011 404 Census not found
40012 400 Key length exceeded
40013 400 Invalid ballot inputs hash
40014 403 Unauthorized
40015 400 Malformed parameter
40017 400 Malformed address
40018 400 Ballot already submitted
40019 409 Ballot is already processing
40020 400 Process is not accepting votes
40021 400 Not supported chain Id
40022 400 Worker not available
40023 400 Malformed worker info
40024 403 invalid worker authentication token
40025 403 expired worker authentication token
40026 404 worker not found
50001 500 Marshaling (server-side) JSON failed
50002 500 Internal server error

Endpoints

Health Check
GET /ping

Simple health check endpoint to verify the API server is running.

Response: Empty response with HTTP 200 OK status

Errors:

  • None
Information
GET /info

Returns information needed by the client to generate a ballot zkSNARK proof, including circuit URLs, hashes, and smart contract addresses.

Response Body:

{
  "circuitUrl": "string",
  "circuitHash": "hexString",
  "provingKeyUrl": "string",
  "provingKeyHash": "hexString",
  "verificationKeyUrl": "string",
  "verificationKeyHash": "hexString",
  "ballotProofWasmHelperUrl": "string",
  "ballotProofWasmHelperHash": "hexString",
  "ballotProofWasmHelperExecJsUrl": "string",
  "ballotProofWasmHelperExecJsHash": "hexString",
  "contracts": {
    "process": "address",
    "organization": "address",
    "stateTransitionVerifier": "address",
    "resultsVerifier": "address",
  },
  "network": { 
    "sepolia": 11155111
  },
  "sequencerAddress": "hexString"
}

Errors:

  • 50001: Marshaling server JSON failed
  • 50002: Internal server error (invalid network configuration)
Process Management
POST /processes

Creates a new voting process setup and returns it.

The signature is the byte representation of the string I am creating a new voting process for the davinci.vote protocol identified with id {processId}, where processId is the hexadecimal string (without 0x prefix) of the process identifier fetch on the smart contract.

The censusOrigin specifies the origin type of the census used in the request. This attribute allows the API to determine how the census data should be processed or verified. It can be:

  • 1 –> CensusOriginMerkleTree: Indicates that the census is derived from a Merkle Tree structure. This is typically used when the census data is represented as cryptographic proofs for membership verification.
  • 2 -> CensusOriginCSP: Indicates that the census is provided by a Credential Service Providers (CSP). This origin is commonly used when the census data is managed by an external trusted provider.

Request Body:

{
  "processId": "hexBytes",
  "censusOrigin": "number",
  "censusRoot": "hexBytes",
  "ballotMode": {
    "numFields": "number",
    "maxValue": "bigintStr",
    "minValue": "bigintStr",
    "uniqueValues": "boolean",
    "costFromWeight": "boolean",
    "costExponent": "number",
    "maxValueSum": "bigintStr",
    "minValueSum": "bigintStr"
  },
  "signature": "hexBytes"
}

Response Body:

{
  "processId": "hexBytes",
  "encryptionPubKey": ["bigintStr", "bigintStr"],
  "stateRoot": "hexBytes",
  "ballotMode": {
    "numFields": "number",
    "maxValue": "bigintStr",
    "minValue": "bigintStr",
    "uniqueValues": "boolean",
    "costFromWeight": "boolean",
    "costExponent": "number",
    "maxValueSum": "bigintStr",
    "minValueSum": "bigintStr"
  }
}

Errors:

  • 40004: Malformed JSON body
  • 40005: Invalid signature
  • 50002: Internal server error
Metadata Management
POST /metadata

Sets metadata for a voting process.

Request Body:

{
  "title": {
    "languageCode": "string" // Language code as key, text as value. Example: {"en": "Election", "es": "Elección"}
  },
  "description": {
    "languageCode": "string" // Language code as key, text as value
  },
  "media": {
    "header": "string", // URL to header image
    "logo": "string"    // URL to logo image
  },
  "questions": [
    {
      "title": {
        "languageCode": "string" // Language code as key, text as value
      },
      "description": {
        "languageCode": "string" // Language code as key, text as value
      },
      "choices": [
        {
          "title": {
            "languageCode": "string" // Language code as key, text as value
          },
          "value": "number",
          "meta": {
            "key": "string" // Free-form key-value pairs, can contain any valid JSON
          }
        }
      ],
      "meta": {
        "key": "string" // Free-form key-value pairs, can contain any valid JSON
      }
    }
  ],
  "type": {
    "name": "string",
    "properties": {
      "key": "string" // Free-form key-value pairs, can contain any valid JSON
    }
  },
  "version": "string",
  "meta": {
    "key": "string" // Free-form key-value pairs, can contain any valid JSON
  }
}

Response Body:

{
  "hash": "hexBytes"
}

Errors:

  • 40004: Malformed JSON body
  • 50001: Marshaling server JSON failed
  • 50002: Internal server error
GET /metadata/{metadataHash}

Retrieves metadata by its hash.

URL Parameters:

  • metadataHash: Metadata hash in hexadecimal format

Response Body: Returns the complete metadata object as per the POST request format.

Errors:

  • 40001: Resource not found
  • 40004: Malformed parameter
  • 50002: Internal server error
GET /processes

Lists all available voting process IDs.

Response Body:

{
  "processes": [
    "hexBytes",
    "hexBytes",
    "hexBytes"
  ]
}

Errors:

  • 50002: Internal server error
GET /processes/{processId}

Gets information about an existing voting process. It must exist in the smart contract.

URL Parameters:

  • processId: Process ID in hexadecimal format

Response Body:

{
  "id": "hexBytes",
  "status": "number",
  "organizationId": "address",
  "encryptionKey": {
    "x": "bigintStr",
    "y": "bigintStr"
  },
  "stateRoot": "hexBytes",
  "result": ["bigintStr"],
  "startTime": "timestamp",
  "duration": "duration",
  "metadataURI": "string", // URI/URL to fetch the process metadata
  "ballotMode": {
    "numFields": "number",
    "maxValue": "bigintStr",
    "minValue": "bigintStr",
    "uniqueValues": "boolean",
    "costFromWeight": "boolean",
    "costExponent": "number",
    "maxValueSum": "bigintStr",
    "minValueSum": "bigintStr"
  },
  "census": {
    "censusOrigin": "number",
    "maxVotes": "bigintStr",
    "censusRoot": "hexBytes",
    "censusURI": "string"
  },
  "voteCount": "bigintStr", // Total number of votes cast in the process
  "voteOverwrittenCount": "bigintStr", // Number of times voters changed their vote
  "isAcceptingVotes": "boolean", // Whether the Sequencer is currently accepting votes for this process
  "sequencerStats": { // Stats about the Sequencer runing the API (not the whole network)
    "stateTransitionCount": "number", // Total number of state transitions performed
    "lastStateTransitionDate": "date", // Date of the most recent state transition
    "settledStateTransitionCount": "number", // Number of state transitions settled to the Ethereum blockchain
    "aggregatedVotesCount": "number", // Total number of votes that have been aggregated into batches
    "verifiedVotesCount": "number", // Total number of votes that have been cryptographically verified
    "pendingVotesCount": "number", // Number of votes waiting to be processed
    "currentBatchSize": "number", // Number of votes in the current batch being prepared
    "lastBatchSize": "number" // Number of votes in the last completed batch
  }
}

Errors:

  • 40006: Malformed process ID
  • 40007: Process not found
  • 50002: Internal server error
Census Management
POST /censuses

Creates a new census.

Response Body:

{
  "census": "uuid"
}

Errors:

  • 50002: Internal server error
POST /censuses/{censusId}/participants

Adds participants to an existing census.

URL Parameters:

  • censusId: Census UUID

Request Body:

{
  "participants": [
    {
      "key": "hexBytes", // if more than 20 bytes, it is hashed and truncated
      "weight": "bigintStr" // optional, defaults to 1
    }
  ]
}

Response: Empty response with HTTP 200 OK status

Errors:

  • 40004: Malformed JSON body
  • 40010: Invalid census ID
  • 40011: Census not found
  • 50002: Internal server error
GET /censuses/{censusId}/participants

Gets the list of participants in a census.

URL Parameters:

  • censusId: Census UUID

Response Body:

{
  "participants": [
    {
      "key": "hexBytes",
      "weight": "bigintStr"
    }
  ]
}

Errors:

  • 40004: Malformed JSON body
  • 40010: Invalid census ID
  • 50002: Internal server error
GET /censuses/{censusId}/root

Gets the Merkle root of a census.

URL Parameters:

  • censusId: Census UUID

Response Body:

{
  "root": "hexBytes"
}

Errors:

  • 40010: Invalid census ID
  • 50002: Internal server error
GET /censuses/{censusId}/size

Gets the number of participants in a census.

URL Parameters:

  • censusId: Census UUID or census merkle root (hex encoded)

Response Body:

{
  "size": "number"
}

Errors:

  • 40010: Invalid census ID
  • 50002: Internal server error
DELETE /censuses/{censusId}

Deletes a census.

URL Parameters:

  • censusId: Census UUID

Response: Empty response with HTTP 200 OK status

Errors:

  • 40010: Invalid census ID
  • 50002: Internal server error
GET /censuses/{censusRoot}/proof

Gets a Merkle proof for a participant in a census.

URL Parameters:

  • censusRoot: Census merkle root (hex encoded)

Query Parameters:

  • key: Participant key (hex encoded)

Response Body:

{
  "root": "hexBytes",
  "address": "hexBytes",
  "weight": "bigintStr",
  "censusOrigin": 1,        // 1 for merkle proofs, 2 for csp proofs
  "value": "hexBytes",      // merkle proof: the weight encoded to hexBytes
  "siblings": "hexBytes",   // merkle proof: encoded siblings path to find the leaf
  "processId": "hexBytes",  // csp proof: the process id signed with the address
  "publicKey": "hexBytes",  // csp proof: the public key of the csp
  "signature": "hexBytes",  // csp proof: the signature that proofs that the voter is in the census
}

Errors:

  • 40001: Resource not found
  • 40004: Malformed body (invalid key)
  • 40010: Invalid census ID
  • 50002: Internal server error
Vote Management
POST /votes

Register a new vote for a voting process.

Request Body:

{
  "processId": "hexBytes",
  "censusProof": {
    "root": "hexBytes",
    "address": "hexBytes",
    "weight": "bigintStr",
    "censusOrigin": 1,        // 1 for merkle proofs, 2 for csp proofs
    "value": "hexBytes",      // merkle proof: the weight encoded to hexBytes
    "siblings": "hexBytes",   // merkle proof: encoded siblings path to find the leaf
    "processId": "hexBytes",  // csp proof: the process id signed with the address
    "publicKey": "hexBytes",  // csp proof: the public key of the csp
    "signature": "hexBytes",  // csp proof: the signature that proofs that the voter is in the census
  },
  "ballot": {
    "curveType": "string",
    "ciphertexts": [
      {
        "c1": ["bigintStrX","bigintStrY"],
        "c2": ["bigintStrX","bigintStrY"]
      },
      {
        "c1": ["bigintStrX","bigintStrY"],
        "c2": ["bigintStrX","bigintStrY"]
      }
    ...
    ]
  },
  "ballotProof": {
    "pi_a": ["string"],
    "pi_b": [["string"]],
    "pi_c": ["string"],
    "protocol": "string"
  },
  "ballotInputsHash": "bigintStr",
  "publicKey": "hexBytes",
  "signature": "hexBytes",
  "voteId": "hexBytes",
}

Errors:

  • 40001: Resource not found (process not found)
  • 40004: Malformed JSON body
  • 40005: Invalid signature
  • 40008: Invalid census proof
  • 40009: Invalid ballot proof
  • 40013: Invalid ballot inputs hash
  • 40018: Ballot already submitted
  • 40019: Ballot is already processing
  • 40020: Process is not accepting votes
  • 50002: Internal server error
GET /votes/{processId}/address/{address}

Gets a vote by its address for a specific process.

URL Parameters:

  • processId: Process ID in hexadecimal format
  • address: address value as a hexdecimal string

Response Body: Returns the encrypted ballot if found.

Errors:

  • 40001: Resource not found
  • 40006: Malformed process ID
  • 40017: Malformed address
  • 40007: Process not found
  • 50002: Internal server error
Vote Status
GET /votes/{processId}/voteId/{voteId}

Gets the status of a specific vote within a voting process.

URL Parameters:

  • processId: Process ID in hexadecimal format
  • voteId: Vote ID in hexadecimal format

Response Body:

{
  "status": "string"
}

The status can be one of the following values:

  • "pending": The vote has been submitted but not yet verified
  • "verified": The vote has been verified
  • "aggregated": The vote has been included in an aggregated batch
  • "processed": The vote has been included in a state transition batch
  • "settled": The vote has been settled on the Ethereum blockchain
  • "error": An error occurred during processing

Errors:

  • 40001: Resource not found (vote not found)
  • 40006: Malformed process ID
  • 40004: Malformed vote ID
  • 50002: Internal server error
Sequencer Statistics
GET /sequencer/stats

Gets overall statistics for the sequencer service, including aggregated metrics across all active processes.

Response Body:

{
  "activeProcesses": "number",
  "pendingVotes": "number",
  "verifiedVotes": "number",
  "aggregatedVotes": "number",
  "stateTransitions": "number",
  "settledStateTransitions": "number",
  "lastStateTransitionDate": "date"
}

Errors:

  • 50001: Marshaling server JSON failed
  • 50002: Internal server error
GET /sequencer/workers

Gets a list of all worker nodes with their statistics.

Response Body:

{
  "workers": [
    {
      "name": "worker-name-1",
      "successCount": 150,
      "failedCount": 5
    },
    {
      "name": "**************************************7C",
      "successCount": 200,
      "failedCount": 2
    }
  ]
}

Errors:

  • 50002: Internal server error

Documentation

Index

Constants

View Source
const (
	// Health endpoints
	PingEndpoint = "/ping" // Health check endpoint

	// Process endpoints
	ProcessesEndpoint = "/processes"                           // GET: List processes, POST: Create process
	ProcessURLParam   = "processId"                            // URL parameter for process ID
	ProcessEndpoint   = "/processes/{" + ProcessURLParam + "}" // GET: Get process info

	// Vote endpoints
	VotesEndpoint = "/votes" // POST: Submit a vote

	// Vote status endpoints
	VoteStatusVoteIDParam = "voteId"                                                                            // URL parameter for vote ID
	VoteStatusEndpoint    = VotesEndpoint + "/{" + ProcessURLParam + "}/voteId/{" + VoteStatusVoteIDParam + "}" // GET: Check vote status

	// Vote address endpoint
	VoteByAddressAddressParam = "address"                                                                                // URL parameter for address
	VoteByAddressEndpoint     = VotesEndpoint + "/{" + ProcessURLParam + "}/address/{" + VoteByAddressAddressParam + "}" // GET: Get vote by address

	// Info endpoint
	InfoEndpoint = "/info" // GET: Get ballot proof information

	// Host load endpoint
	HostLoadEndpoint = "/info/load" // GET: Get host load metrics

	// Static file serving endpoint
	StaticFilesEndpoint = "/app*" // GET: Serve static files from the /webapp directory

	// Census endpoints
	CensusURLParam                = "censusId"                                        // URL parameter for census ID
	NewCensusEndpoint             = "/censuses"                                       // POST: Create a new census
	AddCensusParticipantsEndpoint = "/censuses/{" + CensusURLParam + "}/participants" // POST: Add participants to census
	GetCensusParticipantsEndpoint = "/censuses/{" + CensusURLParam + "}/participants" // GET: Get census participants
	GetCensusRootEndpoint         = "/censuses/{" + CensusURLParam + "}/root"         // GET: Get census root
	GetCensusSizeEndpoint         = "/censuses/{" + CensusURLParam + "}/size"         // GET: Get census size
	DeleteCensusEndpoint          = "/censuses/{" + CensusURLParam + "}"              // DELETE: Delete census
	GetCensusProofEndpoint        = "/censuses/{" + CensusURLParam + "}/proof"        // GET: Get census proof

	// Worker URL params and endpoints
	SequencerUUIDParam      = "uuid"    // Param for worker UUID
	WorkerAddressQueryParam = "address" // URL query param for worker address
	WorkerNameQueryParam    = "name"    // URL query param for worker name
	WorkerTokenQueryParam   = "token"   // URL query param for worker token

	WorkersEndpoint         = "/workers/{" + SequencerUUIDParam + "}" // Base workers endpoint
	WorkerTokenDataEndpoint = WorkersEndpoint + "/authData"           // GET: Message to be signed by workers
	WorkerJobEndpoint       = WorkersEndpoint + "/job"                // GET: New job for worker POST: Submit job from worker

	// Sequencer endpoints
	SequencerWorkersEndpoint = "/sequencer/workers" // GET: List worker statistics

	// Metadata endpoints
	MetadataHashParam   = "metadataHash"                                       // URL parameter for metadata hash
	MetadataSetEndpoint = "/metadata"                                          // POST: Set metadata
	MetadataGetEndpoint = MetadataSetEndpoint + "/{" + MetadataHashParam + "}" // GET: Get metadata
)

Variables

View Source
var (
	ErrResourceNotFound         = Error{Code: 40001, HTTPstatus: http.StatusNotFound, Err: fmt.Errorf("resource not found")}
	ErrMalformedBody            = Error{Code: 40004, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("malformed JSON body")}
	ErrInvalidSignature         = Error{Code: 40005, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("invalid signature")}
	ErrMalformedProcessID       = Error{Code: 40006, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("malformed process ID")}
	ErrProcessNotFound          = Error{Code: 40007, HTTPstatus: http.StatusNotFound, Err: fmt.Errorf("process not found")}
	ErrInvalidCensusProof       = Error{Code: 40008, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("invalid census proof")}
	ErrInvalidBallotProof       = Error{Code: 40009, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("invalid ballot proof")}
	ErrInvalidCensusID          = Error{Code: 40010, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("invalid census ID")}
	ErrCensusNotFound           = Error{Code: 40011, HTTPstatus: http.StatusNotFound, Err: fmt.Errorf("census not found")}
	ErrKeyLengthExceeded        = Error{Code: 40012, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("key length exceeded")}
	ErrInvalidBallotInputsHash  = Error{Code: 40013, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("invalid ballot inputs hash")}
	ErrUnauthorized             = Error{Code: 40014, HTTPstatus: http.StatusForbidden, Err: fmt.Errorf("unauthorized")}
	ErrMalformedParam           = Error{Code: 40015, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("malformed parameter")}
	ErrMalformedNullifier       = Error{Code: 40016, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("malformed nullifier")}
	ErrMalformedAddress         = Error{Code: 40017, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("malformed address")}
	ErrBallotAlreadySubmitted   = Error{Code: 40018, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("ballot already submitted")}
	ErrBallotAlreadyProcessing  = Error{Code: 40019, HTTPstatus: http.StatusConflict, Err: fmt.Errorf("ballot is already processing")}
	ErrProcessNotAcceptingVotes = Error{Code: 40020, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("process is not accepting votes")}
	ErrInvalidContractVersion   = Error{Code: 40021, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("not supported contract version")}
	// Worker errors
	ErrWorkerNotAvailable     = Error{Code: 40022, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("worker not available")}
	ErrMalformedWorkerInfo    = Error{Code: 40023, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("malformed worker info")}
	ErrInvalidWorkerAuthtoken = Error{Code: 40024, HTTPstatus: http.StatusForbidden, Err: fmt.Errorf("invalid worker authentication token")}
	ErrExpiredWorkerAuthtoken = Error{Code: 40025, HTTPstatus: http.StatusForbidden, Err: fmt.Errorf("expired worker authentication token")}
	ErrWorkerNotFound         = Error{Code: 40026, HTTPstatus: http.StatusNotFound, Err: fmt.Errorf("worker not found")}

	ErrMarshalingServerJSONFailed = Error{Code: 50001, HTTPstatus: http.StatusInternalServerError, Err: fmt.Errorf("marshaling (server-side) JSON failed")}
	ErrGenericInternalServerError = Error{Code: 50002, HTTPstatus: http.StatusInternalServerError, Err: fmt.Errorf("internal server error")}
)

The custom Error type satisfies the error interface. Error() returns a human-readable description of the error.

Error codes in the 40001-49999 range are the user's fault, and they return HTTP Status 400 or 404 (or even 204), whatever is most appropriate.

Error codes 50001-59999 are the server's fault and they return HTTP Status 500 or 503, or something else if appropriate.

The initial list of errors were more or less grouped by topic, but the list grows with time in a random fashion. NEVER change any of the current error codes, only append new errors after the current last 4XXX or 5XXX If you notice there's a gap (say, error code 4010, 4011 and 4013 exist, 4012 is missing) DON'T fill in the gap, that code was used in the past for some error (not anymore) and shouldn't be reused. There's no correlation between Code and HTTP Status, for example the fact that Code 4045 returns HTTP Status 404 Not Found is just a coincidence

Do note that HTTPstatus 204 No Content implies the response body will be empty, so the Code and Message will actually be discarded, never sent to the client

View Source
var DisabledLogging = false

DisabledLogging is a global flag to disable logging middleware

View Source
var LogExcludedPrefixes = []string{
	PingEndpoint,
	WorkersEndpoint,
	InfoEndpoint,
}

LogExcludedPrefixes defines URL prefixes to exclude from request logging

Functions

func EndpointWithParam

func EndpointWithParam(path, key, param string) string

EndpointWithParam creates an endpoint URL by replacing the parameter placeholder with the actual value. Used to build fully qualified endpoint URLs.

Types

type API

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

API type represents the API HTTP server with JWT authentication capabilities.

func New

func New(ctx context.Context, conf *APIConfig) (*API, error)

New creates a new API instance with the given configuration. It also initializes the storage and starts the HTTP server.

func (*API) ProcessIDVersion

func (a *API) ProcessIDVersion() ([]byte, error)

ProcessIDVersion returns the expected ProcessID version for the current network and contract address. It can be used to validate ProcessIDs.

func (*API) Router

func (a *API) Router() *chi.Mux

Router returns the chi router for testing purposes

type APIConfig

type APIConfig struct {
	Host       string
	Port       int
	Storage    *stg.Storage // Optional: use existing storage instance
	Network    string       // Optional: web3 network shortname
	Web3Config config.DavinciWeb3Config
	// Worker configuration
	SequencerWorkersSeed       string                  // Seed for workers authentication over current sequencer
	WorkersAuthtokenExpiration time.Duration           // Expiration time for worker authentication tokens
	WorkerJobTimeout           time.Duration           // Worker job timeout
	WorkerBanRules             *workers.WorkerBanRules // Custom ban rules for workers
}

APIConfig type represents the configuration for the API HTTP server. It includes the host, port and optionally an existing storage instance.

type CensusParticipant

type CensusParticipant struct {
	Key    types.HexBytes `json:"key"`
	Weight *types.BigInt  `json:"weight,omitempty"`
}

CensusParticipant is a participant in a census.

type CensusParticipants

type CensusParticipants struct {
	Participants []*CensusParticipant `json:"participants"`
}

CensusParticipants is a list of participants in a census.

type ContractAddresses

type ContractAddresses struct {
	ProcessRegistry           string `json:"process"`
	OrganizationRegistry      string `json:"organization"`
	StateTransitionZKVerifier string `json:"stateTransitionVerifier"`
	ResultsZKVerifier         string `json:"resultsVerifier"`
}

ContractAddresses holds the smart contract addresses needed by the client

type Error

type Error struct {
	Err        error
	Code       int
	HTTPstatus int
}

Error is used by handler functions to wrap errors, assigning a unique error code and also specifying which HTTP Status should be used.

func (Error) Error

func (e Error) Error() string

Error returns the Message contained inside the APIerror

func (Error) MarshalJSON

func (e Error) MarshalJSON() ([]byte, error)

MarshalJSON returns a JSON containing Err.Error() and Code. Field HTTPstatus is ignored.

Example output: {"error":"account not found","code":4003}

func (Error) With

func (e Error) With(s string) Error

With returns a copy of APIerror with the string appended at the end of e.Err

func (Error) WithErr

func (e Error) WithErr(err error) Error

WithErr returns a copy of APIerror with err.Error() appended at the end of e.Err

func (Error) Withf

func (e Error) Withf(format string, args ...any) Error

Withf returns a copy of APIerror with the Sprintf formatted string appended at the end of e.Err

func (Error) Write

func (e Error) Write(w http.ResponseWriter)

Write serializes a JSON msg using APIerror.Message and APIerror.Code and passes that to ctx.Send()

type HostLoadResponse

type HostLoadResponse struct {
	MemStats            any                `json:"memStats,omitempty"`
	HostLoad1           float64            `json:"hostLoad1,omitempty"`
	HostMemUsedPercent  float64            `json:"hostMemUsedPercent,omitempty"`
	HostDiskUsedPercent map[string]float64 `json:"hostDiskUsedPercent,omitempty"`
}

HostLoadResponse is the exact shape we return to the client.

type LoggingConfig

type LoggingConfig struct {
	MaxBodyLog       int
	ExcludedPrefixes []string // URL path prefixes to exclude from logging
}

LoggingConfig holds configuration for the logging middleware

func DefaultLoggingConfig

func DefaultLoggingConfig() LoggingConfig

DefaultLoggingConfig returns a LoggingConfig with sensible defaults

type NewCensus

type NewCensus struct {
	Census uuid.UUID `json:"census"`
}

NewCensus is the response to a new census creation request.

type ProcessList

type ProcessList struct {
	Processes []types.HexBytes `json:"processes"`
}

ProcessList is the response returned by the process list endpoint.

type ProcessResponse

type ProcessResponse struct {
	types.Process
	IsAcceptingVotes bool `json:"isAcceptingVotes"`
}

type SequencerInfo

type SequencerInfo struct {
	CircuitURL           string            `json:"circuitUrl"`
	CircuitHash          string            `json:"circuitHash"`
	WASMhelperURL        string            `json:"ballotProofWasmHelperUrl"`
	WASMhelperHash       string            `json:"ballotProofWasmHelperHash"`
	WASMhelperExecJsURL  string            `json:"ballotProofWasmHelperExecJsUrl"`
	WASMhelperExecJsHash string            `json:"ballotProofWasmHelperExecJsHash"`
	ProvingKeyURL        string            `json:"provingKeyUrl"`
	ProvingKeyHash       string            `json:"provingKeyHash"`
	VerificationKeyURL   string            `json:"verificationKeyUrl"`
	VerificationKeyHash  string            `json:"verificationKeyHash"`
	Contracts            ContractAddresses `json:"contracts"`
	Network              map[string]uint32 `json:"network,omitempty"`
	SequencerAddress     types.HexBytes    `json:"sequencerAddress"`
}

SequencerInfo contains any relevant information about the current sequencer for a client.

type SequencerStatsResponse

type SequencerStatsResponse struct {
	storage.Stats
	ActiveProcesses int `json:"activeProcesses"`
	PendingVotes    int `json:"pendingVotes"`
}

SequencerStatsResponse is the response returned by the sequencer stats endpoint.

type SetMetadataResponse

type SetMetadataResponse struct {
	Hash types.HexBytes `json:"hash"`
}

SetMetadataResponse is the response returned by the set metadata endpoint.

type Vote

type Vote struct {
	ProcessID        types.HexBytes           `json:"processId"`
	CensusProof      types.CensusProof        `json:"censusProof"`
	Ballot           *elgamal.Ballot          `json:"ballot"`
	BallotProof      *circomgnark.CircomProof `json:"ballotProof"`
	BallotInputsHash *types.BigInt            `json:"ballotInputsHash"`
	Address          types.HexBytes           `json:"address"`
	Signature        types.HexBytes           `json:"signature"`
	VoteID           types.HexBytes           `json:"voteId"`
}

Vote is the struct to represent a vote in the system. It will be provided by the user to cast a vote in a process.

type VoteResponse

type VoteResponse struct {
	VoteID types.HexBytes `json:"voteId"`
}

VoteResponse is the response returned by the vote submission endpoint.

type VoteStatusResponse

type VoteStatusResponse struct {
	Status string `json:"status"`
}

VoteStatusResponse is the response returned by the vote status endpoint.

type WorkerAuthDataResponse

type WorkerAuthDataResponse struct {
	Message         string         `json:"message"`
	Signature       types.HexBytes `json:"signature"`
	CreatedAt       string         `json:"createdAt"`
	AuthTokenSuffix types.HexBytes `json:"authTokenSuffix"`
}

WorkerAuthDataResponse is the response returned by the worker sign message endpoint.

type WorkerInfo

type WorkerInfo struct {
	Name         string `json:"name"`
	SuccessCount int64  `json:"successCount"`
	FailedCount  int64  `json:"failedCount"`
}

WorkerInfo contains information about a worker node.

type WorkerJobResponse

type WorkerJobResponse struct {
	VoteID       types.HexBytes `json:"voteId"`
	Address      string         `json:"address"`
	SuccessCount int64          `json:"successCount"`
	FailedCount  int64          `json:"failedCount"`
}

WorkerJobResponse is the response returned by the worker job submission endpoint.

type WorkersListResponse

type WorkersListResponse struct {
	Workers []WorkerInfo `json:"workers"`
}

WorkersListResponse is the response returned by the workers list endpoint.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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