api.go
Overview
The [api.go](/projects/291/69232) file defines a foundational API layer for the software project’s blockchain-related modules, referred to as *coinstacks*. It provides standardized data types, interfaces, and error models for representing blockchain network information, account details, transactions, and pagination in API responses. Additionally, it declares common request parameter structures and a base interface (`BaseAPI`) that all coinstack implementations must follow.
This file serves as a shared contract and utility set enabling consistent API behavior and data exchange formats across different blockchain implementations within the system. It also includes Swagger annotations to support automatic API documentation generation.
Contents and Detailed Explanation
Package Declaration
package api
Defines the `api` package which groups core API types and functionality used throughout all coinstacks.
Error Models
These structs represent standard HTTP error responses, useful for API clients to handle errors consistently.
Error
type Error struct { Message string `json:"message"` }Purpose: Generic API error with a message.
Fields:
Message: Description of the error.
Swagger: Identified as
ApiError.
BadRequestError
type BadRequestError struct { Error string `json:"error"` }Purpose: Represents HTTP 400 Bad Request error details.
Fields:
Error: Error message.
ValidationError
type ValidationError struct { Message string `json:"message"` Details map[string]string `json:"details"` }Purpose: HTTP 422 Validation Error with detailed validation failure reasons.
Fields:
Message: General validation failure message.Details: Map of field names to error descriptions.
InternalServerError
type InternalServerError struct { Message string `json:"message"` }Purpose: HTTP 500 Internal Server Error representation.
Fields:
Message: Error message describing the server failure.
Core Interfaces and Structs
These define the basic data contracts for blockchain data entities.
Info Interface and BaseInfo Struct
type Info interface {
network() string
}
type BaseInfo struct {
Network string `json:"network"`
}
func (b BaseInfo) network() string {
return b.Network
}
Info Interface: Requires a
network()method returning the network name.BaseInfo: Contains the
Networkfield representing the blockchain network (e.g., "mainnet").Usage:
BaseInfoimplementsInfo, providing fundamental chain info.
Account Interface and BaseAccount Struct
type Account interface {
balance() string
pubkey() string
}
type BaseAccount struct {
Balance string `json:"balance"`
UnconfirmedBalance string `json:"unconfirmedBalance"`
Pubkey string `json:"pubkey"`
}
func (b BaseAccount) balance() string {
return b.Balance
}
func (b BaseAccount) pubkey() string {
return b.Pubkey
}
Account Interface: Requires methods for retrieving balance and public key.
BaseAccount: Provides core account details including:
Balance(confirmed balance)UnconfirmedBalance(pending transactions)Pubkey(address or extended public key)
Usage:
BaseAccountfulfillsAccountinterface.
Pagination Struct
type Pagination struct {
Cursor string `json:"cursor,omitempty"`
}
Represents pagination metadata.
Cursoris a base64 encoded string used to fetch the next page.If empty or omitted, it indicates no further pages.
Tx Interface and BaseTx Struct
type Tx interface {
txid() string
blockHash() *string
blockHeight() int
timestamp() int
}
type BaseTx struct {
TxID string `json:"txid"`
BlockHash *string `json:"blockHash,omitempty"`
BlockHeight int `json:"blockHeight"`
Timestamp int `json:"timestamp"`
}
func (b *BaseTx) txid() string {
return b.TxID
}
func (b *BaseTx) blockHash() *string {
return b.BlockHash
}
func (b *BaseTx) blockHeight() int {
return b.BlockHeight
}
func (b *BaseTx) timestamp() int {
return b.Timestamp
}
Tx Interface: Defines methods to access transaction details.
BaseTx: Contains:
TxID: Transaction hash.BlockHash: Hash of the block containing the transaction (optional).BlockHeight: Height of the block.Timestamp: Unix epoch timestamp in milliseconds.
BaseTximplements theTxinterface.
TxHistory Interface and BaseTxHistory Struct
type TxHistory interface {
pubkey() string
txs() []Tx
}
type BaseTxHistory struct {
Pagination
Pubkey string `json:"pubkey"`
Txs []Tx `json:"txs"`
}
func (b BaseTxHistory) pubkey() string {
return b.Pubkey
}
func (b BaseTxHistory) txs() []Tx {
return b.Txs
}
TxHistory Interface: Requires methods to get public key and list of transactions.
BaseTxHistory: Embeds
Paginationand stores:Pubkey: The address or xpub the history belongs to.Txs: Slice of transactions.
Implements the
TxHistoryinterface.
TxBody Struct
type TxBody struct {
RawTx string `json:"rawTx"`
}
Represents the raw transaction payload for sending transactions.
Request Parameter Structs
These structs are used to bind and validate HTTP request parameters.
PubkeyParam
type PubkeyParam struct { Pubkey string `json:"pubkey"` }Used for API endpoints needing a public key or address parameter.
Bound from URL path.
PaginationParam
type PaginationParam struct { Cursor string `json:"cursor"` PageSize int `json:"pageSize"` }Query parameters for paginated requests.
PaginatedPubkeyParam
type PaginatedPubkeyParam struct { PubkeyParam PaginationParam }Combines
PubkeyParamandPaginationParam.Used for endpoints that accept both public key and pagination.
TxParam
type TxParam struct { Body struct { TxBody } }Used for endpoints accepting transaction data in the request body (e.g., sending a transaction).
Other Models
TransactionHash
type TransactionHash stringRepresents a transaction hash string.
GasAmount
type GasAmount stringRepresents the gas amount as a string.
BaseAPI Interface
type BaseAPI interface {
GetInfo() (Info, error)
GetAccount(pubkey string) (Account, error)
GetTxHistory(pubkey string, cursor string, pageSize int) (TxHistory, error)
SendTx(hex string) (string, error)
}
Purpose: Defines the core API methods all coinstacks must implement.
Methods:
GetInfo(): Returns network info implementingInfo.GetAccount(pubkey string): Returns account info for given public key.GetTxHistory(pubkey string, cursor string, pageSize int): Returns paginated transaction history.SendTx(hex string): Sends a raw transaction hex string and returns the transaction hash.
Important Implementation Details and Algorithms
The file primarily defines data contracts and interfaces without complex algorithms.
Interfaces are designed for polymorphism, enabling different blockchain implementations to provide their own versions of accounts, transactions, and histories while adhering to a unified API.
Use of pointer receivers for some methods (e.g.,
BaseTx) allows efficient method calls.Pagination uses a base64 encoded cursor string to fetch subsequent pages, a common approach to stateless pagination in APIs.
Swagger annotations (
swagger:model,swagger:parameters) are used to generate OpenAPI specifications automatically, improving API discoverability and client generation.
Interaction with Other System Components
Coinstacks: Each blockchain-specific module (coinstack) implements the
BaseAPIinterface in this file, ensuring consistent API behavior across blockchains.HTTP Server: The parameter structs (
PubkeyParam,PaginationParam, etc.) are used by HTTP route handlers to bind and validate incoming requests.Swagger/OpenAPI: Annotations facilitate automated generation of API documentation, helping frontend and third-party clients understand and integrate with the APIs.
Middleware: Although not defined here, the package comment mentions useful middlewares for HTTP servers, indicating this file is part of a broader HTTP API infrastructure.
Usage Examples
Implementing BaseAPI in a Coinstack
type MyCoinstackAPI struct {
// internal fields like client or config
}
func (api *MyCoinstackAPI) GetInfo() (api.Info, error) {
return api.BaseInfo{Network: "mainnet"}, nil
}
func (api *MyCoinstackAPI) GetAccount(pubkey string) (api.Account, error) {
// fetch account data ...
return &api.BaseAccount{
Balance: "1000000",
UnconfirmedBalance: "0",
Pubkey: pubkey,
}, nil
}
// Implement other interface methods...
Handling a Paginated Request
func handleTxHistory(c *gin.Context, api api.BaseAPI) {
var params api.PaginatedPubkeyParam
if err := c.BindQuery(¶ms); err != nil {
c.JSON(400, api.BadRequestError{Error: "Invalid parameters"})
return
}
history, err := api.GetTxHistory(params.Pubkey, params.Cursor, params.PageSize)
if err != nil {
c.JSON(500, api.InternalServerError{Message: err.Error()})
return
}
c.JSON(200, history)
}
Visual Diagram
classDiagram
class BaseAPI {
+GetInfo() Info
+GetAccount(pubkey string) Account
+GetTxHistory(pubkey string, cursor string, pageSize int) TxHistory
+SendTx(hex string) string
}
class Info {
<<interface>>
+network() string
}
class BaseInfo {
+Network: string
+network() string
}
class Account {
<<interface>>
+balance() string
+pubkey() string
}
class BaseAccount {
+Balance: string
+UnconfirmedBalance: string
+Pubkey: string
+balance() string
+pubkey() string
}
class Tx {
<<interface>>
+txid() string
+blockHash() *string
+blockHeight() int
+timestamp() int
}
class BaseTx {
+TxID: string
+BlockHash: *string
+BlockHeight: int
+Timestamp: int
+txid() string
+blockHash() *string
+blockHeight() int
+timestamp() int
}
class TxHistory {
<<interface>>
+pubkey() string
+txs() []Tx
}
class BaseTxHistory {
+Cursor: string
+Pubkey: string
+Txs: []Tx
+pubkey() string
+txs() []Tx
}
BaseAPI ..> Info : returns
BaseAPI ..> Account : returns
BaseAPI ..> TxHistory : returns
BaseInfo ..|> Info
BaseAccount ..|> Account
BaseTx ..|> Tx
BaseTxHistory ..|> TxHistory
Summary
The [api.go](/projects/291/69232) file is a critical foundational component defining standard data types, interfaces, and error models to support consistent API design and implementation across multiple blockchain stacks in the system. It enables polymorphic behavior through interfaces, supports pagination, and integrates with Swagger for API documentation. This design promotes modularity, reusability, and clarity in the project's blockchain API layer.