Files
KamadoPool/api/internal/config/config.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

83 lines
2.2 KiB
Go

// Package config loads kamado-api configuration from environment variables.
// Missing required values are a hard error at startup; optional values get
// documented defaults.
package config
import (
"fmt"
"os"
"strconv"
"time"
)
type Config struct {
// HTTP server
ListenAddr string
// CKPool socket
CKPoolSockDir string
// Bitcoin Core RPC
BitcoinRPCURL string // full URL e.g. http://bitcoind:8332
BitcoinRPCUser string
BitcoinRPCPassword string
BitcoinRPCTimeout time.Duration
// ZMQ (Phase 2b)
BitcoinZMQBlock string // e.g. tcp://bitcoind:28332, empty to disable
// CKPool log file, for block-solve detection (Phase 2b)
CKPoolLogFile string
// SQLite DB path for persistence (Phase 2b)
DBPath string
// Poll interval for refreshing ckpool stats
PollInterval time.Duration
}
func FromEnv() (*Config, error) {
cfg := &Config{
ListenAddr: getenv("LISTEN_ADDR", ":8080"),
CKPoolSockDir: getenv("CKPOOL_SOCKDIR", "/run/ckpool"),
BitcoinRPCURL: os.Getenv("BITCOIN_RPC_URL"),
BitcoinRPCUser: os.Getenv("BITCOIN_RPC_USER"),
BitcoinRPCPassword: os.Getenv("BITCOIN_RPC_PASSWORD"),
BitcoinRPCTimeout: getenvDuration("BITCOIN_RPC_TIMEOUT", 10*time.Second),
BitcoinZMQBlock: os.Getenv("BITCOIN_ZMQ_BLOCK"),
CKPoolLogFile: getenv("CKPOOL_LOGFILE", "/var/log/ckpool/ckpool.log"),
DBPath: getenv("DB_PATH", "/var/lib/kamado/kamado.db"),
PollInterval: getenvDuration("POLL_INTERVAL", 5*time.Second),
}
if cfg.BitcoinRPCURL == "" {
return nil, fmt.Errorf("BITCOIN_RPC_URL is required")
}
if cfg.BitcoinRPCUser == "" || cfg.BitcoinRPCPassword == "" {
return nil, fmt.Errorf("BITCOIN_RPC_USER and BITCOIN_RPC_PASSWORD are required")
}
return cfg, nil
}
func getenv(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
func getenvDuration(key string, def time.Duration) time.Duration {
v := os.Getenv(key)
if v == "" {
return def
}
// Accept both Go duration syntax ("5s", "10s") and bare seconds ("10").
if d, err := time.ParseDuration(v); err == nil {
return d
}
if n, err := strconv.Atoi(v); err == nil {
return time.Duration(n) * time.Second
}
return def
}