1 // Package fetch fills an instance from another instance's service.
2 //
3 // It is the client half of the seeding path: read the manifest, check its
4 // signature against the key the operator pinned, ask for the chunks that cover
5 // a range, and verify every chunk against the name it was asked for before a
6 // block goes into the store. A serving instance can refuse to answer and can
7 // answer late; it cannot hand over bytes that pass under a name they do not
8 // hash to.
9 package fetch
10 11 import (
12 "context"
13 "encoding/binary"
14 "encoding/json"
15 "errors"
16 "fmt"
17 "io"
18 "net/http"
19 "time"
20 21 "git.smesh.lol/btcd-lite/internal/chunk"
22 "git.smesh.lol/btcd-lite/internal/manifest"
23 "git.smesh.lol/btcd-lite/internal/serve"
24 "git.smesh.lol/btcd-lite/internal/store"
25 )
26 27 // Client fills from one service.
28 type Client struct {
29 // Base is the service's URL, without a trailing slash.
30 Base string
31 // HTTP is the transport; nil means a client with a one-minute timeout.
32 HTTP *http.Client
33 // Logf receives one line per request; nil discards them.
34 Logf func(string, ...any)
35 }
36 37 // Manifest reads the service's manifest and, when pub is not nil, requires its
38 // signature to verify against pub. A client that pins no key accepts an
39 // unsigned manifest; every chunk it downloads is still checked against its
40 // name, so no key changes whether wrong bytes are refused.
41 func (c *Client) Manifest(ctx context.Context, pub []byte) (*manifest.Manifest, error) {
42 raw, err := c.get(ctx, c.Base+"/v1/manifest")
43 if err != nil {
44 return nil, err
45 }
46 if pub == nil {
47 var m manifest.Manifest
48 if err := json.Unmarshal(raw, &m); err != nil {
49 return nil, fmt.Errorf("fetch: manifest: %w", err)
50 }
51 return &m, nil
52 }
53 return manifest.Verify(raw, pub)
54 }
55 56 // Blocks fills a body store's heights [from,to) for a chain. It returns how
57 // many blocks it filed.
58 //
59 // It asks the service for the chunks covering the range rather than reading
60 // them from the manifest: the service cuts chunks from what it holds now, and
61 // the names it answers with are the ones it will serve.
62 func (c *Client) Blocks(ctx context.Context, chainName string, from, to uint32, bodies *store.BlockStore) (int, error) {
63 names, err := c.rangeNames(ctx, chainName, chunk.Blocks.String(), from, to)
64 if err != nil {
65 return 0, err
66 }
67 filed := 0
68 for _, name := range names {
69 raw, err := c.chunk(ctx, name)
70 if err != nil {
71 return filed, err
72 }
73 at := 0
74 for at < len(raw) {
75 if at+4 > len(raw) {
76 return filed, errors.New("fetch: a block length runs past its chunk")
77 }
78 n := int(binary.LittleEndian.Uint32(raw[at:]))
79 if at+4+n > len(raw) {
80 return filed, fmt.Errorf("fetch: a block of %d bytes runs past its chunk", n)
81 }
82 block := raw[at+4 : at+4+n]
83 at += 4 + n
84 h := serve.HeaderHash(block)
85 if err := bodies.PutBlock(h, block); err != nil && !errors.Is(err, store.ErrBlockExists) {
86 return filed, err
87 }
88 filed++
89 }
90 }
91 return filed, nil
92 }
93 94 // Records splits one chunk of length-prefixed records and calls fn for each.
95 // It is the reader a caller that wants blocks rather than a store uses.
96 func Records(raw []byte, fn func(block []byte)) error {
97 at := 0
98 for at < len(raw) {
99 if at+4 > len(raw) {
100 return errors.New("fetch: a length runs past its chunk")
101 }
102 n := int(binary.LittleEndian.Uint32(raw[at:]))
103 if at+4+n > len(raw) {
104 return fmt.Errorf("fetch: a record of %d bytes runs past its chunk", n)
105 }
106 fn(raw[at+4 : at+4+n])
107 at += 4 + n
108 }
109 return nil
110 }
111 112 func (c *Client) rangeNames(ctx context.Context, chainName, kind string, from, to uint32) ([]string, error) {
113 u := fmt.Sprintf("%s/v1/chains/%s/%s/%d-%d", c.Base, chainName, kind, from, to)
114 body, err := c.get(ctx, u)
115 if err != nil {
116 return nil, err
117 }
118 var listed struct {
119 Chunks []string `json:"chunks"`
120 }
121 if err := json.Unmarshal(body, &listed); err != nil {
122 return nil, fmt.Errorf("fetch: range answer: %w", err)
123 }
124 if len(listed.Chunks) == 0 {
125 return nil, errors.New("fetch: the range has no chunks")
126 }
127 return listed.Chunks, nil
128 }
129 130 func (c *Client) chunk(ctx context.Context, name string) ([]byte, error) {
131 return c.chunkAt(ctx, name, c.Base+"/v1/chunks/")
132 }
133 134 // chunkAt fetches a chunk by name from a prefix and checks the name.
135 func (c *Client) chunkAt(ctx context.Context, name, prefix string) ([]byte, error) {
136 raw, err := c.get(ctx, prefix+name)
137 if err != nil {
138 return nil, err
139 }
140 if got := chunk.Name(raw).String(); got != name {
141 return nil, fmt.Errorf("fetch: a chunk asked for as %s hashes to %s", name, got)
142 }
143 return raw, nil
144 }
145 146 func (c *Client) get(ctx context.Context, u string) ([]byte, error) {
147 h := c.HTTP
148 if h == nil {
149 h = &http.Client{Timeout: time.Minute}
150 }
151 req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
152 if err != nil {
153 return nil, err
154 }
155 resp, err := h.Do(req)
156 if err != nil {
157 return nil, err
158 }
159 defer resp.Body.Close()
160 body, err := io.ReadAll(io.LimitReader(resp.Body, 512<<20))
161 if err != nil {
162 return nil, err
163 }
164 if resp.StatusCode != http.StatusOK {
165 return nil, fmt.Errorf("fetch: %s: %d %s", u, resp.StatusCode, body)
166 }
167 if c.Logf != nil {
168 c.Logf("fetch: %s %d bytes", u, len(body))
169 }
170 return body, nil
171 }
172