backup_test.go raw
1 package e2e
2
3 import (
4 "bytes"
5 "context"
6 "errors"
7 "net"
8 "testing"
9 "time"
10
11 "git.smesh.lol/nostrino/pkg/backup"
12 "git.smesh.lol/nostrino/pkg/btcwire"
13 "git.smesh.lol/nostrino/pkg/chain"
14 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
15 "git.smesh.lol/nostrino/pkg/neutrino"
16 )
17
18 // backupApplier adapts a light client to the backup format: the chunks carry bytes, and the
19 // client is what decides whether those bytes describe the chain it holds.
20 type backupApplier struct {
21 client *neutrino.Client
22 }
23
24 func (a backupApplier) ApplyHeaders(from uint32, headers []btcwire.BlockHeader) (int, error) {
25 return a.client.ApplyHeaders(from, headers)
26 }
27
28 func (a backupApplier) ApplyFilterHeaders(from uint32, hashes, headers []chainhash.Hash) (int, error) {
29 return a.client.ApplyFilterHeaders(from, hashes, headers)
30 }
31
32 func (a backupApplier) ApplyFilters(records []backup.FilterRecord) (int, error) {
33 proofs := make([]neutrino.FilterProof, 0, len(records))
34
35 for _, record := range records {
36 proofs = append(proofs, neutrino.FilterProof{
37 Height: record.Height,
38 BlockHash: record.BlockHash,
39 FilterHash: record.FilterHash,
40 Filter: record.Filter,
41 })
42 }
43
44 return a.client.ApplyFilters(proofs)
45 }
46
47 // exportChain writes a manifest and its chunks for a synced store, which is what the page does
48 // one chunk at a time.
49 func exportChain(t *testing.T, store neutrino.Store, anchor neutrino.Anchor) (backup.Manifest, map[string][]byte) {
50 t.Helper()
51
52 files := map[string][]byte{}
53 chunks := []backup.ChunkInfo{}
54
55 add := func(chunk backup.Chunk, err error) {
56 if err != nil {
57 t.Fatal(err)
58 }
59
60 raw, err := backup.Encode(chunk)
61
62 if err != nil {
63 t.Fatal(err)
64 }
65
66 info := backup.ChunkInfo{
67 File: backup.ChunkFile(chunk.Kind, chunk.From),
68 Kind: chunk.Kind,
69 From: chunk.From,
70 Count: chunk.Count,
71 Bytes: uint64(len(raw)),
72 SHA256: backup.Sum(raw),
73 }
74
75 if _, repeated := files[info.File]; repeated {
76 t.Fatalf("%s was written twice", info.File)
77 }
78
79 files[info.File] = raw
80 chunks = append(chunks, info)
81 }
82
83 tip, _, _ := store.HeaderTip()
84 filterTip, _ := store.FilterTip()
85
86 if filterTip < tip {
87 tip = filterTip
88 }
89
90 // Headers begin above the anchor. Filter headers begin where the filter header chain does:
91 // one above the anchor's filter height, which is zero for an anchor that trusts none.
92 filterFrom := uint32(0)
93
94 if anchor.FilterHeight >= 0 {
95 filterFrom = uint32(anchor.FilterHeight) + 1
96 }
97
98 // Exports in small pieces so the test exercises more than one chunk of each kind.
99 for height := anchor.Height + 1; height <= tip; height += 5 {
100 last := height + 4
101
102 if last > tip {
103 last = tip
104 }
105
106 add(backup.ExportHeaders(store, height, last-height+1))
107 }
108
109 for height := filterFrom; height <= tip; height += 5 {
110 last := height + 4
111
112 if last > tip {
113 last = tip
114 }
115
116 add(backup.ExportFilterHeaders(store, height, last-height+1))
117 }
118
119 for height := filterFrom; height <= tip; {
120 chunk, err := backup.ExportFilters(store, height, tip-height+1, 3*1024)
121
122 if err != nil {
123 t.Fatal(err)
124 }
125
126 add(chunk, nil)
127
128 height = chunk.From + chunk.Count
129 }
130
131 filterBytes := uint64(0)
132
133 for _, chunk := range chunks {
134 if chunk.Kind == backup.Filters {
135 filterBytes += chunk.Bytes
136 }
137 }
138
139 chainBackup := backup.Chain{
140 Name: "btc", Network: chain.Regtest.Name,
141 Anchor: backup.Anchor{
142 Height: anchor.Height,
143 BlockHash: anchor.BlockHash.String(),
144 FilterHeader: anchor.FilterHeader.String(),
145 },
146 HeaderFrom: anchor.Height + 1,
147 FilterFrom: filterFrom,
148 Tip: tip,
149 Headers: tip - anchor.Height,
150 FilterHeaders: tip - filterFrom + 1,
151 Filters: tip - filterFrom + 1,
152 FilterBytes: filterBytes,
153 Chunks: chunks,
154 }
155
156 manifest := backup.Manifest{Version: backup.Version, Created: time.Now().UTC(), Chains: []backup.Chain{chainBackup}}
157
158 raw, err := backup.Marshal(manifest)
159
160 if err != nil {
161 t.Fatalf("manifest: %v", err)
162 }
163
164 files[backup.ManifestName] = raw
165
166 return manifest, files
167 }
168
169 // TestABackupRestoresAVerifiedChain: a synced store's headers, filter headers and filters
170 // survive a trip through the backup format into a fresh store, and a damaged chunk is refused
171 // by the checks rather than accepted into the chain.
172 func TestABackupRestoresAVerifiedChain(t *testing.T) {
173 h := newHarness(t, 24)
174
175 source := neutrino.NewMemory()
176 client := h.client(t, source)
177
178 ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
179 defer cancel()
180
181 if _, err := client.Sync(ctx); err != nil {
182 t.Fatalf("sync: %v", err)
183 }
184
185 anchor, ok := source.Anchor()
186
187 if !ok {
188 t.Fatal("the synced store has no anchor")
189 }
190
191 _, files := exportChain(t, source, anchor)
192
193 parsed, err := backup.Parse(files[backup.ManifestName])
194
195 if err != nil {
196 t.Fatalf("the manifest does not parse: %v", err)
197 }
198
199 // A fresh store, seeded the way a first sync would seed it: the profile's anchor and
200 // genesis header. Everything above height 0 arrives from the backup.
201 restored := neutrino.NewMemory()
202
203 if err := restored.SetAnchor(anchor); err != nil {
204 t.Fatal(err)
205 }
206
207 if err := restored.PutHeaders(0, []btcwire.BlockHeader{chain.Regtest.GenesisHeader}); err != nil {
208 t.Fatal(err)
209 }
210
211 target, err := neutrino.New(neutrino.Config{
212 Profile: &chain.Regtest,
213 Store: restored,
214 // Verifying a backup needs no peer: the checks are against the store.
215 Dial: func(context.Context) (net.Conn, error) {
216 return nil, errors.New("backup: no peer")
217 },
218 })
219
220 if err != nil {
221 t.Fatal(err)
222 }
223
224 applier := backupApplier{client: target}
225 chainBackup := parsed.Chains[0]
226
227 // Kinds in dependency order: filters need the headers and the filter header chain.
228 for _, kind := range []backup.Kind{backup.Headers, backup.FilterHeaders, backup.Filters} {
229 for _, info := range chainBackup.Chunks {
230 if info.Kind != kind {
231 continue
232 }
233
234 chunk, err := backup.VerifyChunk(info, files[info.File])
235
236 if err != nil {
237 t.Fatalf("%s: %v", info.File, err)
238 }
239
240 accepted, err := backup.ImportChunk(applier, chunk)
241
242 if err != nil {
243 t.Fatalf("%s: %v", info.File, err)
244 }
245
246 if accepted != int(info.Count) {
247 t.Fatalf("%s: accepted %d of %d records", info.File, accepted, info.Count)
248 }
249 }
250 }
251
252 // The restored store holds the same chain, byte for byte.
253 if tip, _, ok := restored.HeaderTip(); !ok || tip != chainBackup.Tip {
254 t.Fatalf("restored tip %d, want %d", tip, chainBackup.Tip)
255 }
256
257 for height := uint32(1); height <= chainBackup.Tip; height++ {
258 want, ok := source.Filter(height)
259
260 if !ok {
261 t.Fatalf("the source has no filter at %d", height)
262 }
263
264 got, ok := restored.Filter(height)
265
266 if !ok {
267 t.Fatalf("the restored store has no filter at %d", height)
268 }
269
270 if !bytes.Equal(got, want) {
271 t.Fatalf("filter %d differs after the restore", height)
272 }
273 }
274
275 // And the wallet's own scan sees the same coin-bearing block.
276 matches, err := neutrino.MatchStoredScripts(restored, 0, 0, [][]byte{h.node.Script(7)})
277
278 if err != nil {
279 t.Fatal(err)
280 }
281
282 if len(matches) != 1 || matches[0] != 7 {
283 t.Fatalf("restored matches %v, want [7]", matches)
284 }
285
286 // A filter chunk whose bytes were edited fails its hash check.
287 filterInfo := firstChunk(t, chainBackup, backup.Filters)
288 filterRaw := append([]byte(nil), files[filterInfo.File]...)
289 filterRaw[len(filterRaw)-1] ^= 0xff
290
291 // The manifest digest catches it before the chain checks even run.
292 if _, err := backup.VerifyChunk(filterInfo, filterRaw); err == nil {
293 t.Fatal("a chunk that does not match its digest was accepted")
294 }
295
296 // With a matching digest but edited bytes — the case a hostile manifest would present —
297 // the chain checks refuse it: the filter no longer hashes to the committed value.
298 forged := make([]byte, len(filterRaw))
299 copy(forged, filterRaw)
300
301 edited, err := backup.Decode(forged)
302
303 if err != nil {
304 t.Fatalf("the edited chunk no longer decodes: %v", err)
305 }
306
307 if _, err := backup.ImportChunk(applier, edited); err == nil {
308 t.Fatal("a filter that does not hash to its commitment was accepted")
309 }
310
311 // A header that fails the chain's checks is refused too. The store that already holds
312 // the chain would skip it as a covered height, so the edited chunk goes into a fresh
313 // one: the claim being tested is that a backup cannot introduce a header the chain
314 // would not have accepted from a peer.
315 fresh := neutrino.NewMemory()
316
317 if err := fresh.SetAnchor(anchor); err != nil {
318 t.Fatal(err)
319 }
320
321 if err := fresh.PutHeaders(0, []btcwire.BlockHeader{chain.Regtest.GenesisHeader}); err != nil {
322 t.Fatal(err)
323 }
324
325 freshClient, err := neutrino.New(neutrino.Config{
326 Profile: &chain.Regtest, Store: fresh,
327 Dial: func(context.Context) (net.Conn, error) {
328 return nil, errors.New("backup: no peer")
329 },
330 })
331
332 if err != nil {
333 t.Fatal(err)
334 }
335
336 headerInfo := firstChunk(t, chainBackup, backup.Headers)
337 headerRaw := append([]byte(nil), files[headerInfo.File]...)
338 headerRaw[20] ^= 0xff // inside the first header's merkle root
339
340 editedHeader, err := backup.Decode(headerRaw)
341
342 if err != nil {
343 t.Fatalf("the edited header chunk no longer decodes: %v", err)
344 }
345
346 if _, err := backup.ImportChunk(backupApplier{client: freshClient}, editedHeader); err == nil {
347 t.Fatal("a header that the chain does not verify was accepted")
348 }
349 }
350
351 // firstChunk returns the first chunk of a kind.
352 func firstChunk(t *testing.T, chainBackup backup.Chain, kind backup.Kind) backup.ChunkInfo {
353 t.Helper()
354
355 for _, info := range chainBackup.Chunks {
356 if info.Kind == kind {
357 return info
358 }
359 }
360
361 t.Fatalf("the backup has no %s chunk", kind)
362
363 return backup.ChunkInfo{}
364 }
365