Files
KamadoPool/api/internal/bitcoind/rpc.go
T
satoshi 89904d5e08 Enrich found-block records with real coinbase reward
Adds RPC.GetBlock(hash, verbosity=2) and a CoinbaseReward
helper that sums the first tx's outputs. IngestBlockEvents
now does getblockhash -> getblock -> sum(vout) so
BlockRecord.RewardBT carries the actual BTC paid out on
solve instead of always being zero. Both RPC calls share a
single 5s deadline and are best-effort — bitcoind being
down just leaves the reward at zero.
2026-04-14 17:02:39 +03:00

178 lines
4.6 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
}