Phase 2a: kamado-api Go middleware (core MVP)
Go 1.22 module that polls CKPool's Unix socket control API, queries
Bitcoin Core over JSON-RPC, merges both into a thread-safe snapshot, and
serves it over REST. Layout:
api/
├── cmd/kamado-api/main.go signal-aware entrypoint
└── internal/
├── config/ env var loader with validation
├── ckpool/ socket client (4-byte LE length-prefixed wire
│ protocol verified against libckpool.c), typed
│ response models for poolstats/users/workers/
│ clients/uptime, + unit tests using a fake
│ unix socket server
├── bitcoind/ minimal JSON-RPC client, getblockchaininfo
│ and getnetworkhashps
├── state/ Aggregator that refreshes a merged Snapshot
│ on a ticker; readers get a copy under RWMutex
└── httpapi/ REST handlers on Go 1.22 ServeMux:
/api/health /api/pool /api/users
/api/workers /api/clients /api/snapshot
CKPool stores hashrate as "dsps" (diff shares per second); we convert
to H/s via the 2^32 constant used by GoBrrr-Pool and other clients.
Every stat CKPool exposes to its socket API is surfaced — useragent,
IP, per-client diff, per-worker best diff — closing the gap against
Bassin which only reads the 60-second stats files.
Dockerfile does a CGO_ENABLED=0 static build on golang:1.22-bookworm
with -trimpath -ldflags=-s -w. docker-compose now runs both ckpool and
kamado-api, sharing a named volume for /run/ckpool so the API can
dial the stratifier socket directly.
Deferred to Phase 2b (called out in README):
- Bitcoin Core ZMQ hashblock subscriber
- WebSocket push for real-time UI updates
- SQLite persistence (block history, best-share history)
- CKPool log tailer for "Solved and confirmed block" detection
Tests and build NOT run in this commit — Go isn't installed in the
dev environment. Run `make api-test` or `make api` to verify.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
d48035b366
commit
bd0b1b0318
@@ -0,0 +1,124 @@
|
||||
// Package bitcoind provides a minimal Bitcoin Core JSON-RPC client.
|
||||
// Only the methods kamado-api actually needs are implemented.
|
||||
package bitcoind
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type RPC struct {
|
||||
URL string
|
||||
User string
|
||||
Password string
|
||||
HTTP *http.Client
|
||||
}
|
||||
|
||||
func NewRPC(url, user, password string, timeout time.Duration) *RPC {
|
||||
return &RPC{
|
||||
URL: url,
|
||||
User: user,
|
||||
Password: password,
|
||||
HTTP: &http.Client{Timeout: timeout},
|
||||
}
|
||||
}
|
||||
|
||||
type rpcRequest struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID string `json:"id"`
|
||||
Method string `json:"method"`
|
||||
Params []any `json:"params"`
|
||||
}
|
||||
|
||||
type rpcResponse struct {
|
||||
Result json.RawMessage `json:"result"`
|
||||
Error *rpcError `json:"error"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
type rpcError struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func (e *rpcError) Error() string {
|
||||
return fmt.Sprintf("bitcoind rpc error %d: %s", e.Code, e.Message)
|
||||
}
|
||||
|
||||
// Call performs a single JSON-RPC request and unmarshals the result.
|
||||
func (c *RPC) Call(ctx context.Context, method string, params []any, out any) error {
|
||||
body, err := json.Marshal(rpcRequest{
|
||||
JSONRPC: "1.0",
|
||||
ID: "kamado",
|
||||
Method: method,
|
||||
Params: params,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", c.URL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.SetBasicAuth(c.User, c.Password)
|
||||
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("bitcoind rpc: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("bitcoind rpc: read body: %w", err)
|
||||
}
|
||||
// bitcoind returns 500 on rpc errors but still with a valid JSON body.
|
||||
var rr rpcResponse
|
||||
if err := json.Unmarshal(raw, &rr); err != nil {
|
||||
return fmt.Errorf("bitcoind rpc: unmarshal (status %d): %w: %s", resp.StatusCode, err, string(raw))
|
||||
}
|
||||
if rr.Error != nil {
|
||||
return rr.Error
|
||||
}
|
||||
if out != nil {
|
||||
return json.Unmarshal(rr.Result, out)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---- typed method wrappers ----
|
||||
|
||||
type BlockchainInfo struct {
|
||||
Chain string `json:"chain"`
|
||||
Blocks int64 `json:"blocks"`
|
||||
Headers int64 `json:"headers"`
|
||||
BestBlockHash string `json:"bestblockhash"`
|
||||
Difficulty float64 `json:"difficulty"`
|
||||
MedianTime int64 `json:"mediantime"`
|
||||
VerificationProgress float64 `json:"verificationprogress"`
|
||||
InitialBlockDownload bool `json:"initialblockdownload"`
|
||||
}
|
||||
|
||||
func (c *RPC) GetBlockchainInfo(ctx context.Context) (*BlockchainInfo, error) {
|
||||
var out BlockchainInfo
|
||||
if err := c.Call(ctx, "getblockchaininfo", nil, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
// NetworkHashPS returns the network hashrate at the given block height.
|
||||
// `blocks` is a window (default 120). Pass -1 to use the default.
|
||||
func (c *RPC) GetNetworkHashPS(ctx context.Context, blocks, height int) (float64, error) {
|
||||
var out float64
|
||||
if err := c.Call(ctx, "getnetworkhashps", []any{blocks, height}, &out); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
Reference in New Issue
Block a user