1 package serve
2 3 import (
4 "context"
5 "fmt"
6 7 "git.smesh.lol/nostrino/pkg/btcwire"
8 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
9 )
10 11 // HeaderSource returns neutrino's header source for one chain of this view.
12 //
13 // One call answers one window. A height the chain does not hold ends the
14 // answer: that is how a source says "nothing more from me", and the client
15 // goes to its peer for the rest. Nothing is trusted because it came from here:
16 // every header a source supplies goes through the same proof-of-work and parent
17 // checks as a peer's.
18 //
19 // The headers come from the chain's header store and not from the bodies: a
20 // client syncing headers wants the chain this instance verified, which exists
21 // before the bodies do.
22 func (v *View) HeaderSource(chainName string) func(context.Context, uint32, uint32) ([]btcwire.BlockHeader, error) {
23 return func(ctx context.Context, from, to uint32) ([]btcwire.BlockHeader, error) {
24 headers, ok := v.Headers[chainName]
25 if !ok {
26 return nil, fmt.Errorf("serve: this instance holds no chain %q", chainName)
27 }
28 var out []btcwire.BlockHeader
29 for h := from; h <= to; h++ {
30 hdr, ok := headers.Header(h)
31 if !ok {
32 break
33 }
34 out = append(out, hdr)
35 }
36 return out, nil
37 }
38 }
39 40 // BlockSource returns neutrino's block source over this view: a body by hash.
41 //
42 // The body store is keyed by hash, so the answer needs no chain and no height:
43 // the hash is the name. A body the store does not hold is not answered and the
44 // client falls back to its peer. Nothing here is trusted: the client checks the
45 // body against the header it already accepted, so a wrong body costs a refused
46 // block and not a wrong chain.
47 func (v *View) BlockSource() func(context.Context, chainhash.Hash) ([]byte, error) {
48 return func(ctx context.Context, hash chainhash.Hash) ([]byte, error) {
49 if v.Bodies == nil {
50 return nil, fmt.Errorf("serve: this view holds no blocks")
51 }
52 raw, err := v.Bodies.GetBlock(hash)
53 if err != nil {
54 return nil, fmt.Errorf("serve: %w", err)
55 }
56 return raw, nil
57 }
58 }
59