1 // Package process turns a fill's staging log into stored blocks.
2 //
3 // It is the second half of the split the plan makes: the download writes bytes
4 // it has not checked to a log nothing serves, and this pass hashes each body
5 // against the claim the downloader made and against the header chain at that
6 // height. Only a body that passes both becomes a stored block. A body that
7 // fails is dropped and its height is written down, and the next fill asks for
8 // it again because a height with no block is a height its walk visits.
9 //
10 // It is the only reader of the staging log. Nothing that serves data reads it,
11 // which is the property the split rests on: unverified bytes are not reachable
12 // from any serving path.
13 package process
14 15 import (
16 "errors"
17 "fmt"
18 "os"
19 "path/filepath"
20 21 "git.smesh.lol/btcd-lite/internal/serve"
22 "git.smesh.lol/btcd-lite/internal/staging"
23 "git.smesh.lol/btcd-lite/internal/store"
24 )
25 26 // Config is what a processing pass reads from and writes to.
27 type Config struct {
28 // Chain names the pass in the log lines and selects the header store's
29 // height-to-hash answers. It is not used to file anything: bodies are
30 // filed by hash.
31 Chain string
32 // Staging is the log the download wrote.
33 Staging *staging.Log
34 // Bodies is where a body that passes goes.
35 Bodies *store.BlockStore
36 // Headers is the chain's header store, the authority for height to hash.
37 Headers *store.HeaderStore
38 // Missing, when set, is where a dropped height is recorded: one line per
39 // drop, appended.
40 Missing string
41 // Logf receives diagnostics; nil discards them.
42 Logf func(string, ...any)
43 }
44 45 // Result is what a pass did.
46 type Result struct {
47 // Kept is the number of bodies now stored.
48 Kept int
49 // Dropped is the number of bodies refused.
50 Dropped int
51 // Failed lists the heights whose bodies were refused, in claim order.
52 Failed []uint32
53 // Bytes is how much the pass read from the log.
54 Bytes int64
55 }
56 57 // ErrNoHeader is a claim at a height the chain does not have.
58 var ErrNoHeader = errors.New("process: the header chain has no such height")
59 60 // Run walks the log, checks every body against its claim and its header, files
61 // the ones that pass and drains the log.
62 //
63 // A failed body does not stop the pass: one bad answer from one peer is not a
64 // reason to throw away the rest of a fill. The pass is idempotent per body, so
65 // a rerun after a crash stores what was already stored without complaint.
66 func Run(cfg Config) (Result, error) {
67 if cfg.Staging == nil || cfg.Bodies == nil || cfg.Headers == nil {
68 return Result{}, errors.New("process: staging, bodies and headers are required")
69 }
70 if cfg.Logf == nil {
71 cfg.Logf = func(string, ...any) {}
72 }
73 var res Result
74 var missing []byte
75 err := cfg.Staging.Walk(func(c staging.Claim, body []byte) error {
76 res.Bytes += int64(len(body))
77 reason := cfg.check(c, body)
78 if reason != "" {
79 res.Dropped++
80 res.Failed = append(res.Failed, c.Height)
81 cfg.Logf("process %s: height %d dropped: %s", cfg.Chain, c.Height, reason)
82 if cfg.Missing != "" {
83 missing = append(missing, fmt.Sprintf("%s %d %s %s\n", cfg.Chain, c.Height, c.Hash, reason)...)
84 }
85 return nil
86 }
87 if err := cfg.Bodies.PutBlock(c.Hash, body); err != nil {
88 if errors.Is(err, store.ErrBlockExists) {
89 res.Kept++
90 return nil
91 }
92 return fmt.Errorf("process: store height %d: %w", c.Height, err)
93 }
94 res.Kept++
95 return nil
96 })
97 if err != nil {
98 return res, err
99 }
100 if len(missing) > 0 && cfg.Missing != "" {
101 if err := os.MkdirAll(filepath.Dir(cfg.Missing), 0o755); err != nil {
102 return res, err
103 }
104 f, err := os.OpenFile(cfg.Missing, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
105 if err != nil {
106 return res, fmt.Errorf("process: %w", err)
107 }
108 if _, err := f.Write(missing); err != nil {
109 f.Close()
110 return res, fmt.Errorf("process: %w", err)
111 }
112 if err := f.Close(); err != nil {
113 return res, fmt.Errorf("process: %w", err)
114 }
115 }
116 if err := cfg.Staging.Drain(); err != nil {
117 return res, err
118 }
119 cfg.Logf("process %s: %d bodies kept, %d dropped, %d bytes read", cfg.Chain, res.Kept, res.Dropped, res.Bytes)
120 return res, nil
121 }
122 123 // check returns why a body cannot be stored, or the empty string.
124 func (cfg Config) check(c staging.Claim, body []byte) string {
125 got := serve.HeaderHash(body)
126 if got != c.Hash {
127 return fmt.Sprintf("the body hashes to %s, the claim %s", got, c.Hash)
128 }
129 hdr, ok := cfg.Headers.Header(c.Height)
130 if !ok {
131 return ErrNoHeader.Error()
132 }
133 if got := hdr.BlockHash(); got != c.Hash {
134 return fmt.Sprintf("height %d is %s on the chain, the claim %s", c.Height, got, c.Hash)
135 }
136 return ""
137 }
138 139 // MissingName is the file a dropped height is recorded in, under an instance's
140 // blocks directory.
141 func MissingName(data, chainName string) string {
142 return filepath.Join(data, "blocks", "missing", chainName+".log")
143 }
144