// Package fetch fills an instance from another instance's service. // // It is the client half of the seeding path: read the manifest, check its // signature against the key the operator pinned, ask for the chunks that cover // a range, and verify every chunk against the name it was asked for before a // block goes into the store. A serving instance can refuse to answer and can // answer late; it cannot hand over bytes that pass under a name they do not // hash to. package fetch import ( "context" "encoding/binary" "encoding/json" "errors" "fmt" "io" "net/http" "time" "git.smesh.lol/btcd-lite/internal/chunk" "git.smesh.lol/btcd-lite/internal/manifest" "git.smesh.lol/btcd-lite/internal/serve" "git.smesh.lol/btcd-lite/internal/store" ) // Client fills from one service. type Client struct { // Base is the service's URL, without a trailing slash. Base string // HTTP is the transport; nil means a client with a one-minute timeout. HTTP *http.Client // Logf receives one line per request; nil discards them. Logf func(string, ...any) } // Manifest reads the service's manifest and, when pub is not nil, requires its // signature to verify against pub. A client that pins no key accepts an // unsigned manifest; every chunk it downloads is still checked against its // name, so no key changes whether wrong bytes are refused. func (c *Client) Manifest(ctx context.Context, pub []byte) (*manifest.Manifest, error) { raw, err := c.get(ctx, c.Base+"/v1/manifest") if err != nil { return nil, err } if pub == nil { var m manifest.Manifest if err := json.Unmarshal(raw, &m); err != nil { return nil, fmt.Errorf("fetch: manifest: %w", err) } return &m, nil } return manifest.Verify(raw, pub) } // Blocks fills a body store's heights [from,to) for a chain. It returns how // many blocks it filed. // // It asks the service for the chunks covering the range rather than reading // them from the manifest: the service cuts chunks from what it holds now, and // the names it answers with are the ones it will serve. func (c *Client) Blocks(ctx context.Context, chainName string, from, to uint32, bodies *store.BlockStore) (int, error) { names, err := c.rangeNames(ctx, chainName, chunk.Blocks.String(), from, to) if err != nil { return 0, err } filed := 0 for _, name := range names { raw, err := c.chunk(ctx, name) if err != nil { return filed, err } at := 0 for at < len(raw) { if at+4 > len(raw) { return filed, errors.New("fetch: a block length runs past its chunk") } n := int(binary.LittleEndian.Uint32(raw[at:])) if at+4+n > len(raw) { return filed, fmt.Errorf("fetch: a block of %d bytes runs past its chunk", n) } block := raw[at+4 : at+4+n] at += 4 + n h := serve.HeaderHash(block) if err := bodies.PutBlock(h, block); err != nil && !errors.Is(err, store.ErrBlockExists) { return filed, err } filed++ } } return filed, nil } // Records splits one chunk of length-prefixed records and calls fn for each. // It is the reader a caller that wants blocks rather than a store uses. func Records(raw []byte, fn func(block []byte)) error { at := 0 for at < len(raw) { if at+4 > len(raw) { return errors.New("fetch: a length runs past its chunk") } n := int(binary.LittleEndian.Uint32(raw[at:])) if at+4+n > len(raw) { return fmt.Errorf("fetch: a record of %d bytes runs past its chunk", n) } fn(raw[at+4 : at+4+n]) at += 4 + n } return nil } func (c *Client) rangeNames(ctx context.Context, chainName, kind string, from, to uint32) ([]string, error) { u := fmt.Sprintf("%s/v1/chains/%s/%s/%d-%d", c.Base, chainName, kind, from, to) body, err := c.get(ctx, u) if err != nil { return nil, err } var listed struct { Chunks []string `json:"chunks"` } if err := json.Unmarshal(body, &listed); err != nil { return nil, fmt.Errorf("fetch: range answer: %w", err) } if len(listed.Chunks) == 0 { return nil, errors.New("fetch: the range has no chunks") } return listed.Chunks, nil } func (c *Client) chunk(ctx context.Context, name string) ([]byte, error) { return c.chunkAt(ctx, name, c.Base+"/v1/chunks/") } // chunkAt fetches a chunk by name from a prefix and checks the name. func (c *Client) chunkAt(ctx context.Context, name, prefix string) ([]byte, error) { raw, err := c.get(ctx, prefix+name) if err != nil { return nil, err } if got := chunk.Name(raw).String(); got != name { return nil, fmt.Errorf("fetch: a chunk asked for as %s hashes to %s", name, got) } return raw, nil } func (c *Client) get(ctx context.Context, u string) ([]byte, error) { h := c.HTTP if h == nil { h = &http.Client{Timeout: time.Minute} } req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) if err != nil { return nil, err } resp, err := h.Do(req) if err != nil { return nil, err } defer resp.Body.Close() body, err := io.ReadAll(io.LimitReader(resp.Body, 512<<20)) if err != nil { return nil, err } if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("fetch: %s: %d %s", u, resp.StatusCode, body) } if c.Logf != nil { c.Logf("fetch: %s %d bytes", u, len(body)) } return body, nil }