package gate import ( "encoding/hex" "errors" "io" "net/http" "net/http/httptest" "path/filepath" "testing" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/nostrino/pkg/neutrino" "git.smesh.lol/btcd-lite/internal/chains" "git.smesh.lol/btcd-lite/internal/fetch" "git.smesh.lol/btcd-lite/internal/store" "git.smesh.lol/btcd-lite/internal/utxo" utxoserve "git.smesh.lol/btcd-lite/internal/utxo/serve" utxostore "git.smesh.lol/btcd-lite/internal/utxo/store" "git.smesh.lol/btcd-lite/internal/utxobuild" ) // mapSource is a block source over bodies already in memory, with a count of // what the walk asked it for. type mapSource struct { bodies map[uint32][]byte reads int } func (m *mapSource) Block(height uint32) ([]byte, error) { raw, ok := m.bodies[height] if !ok { return nil, errNoBody } m.reads++ return raw, nil } var errNoBody = errors.New("gate: no body at that height") // rpcBodies reads every raw block from the node over RPC, which is the fixture // for a builder test: the transport is gated elsewhere and this keeps a // three-hundred-block chain from taking minutes. func rpcBodies(t *testing.T, r *rig, tip int) map[uint32][]byte { t.Helper() out := make(map[uint32][]byte, tip+1) for h := 0; h <= tip; h++ { hash := r.must(t, "getblockhash", itoa(h)) raw, err := hex.DecodeString(r.must(t, "getblock", hash, "0")) if err != nil { t.Fatalf("height %d: %v", h, err) } out[uint32(h)] = raw } return out } // anchoredHeaderStore is a header store with an anchor and no headers: it is // what a filter fold needs, and nothing else here does. func anchoredHeaderStore(t *testing.T, dir string, genesis chainhash.Hash) *store.HeaderStore { t.Helper() hs, err := store.NewHeaderStore(dir) if err != nil { t.Fatal(err) } t.Cleanup(func() { hs.Close() }) if err := hs.SetAnchor(neutrino.Anchor{Height: 0, BlockHash: genesis, FilterHeight: -1}); err != nil { t.Fatal(err) } return hs } // TestSnapshotFiltersAndFold: the builder snapshots on the retarget heights and // nowhere else, builds a filter per block that is the node's filter, and folds // the filter headers into the chain's header store. func TestSnapshotFiltersAndFold(t *testing.T) { r := nodeOn(t) r.createWallet(t) r.mine(t, 300) tip := r.height(t) bodies := rpcBodies(t, r, tip) src := &mapSource{bodies: bodies} dir := t.TempDir() interval := chains.Regtest().Exported.Retarget if interval != 144 { t.Fatalf("the regtest retarget is %d", interval) } if _, err := utxobuild.BuildChains(utxobuild.ChainsConfig{ Dir: filepath.Join(dir, "utxo"), Interval: interval, SharedLast: chains.SharedLastHeight, Chains: []utxobuild.ChainInput{ {Name: "btc", Tip: uint32(tip), Blocks: src}, }, Logf: t.Logf, }); err != nil { t.Fatalf("build: %v", err) } // Snapshots at the retarget heights and nowhere else. sets := filepath.Join(dir, "utxo", "canonical") idx, err := utxoserve.Open(utxoserve.Chain{ Name: "btc", Sets: []string{sets}, Diffs: []string{filepath.Join(dir, "utxo", "diff", "shared")}, Interval: interval, }) if err != nil { t.Fatal(err) } var got []uint32 for h := uint32(0); h <= uint32(tip); h++ { if _, ok := idx.Name(h); ok { got = append(got, h) } } want := []uint32{0, 144, 288} if len(got) != len(want) { t.Fatalf("snapshots at %v, want %v", got, want) } for i := range want { if got[i] != want[i] { t.Fatalf("snapshots at %v, want %v", got, want) } } // Filters are no longer built here: internal/filterbuild owns them, and // TestFiltersComputedFromBodies checks them byte for byte. t.Logf("snapshots at %v", want) } // TestClientReachesAnyHeight: a client starts at a snapshot, applies per-block // diffs, and arrives at the name the builder's walk gave every height. func TestClientReachesAnyHeight(t *testing.T) { r := nodeOn(t) r.createWallet(t) r.mine(t, 300) tip := r.height(t) bodies := rpcBodies(t, r, tip) src := &mapSource{bodies: bodies} dir := t.TempDir() interval := chains.Regtest().Exported.Retarget // The replay is the reference for the name at every height, including the // heights between snapshots: it holds the set, so it can name one. The // streamed walk cannot, and does not have to: the client's job is to arrive // at the same set the replay would. walk := map[uint32]chainhash.Hash{} utxobuild.Debug(func(h uint32, entries int, name chainhash.Hash) { walk[h] = name }, nil) defer utxobuild.Debug(nil, nil) ref := t.TempDir() if _, err := utxobuild.Build(utxobuild.Config{ Dir: filepath.Join(ref, "utxo"), DiffDir: filepath.Join(ref, "diff"), Chain: "btc", Interval: interval, From: 0, To: uint32(tip) + 1, Blocks: src, Logf: t.Logf, }); err != nil { t.Fatalf("replay: %v", err) } utxobuild.Debug(nil, nil) if _, err := utxobuild.BuildChains(utxobuild.ChainsConfig{ Dir: filepath.Join(dir, "utxo"), Interval: interval, SharedLast: chains.SharedLastHeight, Chains: []utxobuild.ChainInput{{Name: "btc", Tip: uint32(tip), Blocks: src}}, Logf: t.Logf, }); err != nil { t.Fatalf("build: %v", err) } sets, diffs := filepath.Join(dir, "utxo", "canonical"), filepath.Join(dir, "utxo", "diff", "shared") mux := http.NewServeMux() utxoserve.Routes(mux, utxoserve.Chain{Name: "btc", Sets: []string{sets}, Diffs: []string{diffs}, Interval: interval}) srv := httptest.NewServer(mux) defer srv.Close() cl := &fetch.Client{Base: srv.URL} dst := t.TempDir() n, err := cl.UTXO(t.Context(), "btc", dst) if err != nil { t.Fatalf("fetch: %v", err) } if want := 3; n != want { t.Fatalf("the client reached %d snapshots, want %d", n, want) } for _, h := range []uint32{0, 144, 288} { got, err := utxostore.SetName(dst, h) if err != nil { t.Fatalf("height %d: %v", h, err) } if got != walk[h] { t.Fatalf("height %d: the client has %s, the walk had %s", h, got, walk[h]) } } // Between two snapshots: the run from 144 to 200 applied in order gives the // walk's name at 200. set, err := utxostore.LoadSet(dst, 144) if err != nil { t.Fatal(err) } run := getBytes(t, srv.URL+"/v1/utxo/btc/diffs/145-201") set, err = applyRun(t, set, run) if err != nil { t.Fatal(err) } if got := utxostore.NameOf(set); got != walk[200] { t.Fatalf("the client's set at 200 is %s, the walk's is %s", got, walk[200]) } t.Logf("reached %d snapshots and the walk's name at 200", n) } // applyRun applies a stream of length-prefixed diffs. func applyRun(t *testing.T, set []utxo.Entry, run []byte) ([]utxo.Entry, error) { t.Helper() at := 0 for at < len(run) { n := int(binaryLE(run[at:])) d, err := utxo.DecodeDiff(run[at+4 : at+4+n]) if err != nil { return nil, err } at += 4 + n if set, err = d.ApplyTo(set); err != nil { return nil, err } } return set, nil } // TestSharedPrefixIsWalkedOnce: two chains of the same length share one walk of // the prefix. The count is the whole claim: 101 prefix reads, then each chain's // own two hundred, not two copies of three hundred. func TestSharedPrefixIsWalkedOnce(t *testing.T) { r := nodeOn(t) r.createWallet(t) r.mine(t, 400) tip := r.height(t) bodies := rpcBodies(t, r, tip) btc := &mapSource{bodies: bodies} xbt := &mapSource{bodies: bodies} dir := t.TempDir() // Above one interval, so the fork sits past the first snapshot boundary: a // prefix shorter than an interval leaves the chain nothing to continue from // and it starts at height 0, writing a base of its own. const sharedLast = 250 if _, err := utxobuild.BuildChains(utxobuild.ChainsConfig{ Dir: filepath.Join(dir, "utxo"), Interval: chains.Regtest().Exported.Retarget, SharedLast: sharedLast, Chains: []utxobuild.ChainInput{ {Name: "btc", Tip: uint32(tip), Blocks: btc}, {Name: "xbt", Tip: uint32(tip), Blocks: xbt}, }, Logf: t.Logf, }); err != nil { t.Fatalf("build: %v", err) } prefix := sharedLast + 1 post := tip + 1 - prefix // A streamed walk reads an epoch's blocks twice, once to learn what they // spend and once to apply them, because it cannot hold 2016 bodies. What it // must not do is re-walk a prefix beyond the snapshot boundary below the // fork: that remainder is at most one interval, and the shared walk owns // everything below it. interval := int(chains.Regtest().Exported.Retarget) remainder := prefix % interval if remainder == 0 { remainder = interval } // The first chain's count covers the shared walk and its own walk. if want := 2*prefix + 2*(remainder+post); btc.reads > want { t.Fatalf("the first chain read %d bodies, want at most %d (two reads of %d prefix + %d own)", btc.reads, want, prefix, post) } if want := 2 * (remainder + post); xbt.reads > want { t.Fatalf("the second chain read %d bodies, want at most %d (%d remaining prefix + %d own): it re-walked the prefix", xbt.reads, want, remainder, post) } // The prefix's snapshots and diffs are in one place, and only there. if _, err := utxostore.SetName(filepath.Join(dir, "utxo", "canonical"), 0); err != nil { t.Fatalf("no shared snapshot at 0: %v", err) } if _, err := utxostore.SetName(filepath.Join(dir, "utxo", "chain-xbt"), 0); err == nil { t.Fatal("the second chain wrote its own copy of the prefix's base") } t.Logf("prefix walked once: %d reads + %d + %d for two chains of %d", btc.reads, xbt.reads, 0, tip+1) } // TestSnapshotHeightIsNotAServedRange: a diff run that crosses a snapshot is // refused, and one that ends on it is served. func TestSnapshotHeightIsNotAServedRange(t *testing.T) { r := nodeOn(t) r.createWallet(t) r.mine(t, 150) tip := r.height(t) bodies := rpcBodies(t, r, tip) dir := t.TempDir() interval := chains.Regtest().Exported.Retarget if _, err := utxobuild.BuildChains(utxobuild.ChainsConfig{ Dir: filepath.Join(dir, "utxo"), Interval: interval, SharedLast: chains.SharedLastHeight, Chains: []utxobuild.ChainInput{{Name: "btc", Tip: uint32(tip), Blocks: &mapSource{bodies: bodies}}}, Logf: t.Logf, }); err != nil { t.Fatalf("build: %v", err) } sets, diffs := filepath.Join(dir, "utxo", "canonical"), filepath.Join(dir, "utxo", "diff", "shared") mux := http.NewServeMux() utxoserve.Routes(mux, utxoserve.Chain{Name: "btc", Sets: []string{sets}, Diffs: []string{diffs}, Interval: interval}) srv := httptest.NewServer(mux) defer srv.Close() if resp := getStatus(t, srv.URL+"/v1/utxo/btc/diffs/1-145"); resp != 200 { t.Fatalf("a run ending on the snapshot answered %d", resp) } if resp := getStatus(t, srv.URL+"/v1/utxo/btc/diffs/1-146"); resp != 400 { t.Fatalf("a run across the snapshot answered %d, want 400", resp) } } // getBytes fetches a response body that is not JSON. func getBytes(t *testing.T, u string) []byte { t.Helper() resp, err := http.Get(u) if err != nil { t.Fatal(err) } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { t.Fatal(err) } if resp.StatusCode != http.StatusOK { t.Fatalf("%s: %d %s", u, resp.StatusCode, body) } return body } func getStatus(t *testing.T, u string) int { t.Helper() resp, err := http.Get(u) if err != nil { t.Fatal(err) } resp.Body.Close() return resp.StatusCode } // binaryLE reads the first four bytes of b little-endian, which is how a diff // run frames each record. func binaryLE(b []byte) uint32 { return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 }