package main import ( "bytes" "context" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "os" "strings" "time" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/crypto/chainhash" ) // node is the read-only side of a Bitcoin Core or Knots JSON-RPC endpoint. // // Only four calls are here, and only ones that read: the cache has no business // changing the node's state, and a client that cannot call a method cannot be // written to call it by accident. type node struct { endpoint string auth string http *http.Client next uint64 } // newNode prepares a client. The endpoint may carry the credentials as // http://user:pass@host:port; otherwise cookiePath names a bitcoind .cookie // file, which is where a node without rpcuser/rpcpassword writes its own. func newNode(rawURL, cookiePath string) (*node, error) { u, err := url.Parse(rawURL) if err != nil { return nil, fmt.Errorf("node url: %w", err) } if u.Scheme != "http" && u.Scheme != "https" { return nil, fmt.Errorf("node url %q must start with http:// or https://", rawURL) } n := &node{ endpoint: u.String(), http: &http.Client{ // A block filter is a small response, but the node may be busy with // a chain load and take a while to answer the first one. Timeout: 2 * time.Minute, Transport: &http.Transport{ MaxIdleConns: 4, MaxIdleConnsPerHost: 4, // The node closes an idle RPC connection at its own // -rpcservertimeout (60 s by default), and reusing one in the // moment it is closed reads as "server closed idle connection" // or a bare EOF. Dropping idle connections well before that, // and retrying a transport failure below, is what keeps a // poller that runs for days from dying on a socket the node // tidied up. IdleConnTimeout: 20 * time.Second, }, }, } if u.User != nil { pass, _ := u.User.Password() n.auth = basicAuth(u.User.Username(), pass) u.User = nil n.endpoint = u.String() } else if cookiePath != "" { raw, err := os.ReadFile(cookiePath) if err != nil { return nil, fmt.Errorf("read cookie: %w", err) } user, pass, ok := strings.Cut(strings.TrimSpace(string(raw)), ":") if !ok || user == "" { return nil, fmt.Errorf("cookie file %s is not user:password", cookiePath) } n.auth = basicAuth(user, pass) } return n, nil } func basicAuth(user, pass string) string { return "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+pass)) } // rpcError is the node's own error object, which is never a transport failure: // the node answered, and the answer was no. type rpcError struct { Code int `json:"code"` Message string `json:"message"` } func (e *rpcError) Error() string { return fmt.Sprintf("node error %d: %s", e.Code, e.Message) } // errCredentials is the node refusing the user or password. It is an answer, not // a broken socket, so it is not retried. var errCredentials = errors.New("the node refused the credentials") // call performs one JSON-RPC request, retrying a transport failure. // // Every method here reads, so a retry cannot repeat an effect: the only thing a // second attempt can do is ask the same question again. A node error is never // retried, because the node answered. func (n *node) call(ctx context.Context, method string, params []any, out any) error { for attempt := 1; ; attempt++ { err := n.callOnce(ctx, method, params, out) if err == nil { return nil } var answer *rpcError if errors.As(err, &answer) || errors.Is(err, errCredentials) || ctx.Err() != nil { return err } if attempt >= 3 { return err } select { case <-ctx.Done(): return err case <-time.After(time.Duration(attempt) * 200 * time.Millisecond): } } } // callOnce performs one JSON-RPC request without a retry. func (n *node) callOnce(ctx context.Context, method string, params []any, out any) error { n.next++ request := map[string]any{ "jsonrpc": "1.0", "id": n.next, "method": method, "params": params, } body, err := json.Marshal(request) if err != nil { return err } req, err := http.NewRequestWithContext(ctx, http.MethodPost, n.endpoint, bytes.NewReader(body)) if err != nil { return err } req.Header.Set("Content-Type", "application/json") if n.auth != "" { req.Header.Set("Authorization", n.auth) } resp, err := n.http.Do(req) if err != nil { return fmt.Errorf("%s: %w", method, err) } defer resp.Body.Close() raw, err := io.ReadAll(io.LimitReader(resp.Body, 64<<20)) if err != nil { return fmt.Errorf("%s: read answer: %w", method, err) } if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden { return fmt.Errorf("%s: %w (http %d)", method, errCredentials, resp.StatusCode) } var envelope struct { Result json.RawMessage `json:"result"` Error *rpcError `json:"error"` } if err := json.Unmarshal(raw, &envelope); err != nil { return fmt.Errorf("%s: http %d, unparseable answer: %w", method, resp.StatusCode, err) } if envelope.Error != nil { return fmt.Errorf("%s: %w", method, envelope.Error) } if len(envelope.Result) == 0 { return fmt.Errorf("%s: http %d, no result", method, resp.StatusCode) } if out != nil { if err := json.Unmarshal(envelope.Result, out); err != nil { return fmt.Errorf("%s: decode result: %w", method, err) } } return nil } // tip returns the node's block height. func (n *node) tip(ctx context.Context) (uint32, error) { var height uint32 if err := n.call(ctx, "getblockcount", []any{}, &height); err != nil { return 0, err } return height, nil } // blockHash returns the block hash at a height. func (n *node) blockHash(ctx context.Context, height uint32) (chainhash.Hash, error) { var text string if err := n.call(ctx, "getblockhash", []any{height}, &text); err != nil { return chainhash.Hash{}, err } var hash chainhash.Hash if err := decodeHash(text, hash[:]); err != nil { return chainhash.Hash{}, fmt.Errorf("getblockhash %d: %w", height, err) } return hash, nil } // header returns one block header as the node encodes it on the wire. // // getblockheader with false answers the header's hex, not a JSON object: the event carries // exactly the bytes a client checks against the header's own hash, so nothing here re-encodes // what the node said. The hash is looked up first because the call takes a hash and the // publisher walks heights. func (n *node) header(ctx context.Context, height uint32) (btcwire.BlockHeader, error) { hash, err := n.blockHash(ctx, height) if err != nil { return btcwire.BlockHeader{}, err } var text string if err := n.call(ctx, "getblockheader", []any{hash.String(), false}, &text); err != nil { return btcwire.BlockHeader{}, err } raw, err := hex.DecodeString(text) if err != nil { return btcwire.BlockHeader{}, fmt.Errorf("getblockheader %d: %w", height, err) } var header btcwire.BlockHeader if err := header.DeserializeAny(raw); err != nil { return btcwire.BlockHeader{}, fmt.Errorf("getblockheader %d: %w", height, err) } if header.BlockHash() != hash { return btcwire.BlockHeader{}, fmt.Errorf("getblockheader %d: node returned %s, want %s", height, header.BlockHash().String(), hash.String()) } return header, nil } // block returns one raw block by hash. // // It is the read behind the block cache: getblock with verbosity 0 answers the block's hex, // which is the same bytes the P2P network would carry, so a sidecar that has no direct peer // still holds the real block and not a re-encoding of one. func (n *node) block(ctx context.Context, height uint32) ([]byte, error) { hash, err := n.blockHash(ctx, height) if err != nil { return nil, err } return n.blockByHash(ctx, hash) } // blockByHash returns one raw block by hash, which is what the HTTP service is asked for. func (n *node) blockByHash(ctx context.Context, hash chainhash.Hash) ([]byte, error) { var text string if err := n.call(ctx, "getblock", []any{hash.String(), 0}, &text); err != nil { return nil, err } raw, err := hex.DecodeString(text) if err != nil { return nil, fmt.Errorf("getblock %s: %w", hash.String(), err) } if len(raw) < btcwire.BlockHeaderSize { return nil, fmt.Errorf("getblock %s: %d bytes", hash.String(), len(raw)) } return raw, nil } // blockTime returns the header time of a block, which is what the event's // created_at is set to: a chain time is stable, so the event id is too. func (n *node) blockTime(ctx context.Context, height uint32) (int64, error) { hash, err := n.blockHash(ctx, height) if err != nil { return 0, err } var header struct { Time int64 `json:"time"` } if err := n.call(ctx, "getblockheader", []any{hash.String(), true}, &header); err != nil { return 0, err } if header.Time <= 0 { return 0, fmt.Errorf("getblockheader %s: no time", hash) } return header.Time, nil } // filter returns one compact filter and the filter hash that commits to it. // // The node answers with the filter and its filter *header*, which commits to // this filter and the previous one. The client compares filter hashes, so the // hash is what is carried; it is defined as the double SHA-256 of the filter // bytes, so it is computed rather than fetched. func (n *node) filter(ctx context.Context, height uint32) ([]byte, chainhash.Hash, error) { hash, err := n.blockHash(ctx, height) if err != nil { return nil, chainhash.Hash{}, err } var answer struct { Filter string `json:"filter"` Header string `json:"header"` } if err := n.call(ctx, "getblockfilter", []any{hash.String()}, &answer); err != nil { return nil, chainhash.Hash{}, err } if answer.Filter == "" || answer.Header == "" { return nil, chainhash.Hash{}, fmt.Errorf("getblockfilter %s: empty answer (blockfilterindex off?)", hash) } filter, err := hex.DecodeString(answer.Filter) if err != nil { return nil, chainhash.Hash{}, fmt.Errorf("getblockfilter %s: filter is not hex: %w", hash, err) } if len(filter) == 0 { return nil, chainhash.Hash{}, fmt.Errorf("getblockfilter %s: zero-length filter", hash) } return filter, chainhash.DoubleHashH(filter), nil } // decodeHash parses a display-order (byte-reversed) hash into wire order. func decodeHash(text string, dst []byte) error { if len(text) != len(dst)*2 { return errors.New("wrong hex length") } raw, err := hex.DecodeString(text) if err != nil { return err } for i := range dst { dst[i] = raw[len(raw)-1-i] } return nil }