api.go
Overview
The [api.go](/projects/291/69232) file implements the HTTP API server for accessing the Thorchain-V1 blockchain data through the unchained backend service. It exposes RESTful endpoints that provide blockchain information, transaction history, and transaction details using JSON over HTTP. This file sets up routing, middleware, server configuration, and integration with other system components such as metrics, websockets, and CORS handling.
Key features include:
HTTP router setup with Gorilla Mux
Prometheus metrics endpoint
Health checks and API documentation redirects
Swagger UI and OpenAPI spec serving
Integration with Thorchain-V1 specific client and services
Graceful server configuration with timeouts and pprof profiling
API versioning and endpoint grouping
Input validation middleware for public keys
Websocket connection manager for real-time updates
This file acts as the entry point for the Thorchain-V1 API server and wraps underlying cosmos API functionality with Thorchain-specific logic.
Package and Imports
Package
apiprovides access to Thorchain-V1 chain data.Imports include:
Standard libs:
net/http,fmt,time,strconv,path/filepathThird-party:
gorilla/mux(HTTP router), prometheus/client_golang (metrics),rs/cors(CORS middleware)Internal packages for logging, cosmos API, websocket management, Thorchain-V1 client, and metrics.
Constants
Constant | Type | Description |
|---|---|---|
`int` | HTTP server port (3000) | |
`PPROF_PORT` | `int` | Profiling server port (3001) |
`GRACEFUL_SHUTDOWN` | `time.Duration` | Duration for graceful shutdown (15s) |
`WRITE_TIMEOUT` | `time.Duration` | HTTP write timeout (15s) |
`READ_TIMEOUT` | `time.Duration` | HTTP read timeout (15s) |
`IDLE_TIMEOUT` | `time.Duration` | HTTP idle timeout (60s) |
Types
API struct
type API struct {
*cosmos.API
handler *Handler
}
Extends the generic
cosmos.APIstruct to specialize it for Thorchain-V1.Contains a reference to a
Handlerwhich implements Thorchain-specific request handling.
Functions
New
func New(
cfg cosmos.Config,
httpClient *cosmos.HTTPClient,
wsClient *cosmos.WSClient,
blockService *cosmos.BlockService,
swaggerPath string,
prometheus *metrics.Prometheus,
) *API
Description
Creates and configures a new Thorchain-V1 API server instance. Sets up HTTP routing, middleware, metrics, websocket management, profiling, and server timeouts.
Parameters
Parameter | Type | Description |
|---|---|---|
`cfg` | `cosmos.Config` | Configuration including denomination and fees |
`httpClient` | `*cosmos.HTTPClient` | HTTP client for blockchain node communication |
`wsClient` | `*cosmos.WSClient` | Websocket client for real-time blockchain data |
`blockService` | `*cosmos.BlockService` | Service to fetch block data |
`swaggerPath` | `string` | File path to OpenAPI Swagger specification |
`prometheus` | `*metrics.Prometheus` | Prometheus metrics collector |
Returns
*API- Pointer to a fully configured API server instance.
Usage Example
cfg := cosmos.Config{
Denom: "rune",
NativeFee: 0.0001,
}
httpClient := cosmos.NewHTTPClient(...)
wsClient := cosmos.NewWSClient(...)
blockService := cosmos.NewBlockService(...)
prom := metrics.NewPrometheus()
apiServer := api.New(cfg, httpClient, wsClient, blockService, "./swagger.json", prom)
Implementation Highlights
Initializes Gorilla Mux router.
Creates a Thorchain-specific
Handlerwhich embeds a generic cosmosHandler.Creates a websocket manager for client connections.
Configures HTTP server with timeouts and CORS middleware (allow all origins).
Launches pprof server concurrently on port 3001 for profiling.
Registers middleware for API scheme enforcement and logging.
Registers routes for:
/redirect to docs/healthhealth check with current connection count/metricsPrometheus metrics endpoint/swaggerserve OpenAPI spec JSON file/docs/serve Swagger UI static files/api/v1/*API version 1 endpoints with subrouters and middleware
Validates that the handler implements required interfaces (
api.BaseAPIandcosmos.CoinSpecificHandler).Sets global HTTP handler.
API Methods
These methods implement the handlers for various API endpoints, essentially forwarding calls to the embedded `cosmos.API`.
Info
func (a *API) Info(w http.ResponseWriter, r *http.Request)
Handles
GET /api/v1/infoReturns general information about the running Thorchain-V1 coinstack.
Response: HTTP 200 with JSON
Infoobject.
TxHistory
func (a *API) TxHistory(w http.ResponseWriter, r *http.Request)
Handles
GET /api/v1/account/{pubkey}/txsReturns paginated transaction history for the given public key.
Parameters: Public key validated by middleware.
Responses:
200:
TxHistoryJSON400: Bad request error
500: Internal server error
Tx
func (a *API) Tx(w http.ResponseWriter, r *http.Request)
Handles
GET /api/v1/tx/{txid}Returns detailed transaction information by transaction ID.
Responses:
200:
TxJSON400: Bad request error
500: Internal server error
Implementation Details and Algorithms
Routing: Uses Gorilla Mux for dynamic routing and subrouters, enabling versioning and middleware assignment per route group.
Middleware:
api.Schemeenforces request scheme (e.g., HTTPS).api.Loggerintegrates Prometheus metrics with request logging.cosmos.ValidatePubkeymiddleware validates the public key format and rejects invalid requests early.
Websocket Management: Manages websocket connections for clients subscribing to live blockchain data updates.
Profiling: A separate goroutine runs
pprofon port 3001 for runtime profiling and debugging.Graceful Shutdown: Constants define timeouts for clean shutdown and connection handling.
Swagger/OpenAPI: Serves API documentation and Swagger UI for easy exploration of API endpoints.
Error Handling: Standardized HTTP status codes and response formats used for client errors and server errors.
Interaction with Other System Components
cosmos.API: The base API implementation providing generic blockchain API logic is embedded. This file adds Thorchain-V1 specific handler logic on top.
thorchainV1.NewHTTPClient: Provides Thorchain-specific HTTP client for node communication.
cosmos.Handler: Base handler for common blockchain request handling.
metrics.Prometheus: Collects and exposes Prometheus metrics for monitoring.
websocket.Manager: Handles websocket client connections and message broadcasting.
Logging: Uses internal logger for structured logs.
Static assets: Serves Swagger UI files from the
./static/swaggeruidirectory.
API Endpoint Summary
HTTP Method | Path | Handler | Description |
|---|---|---|---|
GET | `/` | `api.DocsRedirect` | Redirects to API docs |
GET | `/health` | Inline handler | Health check returning status |
GET | `/metrics` | `promhttp.Handler` | Exposes Prometheus metrics |
GET | `/swagger` | Inline handler | Serves OpenAPI Swagger JSON |
GET | `/docs/` | Static FileServer | Serves Swagger UI static assets |
GET | `/api/v1/info` | `API.Info` | Returns coinstack info |
GET | `/api/v1/account/{pubkey}/txs` | `API.TxHistory` | Gets paginated tx history |
GET | `/api/v1/tx/{txid}` | `API.Tx` | Gets transaction details |
Visual Diagram
flowchart TD
subgraph API Server Initialization
A[New(cfg, httpClient, wsClient, blockService, swaggerPath, prometheus)] --> B[Create Gorilla Mux Router]
B --> C[Create Thorchain Handler]
C --> D[Create Websocket Manager]
D --> E[Create HTTP Server with CORS and Timeouts]
E --> F[Setup pprof Server (Goroutine)]
F --> G[Register Middleware (Scheme, Logger)]
G --> H[Register Routes (/health, /metrics, /swagger, /docs, /api/v1/*)]
H --> I[Return API Instance]
end
subgraph Request Handling
I --> J[Incoming HTTP Request]
J --> K{Route Match}
K -->|/api/v1/info| L[API.Info -> cosmos.API.Info]
K -->|/api/v1/account/{pubkey}/txs| M[API.TxHistory -> cosmos.API.TxHistory]
K -->|/api/v1/tx/{txid}| N[API.Tx -> cosmos.API.Tx]
K -->|Other| O[Static or Redirect Handlers]
end
Summary
The [api.go](/projects/291/69232) file is the backbone of the Thorchain-V1 unchained API server. It configures and exposes a set of RESTful endpoints backed by a cosmos-based blockchain API, enhanced with Thorchain-specific logic. Its modular design leverages middleware, websocket management, metrics, and profiling to provide a robust, observable, and maintainable API service. This file fits into the larger system as the HTTP interface layer that clients and services interact with to query blockchain data and transactions.