package gate import ( "context" "fmt" "net" "net/http" "os" "os/exec" "path/filepath" "strconv" "testing" "time" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/neutrino" btcdwire "github.com/btcsuite/btcd/wire/v2" "git.smesh.lol/btcd-lite/internal/litedial" "git.smesh.lol/btcd-lite/internal/chains" "git.smesh.lol/btcd-lite/internal/store" "git.smesh.lol/btcd-lite/internal/v2peer" ) // rig is a regtest node started on the parent chain's consensus parameters. type rig struct { dir string port string p2p int cmd *exec.Cmd stopped bool // binDir is the install the node and its cli come from, when a caller wants // a specific one: the fork's node is a different build of the same program. binDir string } // nodeOn starts a node and skips when no bitcoind is on PATH. // // The node runs on the parent chain's parameters. The fork's difference is the // header form, which the version 2 header fixture covers; this rig is for the // peer path, and a peer serving Bitcoin-format blocks exercises every part of // it that does not depend on the fork. func nodeOn(t *testing.T) *rig { t.Helper() return rigFrom(t, "", 0) } // forkNodeOn is a node from the fork's own install, which carries the fork's // consensus rules and its version 2 header form. func forkNodeOn(t *testing.T) *rig { t.Helper() return rigFrom(t, forkBinDir, 0) } const forkBinDir = "/home/mleku/s/bitcoin-knots/bin" // rigFrom starts a node from binDir's install, or from PATH when binDir is // empty. // nodeConnectedTo starts a second node that syncs the first one's chain and // then mines on top of it. That is how two regtest nodes come to share a prefix: // two started from scratch agree on genesis and on nothing above it. func nodeConnectedTo(t *testing.T, peer *rig) *rig { t.Helper() // The chain's tip is already in the first node's chain, so waiting for the // connection to settle is waiting for the tip to arrive. r := rigFrom(t, "", peer.p2p) r.waitTip(t, peer.height(t)) return r } // waitTip waits until the node's chain is at a height. func (r *rig) waitTip(t *testing.T, want int) { t.Helper() // Ninety seconds, not thirty: a second node syncing while the rest of the // suite runs its own nodes can take longer than a quiet machine would, and a // deadline that short makes this a flake rather than a test. deadline := time.Now().Add(90 * time.Second) for { got, err := r.cli("getblockcount") if err == nil { if n, err := strconv.Atoi(trim(got)); err == nil && n >= want { return } } if time.Now().After(deadline) { t.Fatalf("the node at %s did not reach height %d", r.dir, want) } time.Sleep(100 * time.Millisecond) } } // height is the node's chain tip. func (r *rig) height(t *testing.T) int { t.Helper() n, err := strconv.Atoi(r.must(t, "getblockcount")) if err != nil { t.Fatal(err) } return n } func rigFrom(t *testing.T, binDir string, connect int) *rig { t.Helper() bitcoind, err := exec.LookPath("bitcoind") if err != nil { // The rig's install lives outside PATH on this machine; naming it here // is the difference between a gate that runs and a gate that is skipped // on the machine it was written for. bitcoind = "/home/mleku/s/bitcoin-core/bin/bitcoind" if _, statErr := os.Stat(bitcoind); statErr != nil { t.Skip("no bitcoind: not on PATH and not at the rig's install") } } if _, err := exec.LookPath("bitcoin-cli"); err != nil { cli := "/home/mleku/s/bitcoin-core/bin/bitcoin-cli" if _, statErr := os.Stat(cli); statErr != nil { t.Skip("no bitcoin-cli: not on PATH and not at the rig's install") } } if binDir != "" { bitcoind = filepath.Join(binDir, "bitcoind") } _ = chains.Parent r := &rig{dir: t.TempDir(), p2p: freePort(t), port: strconv.Itoa(freePort(t)), binDir: binDir} args := []string{ // Regtest is the parent chain's genesis, magic and difficulty already. // The exported parameters exist so a harness can start the fork's own // chain; a stock bitcoind has no flags for them, so they are not passed. "-regtest", "-datadir=" + r.dir, "-port=" + strconv.Itoa(r.p2p), "-rpcport=" + r.port, "-listen=1", "-listenonion=0", "-dnsseed=0", "-server=1", "-rpcuser=gate", "-rpcpassword=gate", "-blockfilterindex=1", // -peerblockfilters is what makes a node advertise NODE_COMPACT_FILTERS // and answer getcfheaders; the index alone is not enough, and the // default is off. "-peerblockfilters=1", "-fallbackfee=0.0002", "-printtoconsole=0", "-logtimestamps=0", } if connect != 0 { args = append(args, "-connect=127.0.0.1:"+strconv.Itoa(connect)) } r.cmd = exec.Command(bitcoind, args...) r.cmd.Stdout = os.Stderr r.cmd.Stderr = os.Stderr if err := r.cmd.Start(); err != nil { t.Skipf("bitcoind did not start: %v", err) } t.Cleanup(r.stop) // Ninety seconds for a node to answer its own RPC. The suite starts several // bitcoinds, and under that load a node that is still loading its chain can // miss a thirty second window, which makes this a flake and not a finding. deadline := time.Now().Add(90 * time.Second) for { if _, err := r.cli("getblockcount"); err == nil { return r } if time.Now().After(deadline) { t.Fatalf("the node at %s did not answer", r.dir) } time.Sleep(100 * time.Millisecond) } } func (r *rig) stop() { if r.stopped { return } r.stopped = true _ = r.cmd.Process.Signal(os.Interrupt) done := make(chan struct{}) go func() { _ = r.cmd.Wait(); close(done) }() select { case <-done: case <-time.After(20 * time.Second): _ = r.cmd.Process.Kill() <-done } } // cliPath is the bitcoin-cli the rig uses: the one on PATH, else the rig's. func cliPath() string { return rigCli("") } // rigCli is the cli from binDir's install, or the one on PATH. func rigCli(binDir string) string { if binDir != "" { return filepath.Join(binDir, "bitcoin-cli") } if p, err := exec.LookPath("bitcoin-cli"); err == nil { return p } return "/home/mleku/s/bitcoin-core/bin/bitcoin-cli" } func (r *rig) cli(args ...string) (string, error) { full := append([]string{"-regtest", "-rpcport=" + r.port, "-rpcuser=gate", "-rpcpassword=gate"}, args...) out, err := exec.Command(rigCli(r.binDir), full...).CombinedOutput() return string(out), err } func (r *rig) must(t *testing.T, args ...string) string { t.Helper() out, err := r.cli(args...) if err != nil { t.Fatalf("bitcoin-cli %v: %v\n%s", args, err, out) } return trim(out) } func (r *rig) createWallet(t *testing.T) { t.Helper() if _, err := r.cli("createwallet", "gate"); err != nil { if out, err2 := r.cli("loadwallet", "gate"); err2 != nil { t.Fatalf("createwallet/loadwallet: %v %s", err, out) } } } func (r *rig) mine(t *testing.T, n int) { t.Helper() addr := r.must(t, "getnewaddress") if _, err := r.cli("generatetoaddress", strconv.Itoa(n), addr); err != nil { t.Fatalf("generatetoaddress: %v", err) } } func trim(s string) string { for len(s) > 0 { c := s[len(s)-1] if c == '\n' || c == '\r' || c == ' ' { s = s[:len(s)-1] continue } break } return s } // freePort returns a closed TCP port above the registered range, so the rig // cannot land on anything else on this machine. func freePort(t *testing.T) int { t.Helper() for p := 19100 + int(time.Now().UnixNano()%350)*2; p < 19800; p += 2 { l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", p)) if err != nil { continue } l.Close() return p } t.Fatal("no free port") return 0 } // syncHeaders runs the header chain over p2p against a peer, which is what the // filler's block walk needs to have heights to ask for. It returns the // connection it used, which the caller closes. func syncHeaders(t *testing.T, headers *store.HeaderStore, addr string, v2 ...bool) *v2peer.Peer { useV2 := true if len(v2) > 0 { useV2 = v2[0] } t.Helper() // The header chain comes over the same connection type the filler uses: // btcd's handshake and btcd's BIP324 transport. The connection is handed // back rather than closed, so a caller that goes on to the bodies does it // on one connection, as an instance does, and not on a second one the node // may refuse for arriving too soon after the first. // The instance's own dialler, so a gate cannot pass or fail on a // connection the instance would never build. p, err := litedial.Connect(context.Background(), addr, "/btcd-lite:gate/", btcdwire.BitcoinNet(0xDAB5BFFA), 20*time.Second, useV2, t.Logf) if err != nil { t.Fatalf("header sync: %v", err) } // The store starts at the chain's own genesis header: a store anchored on // anything else refuses the first header a peer sends, because that // header's PrevBlock is the real genesis. The gate runs against a regtest // node, so it is the regtest chain's genesis. chainInfo := chains.Regtest() genesis, err := chainInfo.Genesis() if err != nil { t.Fatal(err) } if err := headers.SetAnchor(neutrino.Anchor{Height: 0, BlockHash: genesis.BlockHash(), FilterHeight: -1}); err != nil { t.Fatalf("anchor: %v", err) } if err := headers.PutHeaders(0, []btcwire.BlockHeader{genesis}); err != nil { t.Fatalf("seed genesis: %v", err) } if err := p.SyncHeaders(headers, t.Logf); err != nil { t.Fatalf("header sync: %v", err) } return p } // p2pAddr is the p2p address the gate probes: BTCD_LITE_P2P_TEST, else the // rig's Bitcoin Core node. func p2pAddr(t *testing.T) string { t.Helper() if v := os.Getenv("BTCD_LITE_P2P_TEST"); v != "" { return v } return "127.0.0.1:18444" } // itoa is strconv.Itoa with the import the helper file already has. func itoa(n int) string { return strconv.Itoa(n) } // waitHTTP waits until a URL answers. func waitHTTP(t *testing.T, u string) { t.Helper() deadline := time.Now().Add(20 * time.Second) for time.Now().Before(deadline) { resp, err := http.Get(u) if err == nil { resp.Body.Close() return } time.Sleep(50 * time.Millisecond) } t.Fatalf("nothing answered at %s", u) } // seedHeaderChain anchors a store on the first block's header and writes the // headers of blocks 0..tip. A range is heights, and a height is a header: a // body store with no header chain beside it cannot answer by height. func seedHeaderChain(t *testing.T, hs *store.HeaderStore, rawAt func(uint32) []byte, tip uint32) { t.Helper() hdrs := make([]btcwire.BlockHeader, 0, tip+1) for h := uint32(0); h <= tip; h++ { raw := rawAt(h) if len(raw) < btcwire.BlockHeaderSize { t.Fatalf("height %d is %d bytes", h, len(raw)) } var hdr btcwire.BlockHeader if err := hdr.Deserialize(raw[:btcwire.BlockHeaderSize]); err != nil { t.Fatalf("height %d: %v", h, err) } hdrs = append(hdrs, hdr) } if err := hs.SetAnchor(neutrino.Anchor{Height: 0, BlockHash: hdrs[0].BlockHash(), FilterHeight: -1}); err != nil { t.Fatal(err) } if err := hs.PutHeaders(0, hdrs); err != nil { t.Fatal(err) } }