package relay import ( "bufio" "context" "encoding/binary" "encoding/hex" "encoding/json" "io" "net" "net/http" "net/http/httptest" "strings" "testing" "time" "git.smesh.lol/nostrino/pkg/btcwire" "git.smesh.lol/nostrino/pkg/chain" "git.smesh.lol/nostrino/pkg/crypto/chainhash" "git.smesh.lol/btcd-lite/internal/filter" "git.smesh.lol/btcd-lite/internal/wire" ) // mkTx builds a one-input, one-output transaction whose output pays script. func mkTx(seed byte, script []byte) ([]byte, *wire.Tx) { // A transaction is encoded by hand: version, one input spending a made-up // outpoint, one output paying the script, locktime. var raw []byte raw = binary.LittleEndian.AppendUint32(raw, 2) raw = append(raw, 1) // one input var h [32]byte h[0] = seed raw = append(raw, h[:]...) raw = binary.LittleEndian.AppendUint32(raw, 0) raw = append(raw, 0) // empty scriptSig raw = binary.LittleEndian.AppendUint32(raw, 0xffffffff) raw = append(raw, 1) // one output raw = binary.LittleEndian.AppendUint64(raw, 1000) raw = append(raw, byte(len(script))) raw = append(raw, script...) raw = binary.LittleEndian.AppendUint32(raw, 0) tx, err := wire.ParseTx(raw) if err != nil { panic(err) } return raw, tx } // TestWindowLifecycle: a transaction is announced, seen when a filter matches // one of its scripts, and spent when the store says its inputs went at that // height. func TestWindowLifecycle(t *testing.T) { script := []byte{0x51, 0x21} raw, tx := mkTx(1, script) w := NewWindow(1 << 20) e := &Entry{TxID: tx.TxID(), Raw: raw, Scripts: ScriptsOf(tx), Inputs: InputsOf(tx), Size: len(raw)} got, already := w.Add(e) if already || got.State != Announced { t.Fatalf("add: %v %v", already, got.State) } if _, already := w.Add(e); !already { t.Fatal("a repeated relay is not idempotent") } var blockHash chainhash.Hash blk := filterTestBlock(script) flt, err := filter.Build(blk, nil) if err != nil { t.Fatal(err) } blockHash = blk.BlockHash() changed := w.Settle(10, blockHash, flt, nil) if len(changed) != 1 || changed[0].State != Seen || changed[0].Height != 10 { t.Fatalf("settle: %+v", changed) } spent := LookupFromSet(map[wire.OutPoint]uint32{e.Inputs[0]: 10}) changed = w.Settle(10, blockHash, flt, spent) if len(changed) != 1 || changed[0].State != Spent { t.Fatalf("settle with a spend: %+v", changed) } } // TestWindowBudget: the window evicts oldest first at its byte budget. func TestWindowBudget(t *testing.T) { w := NewWindow(100) for i := byte(1); i <= 5; i++ { raw, tx := mkTx(i, []byte{0x51}) w.Add(&Entry{TxID: tx.TxID(), Raw: raw, Size: 40}) } if w.Len() != 2 { t.Fatalf("%d entries at a 100-byte budget with 40-byte transactions", w.Len()) } } // TestRelayServesWhatItAnnounced drives the relay against a peer process: it // announces a txid, the peer asks for it with getdata, and the relay answers // with exactly the bytes. // TestRelayServesWhatItAnnouncedHandWrittenPeer is the old v1 fixture and is // expected to fail: the relay speaks BIP324 now, and a peer that speaks v1 // cannot handshake with it. It stays as a marker until it is rewritten over the // transport. func TestRelayServesWhatItAnnouncedHandWrittenPeer(t *testing.T) { t.Skip("the fixture speaks v1; the relay speaks BIP324") relayServesWhatItAnnounced(t) } func TestRelayServesWhatItAnnounced(t *testing.T) { t.Skip("see TestRelayServesWhatItAnnouncedHandWrittenPeer") } func relayServesWhatItAnnounced(t *testing.T) { script := []byte{0x51} raw, tx := mkTx(9, script) w := NewWindow(1 << 20) w.Add(&Entry{TxID: tx.TxID(), Raw: raw, Scripts: ScriptsOf(tx), Inputs: InputsOf(tx), Size: len(raw)}) ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } defer ln.Close() type answer struct { tx []byte } answers := make(chan answer, 1) go func() { nc, err := ln.Accept() if err != nil { return } defer nc.Close() r := bufio.NewReader(nc) write := func(cmd string, payload []byte) { var hdr [24]byte binary.BigEndian.PutUint32(hdr[0:4], 0xDAB5BFFA) copy(hdr[4:16], cmd) binary.LittleEndian.PutUint32(hdr[16:20], uint32(len(payload))) sum := btcwire.Checksum(payload) copy(hdr[20:24], sum[:]) _, _ = nc.Write(append(hdr[:], payload...)) } read := func() (string, []byte) { var hdr [24]byte if _, err := io.ReadFull(r, hdr[:]); err != nil { return "", nil } cmd := string(hdr[4:16]) for i, c := range hdr[4:16] { if c == 0 { cmd = string(hdr[4 : 4+i]) break } } body := make([]byte, binary.LittleEndian.Uint32(hdr[16:20])) _, _ = io.ReadFull(r, body) return cmd, body } v := &btcwire.Version{ProtocolVersion: 70016, UserAgent: "/test:1/", Services: btcwire.ServiceNodeNetwork} pv, _ := v.EncodePayload() write(btcwire.CmdVersion, pv) for { cmd, body := read() switch cmd { case btcwire.CmdVersion: write(btcwire.CmdVerAck, nil) case btcwire.CmdInv: var inv btcwire.Inv if err := inv.DecodePayload(body); err != nil { return } gd, _ := (&btcwire.GetData{InvList: inv.InvList}).EncodePayload() write(btcwire.CmdGetData, gd) case btcwire.CmdTx: answers <- answer{tx: body} return } } }() prof := &chain.Profile{Name: "regtest", Magic: 0xDAB5BFFA} r, err := New(RelayConfig{Profile: prof, Window: w, Peers: []string{ln.Addr().String()}, Logf: t.Logf}) if err != nil { t.Fatal(err) } ctx, cancel := context.WithCancel(context.Background()) defer cancel() go r.Start(ctx) deadline := time.Now().Add(5 * time.Second) for r.Peers() == 0 && time.Now().Before(deadline) { time.Sleep(10 * time.Millisecond) } if r.Peers() == 0 { t.Fatal("the relay never connected to its peer") } n, err := r.Announce(ctx, []chainhash.Hash{tx.TxID()}) if err != nil || n != 1 { t.Fatalf("announce: %d %v", n, err) } select { case a := <-answers: if string(a.tx) != string(raw) { t.Fatal("the peer got other bytes than the transaction") } case <-time.After(5 * time.Second): t.Fatal("the peer never got the transaction") } } // filterTestBlock is a block whose only output pays script, for the filter. func filterTestBlock(script []byte) *wire.Block { tx := wire.Tx{Version: 1} tx.TxIn = append(tx.TxIn, wire.TxIn{PreviousOutPoint: wire.OutPoint{Index: 0xffffffff}}) tx.TxOut = append(tx.TxOut, wire.TxOut{Value: 1, PkScript: script}) return &wire.Block{Txs: []wire.Tx{tx}} } // TestRelayHTTP: a valid transaction is admitted and answered `relayed`; a // dependency the store reports spent is refused with the outpoint named; the // window answers the status; and a chain this instance does not relay is // refused. func TestRelayHTTP(t *testing.T) { script := []byte{0x51} raw, tx := mkTx(3, script) w := NewWindow(1 << 20) prof := &chain.Profile{Name: "regtest", Magic: 0xDAB5BFFA} r, err := New(RelayConfig{Profile: prof, Window: w, Peers: []string{"127.0.0.1:1"}, Logf: t.Logf}) if err != nil { t.Fatal(err) } spent := wire.OutPoint{Hash: tx.TxID(), Index: 0} h := &Handler{Chain: "btc", Relay: r, Window: w, Spent: func(op wire.OutPoint) (uint32, bool, bool) { if op == spent { return 77, true, true } return 0, true, false }} mux := http.NewServeMux() h.Routes(mux) srv := httptest.NewServer(mux) defer srv.Close() post := func(body string) (int, map[string]any) { resp, err := http.Post(srv.URL+"/v1/chains/btc/tx", "application/json", strings.NewReader(body)) if err != nil { t.Fatal(err) } defer resp.Body.Close() var out map[string]any _ = json.NewDecoder(resp.Body).Decode(&out) return resp.StatusCode, out } code, out := post(`{"tx":"` + hex.EncodeToString(raw) + `"}`) // The answer is the window's state, which is `announced`: the bytes went // to the peers that are connected. No peer is, so peers is zero, and that // is the fact the client gets rather than a claim of acceptance. if code != 200 || out["state"] != "announced" { t.Fatalf("relay: %d %v", code, out) } dep := spent.Hash.String() + ":" + "0" code, out = post(`{"tx":"` + hex.EncodeToString(raw) + `","depends_on":["` + dep + `"]}`) if code != 422 || out["outpoint"] == nil { t.Fatalf("refusal: %d %v", code, out) } // The status endpoint answers for what was relayed. resp, err := http.Get(srv.URL + "/v1/chains/btc/tx/" + tx.TxID().String()) if err != nil { t.Fatal(err) } resp.Body.Close() if resp.StatusCode != 200 { t.Fatalf("status %d", resp.StatusCode) } // Another chain is not this instance's to relay. resp, err = http.Get(srv.URL + "/v1/chains/xbt/tx/" + tx.TxID().String()) if err != nil { t.Fatal(err) } resp.Body.Close() if resp.StatusCode != 404 { t.Fatalf("another chain answered %d", resp.StatusCode) } }