api

package
v0.0.0-...-03d24db Latest Latest
Warning

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

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

README

API Documentation

This document describes the HTTP API endpoints.

Endpoints

Health Check
GET /ping

Example: GET /ping Simple health check endpoint to verify the API server is running.

Response: Empty response with HTTP 200 OK status

Process Management
POST /process

Example: POST /process Creates a new voting process setup and returns it. The process is not stored.

Request Body:

{
  "censusRoot": "hexBytes",
  "ballotMode": {
    "maxCount": "number",
    "maxValue": "bigintStr",
    "minValue": "bigintStr",
    "forceUniqueness": "boolean",
    "costFromWeight": "boolean",
    "costExponent": "number",
    "maxTotalCost": "bigintStr",
    "minTotalCost": "bigintStr"
  },
  "nonce": "number",
  "chainID": "number",
  "signature": "bytes"
}

Response Body:

{
  "processID": "hexBytes",
  "encryptionPubKey": ["bigintStr", "bigintStr"],
  "stateRoot": "hexBytes"
}
GET /process?id=000005390056d6ed515b2e0af39bb068f587d0de83facd1b0000000000000003

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

Response Body:

{
  "id": "hexBytes",
  "status": "number",
  "organizationId": "address",
  "encryptionKey": {
    "x": "bigintStr",
    "y": "bigintStr"
  },
  "stateRoot": "hexBytes",
  "result": ["bigintStr"],
  "startTime": "timestamp",
  "duration": "duration",
  "metadataURI": "string",
  "ballotMode": {
    "maxCount": "number",
    "maxValue": "bigintStr",
    "minValue": "bigintStr",
    "forceUniqueness": "boolean",
    "costFromWeight": "boolean",
    "costExponent": "number",
    "maxTotalCost": "bigintStr",
    "minTotalCost": "bigintStr"
  },
  "census": {
    "censusOrigin": "number",
    "maxVotes": "bigintStr",
    "censusRoot": "hexBytes",
    "censusURI": "string"
  },
  "metadata": {
    "title": {
      "languageCode": "string"
    },
    "description": {
      "languageCode": "string"
    },
    "media": {
      "header": "string",
      "logo": "string"
    },
    "questions": [
      {
        "title": {
          "languageCode": "string"
        },
        "description": {
          "languageCode": "string"
        },
        "choices": [
          {
            "title": {
              "languageCode": "string"
            },
            "value": "number",
            "meta": {
              "key": "string"
            }
          }
        ],
        "meta": {
          "key": "string"
        }
      }
    ],
    "processType": {
      "name": "string",
      "properties": {
        "key": "string"
      }
    }
  }
}
Census Management
POST /census

Example: POST /census Creates a new census.

Response Body:

{
  "census": "uuid"
}
POST /census/participants?id=5fac16ce-3555-41a1-9ad9-a9176e8d08be

Adds participants to an existing census.

URL Parameters:

  • id: Census UUID

Request Body:

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

Response: Empty response with HTTP 200 OK status

GET /census/participants?id=5fac16ce-3555-41a1-9ad9-a9176e8d08be

Gets the list of participants in a census.

URL Parameters:

  • id: Census UUID

Response Body:

{
  "participants": [
    {
      "key": "hexBytes",
      "weight": "bigintStr"
    }
  ]
}
GET /census/root?id=5fac16ce-3555-41a1-9ad9-a9176e8d08be

Gets the Merkle root of a census.

URL Parameters:

  • id: Census UUID

Response Body:

{
  "root": "hexBytes"
}
GET /census/size?id=5fac16ce-3555-41a1-9ad9-a9176e8d08be

Gets the number of participants in a census.

URL Parameters: Accepts one of both:

  • id: Census UUID
  • root: Census merkle root (hex encoded)

Response Body:

{
  "size": "number"
}
DELETE /census?id=5fac16ce-3555-41a1-9ad9-a9176e8d08be

Deletes a census.

URL Parameters:

  • id: Census UUID

Response: Empty response with HTTP 200 OK status

GET /census/proof?root=bb7f7eef18b85b131...&key=4179e431856a710bd...

Gets a Merkle proof for a participant in a census.

URL Parameters:

  • root: Census merkle root (hex encoded)
  • key: Participant key (hex encoded)

Response Body:

{
  "root": "hexBytes",
  "key": "hexBytes",
  "value": "hexBytes",
  "siblings": "hexBytes",
  "weight": "bigintStr" // the value transformed to bigInt
}

Error Responses

All endpoints may return error responses with the following format:

{
  "error": "string"
}

Common HTTP status codes:

  • 200: Success
  • 400: Bad Request
  • 404: Not Found
  • 500: Internal Server Error

Documentation

Index

Constants

View Source
const (
	// ProcessEndpoint is the endpoint for creating a new voting process
	ProcessEndpoint = "/process"
	// PingEndpoint is the endpoint for checking the API status
	PingEndpoint = "/ping"

	// NewCensusEndpoint is the endpoint for creating a new census
	NewCensusEndpoint = "/census"
	// AddCensusParticipantsEndpoint is the endpoint for adding participants to a census
	AddCensusParticipantsEndpoint = "/census/participants"
	// GetCensusParticipantsEndpoint is the endpoint for getting the participants of a census
	GetCensusParticipantsEndpoint = "/census/participants"
	// GetCensusRootEndpoint is the endpoint for getting the root of a census
	GetCensusRootEndpoint = "/census/root"
	// GetCensusSizeEndpoint is the endpoint for getting the size of a census
	GetCensusSizeEndpoint = "/census/size"
	// DeleteCensusEndpoint is the endpoint for deleting a census
	DeleteCensusEndpoint = "/census"
	// GetCensusProofEndpoint is the endpoint for getting a proof of a census
	GetCensusProofEndpoint = "/census/proof"
)

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")}

	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")}

	ErrInvalidCensusID = Error{Code: 40020, HTTPstatus: http.StatusBadRequest, Err: fmt.Errorf("invalid census ID")}
	ErrCensusNotFound  = Error{Code: 40021, HTTPstatus: http.StatusNotFound, Err: fmt.Errorf("census not found")}
)

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

Functions

This section is empty.

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(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) 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
}

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 CensusRoot

type CensusRoot struct {
	Root types.HexBytes `json:"root"`
}

CensusRoot is the response to a census root request.

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 NewCensus

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

NewCensus is the response to a new census creation request.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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