blockstall_test.go raw
1 package bridge
2
3 import (
4 "net"
5 "testing"
6 "time"
7
8 "git.smesh.lol/nostrino/pkg/btcwire"
9 "git.smesh.lol/nostrino/pkg/chain"
10 "git.smesh.lol/nostrino/pkg/crypto/chainhash"
11 )
12
13 // TestABlockTheNodeNeverAnswersEndsTheSession: a node socket can be dead without
14 // being closed. The client writes its getdata, the gateway forwards it into a
15 // socket that will never answer, and nothing arrives. The gateway must end the
16 // session inside the client's own read deadline, so the client gets a close it
17 // can retry from instead of a timeout it cannot tell from a slow transfer.
18 func TestABlockTheNodeNeverAnswersEndsTheSession(t *testing.T) {
19 magic := testMagic
20
21 address := nodeScript(t, magic, func(conn net.Conn, reader *btcwire.Reader) {
22 // Take whatever the gateway forwards and never answer it.
23 for {
24 if _, err := reader.Next(); err != nil {
25 return
26 }
27 }
28 })
29
30 srv := &Server{
31 cfg: Config{
32 Nodes: map[string]Node{
33 "alpha": {Addr: address, Profile: &chain.Profile{Name: "alpha", Magic: magic}},
34 },
35 NodeDialTimeout: 2 * time.Second,
36 IdleTimeout: 10 * time.Second,
37 BlockStallTimeout: 300 * time.Millisecond,
38 Logf: func(string, ...any) {},
39 },
40 conns: make(map[net.Conn]struct{}),
41 wsPerIP: make(map[string]int),
42 done: make(chan struct{}),
43 }
44
45 start := time.Now()
46 runSession(srv, "alpha", func(c net.Conn) {
47 req := &btcwire.GetData{InvList: []btcwire.InvVect{
48 {Type: btcwire.InvVectTypeBlock, Hash: chainhash.Hash{1}},
49 }}
50 payload, err := req.EncodePayload()
51 if err != nil {
52 t.Error(err)
53 return
54 }
55 frame, err := btcwire.EncodeMessage(magic, btcwire.CmdGetData, payload)
56 if err != nil {
57 t.Error(err)
58 return
59 }
60 if _, err := c.Write(frame); err != nil {
61 return
62 }
63 // Stay connected until the session closes.
64 buf := make([]byte, 1)
65 _, _ = c.Read(buf)
66 })
67
68 if lived := time.Since(start); lived > 5*time.Second {
69 t.Fatalf("the session lived %s with an unanswered block, the bound is %s",
70 lived.Round(time.Millisecond), srv.cfg.BlockStallTimeout)
71 }
72 }
73