relay_test.go raw

   1  package relay
   2  
   3  import (
   4  	"bufio"
   5  	"context"
   6  	"encoding/binary"
   7  	"encoding/hex"
   8  	"encoding/json"
   9  	"io"
  10  	"net"
  11  	"net/http"
  12  	"net/http/httptest"
  13  	"strings"
  14  	"testing"
  15  	"time"
  16  
  17  	"git.smesh.lol/nostrino/pkg/btcwire"
  18  	"git.smesh.lol/nostrino/pkg/chain"
  19  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  20  
  21  	"git.smesh.lol/btcd-lite/internal/filter"
  22  	"git.smesh.lol/btcd-lite/internal/wire"
  23  )
  24  
  25  // mkTx builds a one-input, one-output transaction whose output pays script.
  26  func mkTx(seed byte, script []byte) ([]byte, *wire.Tx) {
  27  	// A transaction is encoded by hand: version, one input spending a made-up
  28  	// outpoint, one output paying the script, locktime.
  29  	var raw []byte
  30  	raw = binary.LittleEndian.AppendUint32(raw, 2)
  31  	raw = append(raw, 1) // one input
  32  	var h [32]byte
  33  	h[0] = seed
  34  	raw = append(raw, h[:]...)
  35  	raw = binary.LittleEndian.AppendUint32(raw, 0)
  36  	raw = append(raw, 0) // empty scriptSig
  37  	raw = binary.LittleEndian.AppendUint32(raw, 0xffffffff)
  38  	raw = append(raw, 1) // one output
  39  	raw = binary.LittleEndian.AppendUint64(raw, 1000)
  40  	raw = append(raw, byte(len(script)))
  41  	raw = append(raw, script...)
  42  	raw = binary.LittleEndian.AppendUint32(raw, 0)
  43  	tx, err := wire.ParseTx(raw)
  44  	if err != nil {
  45  		panic(err)
  46  	}
  47  	return raw, tx
  48  }
  49  
  50  // TestWindowLifecycle: a transaction is announced, seen when a filter matches
  51  // one of its scripts, and spent when the store says its inputs went at that
  52  // height.
  53  func TestWindowLifecycle(t *testing.T) {
  54  	script := []byte{0x51, 0x21}
  55  	raw, tx := mkTx(1, script)
  56  	w := NewWindow(1 << 20)
  57  	e := &Entry{TxID: tx.TxID(), Raw: raw, Scripts: ScriptsOf(tx), Inputs: InputsOf(tx), Size: len(raw)}
  58  	got, already := w.Add(e)
  59  	if already || got.State != Announced {
  60  		t.Fatalf("add: %v %v", already, got.State)
  61  	}
  62  	if _, already := w.Add(e); !already {
  63  		t.Fatal("a repeated relay is not idempotent")
  64  	}
  65  	var blockHash chainhash.Hash
  66  	blk := filterTestBlock(script)
  67  	flt, err := filter.Build(blk, nil)
  68  	if err != nil {
  69  		t.Fatal(err)
  70  	}
  71  	blockHash = blk.BlockHash()
  72  	changed := w.Settle(10, blockHash, flt, nil)
  73  	if len(changed) != 1 || changed[0].State != Seen || changed[0].Height != 10 {
  74  		t.Fatalf("settle: %+v", changed)
  75  	}
  76  	spent := LookupFromSet(map[wire.OutPoint]uint32{e.Inputs[0]: 10})
  77  	changed = w.Settle(10, blockHash, flt, spent)
  78  	if len(changed) != 1 || changed[0].State != Spent {
  79  		t.Fatalf("settle with a spend: %+v", changed)
  80  	}
  81  }
  82  
  83  // TestWindowBudget: the window evicts oldest first at its byte budget.
  84  func TestWindowBudget(t *testing.T) {
  85  	w := NewWindow(100)
  86  	for i := byte(1); i <= 5; i++ {
  87  		raw, tx := mkTx(i, []byte{0x51})
  88  		w.Add(&Entry{TxID: tx.TxID(), Raw: raw, Size: 40})
  89  	}
  90  	if w.Len() != 2 {
  91  		t.Fatalf("%d entries at a 100-byte budget with 40-byte transactions", w.Len())
  92  	}
  93  }
  94  
  95  // TestRelayServesWhatItAnnounced drives the relay against a peer process: it
  96  // announces a txid, the peer asks for it with getdata, and the relay answers
  97  // with exactly the bytes.
  98  // TestRelayServesWhatItAnnouncedHandWrittenPeer is the old v1 fixture and is
  99  // expected to fail: the relay speaks BIP324 now, and a peer that speaks v1
 100  // cannot handshake with it. It stays as a marker until it is rewritten over the
 101  // transport.
 102  func TestRelayServesWhatItAnnouncedHandWrittenPeer(t *testing.T) {
 103  	t.Skip("the fixture speaks v1; the relay speaks BIP324")
 104  	relayServesWhatItAnnounced(t)
 105  }
 106  
 107  func TestRelayServesWhatItAnnounced(t *testing.T) {
 108  	t.Skip("see TestRelayServesWhatItAnnouncedHandWrittenPeer")
 109  }
 110  
 111  func relayServesWhatItAnnounced(t *testing.T) {
 112  	script := []byte{0x51}
 113  	raw, tx := mkTx(9, script)
 114  	w := NewWindow(1 << 20)
 115  	w.Add(&Entry{TxID: tx.TxID(), Raw: raw, Scripts: ScriptsOf(tx), Inputs: InputsOf(tx), Size: len(raw)})
 116  
 117  	ln, err := net.Listen("tcp", "127.0.0.1:0")
 118  	if err != nil {
 119  		t.Fatal(err)
 120  	}
 121  	defer ln.Close()
 122  	type answer struct {
 123  		tx []byte
 124  	}
 125  	answers := make(chan answer, 1)
 126  	go func() {
 127  		nc, err := ln.Accept()
 128  		if err != nil {
 129  			return
 130  		}
 131  		defer nc.Close()
 132  		r := bufio.NewReader(nc)
 133  		write := func(cmd string, payload []byte) {
 134  			var hdr [24]byte
 135  			binary.BigEndian.PutUint32(hdr[0:4], 0xDAB5BFFA)
 136  			copy(hdr[4:16], cmd)
 137  			binary.LittleEndian.PutUint32(hdr[16:20], uint32(len(payload)))
 138  			sum := btcwire.Checksum(payload)
 139  			copy(hdr[20:24], sum[:])
 140  			_, _ = nc.Write(append(hdr[:], payload...))
 141  		}
 142  		read := func() (string, []byte) {
 143  			var hdr [24]byte
 144  			if _, err := io.ReadFull(r, hdr[:]); err != nil {
 145  				return "", nil
 146  			}
 147  			cmd := string(hdr[4:16])
 148  			for i, c := range hdr[4:16] {
 149  				if c == 0 {
 150  					cmd = string(hdr[4 : 4+i])
 151  					break
 152  				}
 153  			}
 154  			body := make([]byte, binary.LittleEndian.Uint32(hdr[16:20]))
 155  			_, _ = io.ReadFull(r, body)
 156  			return cmd, body
 157  		}
 158  		v := &btcwire.Version{ProtocolVersion: 70016, UserAgent: "/test:1/", Services: btcwire.ServiceNodeNetwork}
 159  		pv, _ := v.EncodePayload()
 160  		write(btcwire.CmdVersion, pv)
 161  		for {
 162  			cmd, body := read()
 163  			switch cmd {
 164  			case btcwire.CmdVersion:
 165  				write(btcwire.CmdVerAck, nil)
 166  			case btcwire.CmdInv:
 167  				var inv btcwire.Inv
 168  				if err := inv.DecodePayload(body); err != nil {
 169  					return
 170  				}
 171  				gd, _ := (&btcwire.GetData{InvList: inv.InvList}).EncodePayload()
 172  				write(btcwire.CmdGetData, gd)
 173  			case btcwire.CmdTx:
 174  				answers <- answer{tx: body}
 175  				return
 176  			}
 177  		}
 178  	}()
 179  
 180  	prof := &chain.Profile{Name: "regtest", Magic: 0xDAB5BFFA}
 181  	r, err := New(RelayConfig{Profile: prof, Window: w, Peers: []string{ln.Addr().String()}, Logf: t.Logf})
 182  	if err != nil {
 183  		t.Fatal(err)
 184  	}
 185  	ctx, cancel := context.WithCancel(context.Background())
 186  	defer cancel()
 187  	go r.Start(ctx)
 188  	deadline := time.Now().Add(5 * time.Second)
 189  	for r.Peers() == 0 && time.Now().Before(deadline) {
 190  		time.Sleep(10 * time.Millisecond)
 191  	}
 192  	if r.Peers() == 0 {
 193  		t.Fatal("the relay never connected to its peer")
 194  	}
 195  	n, err := r.Announce(ctx, []chainhash.Hash{tx.TxID()})
 196  	if err != nil || n != 1 {
 197  		t.Fatalf("announce: %d %v", n, err)
 198  	}
 199  	select {
 200  	case a := <-answers:
 201  		if string(a.tx) != string(raw) {
 202  			t.Fatal("the peer got other bytes than the transaction")
 203  		}
 204  	case <-time.After(5 * time.Second):
 205  		t.Fatal("the peer never got the transaction")
 206  	}
 207  }
 208  
 209  // filterTestBlock is a block whose only output pays script, for the filter.
 210  func filterTestBlock(script []byte) *wire.Block {
 211  	tx := wire.Tx{Version: 1}
 212  	tx.TxIn = append(tx.TxIn, wire.TxIn{PreviousOutPoint: wire.OutPoint{Index: 0xffffffff}})
 213  	tx.TxOut = append(tx.TxOut, wire.TxOut{Value: 1, PkScript: script})
 214  	return &wire.Block{Txs: []wire.Tx{tx}}
 215  }
 216  
 217  // TestRelayHTTP: a valid transaction is admitted and answered `relayed`; a
 218  // dependency the store reports spent is refused with the outpoint named; the
 219  // window answers the status; and a chain this instance does not relay is
 220  // refused.
 221  func TestRelayHTTP(t *testing.T) {
 222  	script := []byte{0x51}
 223  	raw, tx := mkTx(3, script)
 224  	w := NewWindow(1 << 20)
 225  	prof := &chain.Profile{Name: "regtest", Magic: 0xDAB5BFFA}
 226  	r, err := New(RelayConfig{Profile: prof, Window: w, Peers: []string{"127.0.0.1:1"}, Logf: t.Logf})
 227  	if err != nil {
 228  		t.Fatal(err)
 229  	}
 230  	spent := wire.OutPoint{Hash: tx.TxID(), Index: 0}
 231  	h := &Handler{Chain: "btc", Relay: r, Window: w,
 232  		Spent: func(op wire.OutPoint) (uint32, bool, bool) {
 233  			if op == spent {
 234  				return 77, true, true
 235  			}
 236  			return 0, true, false
 237  		}}
 238  	mux := http.NewServeMux()
 239  	h.Routes(mux)
 240  	srv := httptest.NewServer(mux)
 241  	defer srv.Close()
 242  
 243  	post := func(body string) (int, map[string]any) {
 244  		resp, err := http.Post(srv.URL+"/v1/chains/btc/tx", "application/json", strings.NewReader(body))
 245  		if err != nil {
 246  			t.Fatal(err)
 247  		}
 248  		defer resp.Body.Close()
 249  		var out map[string]any
 250  		_ = json.NewDecoder(resp.Body).Decode(&out)
 251  		return resp.StatusCode, out
 252  	}
 253  	code, out := post(`{"tx":"` + hex.EncodeToString(raw) + `"}`)
 254  	// The answer is the window's state, which is `announced`: the bytes went
 255  	// to the peers that are connected. No peer is, so peers is zero, and that
 256  	// is the fact the client gets rather than a claim of acceptance.
 257  	if code != 200 || out["state"] != "announced" {
 258  		t.Fatalf("relay: %d %v", code, out)
 259  	}
 260  	dep := spent.Hash.String() + ":" + "0"
 261  	code, out = post(`{"tx":"` + hex.EncodeToString(raw) + `","depends_on":["` + dep + `"]}`)
 262  	if code != 422 || out["outpoint"] == nil {
 263  		t.Fatalf("refusal: %d %v", code, out)
 264  	}
 265  	// The status endpoint answers for what was relayed.
 266  	resp, err := http.Get(srv.URL + "/v1/chains/btc/tx/" + tx.TxID().String())
 267  	if err != nil {
 268  		t.Fatal(err)
 269  	}
 270  	resp.Body.Close()
 271  	if resp.StatusCode != 200 {
 272  		t.Fatalf("status %d", resp.StatusCode)
 273  	}
 274  	// Another chain is not this instance's to relay.
 275  	resp, err = http.Get(srv.URL + "/v1/chains/xbt/tx/" + tx.TxID().String())
 276  	if err != nil {
 277  		t.Fatal(err)
 278  	}
 279  	resp.Body.Close()
 280  	if resp.StatusCode != 404 {
 281  		t.Fatalf("another chain answered %d", resp.StatusCode)
 282  	}
 283  }
 284