1 package fetch
2 3 import (
4 "context"
5 "encoding/binary"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "os"
10 "path/filepath"
11 12 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
13 14 "git.smesh.lol/btcd-lite/internal/utxo"
15 utxostore "git.smesh.lol/btcd-lite/internal/utxo/store"
16 )
17 18 // UTXOSnapshot is one boundary of a checkpoint chain as the service lists it,
19 // with the name of the set at that height.
20 type UTXOSnapshot struct {
21 Height uint32 `json:"height"`
22 Name string `json:"name,omitempty"`
23 }
24 25 // UTXOManifest is the checkpoint chain a service lists.
26 type UTXOManifest struct {
27 Chain string `json:"chain"`
28 Base uint32 `json:"base"`
29 Tip uint32 `json:"tip"`
30 Interval uint32 `json:"interval"`
31 Snapshots []UTXOSnapshot `json:"snapshots"`
32 }
33 34 // DiffsPerRequest is how many per-block diffs one request carries. It is the
35 // chunk of a hundred the plan names.
36 const DiffsPerRequest = 100
37 38 // UTXO fetches one chain's checkpoint chain into dir and returns how many
39 // snapshots it reached, counting the base.
40 //
41 // It fetches the base set, then the per-block diffs in chunks, applying each one
42 // and writing the set at every snapshot height. The names it computes are
43 // checked against the manifest's, so a diff the server got wrong is caught at
44 // the next boundary rather than trusted.
45 //
46 // The set is held in memory between snapshots. That is the bound on this side of
47 // the contract: a client that wants a height between two snapshots applies at
48 // most one epoch's diffs, and an epoch of a large chain's set is not small.
49 func (c *Client) UTXO(ctx context.Context, chainName, dir string) (int, error) {
50 urlBase := c.Base + "/v1/utxo/" + chainName
51 body, err := c.get(ctx, urlBase+"/manifest")
52 if err != nil {
53 return 0, err
54 }
55 var m UTXOManifest
56 if err := json.Unmarshal(body, &m); err != nil {
57 return 0, fmt.Errorf("fetch: utxo manifest: %w", err)
58 }
59 if len(m.Snapshots) == 0 {
60 return 0, errors.New("fetch: the manifest lists no snapshots")
61 }
62 if err := os.MkdirAll(dir, 0o755); err != nil {
63 return 0, err
64 }
65 base := m.Snapshots[0]
66 raw, err := c.get(ctx, fmt.Sprintf("%s/snapshot/%d", urlBase, base.Height))
67 if err != nil {
68 return 0, err
69 }
70 if base.Name != "" {
71 if got := chainhash.DoubleHashH(raw).String(); got != base.Name {
72 return 0, fmt.Errorf("fetch: the base set hashes to %s, the manifest says %s", got, base.Name)
73 }
74 }
75 if len(raw)%utxostore.EntrySize != 0 {
76 return 0, fmt.Errorf("fetch: the base set is %d bytes, not a whole number of entries", len(raw))
77 }
78 set := decodeEntries(raw)
79 if err := os.WriteFile(filepath.Join(dir, utxostore.SetFile(base.Height)), raw, 0o644); err != nil {
80 return 0, err
81 }
82 reached := 1
83 // One epoch at a time, in chunks of a hundred diffs: a run cannot cross a
84 // snapshot, and the snapshot is where the name is checked.
85 for i := 1; i < len(m.Snapshots); i++ {
86 prev, next := m.Snapshots[i-1], m.Snapshots[i]
87 for from := prev.Height + 1; from <= next.Height; from += DiffsPerRequest {
88 to := min(from+DiffsPerRequest, next.Height+1)
89 run, err := c.get(ctx, fmt.Sprintf("%s/diffs/%d-%d", urlBase, from, to))
90 if err != nil {
91 return reached, err
92 }
93 if set, err = applyRun(set, run); err != nil {
94 return reached, err
95 }
96 }
97 got := utxostore.NameOf(set)
98 if next.Name != "" && got.String() != next.Name {
99 return reached, fmt.Errorf("fetch: the set at %d hashes to %s, the manifest says %s", next.Height, got, next.Name)
100 }
101 if _, err := utxostore.WriteSetFile(dir, next.Height, set); err != nil {
102 return reached, err
103 }
104 reached++
105 }
106 return reached, nil
107 }
108 109 // applyRun applies one run of length-prefixed per-block diffs to a set.
110 func applyRun(set []utxo.Entry, run []byte) ([]utxo.Entry, error) {
111 at := 0
112 for at < len(run) {
113 if at+4 > len(run) {
114 return nil, errors.New("fetch: a diff length runs past its run")
115 }
116 n := int(binary.LittleEndian.Uint32(run[at:]))
117 if at+4+n > len(run) {
118 return nil, fmt.Errorf("fetch: a diff of %d bytes runs past its run", n)
119 }
120 d, err := utxo.DecodeDiff(run[at+4 : at+4+n])
121 if err != nil {
122 return nil, fmt.Errorf("fetch: diff at %d: %w", at, err)
123 }
124 at += 4 + n
125 if set, err = d.ApplyTo(set); err != nil {
126 return nil, fmt.Errorf("fetch: diff %d..%d: %w", d.From, d.To, err)
127 }
128 }
129 return set, nil
130 }
131 132 // decodeEntries reads a set file's entries.
133 func decodeEntries(raw []byte) []utxo.Entry {
134 out := make([]utxo.Entry, 0, len(raw)/utxostore.EntrySize)
135 buf := make([]byte, utxostore.EntrySize)
136 for i := 0; i+utxostore.EntrySize <= len(raw); i += utxostore.EntrySize {
137 copy(buf, raw[i:i+utxostore.EntrySize])
138 out = append(out, utxo.Decode(buf))
139 }
140 return out
141 }
142