gateway_test.go raw

   1  package bridge
   2  
   3  import (
   4  	"bytes"
   5  	"context"
   6  	"io"
   7  	"net"
   8  	"testing"
   9  	"time"
  10  
  11  	"git.smesh.lol/nostrino/pkg/btcwire"
  12  	"git.smesh.lol/nostrino/pkg/chain"
  13  	"git.smesh.lol/nostrino/pkg/crypto/chainhash"
  14  )
  15  
  16  // nodeScript is a node's socket driven by the test: it accepts, runs body, and stops.
  17  func nodeScript(t *testing.T, magic uint32, body func(net.Conn, *btcwire.Reader)) string {
  18  	t.Helper()
  19  
  20  	ln, err := net.Listen("tcp", "127.0.0.1:0")
  21  
  22  	if err != nil {
  23  		t.Fatal(err)
  24  	}
  25  
  26  	t.Cleanup(func() { ln.Close() })
  27  
  28  	go func() {
  29  		conn, err := ln.Accept()
  30  
  31  		if err != nil {
  32  			return
  33  		}
  34  
  35  		defer conn.Close()
  36  
  37  		body(conn, btcwire.NewReader(conn, magic))
  38  	}()
  39  
  40  	return ln.Addr().String()
  41  }
  42  
  43  // runSession drives one client against the gateway and returns when the session ends.
  44  func runSession(srv *Server, chainName string, client func(net.Conn)) time.Duration {
  45  	clientConn, serverConn := net.Pipe()
  46  	done := make(chan struct{})
  47  	start := time.Now()
  48  
  49  	go func() {
  50  		defer close(done)
  51  		defer serverConn.Close()
  52  		srv.handleConn(context.Background(), serverConn, chainName, "test:"+chainName)
  53  	}()
  54  
  55  	go func() {
  56  		client(clientConn)
  57  	}()
  58  
  59  	<-done
  60  	clientConn.Close()
  61  
  62  	return time.Since(start)
  63  }
  64  
  65  func quietServer(address string, magic uint32) *Server {
  66  	return &Server{
  67  		cfg: Config{
  68  			Nodes: map[string]Node{
  69  				"alpha": {Addr: address, Profile: &chain.Profile{Name: "alpha", Magic: magic}},
  70  			},
  71  			NodeDialTimeout: 2 * time.Second,
  72  			IdleTimeout:     2 * time.Second,
  73  			Logf:            func(string, ...any) {},
  74  		},
  75  		conns:   make(map[net.Conn]struct{}),
  76  		wsPerIP: make(map[string]int),
  77  		done:    make(chan struct{}),
  78  	}
  79  }
  80  
  81  const testMagic uint32 = 0xdab5bffa
  82  
  83  // TestAFailedSessionDoesNotStopTheGateway: a node that closes mid-session ends that session, and
  84  // the next client is still served. This is the shape of the failure that matters: one bad peer
  85  // must not take the gateway down for everyone.
  86  func TestAFailedSessionDoesNotStopTheGateway(t *testing.T) {
  87  	magic := testMagic
  88  	var sessions int
  89  
  90  	address := nodeScript(t, magic, func(conn net.Conn, reader *btcwire.Reader) {
  91  		sessions++
  92  
  93  		// Read one frame, answer, then drop the connection, as a restarted node would.
  94  		if _, err := reader.Next(); err != nil {
  95  			return
  96  		}
  97  
  98  		frame, err := btcwire.EncodeMessage(magic, btcwire.CmdHeaders, nil)
  99  
 100  		if err == nil {
 101  			_, _ = conn.Write(frame)
 102  		}
 103  	})
 104  
 105  	srv := quietServer(address, magic)
 106  
 107  	// The first session is dropped by the node.
 108  	runSession(srv, "alpha", func(client net.Conn) {
 109  		frame, _ := btcwire.EncodeMessage(magic, btcwire.CmdGetHeaders, nil)
 110  		_, _ = client.Write(frame)
 111  		// Wait for the node's reply or the close, whichever comes first.
 112  		_, _ = io.ReadAll(client)
 113  	})
 114  
 115  	if sessions == 0 {
 116  		t.Fatal("the node was never dialed")
 117  	}
 118  
 119  	// The second session still works: the gateway did not exit or wedge itself.
 120  	reader := make(chan string, 1)
 121  
 122  	second := nodeScript(t, magic, func(conn net.Conn, r *btcwire.Reader) {
 123  		msg, err := r.Next()
 124  
 125  		if err != nil {
 126  			return
 127  		}
 128  
 129  		reader <- msg.Command
 130  	})
 131  
 132  	srv.cfg.Nodes["alpha"] = Node{Addr: second, Profile: &chain.Profile{Name: "alpha", Magic: magic}}
 133  
 134  	runSession(srv, "alpha", func(client net.Conn) {
 135  		frame, _ := btcwire.EncodeMessage(magic, btcwire.CmdGetHeaders, nil)
 136  		_, _ = client.Write(frame)
 137  		time.Sleep(200 * time.Millisecond)
 138  	})
 139  
 140  	select {
 141  	case command := <-reader:
 142  		if command != btcwire.CmdGetHeaders {
 143  			t.Fatalf("second session forwarded %q", command)
 144  		}
 145  	case <-time.After(2 * time.Second):
 146  		t.Fatal("the second session never reached the node, so the gateway stopped serving")
 147  	}
 148  }
 149  
 150  // TestAnUnknownChainNeverReachesANode: a client cannot make the gateway dial an arbitrary address by
 151  // naming a chain it does not serve.
 152  func TestAnUnknownChainNeverReachesANode(t *testing.T) {
 153  	dialed := make(chan struct{}, 1)
 154  
 155  	address := nodeScript(t, testMagic, func(conn net.Conn, reader *btcwire.Reader) {
 156  		dialed <- struct{}{}
 157  	})
 158  
 159  	srv := quietServer(address, testMagic)
 160  
 161  	runSession(srv, "ghost", func(client net.Conn) {
 162  		time.Sleep(100 * time.Millisecond)
 163  	})
 164  
 165  	select {
 166  	case <-dialed:
 167  		t.Fatal("a node was dialed for a chain the gateway does not serve")
 168  	case <-time.After(200 * time.Millisecond):
 169  	}
 170  }
 171  
 172  // TestMalformedFramesEndOneSessionOnly: garbage from a client is its own problem. The test process
 173  // would die on an unhandled panic, so surviving this is the assertion.
 174  func TestMalformedFramesEndOneSessionOnly(t *testing.T) {
 175  	magic := testMagic
 176  
 177  	address := nodeScript(t, magic, func(conn net.Conn, reader *btcwire.Reader) {
 178  		_, _ = reader.Next()
 179  	})
 180  
 181  	srv := quietServer(address, magic)
 182  
 183  	for _, junk := range [][]byte{
 184  		bytes.Repeat([]byte{0xff}, 64),                   // never a valid frame
 185  		{0xfa, 0xbf, 0xb5, 0xda, 0x67, 0x65, 0x74, 0x68}, // right magic, truncated command
 186  		{0xfa, 0xbf, 0xb5, 0xda},                         // magic only
 187  	} {
 188  		runSession(srv, "alpha", func(client net.Conn) {
 189  			_, _ = client.Write(junk)
 190  			time.Sleep(50 * time.Millisecond)
 191  		})
 192  	}
 193  }
 194  
 195  // TestACommandOutsideTheAllowlistIsNotForwarded: the gateway forwards the handshake and block data
 196  // it was told to forward, and nothing else, even if a client asks.
 197  func TestACommandOutsideTheAllowlistIsNotForwarded(t *testing.T) {
 198  	magic := testMagic
 199  	seen := make(chan string, 4)
 200  
 201  	address := nodeScript(t, magic, func(conn net.Conn, reader *btcwire.Reader) {
 202  		for {
 203  			msg, err := reader.Next()
 204  
 205  			if err != nil {
 206  				return
 207  			}
 208  
 209  			seen <- msg.Command
 210  		}
 211  	})
 212  
 213  	srv := quietServer(address, magic)
 214  
 215  	runSession(srv, "alpha", func(client net.Conn) {
 216  		// addrv2 is not in DefaultCommands: address discovery is never forwarded, and no
 217  		// allow list was configured to add it.
 218  		frame, _ := btcwire.EncodeMessage(magic, "addrv2", nil)
 219  		_, _ = client.Write(frame)
 220  		time.Sleep(200 * time.Millisecond)
 221  	})
 222  
 223  	select {
 224  	case command := <-seen:
 225  		if command == "addrv2" {
 226  			t.Fatal("a command outside the allowlist was forwarded")
 227  		}
 228  	case <-time.After(200 * time.Millisecond):
 229  	}
 230  }
 231  
 232  // TestASilentNodeEndsTheSession: a node that accepts and says nothing must not hold a client
 233  // forever. The session ends by the idle bound instead of hanging.
 234  func TestASilentNodeEndsTheSession(t *testing.T) {
 235  	magic := testMagic
 236  
 237  	address := nodeScript(t, magic, func(conn net.Conn, reader *btcwire.Reader) {
 238  		// Accept and stay silent, which is what a wedged node looks like.
 239  		time.Sleep(10 * time.Second)
 240  	})
 241  
 242  	srv := quietServer(address, magic)
 243  	srv.cfg.IdleTimeout = 500 * time.Millisecond
 244  
 245  	start := time.Now()
 246  
 247  	runSession(srv, "alpha", func(client net.Conn) {
 248  		frame, _ := btcwire.EncodeMessage(magic, btcwire.CmdGetHeaders, nil)
 249  		_, _ = client.Write(frame)
 250  		time.Sleep(3 * time.Second)
 251  	})
 252  
 253  	if elapsed := time.Since(start); elapsed > 3*time.Second {
 254  		t.Fatalf("a silent node held the session for %s", elapsed)
 255  	}
 256  }
 257  
 258  // TestANodeThatIsNotListeningDoesNotBlockTheGateway: dial failure is a session failure.
 259  func TestANodeThatIsNotListeningDoesNotBlockTheGateway(t *testing.T) {
 260  	srv := quietServer("127.0.0.1:1", testMagic)
 261  	srv.cfg.NodeDialTimeout = 500 * time.Millisecond
 262  
 263  	elapsed := runSession(srv, "alpha", func(client net.Conn) {
 264  		time.Sleep(200 * time.Millisecond)
 265  	})
 266  
 267  	if elapsed > 2*time.Second {
 268  		t.Fatalf("a dead node held the session for %s", elapsed)
 269  	}
 270  }
 271  
 272  // TestBlockRequestsAreSerialisedPerSession: a client that asks for several blocks
 273  // at once gets them one at a time.
 274  //
 275  // A block is the fattest thing a tunnel carries, and a wallet that asked for ten
 276  // would put megabytes into the relay's outbound queue behind its own coordination
 277  // traffic. The gateway splits the getdata and holds each request until the previous
 278  // block has been forwarded; this test is the ordering evidence.
 279  func TestBlockRequestsAreSerialisedPerSession(t *testing.T) {
 280  	magic := testMagic
 281  
 282  	type request struct {
 283  		count int
 284  		at    time.Time
 285  	}
 286  
 287  	seen := make(chan request, 8)
 288  	blocks := make(chan time.Time, 8)
 289  
 290  	address := nodeScript(t, magic, func(conn net.Conn, reader *btcwire.Reader) {
 291  		for {
 292  			msg, err := reader.Next()
 293  
 294  			if err != nil {
 295  				return
 296  			}
 297  
 298  			if msg.Command != btcwire.CmdGetData {
 299  				continue
 300  			}
 301  
 302  			var getdata btcwire.GetData
 303  
 304  			if err := getdata.DecodePayload(msg.Payload); err != nil {
 305  				return
 306  			}
 307  
 308  			seen <- request{count: len(getdata.InvList), at: time.Now()}
 309  
 310  			frame, err := btcwire.EncodeMessage(magic, btcwire.CmdBlock, []byte{0x01})
 311  
 312  			if err != nil {
 313  				return
 314  			}
 315  
 316  			if _, err := conn.Write(frame); err != nil {
 317  				return
 318  			}
 319  
 320  			blocks <- time.Now()
 321  		}
 322  	})
 323  
 324  	srv := quietServer(address, magic)
 325  	srv.cfg.Logf = t.Logf
 326  
 327  	runSession(srv, "alpha", func(client net.Conn) {
 328  		request := btcwire.GetData{InvList: []btcwire.InvVect{
 329  			{Type: btcwire.InvVectTypeWitnessBlock, Hash: chainhash.Hash{1}},
 330  			{Type: btcwire.InvVectTypeWitnessBlock, Hash: chainhash.Hash{2}},
 331  		}}
 332  
 333  		payload, err := request.EncodePayload()
 334  
 335  		if err != nil {
 336  			return
 337  		}
 338  
 339  		frame, err := btcwire.EncodeMessage(magic, btcwire.CmdGetData, payload)
 340  
 341  		if err != nil {
 342  			return
 343  		}
 344  
 345  		if _, err := client.Write(frame); err != nil {
 346  			return
 347  		}
 348  
 349  		// Two blocks come back; read them so the session is not closed by the
 350  		// client's own idle read deadline.
 351  		reader := btcwire.NewReader(client, magic)
 352  
 353  		for i := 0; i < 2; i++ {
 354  			if _, err := reader.Next(); err != nil {
 355  				return
 356  			}
 357  		}
 358  
 359  		time.Sleep(100 * time.Millisecond)
 360  	})
 361  
 362  	first := <-seen
 363  
 364  	if first.count == -1 {
 365  		t.Fatal("the node was dialed but no getdata reached it")
 366  	}
 367  
 368  	second := <-seen
 369  
 370  	if first.count != 1 || second.count != 1 {
 371  		t.Fatalf("the node saw getdata requests of %d and %d inventories, want one each",
 372  			first.count, second.count)
 373  	}
 374  
 375  	firstBlock := <-blocks
 376  	secondBlock := <-blocks
 377  
 378  	if !second.at.After(firstBlock) {
 379  		t.Fatalf("the second block was requested %s before the first was answered",
 380  			firstBlock.Sub(second.at))
 381  	}
 382  
 383  	if !secondBlock.After(firstBlock) {
 384  		t.Fatal("the node answered the two requests out of order")
 385  	}
 386  }
 387