Files
KamadoPool/api/internal/bitcoind/rpc.go
T
satoshi e881bc930d Revamp dashboard and persist pool stats across restarts
Dashboard now renders 10 tiles in a 5x2 overview: hashrate, best
share, miners, network hashrate, and expected block on the top row;
difficulty, block height, block reward, total work, and the
difficulty-adjustment countdown on the bottom row. Difficulty is
rendered with T/P suffixes instead of scientific notation, the main
hashrate card shows the 1-minute value, and the block-height tile
pulses orange when the network tip advances.

Added a 24-hour hashrate area chart below the overview, sampled
once per minute. Samples are persisted to a new hashrate_samples
SQLite table and restored on startup so the chart doesn't reset
every time kamado-api is restarted.

Cumulative pool work (sum of accepted diff-1-normalized shares) is
now tracked across ckpool restarts. The aggregator integrates only
positive deltas on pool.Shares — a regression means ckpool's
counter reset to zero and the baseline is refreshed without losing
the running total. A hasPoolSharesBaseline flag prevents double-
counting on the first refresh after a kamado-api restart. The
value is persisted to a new kv table once per minute.

Next-block reward (subsidy + fees) is fetched from bitcoind
getblocktemplate at most once per minute and surfaced as a tile.

Header's block-height badge now reads prevHeight via untrack() so
the effect doesn't form a dependency cycle with its own write.
2026-04-22 21:07:22 +03:00

196 lines
5.3 KiB
Go

// 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
}
// GetBlockHash returns the block hash at the given height.
func (c *RPC) GetBlockHash(ctx context.Context, height int64) (string, error) {
var out string
if err := c.Call(ctx, "getblockhash", []any{height}, &out); err != nil {
return "", err
}
return out, nil
}
// BlockVerbose2 is the subset of `getblock <hash> 2` we care about.
// Verbosity 2 expands each tx into its full object so we can read the
// coinbase output values without a second getrawtransaction call.
type BlockVerbose2 struct {
Hash string `json:"hash"`
Height int64 `json:"height"`
Confirmations int64 `json:"confirmations"`
Time int64 `json:"time"`
Tx []BlockTx `json:"tx"`
}
type BlockTx struct {
Txid string `json:"txid"`
Vout []BlockVout `json:"vout"`
}
type BlockVout struct {
Value float64 `json:"value"`
N int `json:"n"`
}
// GetBlock returns a verbose-level-2 block decode for the given hash.
func (c *RPC) GetBlock(ctx context.Context, hash string) (*BlockVerbose2, error) {
var out BlockVerbose2
if err := c.Call(ctx, "getblock", []any{hash, 2}, &out); err != nil {
return nil, err
}
return &out, nil
}
// CoinbaseReward sums all outputs of the first transaction in the block
// (the coinbase). In solo mining this is the full subsidy + fees the
// solving worker receives.
func (b *BlockVerbose2) CoinbaseReward() float64 {
if len(b.Tx) == 0 {
return 0
}
var total float64
for _, vout := range b.Tx[0].Vout {
total += vout.Value
}
return total
}
// 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
}
// BlockTemplate is the subset of getblocktemplate we care about: the
// coinbase value (subsidy + fees) and height of the next block.
type BlockTemplate struct {
CoinbaseValue int64 `json:"coinbasevalue"` // satoshis
Height int64 `json:"height"`
}
// GetBlockTemplate fetches the next block template with segwit rules.
// The call is relatively expensive; rate-limit callers to ~1/min.
func (c *RPC) GetBlockTemplate(ctx context.Context) (*BlockTemplate, error) {
var out BlockTemplate
params := []any{map[string]any{"rules": []string{"segwit"}}}
if err := c.Call(ctx, "getblocktemplate", params, &out); err != nil {
return nil, err
}
return &out, nil
}