helpers_test.go raw

   1  package gate
   2  
   3  import (
   4  	"context"
   5  	"fmt"
   6  	"net"
   7  	"net/http"
   8  	"os"
   9  	"os/exec"
  10  	"path/filepath"
  11  	"strconv"
  12  	"testing"
  13  	"time"
  14  
  15  	"git.smesh.lol/nostrino/pkg/btcwire"
  16  	"git.smesh.lol/nostrino/pkg/neutrino"
  17  	btcdwire "github.com/btcsuite/btcd/wire/v2"
  18  
  19  	"git.smesh.lol/btcd-lite/internal/litedial"
  20  
  21  	"git.smesh.lol/btcd-lite/internal/chains"
  22  	"git.smesh.lol/btcd-lite/internal/store"
  23  	"git.smesh.lol/btcd-lite/internal/v2peer"
  24  )
  25  
  26  // rig is a regtest node started on the parent chain's consensus parameters.
  27  type rig struct {
  28  	dir     string
  29  	port    string
  30  	p2p     int
  31  	cmd     *exec.Cmd
  32  	stopped bool
  33  	// binDir is the install the node and its cli come from, when a caller wants
  34  	// a specific one: the fork's node is a different build of the same program.
  35  	binDir string
  36  }
  37  
  38  // nodeOn starts a node and skips when no bitcoind is on PATH.
  39  //
  40  // The node runs on the parent chain's parameters. The fork's difference is the
  41  // header form, which the version 2 header fixture covers; this rig is for the
  42  // peer path, and a peer serving Bitcoin-format blocks exercises every part of
  43  // it that does not depend on the fork.
  44  func nodeOn(t *testing.T) *rig {
  45  	t.Helper()
  46  	return rigFrom(t, "", 0)
  47  }
  48  
  49  // forkNodeOn is a node from the fork's own install, which carries the fork's
  50  // consensus rules and its version 2 header form.
  51  func forkNodeOn(t *testing.T) *rig {
  52  	t.Helper()
  53  	return rigFrom(t, forkBinDir, 0)
  54  }
  55  
  56  const forkBinDir = "/home/mleku/s/bitcoin-knots/bin"
  57  
  58  // rigFrom starts a node from binDir's install, or from PATH when binDir is
  59  // empty.
  60  // nodeConnectedTo starts a second node that syncs the first one's chain and
  61  // then mines on top of it. That is how two regtest nodes come to share a prefix:
  62  // two started from scratch agree on genesis and on nothing above it.
  63  func nodeConnectedTo(t *testing.T, peer *rig) *rig {
  64  	t.Helper()
  65  	// The chain's tip is already in the first node's chain, so waiting for the
  66  	// connection to settle is waiting for the tip to arrive.
  67  	r := rigFrom(t, "", peer.p2p)
  68  	r.waitTip(t, peer.height(t))
  69  	return r
  70  }
  71  
  72  // waitTip waits until the node's chain is at a height.
  73  func (r *rig) waitTip(t *testing.T, want int) {
  74  	t.Helper()
  75  	// Ninety seconds, not thirty: a second node syncing while the rest of the
  76  	// suite runs its own nodes can take longer than a quiet machine would, and a
  77  	// deadline that short makes this a flake rather than a test.
  78  	deadline := time.Now().Add(90 * time.Second)
  79  	for {
  80  		got, err := r.cli("getblockcount")
  81  		if err == nil {
  82  			if n, err := strconv.Atoi(trim(got)); err == nil && n >= want {
  83  				return
  84  			}
  85  		}
  86  		if time.Now().After(deadline) {
  87  			t.Fatalf("the node at %s did not reach height %d", r.dir, want)
  88  		}
  89  		time.Sleep(100 * time.Millisecond)
  90  	}
  91  }
  92  
  93  // height is the node's chain tip.
  94  func (r *rig) height(t *testing.T) int {
  95  	t.Helper()
  96  	n, err := strconv.Atoi(r.must(t, "getblockcount"))
  97  	if err != nil {
  98  		t.Fatal(err)
  99  	}
 100  	return n
 101  }
 102  
 103  func rigFrom(t *testing.T, binDir string, connect int) *rig {
 104  	t.Helper()
 105  	bitcoind, err := exec.LookPath("bitcoind")
 106  	if err != nil {
 107  		// The rig's install lives outside PATH on this machine; naming it here
 108  		// is the difference between a gate that runs and a gate that is skipped
 109  		// on the machine it was written for.
 110  		bitcoind = "/home/mleku/s/bitcoin-core/bin/bitcoind"
 111  		if _, statErr := os.Stat(bitcoind); statErr != nil {
 112  			t.Skip("no bitcoind: not on PATH and not at the rig's install")
 113  		}
 114  	}
 115  	if _, err := exec.LookPath("bitcoin-cli"); err != nil {
 116  		cli := "/home/mleku/s/bitcoin-core/bin/bitcoin-cli"
 117  		if _, statErr := os.Stat(cli); statErr != nil {
 118  			t.Skip("no bitcoin-cli: not on PATH and not at the rig's install")
 119  		}
 120  	}
 121  	if binDir != "" {
 122  		bitcoind = filepath.Join(binDir, "bitcoind")
 123  	}
 124  	_ = chains.Parent
 125  	r := &rig{dir: t.TempDir(), p2p: freePort(t), port: strconv.Itoa(freePort(t)), binDir: binDir}
 126  	args := []string{
 127  		// Regtest is the parent chain's genesis, magic and difficulty already.
 128  		// The exported parameters exist so a harness can start the fork's own
 129  		// chain; a stock bitcoind has no flags for them, so they are not passed.
 130  		"-regtest",
 131  		"-datadir=" + r.dir,
 132  		"-port=" + strconv.Itoa(r.p2p),
 133  		"-rpcport=" + r.port,
 134  		"-listen=1",
 135  		"-listenonion=0",
 136  		"-dnsseed=0",
 137  		"-server=1",
 138  		"-rpcuser=gate",
 139  		"-rpcpassword=gate",
 140  		"-blockfilterindex=1",
 141  		// -peerblockfilters is what makes a node advertise NODE_COMPACT_FILTERS
 142  		// and answer getcfheaders; the index alone is not enough, and the
 143  		// default is off.
 144  		"-peerblockfilters=1",
 145  		"-fallbackfee=0.0002",
 146  		"-printtoconsole=0",
 147  		"-logtimestamps=0",
 148  	}
 149  	if connect != 0 {
 150  		args = append(args, "-connect=127.0.0.1:"+strconv.Itoa(connect))
 151  	}
 152  	r.cmd = exec.Command(bitcoind, args...)
 153  	r.cmd.Stdout = os.Stderr
 154  	r.cmd.Stderr = os.Stderr
 155  	if err := r.cmd.Start(); err != nil {
 156  		t.Skipf("bitcoind did not start: %v", err)
 157  	}
 158  	t.Cleanup(r.stop)
 159  	// Ninety seconds for a node to answer its own RPC. The suite starts several
 160  	// bitcoinds, and under that load a node that is still loading its chain can
 161  	// miss a thirty second window, which makes this a flake and not a finding.
 162  	deadline := time.Now().Add(90 * time.Second)
 163  	for {
 164  		if _, err := r.cli("getblockcount"); err == nil {
 165  			return r
 166  		}
 167  		if time.Now().After(deadline) {
 168  			t.Fatalf("the node at %s did not answer", r.dir)
 169  		}
 170  		time.Sleep(100 * time.Millisecond)
 171  	}
 172  }
 173  
 174  func (r *rig) stop() {
 175  	if r.stopped {
 176  		return
 177  	}
 178  	r.stopped = true
 179  	_ = r.cmd.Process.Signal(os.Interrupt)
 180  	done := make(chan struct{})
 181  	go func() { _ = r.cmd.Wait(); close(done) }()
 182  	select {
 183  	case <-done:
 184  	case <-time.After(20 * time.Second):
 185  		_ = r.cmd.Process.Kill()
 186  		<-done
 187  	}
 188  }
 189  
 190  // cliPath is the bitcoin-cli the rig uses: the one on PATH, else the rig's.
 191  func cliPath() string { return rigCli("") }
 192  
 193  // rigCli is the cli from binDir's install, or the one on PATH.
 194  func rigCli(binDir string) string {
 195  	if binDir != "" {
 196  		return filepath.Join(binDir, "bitcoin-cli")
 197  	}
 198  	if p, err := exec.LookPath("bitcoin-cli"); err == nil {
 199  		return p
 200  	}
 201  	return "/home/mleku/s/bitcoin-core/bin/bitcoin-cli"
 202  }
 203  
 204  func (r *rig) cli(args ...string) (string, error) {
 205  	full := append([]string{"-regtest", "-rpcport=" + r.port, "-rpcuser=gate", "-rpcpassword=gate"}, args...)
 206  	out, err := exec.Command(rigCli(r.binDir), full...).CombinedOutput()
 207  	return string(out), err
 208  }
 209  
 210  func (r *rig) must(t *testing.T, args ...string) string {
 211  	t.Helper()
 212  	out, err := r.cli(args...)
 213  	if err != nil {
 214  		t.Fatalf("bitcoin-cli %v: %v\n%s", args, err, out)
 215  	}
 216  	return trim(out)
 217  }
 218  
 219  func (r *rig) createWallet(t *testing.T) {
 220  	t.Helper()
 221  	if _, err := r.cli("createwallet", "gate"); err != nil {
 222  		if out, err2 := r.cli("loadwallet", "gate"); err2 != nil {
 223  			t.Fatalf("createwallet/loadwallet: %v %s", err, out)
 224  		}
 225  	}
 226  }
 227  
 228  func (r *rig) mine(t *testing.T, n int) {
 229  	t.Helper()
 230  	addr := r.must(t, "getnewaddress")
 231  	if _, err := r.cli("generatetoaddress", strconv.Itoa(n), addr); err != nil {
 232  		t.Fatalf("generatetoaddress: %v", err)
 233  	}
 234  }
 235  
 236  func trim(s string) string {
 237  	for len(s) > 0 {
 238  		c := s[len(s)-1]
 239  		if c == '\n' || c == '\r' || c == ' ' {
 240  			s = s[:len(s)-1]
 241  			continue
 242  		}
 243  		break
 244  	}
 245  	return s
 246  }
 247  
 248  // freePort returns a closed TCP port above the registered range, so the rig
 249  // cannot land on anything else on this machine.
 250  func freePort(t *testing.T) int {
 251  	t.Helper()
 252  	for p := 19100 + int(time.Now().UnixNano()%350)*2; p < 19800; p += 2 {
 253  		l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", p))
 254  		if err != nil {
 255  			continue
 256  		}
 257  		l.Close()
 258  		return p
 259  	}
 260  	t.Fatal("no free port")
 261  	return 0
 262  }
 263  
 264  // syncHeaders runs the header chain over p2p against a peer, which is what the
 265  // filler's block walk needs to have heights to ask for. It returns the
 266  // connection it used, which the caller closes.
 267  func syncHeaders(t *testing.T, headers *store.HeaderStore, addr string, v2 ...bool) *v2peer.Peer {
 268  	useV2 := true
 269  	if len(v2) > 0 {
 270  		useV2 = v2[0]
 271  	}
 272  	t.Helper()
 273  	// The header chain comes over the same connection type the filler uses:
 274  	// btcd's handshake and btcd's BIP324 transport. The connection is handed
 275  	// back rather than closed, so a caller that goes on to the bodies does it
 276  	// on one connection, as an instance does, and not on a second one the node
 277  	// may refuse for arriving too soon after the first.
 278  	// The instance's own dialler, so a gate cannot pass or fail on a
 279  	// connection the instance would never build.
 280  	p, err := litedial.Connect(context.Background(), addr, "/btcd-lite:gate/",
 281  		btcdwire.BitcoinNet(0xDAB5BFFA), 20*time.Second, useV2, t.Logf)
 282  	if err != nil {
 283  		t.Fatalf("header sync: %v", err)
 284  	}
 285  	// The store starts at the chain's own genesis header: a store anchored on
 286  	// anything else refuses the first header a peer sends, because that
 287  	// header's PrevBlock is the real genesis. The gate runs against a regtest
 288  	// node, so it is the regtest chain's genesis.
 289  	chainInfo := chains.Regtest()
 290  	genesis, err := chainInfo.Genesis()
 291  	if err != nil {
 292  		t.Fatal(err)
 293  	}
 294  	if err := headers.SetAnchor(neutrino.Anchor{Height: 0, BlockHash: genesis.BlockHash(), FilterHeight: -1}); err != nil {
 295  		t.Fatalf("anchor: %v", err)
 296  	}
 297  	if err := headers.PutHeaders(0, []btcwire.BlockHeader{genesis}); err != nil {
 298  		t.Fatalf("seed genesis: %v", err)
 299  	}
 300  	if err := p.SyncHeaders(headers, t.Logf); err != nil {
 301  		t.Fatalf("header sync: %v", err)
 302  	}
 303  	return p
 304  }
 305  
 306  // p2pAddr is the p2p address the gate probes: BTCD_LITE_P2P_TEST, else the
 307  // rig's Bitcoin Core node.
 308  func p2pAddr(t *testing.T) string {
 309  	t.Helper()
 310  	if v := os.Getenv("BTCD_LITE_P2P_TEST"); v != "" {
 311  		return v
 312  	}
 313  	return "127.0.0.1:18444"
 314  }
 315  
 316  // itoa is strconv.Itoa with the import the helper file already has.
 317  func itoa(n int) string { return strconv.Itoa(n) }
 318  
 319  // waitHTTP waits until a URL answers.
 320  func waitHTTP(t *testing.T, u string) {
 321  	t.Helper()
 322  	deadline := time.Now().Add(20 * time.Second)
 323  	for time.Now().Before(deadline) {
 324  		resp, err := http.Get(u)
 325  		if err == nil {
 326  			resp.Body.Close()
 327  			return
 328  		}
 329  		time.Sleep(50 * time.Millisecond)
 330  	}
 331  	t.Fatalf("nothing answered at %s", u)
 332  }
 333  
 334  // seedHeaderChain anchors a store on the first block's header and writes the
 335  // headers of blocks 0..tip. A range is heights, and a height is a header: a
 336  // body store with no header chain beside it cannot answer by height.
 337  func seedHeaderChain(t *testing.T, hs *store.HeaderStore, rawAt func(uint32) []byte, tip uint32) {
 338  	t.Helper()
 339  	hdrs := make([]btcwire.BlockHeader, 0, tip+1)
 340  	for h := uint32(0); h <= tip; h++ {
 341  		raw := rawAt(h)
 342  		if len(raw) < btcwire.BlockHeaderSize {
 343  			t.Fatalf("height %d is %d bytes", h, len(raw))
 344  		}
 345  		var hdr btcwire.BlockHeader
 346  		if err := hdr.Deserialize(raw[:btcwire.BlockHeaderSize]); err != nil {
 347  			t.Fatalf("height %d: %v", h, err)
 348  		}
 349  		hdrs = append(hdrs, hdr)
 350  	}
 351  	if err := hs.SetAnchor(neutrino.Anchor{Height: 0, BlockHash: hdrs[0].BlockHash(), FilterHeight: -1}); err != nil {
 352  		t.Fatal(err)
 353  	}
 354  	if err := hs.PutHeaders(0, hdrs); err != nil {
 355  		t.Fatal(err)
 356  	}
 357  }
 358