github.com/julesgoullee/go-ethereum@v1.9.7/p2p/server_test.go (about)

     1  // Copyright 2014 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package p2p
    18  
    19  import (
    20  	"crypto/ecdsa"
    21  	"errors"
    22  	"io"
    23  	"math/rand"
    24  	"net"
    25  	"reflect"
    26  	"testing"
    27  	"time"
    28  
    29  	"github.com/ethereum/go-ethereum/crypto"
    30  	"github.com/ethereum/go-ethereum/internal/testlog"
    31  	"github.com/ethereum/go-ethereum/log"
    32  	"github.com/ethereum/go-ethereum/p2p/enode"
    33  	"github.com/ethereum/go-ethereum/p2p/enr"
    34  	"golang.org/x/crypto/sha3"
    35  )
    36  
    37  // func init() {
    38  // 	log.Root().SetHandler(log.LvlFilterHandler(log.LvlTrace, log.StreamHandler(os.Stderr, log.TerminalFormat(false))))
    39  // }
    40  
    41  type testTransport struct {
    42  	rpub *ecdsa.PublicKey
    43  	*rlpx
    44  
    45  	closeErr error
    46  }
    47  
    48  func newTestTransport(rpub *ecdsa.PublicKey, fd net.Conn) transport {
    49  	wrapped := newRLPX(fd).(*rlpx)
    50  	wrapped.rw = newRLPXFrameRW(fd, secrets{
    51  		MAC:        zero16,
    52  		AES:        zero16,
    53  		IngressMAC: sha3.NewLegacyKeccak256(),
    54  		EgressMAC:  sha3.NewLegacyKeccak256(),
    55  	})
    56  	return &testTransport{rpub: rpub, rlpx: wrapped}
    57  }
    58  
    59  func (c *testTransport) doEncHandshake(prv *ecdsa.PrivateKey, dialDest *ecdsa.PublicKey) (*ecdsa.PublicKey, error) {
    60  	return c.rpub, nil
    61  }
    62  
    63  func (c *testTransport) doProtoHandshake(our *protoHandshake) (*protoHandshake, error) {
    64  	pubkey := crypto.FromECDSAPub(c.rpub)[1:]
    65  	return &protoHandshake{ID: pubkey, Name: "test"}, nil
    66  }
    67  
    68  func (c *testTransport) close(err error) {
    69  	c.rlpx.fd.Close()
    70  	c.closeErr = err
    71  }
    72  
    73  func startTestServer(t *testing.T, remoteKey *ecdsa.PublicKey, pf func(*Peer)) *Server {
    74  	config := Config{
    75  		Name:       "test",
    76  		MaxPeers:   10,
    77  		ListenAddr: "127.0.0.1:0",
    78  		PrivateKey: newkey(),
    79  		Logger:     testlog.Logger(t, log.LvlTrace),
    80  	}
    81  	server := &Server{
    82  		Config:       config,
    83  		newPeerHook:  pf,
    84  		newTransport: func(fd net.Conn) transport { return newTestTransport(remoteKey, fd) },
    85  	}
    86  	if err := server.Start(); err != nil {
    87  		t.Fatalf("Could not start server: %v", err)
    88  	}
    89  	return server
    90  }
    91  
    92  func TestServerListen(t *testing.T) {
    93  	// start the test server
    94  	connected := make(chan *Peer)
    95  	remid := &newkey().PublicKey
    96  	srv := startTestServer(t, remid, func(p *Peer) {
    97  		if p.ID() != enode.PubkeyToIDV4(remid) {
    98  			t.Error("peer func called with wrong node id")
    99  		}
   100  		connected <- p
   101  	})
   102  	defer close(connected)
   103  	defer srv.Stop()
   104  
   105  	// dial the test server
   106  	conn, err := net.DialTimeout("tcp", srv.ListenAddr, 5*time.Second)
   107  	if err != nil {
   108  		t.Fatalf("could not dial: %v", err)
   109  	}
   110  	defer conn.Close()
   111  
   112  	select {
   113  	case peer := <-connected:
   114  		if peer.LocalAddr().String() != conn.RemoteAddr().String() {
   115  			t.Errorf("peer started with wrong conn: got %v, want %v",
   116  				peer.LocalAddr(), conn.RemoteAddr())
   117  		}
   118  		peers := srv.Peers()
   119  		if !reflect.DeepEqual(peers, []*Peer{peer}) {
   120  			t.Errorf("Peers mismatch: got %v, want %v", peers, []*Peer{peer})
   121  		}
   122  	case <-time.After(1 * time.Second):
   123  		t.Error("server did not accept within one second")
   124  	}
   125  }
   126  
   127  func TestServerDial(t *testing.T) {
   128  	// run a one-shot TCP server to handle the connection.
   129  	listener, err := net.Listen("tcp", "127.0.0.1:0")
   130  	if err != nil {
   131  		t.Fatalf("could not setup listener: %v", err)
   132  	}
   133  	defer listener.Close()
   134  	accepted := make(chan net.Conn)
   135  	go func() {
   136  		conn, err := listener.Accept()
   137  		if err != nil {
   138  			t.Error("accept error:", err)
   139  			return
   140  		}
   141  		accepted <- conn
   142  	}()
   143  
   144  	// start the server
   145  	connected := make(chan *Peer)
   146  	remid := &newkey().PublicKey
   147  	srv := startTestServer(t, remid, func(p *Peer) { connected <- p })
   148  	defer close(connected)
   149  	defer srv.Stop()
   150  
   151  	// tell the server to connect
   152  	tcpAddr := listener.Addr().(*net.TCPAddr)
   153  	node := enode.NewV4(remid, tcpAddr.IP, tcpAddr.Port, 0)
   154  	srv.AddPeer(node)
   155  
   156  	select {
   157  	case conn := <-accepted:
   158  		defer conn.Close()
   159  
   160  		select {
   161  		case peer := <-connected:
   162  			if peer.ID() != enode.PubkeyToIDV4(remid) {
   163  				t.Errorf("peer has wrong id")
   164  			}
   165  			if peer.Name() != "test" {
   166  				t.Errorf("peer has wrong name")
   167  			}
   168  			if peer.RemoteAddr().String() != conn.LocalAddr().String() {
   169  				t.Errorf("peer started with wrong conn: got %v, want %v",
   170  					peer.RemoteAddr(), conn.LocalAddr())
   171  			}
   172  			peers := srv.Peers()
   173  			if !reflect.DeepEqual(peers, []*Peer{peer}) {
   174  				t.Errorf("Peers mismatch: got %v, want %v", peers, []*Peer{peer})
   175  			}
   176  
   177  			// Test AddTrustedPeer/RemoveTrustedPeer and changing Trusted flags
   178  			// Particularly for race conditions on changing the flag state.
   179  			if peer := srv.Peers()[0]; peer.Info().Network.Trusted {
   180  				t.Errorf("peer is trusted prematurely: %v", peer)
   181  			}
   182  			done := make(chan bool)
   183  			go func() {
   184  				srv.AddTrustedPeer(node)
   185  				if peer := srv.Peers()[0]; !peer.Info().Network.Trusted {
   186  					t.Errorf("peer is not trusted after AddTrustedPeer: %v", peer)
   187  				}
   188  				srv.RemoveTrustedPeer(node)
   189  				if peer := srv.Peers()[0]; peer.Info().Network.Trusted {
   190  					t.Errorf("peer is trusted after RemoveTrustedPeer: %v", peer)
   191  				}
   192  				done <- true
   193  			}()
   194  			// Trigger potential race conditions
   195  			peer = srv.Peers()[0]
   196  			_ = peer.Inbound()
   197  			_ = peer.Info()
   198  			<-done
   199  		case <-time.After(1 * time.Second):
   200  			t.Error("server did not launch peer within one second")
   201  		}
   202  
   203  	case <-time.After(1 * time.Second):
   204  		t.Error("server did not connect within one second")
   205  	}
   206  }
   207  
   208  // This test checks that tasks generated by dialstate are
   209  // actually executed and taskdone is called for them.
   210  func TestServerTaskScheduling(t *testing.T) {
   211  	var (
   212  		done           = make(chan *testTask)
   213  		quit, returned = make(chan struct{}), make(chan struct{})
   214  		tc             = 0
   215  		tg             = taskgen{
   216  			newFunc: func(running int, peers map[enode.ID]*Peer) []task {
   217  				tc++
   218  				return []task{&testTask{index: tc - 1}}
   219  			},
   220  			doneFunc: func(t task) {
   221  				select {
   222  				case done <- t.(*testTask):
   223  				case <-quit:
   224  				}
   225  			},
   226  		}
   227  	)
   228  
   229  	// The Server in this test isn't actually running
   230  	// because we're only interested in what run does.
   231  	db, _ := enode.OpenDB("")
   232  	srv := &Server{
   233  		Config:    Config{MaxPeers: 10},
   234  		localnode: enode.NewLocalNode(db, newkey()),
   235  		nodedb:    db,
   236  		discmix:   enode.NewFairMix(0),
   237  		quit:      make(chan struct{}),
   238  		running:   true,
   239  		log:       log.New(),
   240  	}
   241  	srv.loopWG.Add(1)
   242  	go func() {
   243  		srv.run(tg)
   244  		close(returned)
   245  	}()
   246  
   247  	var gotdone []*testTask
   248  	for i := 0; i < 100; i++ {
   249  		gotdone = append(gotdone, <-done)
   250  	}
   251  	for i, task := range gotdone {
   252  		if task.index != i {
   253  			t.Errorf("task %d has wrong index, got %d", i, task.index)
   254  			break
   255  		}
   256  		if !task.called {
   257  			t.Errorf("task %d was not called", i)
   258  			break
   259  		}
   260  	}
   261  
   262  	close(quit)
   263  	srv.Stop()
   264  	select {
   265  	case <-returned:
   266  	case <-time.After(500 * time.Millisecond):
   267  		t.Error("Server.run did not return within 500ms")
   268  	}
   269  }
   270  
   271  // This test checks that Server doesn't drop tasks,
   272  // even if newTasks returns more than the maximum number of tasks.
   273  func TestServerManyTasks(t *testing.T) {
   274  	alltasks := make([]task, 300)
   275  	for i := range alltasks {
   276  		alltasks[i] = &testTask{index: i}
   277  	}
   278  
   279  	var (
   280  		db, _ = enode.OpenDB("")
   281  		srv   = &Server{
   282  			quit:      make(chan struct{}),
   283  			localnode: enode.NewLocalNode(db, newkey()),
   284  			nodedb:    db,
   285  			running:   true,
   286  			log:       log.New(),
   287  			discmix:   enode.NewFairMix(0),
   288  		}
   289  		done       = make(chan *testTask)
   290  		start, end = 0, 0
   291  	)
   292  	defer srv.Stop()
   293  	srv.loopWG.Add(1)
   294  	go srv.run(taskgen{
   295  		newFunc: func(running int, peers map[enode.ID]*Peer) []task {
   296  			start, end = end, end+maxActiveDialTasks+10
   297  			if end > len(alltasks) {
   298  				end = len(alltasks)
   299  			}
   300  			return alltasks[start:end]
   301  		},
   302  		doneFunc: func(tt task) {
   303  			done <- tt.(*testTask)
   304  		},
   305  	})
   306  
   307  	doneset := make(map[int]bool)
   308  	timeout := time.After(2 * time.Second)
   309  	for len(doneset) < len(alltasks) {
   310  		select {
   311  		case tt := <-done:
   312  			if doneset[tt.index] {
   313  				t.Errorf("task %d got done more than once", tt.index)
   314  			} else {
   315  				doneset[tt.index] = true
   316  			}
   317  		case <-timeout:
   318  			t.Errorf("%d of %d tasks got done within 2s", len(doneset), len(alltasks))
   319  			for i := 0; i < len(alltasks); i++ {
   320  				if !doneset[i] {
   321  					t.Logf("task %d not done", i)
   322  				}
   323  			}
   324  			return
   325  		}
   326  	}
   327  }
   328  
   329  type taskgen struct {
   330  	newFunc  func(running int, peers map[enode.ID]*Peer) []task
   331  	doneFunc func(task)
   332  }
   333  
   334  func (tg taskgen) newTasks(running int, peers map[enode.ID]*Peer, now time.Time) []task {
   335  	return tg.newFunc(running, peers)
   336  }
   337  func (tg taskgen) taskDone(t task, now time.Time) {
   338  	tg.doneFunc(t)
   339  }
   340  func (tg taskgen) addStatic(*enode.Node) {
   341  }
   342  func (tg taskgen) removeStatic(*enode.Node) {
   343  }
   344  
   345  type testTask struct {
   346  	index  int
   347  	called bool
   348  }
   349  
   350  func (t *testTask) Do(srv *Server) {
   351  	t.called = true
   352  }
   353  
   354  // This test checks that connections are disconnected
   355  // just after the encryption handshake when the server is
   356  // at capacity. Trusted connections should still be accepted.
   357  func TestServerAtCap(t *testing.T) {
   358  	trustedNode := newkey()
   359  	trustedID := enode.PubkeyToIDV4(&trustedNode.PublicKey)
   360  	srv := &Server{
   361  		Config: Config{
   362  			PrivateKey:   newkey(),
   363  			MaxPeers:     10,
   364  			NoDial:       true,
   365  			NoDiscovery:  true,
   366  			TrustedNodes: []*enode.Node{newNode(trustedID, nil)},
   367  		},
   368  	}
   369  	if err := srv.Start(); err != nil {
   370  		t.Fatalf("could not start: %v", err)
   371  	}
   372  	defer srv.Stop()
   373  
   374  	newconn := func(id enode.ID) *conn {
   375  		fd, _ := net.Pipe()
   376  		tx := newTestTransport(&trustedNode.PublicKey, fd)
   377  		node := enode.SignNull(new(enr.Record), id)
   378  		return &conn{fd: fd, transport: tx, flags: inboundConn, node: node, cont: make(chan error)}
   379  	}
   380  
   381  	// Inject a few connections to fill up the peer set.
   382  	for i := 0; i < 10; i++ {
   383  		c := newconn(randomID())
   384  		if err := srv.checkpoint(c, srv.checkpointAddPeer); err != nil {
   385  			t.Fatalf("could not add conn %d: %v", i, err)
   386  		}
   387  	}
   388  	// Try inserting a non-trusted connection.
   389  	anotherID := randomID()
   390  	c := newconn(anotherID)
   391  	if err := srv.checkpoint(c, srv.checkpointPostHandshake); err != DiscTooManyPeers {
   392  		t.Error("wrong error for insert:", err)
   393  	}
   394  	// Try inserting a trusted connection.
   395  	c = newconn(trustedID)
   396  	if err := srv.checkpoint(c, srv.checkpointPostHandshake); err != nil {
   397  		t.Error("unexpected error for trusted conn @posthandshake:", err)
   398  	}
   399  	if !c.is(trustedConn) {
   400  		t.Error("Server did not set trusted flag")
   401  	}
   402  
   403  	// Remove from trusted set and try again
   404  	srv.RemoveTrustedPeer(newNode(trustedID, nil))
   405  	c = newconn(trustedID)
   406  	if err := srv.checkpoint(c, srv.checkpointPostHandshake); err != DiscTooManyPeers {
   407  		t.Error("wrong error for insert:", err)
   408  	}
   409  
   410  	// Add anotherID to trusted set and try again
   411  	srv.AddTrustedPeer(newNode(anotherID, nil))
   412  	c = newconn(anotherID)
   413  	if err := srv.checkpoint(c, srv.checkpointPostHandshake); err != nil {
   414  		t.Error("unexpected error for trusted conn @posthandshake:", err)
   415  	}
   416  	if !c.is(trustedConn) {
   417  		t.Error("Server did not set trusted flag")
   418  	}
   419  }
   420  
   421  func TestServerPeerLimits(t *testing.T) {
   422  	srvkey := newkey()
   423  	clientkey := newkey()
   424  	clientnode := enode.NewV4(&clientkey.PublicKey, nil, 0, 0)
   425  
   426  	var tp = &setupTransport{
   427  		pubkey: &clientkey.PublicKey,
   428  		phs: protoHandshake{
   429  			ID: crypto.FromECDSAPub(&clientkey.PublicKey)[1:],
   430  			// Force "DiscUselessPeer" due to unmatching caps
   431  			// Caps: []Cap{discard.cap()},
   432  		},
   433  	}
   434  
   435  	srv := &Server{
   436  		Config: Config{
   437  			PrivateKey:  srvkey,
   438  			MaxPeers:    0,
   439  			NoDial:      true,
   440  			NoDiscovery: true,
   441  			Protocols:   []Protocol{discard},
   442  		},
   443  		newTransport: func(fd net.Conn) transport { return tp },
   444  		log:          log.New(),
   445  	}
   446  	if err := srv.Start(); err != nil {
   447  		t.Fatalf("couldn't start server: %v", err)
   448  	}
   449  	defer srv.Stop()
   450  
   451  	// Check that server is full (MaxPeers=0)
   452  	flags := dynDialedConn
   453  	dialDest := clientnode
   454  	conn, _ := net.Pipe()
   455  	srv.SetupConn(conn, flags, dialDest)
   456  	if tp.closeErr != DiscTooManyPeers {
   457  		t.Errorf("unexpected close error: %q", tp.closeErr)
   458  	}
   459  	conn.Close()
   460  
   461  	srv.AddTrustedPeer(clientnode)
   462  
   463  	// Check that server allows a trusted peer despite being full.
   464  	conn, _ = net.Pipe()
   465  	srv.SetupConn(conn, flags, dialDest)
   466  	if tp.closeErr == DiscTooManyPeers {
   467  		t.Errorf("failed to bypass MaxPeers with trusted node: %q", tp.closeErr)
   468  	}
   469  
   470  	if tp.closeErr != DiscUselessPeer {
   471  		t.Errorf("unexpected close error: %q", tp.closeErr)
   472  	}
   473  	conn.Close()
   474  
   475  	srv.RemoveTrustedPeer(clientnode)
   476  
   477  	// Check that server is full again.
   478  	conn, _ = net.Pipe()
   479  	srv.SetupConn(conn, flags, dialDest)
   480  	if tp.closeErr != DiscTooManyPeers {
   481  		t.Errorf("unexpected close error: %q", tp.closeErr)
   482  	}
   483  	conn.Close()
   484  }
   485  
   486  func TestServerSetupConn(t *testing.T) {
   487  	var (
   488  		clientkey, srvkey = newkey(), newkey()
   489  		clientpub         = &clientkey.PublicKey
   490  		srvpub            = &srvkey.PublicKey
   491  	)
   492  	tests := []struct {
   493  		dontstart bool
   494  		tt        *setupTransport
   495  		flags     connFlag
   496  		dialDest  *enode.Node
   497  
   498  		wantCloseErr error
   499  		wantCalls    string
   500  	}{
   501  		{
   502  			dontstart:    true,
   503  			tt:           &setupTransport{pubkey: clientpub},
   504  			wantCalls:    "close,",
   505  			wantCloseErr: errServerStopped,
   506  		},
   507  		{
   508  			tt:           &setupTransport{pubkey: clientpub, encHandshakeErr: errors.New("read error")},
   509  			flags:        inboundConn,
   510  			wantCalls:    "doEncHandshake,close,",
   511  			wantCloseErr: errors.New("read error"),
   512  		},
   513  		{
   514  			tt:           &setupTransport{pubkey: clientpub},
   515  			dialDest:     enode.NewV4(&newkey().PublicKey, nil, 0, 0),
   516  			flags:        dynDialedConn,
   517  			wantCalls:    "doEncHandshake,close,",
   518  			wantCloseErr: DiscUnexpectedIdentity,
   519  		},
   520  		{
   521  			tt:           &setupTransport{pubkey: clientpub, phs: protoHandshake{ID: randomID().Bytes()}},
   522  			dialDest:     enode.NewV4(clientpub, nil, 0, 0),
   523  			flags:        dynDialedConn,
   524  			wantCalls:    "doEncHandshake,doProtoHandshake,close,",
   525  			wantCloseErr: DiscUnexpectedIdentity,
   526  		},
   527  		{
   528  			tt:           &setupTransport{pubkey: clientpub, protoHandshakeErr: errors.New("foo")},
   529  			dialDest:     enode.NewV4(clientpub, nil, 0, 0),
   530  			flags:        dynDialedConn,
   531  			wantCalls:    "doEncHandshake,doProtoHandshake,close,",
   532  			wantCloseErr: errors.New("foo"),
   533  		},
   534  		{
   535  			tt:           &setupTransport{pubkey: srvpub, phs: protoHandshake{ID: crypto.FromECDSAPub(srvpub)[1:]}},
   536  			flags:        inboundConn,
   537  			wantCalls:    "doEncHandshake,close,",
   538  			wantCloseErr: DiscSelf,
   539  		},
   540  		{
   541  			tt:           &setupTransport{pubkey: clientpub, phs: protoHandshake{ID: crypto.FromECDSAPub(clientpub)[1:]}},
   542  			flags:        inboundConn,
   543  			wantCalls:    "doEncHandshake,doProtoHandshake,close,",
   544  			wantCloseErr: DiscUselessPeer,
   545  		},
   546  	}
   547  
   548  	for i, test := range tests {
   549  		t.Run(test.wantCalls, func(t *testing.T) {
   550  			cfg := Config{
   551  				PrivateKey:  srvkey,
   552  				MaxPeers:    10,
   553  				NoDial:      true,
   554  				NoDiscovery: true,
   555  				Protocols:   []Protocol{discard},
   556  				Logger:      testlog.Logger(t, log.LvlTrace),
   557  			}
   558  			srv := &Server{
   559  				Config:       cfg,
   560  				newTransport: func(fd net.Conn) transport { return test.tt },
   561  				log:          cfg.Logger,
   562  			}
   563  			if !test.dontstart {
   564  				if err := srv.Start(); err != nil {
   565  					t.Fatalf("couldn't start server: %v", err)
   566  				}
   567  				defer srv.Stop()
   568  			}
   569  			p1, _ := net.Pipe()
   570  			srv.SetupConn(p1, test.flags, test.dialDest)
   571  			if !reflect.DeepEqual(test.tt.closeErr, test.wantCloseErr) {
   572  				t.Errorf("test %d: close error mismatch: got %q, want %q", i, test.tt.closeErr, test.wantCloseErr)
   573  			}
   574  			if test.tt.calls != test.wantCalls {
   575  				t.Errorf("test %d: calls mismatch: got %q, want %q", i, test.tt.calls, test.wantCalls)
   576  			}
   577  		})
   578  	}
   579  }
   580  
   581  type setupTransport struct {
   582  	pubkey            *ecdsa.PublicKey
   583  	encHandshakeErr   error
   584  	phs               protoHandshake
   585  	protoHandshakeErr error
   586  
   587  	calls    string
   588  	closeErr error
   589  }
   590  
   591  func (c *setupTransport) doEncHandshake(prv *ecdsa.PrivateKey, dialDest *ecdsa.PublicKey) (*ecdsa.PublicKey, error) {
   592  	c.calls += "doEncHandshake,"
   593  	return c.pubkey, c.encHandshakeErr
   594  }
   595  
   596  func (c *setupTransport) doProtoHandshake(our *protoHandshake) (*protoHandshake, error) {
   597  	c.calls += "doProtoHandshake,"
   598  	if c.protoHandshakeErr != nil {
   599  		return nil, c.protoHandshakeErr
   600  	}
   601  	return &c.phs, nil
   602  }
   603  func (c *setupTransport) close(err error) {
   604  	c.calls += "close,"
   605  	c.closeErr = err
   606  }
   607  
   608  // setupConn shouldn't write to/read from the connection.
   609  func (c *setupTransport) WriteMsg(Msg) error {
   610  	panic("WriteMsg called on setupTransport")
   611  }
   612  func (c *setupTransport) ReadMsg() (Msg, error) {
   613  	panic("ReadMsg called on setupTransport")
   614  }
   615  
   616  func newkey() *ecdsa.PrivateKey {
   617  	key, err := crypto.GenerateKey()
   618  	if err != nil {
   619  		panic("couldn't generate key: " + err.Error())
   620  	}
   621  	return key
   622  }
   623  
   624  func randomID() (id enode.ID) {
   625  	for i := range id {
   626  		id[i] = byte(rand.Intn(255))
   627  	}
   628  	return id
   629  }
   630  
   631  // This test checks that inbound connections are throttled by IP.
   632  func TestServerInboundThrottle(t *testing.T) {
   633  	const timeout = 5 * time.Second
   634  	newTransportCalled := make(chan struct{})
   635  	srv := &Server{
   636  		Config: Config{
   637  			PrivateKey:  newkey(),
   638  			ListenAddr:  "127.0.0.1:0",
   639  			MaxPeers:    10,
   640  			NoDial:      true,
   641  			NoDiscovery: true,
   642  			Protocols:   []Protocol{discard},
   643  			Logger:      testlog.Logger(t, log.LvlTrace),
   644  		},
   645  		newTransport: func(fd net.Conn) transport {
   646  			newTransportCalled <- struct{}{}
   647  			return newRLPX(fd)
   648  		},
   649  		listenFunc: func(network, laddr string) (net.Listener, error) {
   650  			fakeAddr := &net.TCPAddr{IP: net.IP{95, 33, 21, 2}, Port: 4444}
   651  			return listenFakeAddr(network, laddr, fakeAddr)
   652  		},
   653  	}
   654  	if err := srv.Start(); err != nil {
   655  		t.Fatal("can't start: ", err)
   656  	}
   657  	defer srv.Stop()
   658  
   659  	// Dial the test server.
   660  	conn, err := net.DialTimeout("tcp", srv.ListenAddr, timeout)
   661  	if err != nil {
   662  		t.Fatalf("could not dial: %v", err)
   663  	}
   664  	select {
   665  	case <-newTransportCalled:
   666  		// OK
   667  	case <-time.After(timeout):
   668  		t.Error("newTransport not called")
   669  	}
   670  	conn.Close()
   671  
   672  	// Dial again. This time the server should close the connection immediately.
   673  	connClosed := make(chan struct{})
   674  	conn, err = net.DialTimeout("tcp", srv.ListenAddr, timeout)
   675  	if err != nil {
   676  		t.Fatalf("could not dial: %v", err)
   677  	}
   678  	defer conn.Close()
   679  	go func() {
   680  		conn.SetDeadline(time.Now().Add(timeout))
   681  		buf := make([]byte, 10)
   682  		if n, err := conn.Read(buf); err != io.EOF || n != 0 {
   683  			t.Errorf("expected io.EOF and n == 0, got error %q and n == %d", err, n)
   684  		}
   685  		connClosed <- struct{}{}
   686  	}()
   687  	select {
   688  	case <-connClosed:
   689  		// OK
   690  	case <-newTransportCalled:
   691  		t.Error("newTransport called for second attempt")
   692  	case <-time.After(timeout):
   693  		t.Error("connection not closed within timeout")
   694  	}
   695  }
   696  
   697  func listenFakeAddr(network, laddr string, remoteAddr net.Addr) (net.Listener, error) {
   698  	l, err := net.Listen(network, laddr)
   699  	if err == nil {
   700  		l = &fakeAddrListener{l, remoteAddr}
   701  	}
   702  	return l, err
   703  }
   704  
   705  // fakeAddrListener is a listener that creates connections with a mocked remote address.
   706  type fakeAddrListener struct {
   707  	net.Listener
   708  	remoteAddr net.Addr
   709  }
   710  
   711  type fakeAddrConn struct {
   712  	net.Conn
   713  	remoteAddr net.Addr
   714  }
   715  
   716  func (l *fakeAddrListener) Accept() (net.Conn, error) {
   717  	c, err := l.Listener.Accept()
   718  	if err != nil {
   719  		return nil, err
   720  	}
   721  	return &fakeAddrConn{c, l.remoteAddr}, nil
   722  }
   723  
   724  func (c *fakeAddrConn) RemoteAddr() net.Addr {
   725  	return c.remoteAddr
   726  }