main.go
Overview
`main.go` serves as the entry point for the Thorchain API service within the Unchained project. It initializes and configures the necessary components that allow interaction with the Thorchain blockchain network, including HTTP clients, WebSocket clients, block services, and the affiliate fee indexer. The file sets up custom transaction encoding options specific to Thorchain, loads configuration either from environment variables or a specified file, and starts the API server which provides RESTful endpoints documented by a Swagger specification.
This file handles:
Environment and configuration loading.
Custom transaction encoding and decoding tailored for Thorchain.
Creation of clients to interact with Thorchain's LCD (Light Client Daemon), RPC, and WebSocket endpoints.
Initialization of a block service and an affiliate fee indexer.
Setup of Prometheus metrics for monitoring.
Graceful shutdown on receiving system signals.
Launching the HTTP API server to serve requests.
Detailed Explanation
Package and Imports
Uses packages from Cosmos SDK for transaction encoding (
tx), configuration, and Cosmos-related utilities.Imports Thorchain-specific types and Ebifrost Tx decoder from the ThorNode repository to handle Thorchain-specific transaction formats.
Uses internal packages from
unchainedfor configuration loading, logging, metrics, and the Thorchain API implementation.
Global Variables
Variable | Type | Description |
|---|---|---|
Logger instance without additional fields for general logging. | ||
`envPath` | Command line flag for specifying path to environment config file. Defaults to empty string (use OS env). | |
`swaggerPath` | Command line flag for specifying Swagger spec JSON path for API documentation. |
Config Struct
type Config struct {
LCDURL string `mapstructure:"LCD_URL"` // URL for LCD (Light Client Daemon) API v2
LCDV1URL string `mapstructure:"LCD_V1_URL"` // URL for LCD API v1
RPCURL string `mapstructure:"RPC_URL"` // URL for RPC endpoint v2
RPCV1URL string `mapstructure:"RPC_V1_URL"` // URL for RPC endpoint v1
WSURL string `mapstructure:"WS_URL"` // URL for WebSocket endpoint
}
Holds URLs for various Thorchain node endpoints.
Populated from environment variables or config file.
Main Function
func main()
The `main` function orchestrates the entire setup and execution of the Thorchain API service.
Steps:
Parse command line flags (
envPath,swaggerPath).Setup channels:
errChanfor receiving asynchronous errors.sigChanto listen for termination signals (SIGHUP, SIGINT, SIGTERM, SIGQUIT).
Load configuration:
If no
envPathis provided, load from OS environment variables.Otherwise, load from the specified
.envor config file.Panic and exit on failure.
Create a Cosmos encoding configuration:
Uses Thorchain-specific types for interface registration.
Customizes transaction decoding to support Thorchain's injected transactions via Ebifrost Tx decoder.
Create custom TxConfig:
Uses Cosmos SDK’s
txpackage to create a new TxConfig with custom options.Enables default sign modes and uses
ebifrost.TxDecoderfor transaction decoding.
Setup two Cosmos client configurations:
cfgfor v2 endpoints (LCD, RPC, WS).cfgV1for v1 endpoints (LCD, RPC).Both configured with Thorchain-specific Bech32 address prefixes, native denomination ("rune"), and fee parameters.
Initialize Prometheus metrics collector named
"thorchain".Create HTTP clients:
One for v2 (
httpClient).One for v1 (
httpClientV1).Panic on failure.
Create a BlockService using the v2 HTTP client to track blockchain blocks.
Create a WebSocket client to subscribe and listen to real-time blockchain events.
Create an AffiliateFeeIndexer using HTTP clients and WS client:
Responsible for indexing affiliate fee data from Thorchain.
Starts synchronization and panics on error.
Initialize the Thorchain API server with configuration, clients, services, indexer, Swagger spec path, and metrics collector.
Start the API server in a separate goroutine.
Wait for errors or termination signals:
On error, log and panic.
On termination signal, gracefully shutdown the API server and exit.
Key Components and Usage
cosmos.NewEncoding
Creates a codec for encoding/decoding blockchain types.
Registers Thorchain-specific interfaces.
ebifrost.TxDecoder
Custom transaction decoder to handle Thorchain's injected transactions.
Wraps standard Cosmos Tx decoding.
tx.NewTxConfigWithOptions
Creates a TxConfig with custom sign modes and decoder.
cosmos.Config
Configuration struct describing blockchain connection details:
Address prefix formats.
Denomination and fees.
Endpoint URLs.
cosmos.NewHTTPClient
Creates an HTTP client to interact with Thorchain LCD and RPC APIs.
cosmos.NewBlockService
Service to fetch and track blockchain blocks.
cosmos.NewWebsocketClient
Connects to Thorchain WebSocket endpoint to listen for live events.
api.NewAffiliateFeeIndexer
Indexes affiliate fee data from blockchain via HTTP and WS clients.
api.New
Creates the API server providing REST endpoints.
Usage Example
To run the Thorchain API service with default environment variables:
go run main.go
To specify a custom environment file and Swagger spec path:
go run main.go -env=/path/to/config.env -swagger=custom/swagger.json
Implementation Details and Algorithms
Custom Transaction Encoding:
Thorchain requires special transaction decoding due to its injected transactions. This is handled byebifrost.TxDecoderwhich wraps the Cosmos SDK default decoder to process Ebifrost-specific transaction formats.Signal Handling and Graceful Shutdown:
The application listens for Unix termination signals to gracefully shutdown the API server, ensuring all resources and connections are properly closed.Dual Client Setup (v1 and v2):
To maintain backward compatibility and support different versions of Thorchain endpoints, two HTTP clients and corresponding configurations are used simultaneously. The affiliate fee indexer uses both to ensure comprehensive data coverage.Metrics Integration:
Prometheus metrics are integrated into the API server for monitoring request counts, latencies, and other operational metrics.
Interaction with Other Parts of the System
Internal Packages:
config: Loads configuration from environment variables or files.log: Provides logging facilities.metrics: Integrates Prometheus metrics.api: Implements the Thorchain API server and affiliate fee indexer.
External Dependencies:
cosmos-sdk: For blockchain encoding, transactions, and client interfaces.thornode: Thorchain-specific blockchain types and transaction decoding.unchained/coinstacks/thorchain/api: The API layer exposing Thorchain blockchain data.
Services and Clients:
Uses HTTP and WebSocket clients to communicate with Thorchain nodes.
The API server serves RESTful HTTP endpoints, documented via Swagger.
Diagram: Flowchart of Main Function and Component Relationships
flowchart TD
A[Start: main()] --> B[Parse Flags]
B --> C[Load Config\n(env or file)]
C --> D[Create Cosmos Encoding]
D --> E[Create Custom TxConfig with Ebifrost Decoder]
E --> F[Setup Cosmos Configs (v1 & v2)]
F --> G[Initialize Prometheus Metrics]
G --> H[Create HTTP Clients (v1 & v2)]
H --> I[Create BlockService]
I --> J[Create WebSocket Client]
J --> K[Initialize AffiliateFeeIndexer]
K --> L[Start AffiliateFeeIndexer Sync]
L --> M[Create API Server]
M --> N[Start API Server (goroutine)]
N --> O[Wait for ErrChan or SigChan]
O --> |Error Received| P[Log & Panic]
O --> |Signal Received| Q[Shutdown API & Exit]
subgraph Clients and Services
H
I
J
K
end
subgraph Config & Encoding
C
D
E
F
G
end
Summary
`main.go` is the bootstrapper for the Thorchain API service, responsible for:
Configuring blockchain clients and encoding specific to Thorchain.
Handling configuration loading and command-line arguments.
Setting up monitoring, indexing services, and HTTP/WebSocket clients.
Launching the API server with graceful shutdown on termination signals.
This file is critical for initializing the runtime environment and connecting all components to interact seamlessly with the Thorchain blockchain network.