package gate import ( "context" "encoding/hex" "fmt" "path/filepath" "strconv" "testing" "time" "git.smesh.lol/btcd-lite/internal/chains" "git.smesh.lol/btcd-lite/internal/filler" "git.smesh.lol/btcd-lite/internal/process" "git.smesh.lol/btcd-lite/internal/staging" "git.smesh.lol/btcd-lite/internal/store" ) // TestFillerFromPeer mines a chain on a node started for the test, syncs the // header chain over p2p, then fills the body store from the same peer and // requires every stored block to be the node's bytes under the node's hash. // // It exercises the whole path the service's backfill takes: a handshake, a // getheaders chain, one getdata per height, and the body store's placement and // integrity checks. func TestFillerFromPeer(t *testing.T) { r := nodeOn(t) r.createWallet(t) r.mine(t, 120) tip, err := strconv.Atoi(r.must(t, "getblockcount")) if err != nil { t.Fatal(err) } dir := t.TempDir() headers, err := store.NewHeaderStore(filepath.Join(dir, "headers")) if err != nil { t.Fatal(err) } defer headers.Close() bodies, err := store.NewBlockStore(filepath.Join(dir, "blocks")) if err != nil { t.Fatal(err) } defer bodies.Close() peer := fmt.Sprintf("127.0.0.1:%d", r.p2p) synced := syncHeaders(t, headers, peer) t.Logf("headers synced") prof, err := chains.ByName(chains.Parent) if err != nil { t.Fatal(err) } log, err := staging.Open(staging.Dir(dir, "btc")) if err != nil { t.Fatal(err) } defer log.Close() pool, err := filler.NewPool(filler.PoolConfig{ Chain: "btc", Profile: prof.Profile, Headers: headers, Bodies: bodies, Staging: log, Peers: []filler.Peer{{Addr: peer}}, Logf: t.Logf, }) if err != nil { t.Fatal(err) } // The bodies come over the connection the headers did, as they do in // btcd-lited, so the node is not asked for a second connection seconds // after the first. pool.Reuse(peer, synced) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() if err := pool.Run(ctx); err != nil { t.Fatalf("pool: %v", err) } _ = pool.Close() if _, err := process.Run(process.Config{ Chain: "btc", Staging: log, Bodies: bodies, Headers: headers, Logf: t.Logf, }); err != nil { t.Fatalf("process: %v", err) } if got, want := bodies.Len(), tip+1; got != want { t.Fatalf("the store holds %d blocks, the node has %d heights", got, want) } for h := 0; h <= tip; h++ { hash := r.must(t, "getblockhash", strconv.Itoa(h)) want, err := hex.DecodeString(r.must(t, "getblock", hash, "0")) if err != nil { t.Fatalf("height %d: %v", h, err) } hdr, ok := headers.Header(uint32(h)) if !ok { t.Fatalf("height %d: no header", h) } got, err := bodies.GetBlock(hdr.BlockHash()) if err != nil { t.Fatalf("height %d: %v", h, err) } if string(got) != string(want) { t.Fatalf("height %d: the stored block is not the node's", h) } } t.Logf("the filler stored %d blocks from the peer, byte-identical to the node", tip+1) }