node.go raw
1 package main
2
3 import (
4 "bytes"
5 "context"
6 "encoding/base64"
7 "encoding/hex"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "io"
12 "net/http"
13 "net/url"
14 "os"
15 "strings"
16 "time"
17
18 "git.smesh.lol/nostrino/pkg/btcwire"
19 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
20 )
21
22 // node is the read-only side of a Bitcoin Core or Knots JSON-RPC endpoint.
23 //
24 // Only four calls are here, and only ones that read: the cache has no business
25 // changing the node's state, and a client that cannot call a method cannot be
26 // written to call it by accident.
27 type node struct {
28 endpoint string
29 auth string
30 http *http.Client
31 next uint64
32 }
33
34 // newNode prepares a client. The endpoint may carry the credentials as
35 // http://user:pass@host:port; otherwise cookiePath names a bitcoind .cookie
36 // file, which is where a node without rpcuser/rpcpassword writes its own.
37 func newNode(rawURL, cookiePath string) (*node, error) {
38 u, err := url.Parse(rawURL)
39 if err != nil {
40 return nil, fmt.Errorf("node url: %w", err)
41 }
42 if u.Scheme != "http" && u.Scheme != "https" {
43 return nil, fmt.Errorf("node url %q must start with http:// or https://", rawURL)
44 }
45
46 n := &node{
47 endpoint: u.String(),
48 http: &http.Client{
49 // A block filter is a small response, but the node may be busy with
50 // a chain load and take a while to answer the first one.
51 Timeout: 2 * time.Minute,
52 Transport: &http.Transport{
53 MaxIdleConns: 4,
54 MaxIdleConnsPerHost: 4,
55 // The node closes an idle RPC connection at its own
56 // -rpcservertimeout (60 s by default), and reusing one in the
57 // moment it is closed reads as "server closed idle connection"
58 // or a bare EOF. Dropping idle connections well before that,
59 // and retrying a transport failure below, is what keeps a
60 // poller that runs for days from dying on a socket the node
61 // tidied up.
62 IdleConnTimeout: 20 * time.Second,
63 },
64 },
65 }
66
67 if u.User != nil {
68 pass, _ := u.User.Password()
69 n.auth = basicAuth(u.User.Username(), pass)
70 u.User = nil
71 n.endpoint = u.String()
72 } else if cookiePath != "" {
73 raw, err := os.ReadFile(cookiePath)
74 if err != nil {
75 return nil, fmt.Errorf("read cookie: %w", err)
76 }
77 user, pass, ok := strings.Cut(strings.TrimSpace(string(raw)), ":")
78 if !ok || user == "" {
79 return nil, fmt.Errorf("cookie file %s is not user:password", cookiePath)
80 }
81 n.auth = basicAuth(user, pass)
82 }
83
84 return n, nil
85 }
86
87 func basicAuth(user, pass string) string {
88 return "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+pass))
89 }
90
91 // rpcError is the node's own error object, which is never a transport failure:
92 // the node answered, and the answer was no.
93 type rpcError struct {
94 Code int `json:"code"`
95 Message string `json:"message"`
96 }
97
98 func (e *rpcError) Error() string { return fmt.Sprintf("node error %d: %s", e.Code, e.Message) }
99
100 // errCredentials is the node refusing the user or password. It is an answer, not
101 // a broken socket, so it is not retried.
102 var errCredentials = errors.New("the node refused the credentials")
103
104 // call performs one JSON-RPC request, retrying a transport failure.
105 //
106 // Every method here reads, so a retry cannot repeat an effect: the only thing a
107 // second attempt can do is ask the same question again. A node error is never
108 // retried, because the node answered.
109 func (n *node) call(ctx context.Context, method string, params []any, out any) error {
110 for attempt := 1; ; attempt++ {
111 err := n.callOnce(ctx, method, params, out)
112 if err == nil {
113 return nil
114 }
115
116 var answer *rpcError
117 if errors.As(err, &answer) || errors.Is(err, errCredentials) || ctx.Err() != nil {
118 return err
119 }
120
121 if attempt >= 3 {
122 return err
123 }
124
125 select {
126 case <-ctx.Done():
127 return err
128 case <-time.After(time.Duration(attempt) * 200 * time.Millisecond):
129 }
130 }
131 }
132
133 // callOnce performs one JSON-RPC request without a retry.
134 func (n *node) callOnce(ctx context.Context, method string, params []any, out any) error {
135 n.next++
136 request := map[string]any{
137 "jsonrpc": "1.0",
138 "id": n.next,
139 "method": method,
140 "params": params,
141 }
142 body, err := json.Marshal(request)
143 if err != nil {
144 return err
145 }
146
147 req, err := http.NewRequestWithContext(ctx, http.MethodPost, n.endpoint, bytes.NewReader(body))
148 if err != nil {
149 return err
150 }
151 req.Header.Set("Content-Type", "application/json")
152 if n.auth != "" {
153 req.Header.Set("Authorization", n.auth)
154 }
155
156 resp, err := n.http.Do(req)
157 if err != nil {
158 return fmt.Errorf("%s: %w", method, err)
159 }
160 defer resp.Body.Close()
161
162 raw, err := io.ReadAll(io.LimitReader(resp.Body, 64<<20))
163 if err != nil {
164 return fmt.Errorf("%s: read answer: %w", method, err)
165 }
166
167 if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
168 return fmt.Errorf("%s: %w (http %d)", method, errCredentials, resp.StatusCode)
169 }
170
171 var envelope struct {
172 Result json.RawMessage `json:"result"`
173 Error *rpcError `json:"error"`
174 }
175 if err := json.Unmarshal(raw, &envelope); err != nil {
176 return fmt.Errorf("%s: http %d, unparseable answer: %w", method, resp.StatusCode, err)
177 }
178 if envelope.Error != nil {
179 return fmt.Errorf("%s: %w", method, envelope.Error)
180 }
181 if len(envelope.Result) == 0 {
182 return fmt.Errorf("%s: http %d, no result", method, resp.StatusCode)
183 }
184 if out != nil {
185 if err := json.Unmarshal(envelope.Result, out); err != nil {
186 return fmt.Errorf("%s: decode result: %w", method, err)
187 }
188 }
189 return nil
190 }
191
192 // tip returns the node's block height.
193 func (n *node) tip(ctx context.Context) (uint32, error) {
194 var height uint32
195 if err := n.call(ctx, "getblockcount", []any{}, &height); err != nil {
196 return 0, err
197 }
198 return height, nil
199 }
200
201 // blockHash returns the block hash at a height.
202 func (n *node) blockHash(ctx context.Context, height uint32) (chainhash.Hash, error) {
203 var text string
204 if err := n.call(ctx, "getblockhash", []any{height}, &text); err != nil {
205 return chainhash.Hash{}, err
206 }
207 var hash chainhash.Hash
208 if err := decodeHash(text, hash[:]); err != nil {
209 return chainhash.Hash{}, fmt.Errorf("getblockhash %d: %w", height, err)
210 }
211 return hash, nil
212 }
213
214 // header returns one block header as the node encodes it on the wire.
215 //
216 // getblockheader with false answers the header's hex, not a JSON object: the event carries
217 // exactly the bytes a client checks against the header's own hash, so nothing here re-encodes
218 // what the node said. The hash is looked up first because the call takes a hash and the
219 // publisher walks heights.
220 func (n *node) header(ctx context.Context, height uint32) (btcwire.BlockHeader, error) {
221 hash, err := n.blockHash(ctx, height)
222 if err != nil {
223 return btcwire.BlockHeader{}, err
224 }
225 var text string
226 if err := n.call(ctx, "getblockheader", []any{hash.String(), false}, &text); err != nil {
227 return btcwire.BlockHeader{}, err
228 }
229 raw, err := hex.DecodeString(text)
230 if err != nil {
231 return btcwire.BlockHeader{}, fmt.Errorf("getblockheader %d: %w", height, err)
232 }
233 var header btcwire.BlockHeader
234 if err := header.DeserializeAny(raw); err != nil {
235 return btcwire.BlockHeader{}, fmt.Errorf("getblockheader %d: %w", height, err)
236 }
237 if header.BlockHash() != hash {
238 return btcwire.BlockHeader{}, fmt.Errorf("getblockheader %d: node returned %s, want %s",
239 height, header.BlockHash().String(), hash.String())
240 }
241 return header, nil
242 }
243
244 // block returns one raw block by hash.
245 //
246 // It is the read behind the block cache: getblock with verbosity 0 answers the block's hex,
247 // which is the same bytes the P2P network would carry, so a sidecar that has no direct peer
248 // still holds the real block and not a re-encoding of one.
249 func (n *node) block(ctx context.Context, height uint32) ([]byte, error) {
250 hash, err := n.blockHash(ctx, height)
251 if err != nil {
252 return nil, err
253 }
254 return n.blockByHash(ctx, hash)
255 }
256
257 // blockByHash returns one raw block by hash, which is what the HTTP service is asked for.
258 func (n *node) blockByHash(ctx context.Context, hash chainhash.Hash) ([]byte, error) {
259 var text string
260 if err := n.call(ctx, "getblock", []any{hash.String(), 0}, &text); err != nil {
261 return nil, err
262 }
263 raw, err := hex.DecodeString(text)
264 if err != nil {
265 return nil, fmt.Errorf("getblock %s: %w", hash.String(), err)
266 }
267 if len(raw) < btcwire.BlockHeaderSize {
268 return nil, fmt.Errorf("getblock %s: %d bytes", hash.String(), len(raw))
269 }
270 return raw, nil
271 }
272
273 // blockTime returns the header time of a block, which is what the event's
274 // created_at is set to: a chain time is stable, so the event id is too.
275 func (n *node) blockTime(ctx context.Context, height uint32) (int64, error) {
276 hash, err := n.blockHash(ctx, height)
277 if err != nil {
278 return 0, err
279 }
280 var header struct {
281 Time int64 `json:"time"`
282 }
283 if err := n.call(ctx, "getblockheader", []any{hash.String(), true}, &header); err != nil {
284 return 0, err
285 }
286 if header.Time <= 0 {
287 return 0, fmt.Errorf("getblockheader %s: no time", hash)
288 }
289 return header.Time, nil
290 }
291
292 // filter returns one compact filter and the filter hash that commits to it.
293 //
294 // The node answers with the filter and its filter *header*, which commits to
295 // this filter and the previous one. The client compares filter hashes, so the
296 // hash is what is carried; it is defined as the double SHA-256 of the filter
297 // bytes, so it is computed rather than fetched.
298 func (n *node) filter(ctx context.Context, height uint32) ([]byte, chainhash.Hash, error) {
299 hash, err := n.blockHash(ctx, height)
300 if err != nil {
301 return nil, chainhash.Hash{}, err
302 }
303 var answer struct {
304 Filter string `json:"filter"`
305 Header string `json:"header"`
306 }
307 if err := n.call(ctx, "getblockfilter", []any{hash.String()}, &answer); err != nil {
308 return nil, chainhash.Hash{}, err
309 }
310 if answer.Filter == "" || answer.Header == "" {
311 return nil, chainhash.Hash{}, fmt.Errorf("getblockfilter %s: empty answer (blockfilterindex off?)", hash)
312 }
313 filter, err := hex.DecodeString(answer.Filter)
314 if err != nil {
315 return nil, chainhash.Hash{}, fmt.Errorf("getblockfilter %s: filter is not hex: %w", hash, err)
316 }
317 if len(filter) == 0 {
318 return nil, chainhash.Hash{}, fmt.Errorf("getblockfilter %s: zero-length filter", hash)
319 }
320 return filter, chainhash.DoubleHashH(filter), nil
321 }
322
323 // decodeHash parses a display-order (byte-reversed) hash into wire order.
324 func decodeHash(text string, dst []byte) error {
325 if len(text) != len(dst)*2 {
326 return errors.New("wrong hex length")
327 }
328 raw, err := hex.DecodeString(text)
329 if err != nil {
330 return err
331 }
332 for i := range dst {
333 dst[i] = raw[len(raw)-1-i]
334 }
335 return nil
336 }
337