Files
KamadoPool/api/internal/httpapi/server.go
T
satoshiandClaude Opus 4.6 bd0b1b0318 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>
2026-04-12 19:52:27 +03:00

86 lines
2.4 KiB
Go

// Package httpapi serves the Kamado REST API. WebSocket push and static
// UI serving land in a follow-up commit.
package httpapi
import (
"encoding/json"
"log/slog"
"net/http"
"github.com/kamadopool/kamado-api/internal/state"
)
type Server struct {
Agg *state.Aggregator
Log *slog.Logger
}
func New(agg *state.Aggregator, log *slog.Logger) *Server {
return &Server{Agg: agg, Log: log}
}
// Handler returns an http.Handler with all kamado routes mounted under /api.
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /api/health", s.health)
mux.HandleFunc("GET /api/pool", s.pool)
mux.HandleFunc("GET /api/users", s.users)
mux.HandleFunc("GET /api/workers", s.workers)
mux.HandleFunc("GET /api/clients", s.clients)
mux.HandleFunc("GET /api/snapshot", s.snapshot)
return mux
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
// ---- handlers ---------------------------------------------------------
func (s *Server) health(w http.ResponseWriter, r *http.Request) {
snap := s.Agg.Snapshot()
status := http.StatusOK
if !snap.CKPoolOK || !snap.BitcoinOK {
status = http.StatusServiceUnavailable
}
writeJSON(w, status, map[string]any{
"ok": snap.CKPoolOK && snap.BitcoinOK,
"ckpool": snap.CKPoolOK,
"bitcoin": snap.BitcoinOK,
"last_error": snap.LastError,
})
}
func (s *Server) snapshot(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, s.Agg.Snapshot())
}
func (s *Server) pool(w http.ResponseWriter, r *http.Request) {
snap := s.Agg.Snapshot()
writeJSON(w, http.StatusOK, map[string]any{
"pool": snap.Pool,
"uptime_seconds": snap.Uptime,
"hashrate_hs_1m": snap.HashrateHs,
"hashrate_hs_5m": snap.HashrateHs5m,
"hashrate_hs_1h": snap.HashrateHs1h,
"hashrate_hs_24h": snap.HashrateHs24h,
"chain": snap.Chain,
"network_hashrate_hs": snap.NetworkHashrateHs,
})
}
func (s *Server) users(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, s.Agg.Snapshot().Users)
}
func (s *Server) workers(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, s.Agg.Snapshot().Workers)
}
func (s *Server) clients(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, s.Agg.Snapshot().Clients)
}