package e2e import ( "bytes" "context" "errors" "net" "testing" "time" "git.smesh.lol/nostrino/pkg/backup" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/chain" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/nostrino/pkg/neutrino" ) // backupApplier adapts a light client to the backup format: the chunks carry bytes, and the // client is what decides whether those bytes describe the chain it holds. type backupApplier struct { client *neutrino.Client } func (a backupApplier) ApplyHeaders(from uint32, headers []btcwire.BlockHeader) (int, error) { return a.client.ApplyHeaders(from, headers) } func (a backupApplier) ApplyFilterHeaders(from uint32, hashes, headers []chainhash.Hash) (int, error) { return a.client.ApplyFilterHeaders(from, hashes, headers) } func (a backupApplier) ApplyFilters(records []backup.FilterRecord) (int, error) { proofs := make([]neutrino.FilterProof, 0, len(records)) for _, record := range records { proofs = append(proofs, neutrino.FilterProof{ Height: record.Height, BlockHash: record.BlockHash, FilterHash: record.FilterHash, Filter: record.Filter, }) } return a.client.ApplyFilters(proofs) } // exportChain writes a manifest and its chunks for a synced store, which is what the page does // one chunk at a time. func exportChain(t *testing.T, store neutrino.Store, anchor neutrino.Anchor) (backup.Manifest, map[string][]byte) { t.Helper() files := map[string][]byte{} chunks := []backup.ChunkInfo{} add := func(chunk backup.Chunk, err error) { if err != nil { t.Fatal(err) } raw, err := backup.Encode(chunk) if err != nil { t.Fatal(err) } info := backup.ChunkInfo{ File: backup.ChunkFile(chunk.Kind, chunk.From), Kind: chunk.Kind, From: chunk.From, Count: chunk.Count, Bytes: uint64(len(raw)), SHA256: backup.Sum(raw), } if _, repeated := files[info.File]; repeated { t.Fatalf("%s was written twice", info.File) } files[info.File] = raw chunks = append(chunks, info) } tip, _, _ := store.HeaderTip() filterTip, _ := store.FilterTip() if filterTip < tip { tip = filterTip } // Headers begin above the anchor. Filter headers begin where the filter header chain does: // one above the anchor's filter height, which is zero for an anchor that trusts none. filterFrom := uint32(0) if anchor.FilterHeight >= 0 { filterFrom = uint32(anchor.FilterHeight) + 1 } // Exports in small pieces so the test exercises more than one chunk of each kind. for height := anchor.Height + 1; height <= tip; height += 5 { last := height + 4 if last > tip { last = tip } add(backup.ExportHeaders(store, height, last-height+1)) } for height := filterFrom; height <= tip; height += 5 { last := height + 4 if last > tip { last = tip } add(backup.ExportFilterHeaders(store, height, last-height+1)) } for height := filterFrom; height <= tip; { chunk, err := backup.ExportFilters(store, height, tip-height+1, 3*1024) if err != nil { t.Fatal(err) } add(chunk, nil) height = chunk.From + chunk.Count } filterBytes := uint64(0) for _, chunk := range chunks { if chunk.Kind == backup.Filters { filterBytes += chunk.Bytes } } chainBackup := backup.Chain{ Name: "btc", Network: chain.Regtest.Name, Anchor: backup.Anchor{ Height: anchor.Height, BlockHash: anchor.BlockHash.String(), FilterHeader: anchor.FilterHeader.String(), }, HeaderFrom: anchor.Height + 1, FilterFrom: filterFrom, Tip: tip, Headers: tip - anchor.Height, FilterHeaders: tip - filterFrom + 1, Filters: tip - filterFrom + 1, FilterBytes: filterBytes, Chunks: chunks, } manifest := backup.Manifest{Version: backup.Version, Created: time.Now().UTC(), Chains: []backup.Chain{chainBackup}} raw, err := backup.Marshal(manifest) if err != nil { t.Fatalf("manifest: %v", err) } files[backup.ManifestName] = raw return manifest, files } // TestABackupRestoresAVerifiedChain: a synced store's headers, filter headers and filters // survive a trip through the backup format into a fresh store, and a damaged chunk is refused // by the checks rather than accepted into the chain. func TestABackupRestoresAVerifiedChain(t *testing.T) { h := newHarness(t, 24) source := neutrino.NewMemory() client := h.client(t, source) ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) defer cancel() if _, err := client.Sync(ctx); err != nil { t.Fatalf("sync: %v", err) } anchor, ok := source.Anchor() if !ok { t.Fatal("the synced store has no anchor") } _, files := exportChain(t, source, anchor) parsed, err := backup.Parse(files[backup.ManifestName]) if err != nil { t.Fatalf("the manifest does not parse: %v", err) } // A fresh store, seeded the way a first sync would seed it: the profile's anchor and // genesis header. Everything above height 0 arrives from the backup. restored := neutrino.NewMemory() if err := restored.SetAnchor(anchor); err != nil { t.Fatal(err) } if err := restored.PutHeaders(0, []btcwire.BlockHeader{chain.Regtest.GenesisHeader}); err != nil { t.Fatal(err) } target, err := neutrino.New(neutrino.Config{ Profile: &chain.Regtest, Store: restored, // Verifying a backup needs no peer: the checks are against the store. Dial: func(context.Context) (net.Conn, error) { return nil, errors.New("backup: no peer") }, }) if err != nil { t.Fatal(err) } applier := backupApplier{client: target} chainBackup := parsed.Chains[0] // Kinds in dependency order: filters need the headers and the filter header chain. for _, kind := range []backup.Kind{backup.Headers, backup.FilterHeaders, backup.Filters} { for _, info := range chainBackup.Chunks { if info.Kind != kind { continue } chunk, err := backup.VerifyChunk(info, files[info.File]) if err != nil { t.Fatalf("%s: %v", info.File, err) } accepted, err := backup.ImportChunk(applier, chunk) if err != nil { t.Fatalf("%s: %v", info.File, err) } if accepted != int(info.Count) { t.Fatalf("%s: accepted %d of %d records", info.File, accepted, info.Count) } } } // The restored store holds the same chain, byte for byte. if tip, _, ok := restored.HeaderTip(); !ok || tip != chainBackup.Tip { t.Fatalf("restored tip %d, want %d", tip, chainBackup.Tip) } for height := uint32(1); height <= chainBackup.Tip; height++ { want, ok := source.Filter(height) if !ok { t.Fatalf("the source has no filter at %d", height) } got, ok := restored.Filter(height) if !ok { t.Fatalf("the restored store has no filter at %d", height) } if !bytes.Equal(got, want) { t.Fatalf("filter %d differs after the restore", height) } } // And the wallet's own scan sees the same coin-bearing block. matches, err := neutrino.MatchStoredScripts(restored, 0, 0, [][]byte{h.node.Script(7)}) if err != nil { t.Fatal(err) } if len(matches) != 1 || matches[0] != 7 { t.Fatalf("restored matches %v, want [7]", matches) } // A filter chunk whose bytes were edited fails its hash check. filterInfo := firstChunk(t, chainBackup, backup.Filters) filterRaw := append([]byte(nil), files[filterInfo.File]...) filterRaw[len(filterRaw)-1] ^= 0xff // The manifest digest catches it before the chain checks even run. if _, err := backup.VerifyChunk(filterInfo, filterRaw); err == nil { t.Fatal("a chunk that does not match its digest was accepted") } // With a matching digest but edited bytes — the case a hostile manifest would present — // the chain checks refuse it: the filter no longer hashes to the committed value. forged := make([]byte, len(filterRaw)) copy(forged, filterRaw) edited, err := backup.Decode(forged) if err != nil { t.Fatalf("the edited chunk no longer decodes: %v", err) } if _, err := backup.ImportChunk(applier, edited); err == nil { t.Fatal("a filter that does not hash to its commitment was accepted") } // A header that fails the chain's checks is refused too. The store that already holds // the chain would skip it as a covered height, so the edited chunk goes into a fresh // one: the claim being tested is that a backup cannot introduce a header the chain // would not have accepted from a peer. fresh := neutrino.NewMemory() if err := fresh.SetAnchor(anchor); err != nil { t.Fatal(err) } if err := fresh.PutHeaders(0, []btcwire.BlockHeader{chain.Regtest.GenesisHeader}); err != nil { t.Fatal(err) } freshClient, err := neutrino.New(neutrino.Config{ Profile: &chain.Regtest, Store: fresh, Dial: func(context.Context) (net.Conn, error) { return nil, errors.New("backup: no peer") }, }) if err != nil { t.Fatal(err) } headerInfo := firstChunk(t, chainBackup, backup.Headers) headerRaw := append([]byte(nil), files[headerInfo.File]...) headerRaw[20] ^= 0xff // inside the first header's merkle root editedHeader, err := backup.Decode(headerRaw) if err != nil { t.Fatalf("the edited header chunk no longer decodes: %v", err) } if _, err := backup.ImportChunk(backupApplier{client: freshClient}, editedHeader); err == nil { t.Fatal("a header that the chain does not verify was accepted") } } // firstChunk returns the first chunk of a kind. func firstChunk(t *testing.T, chainBackup backup.Chain, kind backup.Kind) backup.ChunkInfo { t.Helper() for _, info := range chainBackup.Chunks { if info.Kind == kind { return info } } t.Fatalf("the backup has no %s chunk", kind) return backup.ChunkInfo{} }