github.com/ethereumproject/go-ethereum@v5.5.2+incompatible/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  	"math/rand"
    23  	"net"
    24  	"reflect"
    25  	"testing"
    26  	"time"
    27  
    28  	"github.com/ethereumproject/go-ethereum/crypto"
    29  	"github.com/ethereumproject/go-ethereum/crypto/sha3"
    30  	"github.com/ethereumproject/go-ethereum/p2p/discover"
    31  )
    32  
    33  func init() {
    34  	// glog.SetV(6)
    35  	// glog.SetToStderr(true)
    36  }
    37  
    38  type testTransport struct {
    39  	id discover.NodeID
    40  	*rlpx
    41  
    42  	closeErr error
    43  }
    44  
    45  func newTestTransport(id discover.NodeID, fd net.Conn) transport {
    46  	wrapped := newRLPX(fd).(*rlpx)
    47  	wrapped.rw = newRLPXFrameRW(fd, secrets{
    48  		MAC:        zero16,
    49  		AES:        zero16,
    50  		IngressMAC: sha3.NewKeccak256(),
    51  		EgressMAC:  sha3.NewKeccak256(),
    52  	})
    53  	return &testTransport{id: id, rlpx: wrapped}
    54  }
    55  
    56  func (c *testTransport) doEncHandshake(prv *ecdsa.PrivateKey, dialDest *discover.Node) (discover.NodeID, error) {
    57  	return c.id, nil
    58  }
    59  
    60  func (c *testTransport) doProtoHandshake(our *protoHandshake) (*protoHandshake, error) {
    61  	return &protoHandshake{ID: c.id, Name: "test"}, nil
    62  }
    63  
    64  func (c *testTransport) close(err error) {
    65  	c.rlpx.fd.Close()
    66  	c.closeErr = err
    67  }
    68  
    69  func startTestServer(t *testing.T, id discover.NodeID, pf func(*Peer)) *Server {
    70  	config := Config{
    71  		Name:       "test",
    72  		MaxPeers:   10,
    73  		ListenAddr: "127.0.0.1:0",
    74  		PrivateKey: newkey(),
    75  	}
    76  	server := &Server{
    77  		Config:       config,
    78  		newPeerHook:  pf,
    79  		newTransport: func(fd net.Conn) transport { return newTestTransport(id, fd) },
    80  	}
    81  	if err := server.Start(); err != nil {
    82  		t.Fatalf("Could not start server: %v", err)
    83  	}
    84  	return server
    85  }
    86  
    87  func TestServerListen(t *testing.T) {
    88  	// start the test server
    89  	connected := make(chan *Peer)
    90  	remid := randomID()
    91  	srv := startTestServer(t, remid, func(p *Peer) {
    92  		if p.ID() != remid {
    93  			t.Error("peer func called with wrong node id")
    94  		}
    95  		if p == nil {
    96  			t.Error("peer func called with nil conn")
    97  		}
    98  		connected <- p
    99  	})
   100  	defer close(connected)
   101  	defer srv.Stop()
   102  
   103  	// dial the test server
   104  	conn, err := net.DialTimeout("tcp", srv.ListenAddr, 5*time.Second)
   105  	if err != nil {
   106  		t.Fatalf("could not dial: %v", err)
   107  	}
   108  	defer conn.Close()
   109  
   110  	select {
   111  	case peer := <-connected:
   112  		if peer.LocalAddr().String() != conn.RemoteAddr().String() {
   113  			t.Errorf("peer started with wrong conn: got %v, want %v",
   114  				peer.LocalAddr(), conn.RemoteAddr())
   115  		}
   116  		peers := srv.Peers()
   117  		if !reflect.DeepEqual(peers, []*Peer{peer}) {
   118  			t.Errorf("Peers mismatch: got %v, want %v", peers, []*Peer{peer})
   119  		}
   120  	case <-time.After(1 * time.Second):
   121  		t.Error("server did not accept within one second")
   122  	}
   123  }
   124  
   125  func TestServerDial(t *testing.T) {
   126  	// run a one-shot TCP server to handle the connection.
   127  	listener, err := net.Listen("tcp", "127.0.0.1:0")
   128  	if err != nil {
   129  		t.Fatalf("could not setup listener: %v", err)
   130  	}
   131  	defer listener.Close()
   132  	accepted := make(chan net.Conn)
   133  	go func() {
   134  		conn, err := listener.Accept()
   135  		if err != nil {
   136  			t.Error("accept error:", err)
   137  			return
   138  		}
   139  		accepted <- conn
   140  	}()
   141  
   142  	// start the server
   143  	connected := make(chan *Peer)
   144  	remid := randomID()
   145  	srv := startTestServer(t, remid, func(p *Peer) { connected <- p })
   146  	defer close(connected)
   147  	defer srv.Stop()
   148  
   149  	// tell the server to connect
   150  	tcpAddr := listener.Addr().(*net.TCPAddr)
   151  	srv.AddPeer(&discover.Node{ID: remid, IP: tcpAddr.IP, TCP: uint16(tcpAddr.Port)})
   152  
   153  	select {
   154  	case conn := <-accepted:
   155  		defer conn.Close()
   156  
   157  		select {
   158  		case peer := <-connected:
   159  			if peer.ID() != remid {
   160  				t.Errorf("peer has wrong id")
   161  			}
   162  			if peer.Name() != "test" {
   163  				t.Errorf("peer has wrong name")
   164  			}
   165  			if peer.RemoteAddr().String() != conn.LocalAddr().String() {
   166  				t.Errorf("peer started with wrong conn: got %v, want %v",
   167  					peer.RemoteAddr(), conn.LocalAddr())
   168  			}
   169  			peers := srv.Peers()
   170  			if !reflect.DeepEqual(peers, []*Peer{peer}) {
   171  				t.Errorf("Peers mismatch: got %v, want %v", peers, []*Peer{peer})
   172  			}
   173  		case <-time.After(1 * time.Second):
   174  			t.Error("server did not launch peer within one second")
   175  		}
   176  
   177  	case <-time.After(1 * time.Second):
   178  		t.Error("server did not connect within one second")
   179  	}
   180  }
   181  
   182  // This test checks that tasks generated by dialstate are
   183  // actually executed and taskdone is called for them.
   184  func TestServerTaskScheduling(t *testing.T) {
   185  	var (
   186  		done           = make(chan *testTask)
   187  		quit, returned = make(chan struct{}), make(chan struct{})
   188  		tc             = 0
   189  		tg             = taskgen{
   190  			newFunc: func(running int, peers map[discover.NodeID]*Peer) []task {
   191  				tc++
   192  				return []task{&testTask{index: tc - 1}}
   193  			},
   194  			doneFunc: func(t task) {
   195  				select {
   196  				case done <- t.(*testTask):
   197  				case <-quit:
   198  				}
   199  			},
   200  		}
   201  	)
   202  
   203  	// The Server in this test isn't actually running
   204  	// because we're only interested in what run does.
   205  	srv := &Server{
   206  		Config:  Config{MaxPeers: 10},
   207  		quit:    make(chan struct{}),
   208  		ntab:    fakeTable{},
   209  		running: true,
   210  	}
   211  	srv.loopWG.Add(1)
   212  	go func() {
   213  		srv.run(tg)
   214  		close(returned)
   215  	}()
   216  
   217  	var gotdone []*testTask
   218  	for i := 0; i < 100; i++ {
   219  		gotdone = append(gotdone, <-done)
   220  	}
   221  	for i, task := range gotdone {
   222  		if task.index != i {
   223  			t.Errorf("task %d has wrong index, got %d", i, task.index)
   224  			break
   225  		}
   226  		if !task.called {
   227  			t.Errorf("task %d was not called", i)
   228  			break
   229  		}
   230  	}
   231  
   232  	close(quit)
   233  	srv.Stop()
   234  	select {
   235  	case <-returned:
   236  	case <-time.After(500 * time.Millisecond):
   237  		t.Error("Server.run did not return within 500ms")
   238  	}
   239  }
   240  
   241  // This test checks that Server doesn't drop tasks,
   242  // even if newTasks returns more than the maximum number of tasks.
   243  func TestServerManyTasks(t *testing.T) {
   244  	alltasks := make([]task, 300)
   245  	for i := range alltasks {
   246  		alltasks[i] = &testTask{index: i}
   247  	}
   248  
   249  	var (
   250  		srv        = &Server{quit: make(chan struct{}), ntab: fakeTable{}, running: true}
   251  		done       = make(chan *testTask)
   252  		start, end = 0, 0
   253  	)
   254  	defer srv.Stop()
   255  	srv.loopWG.Add(1)
   256  	go srv.run(taskgen{
   257  		newFunc: func(running int, peers map[discover.NodeID]*Peer) []task {
   258  			start, end = end, end+maxActiveDialTasks+10
   259  			if end > len(alltasks) {
   260  				end = len(alltasks)
   261  			}
   262  			return alltasks[start:end]
   263  		},
   264  		doneFunc: func(tt task) {
   265  			done <- tt.(*testTask)
   266  		},
   267  	})
   268  
   269  	doneset := make(map[int]bool)
   270  	timeout := time.After(2 * time.Second)
   271  	for len(doneset) < len(alltasks) {
   272  		select {
   273  		case tt := <-done:
   274  			if doneset[tt.index] {
   275  				t.Errorf("task %d got done more than once", tt.index)
   276  			} else {
   277  				doneset[tt.index] = true
   278  			}
   279  		case <-timeout:
   280  			t.Errorf("%d of %d tasks got done within 2s", len(doneset), len(alltasks))
   281  			for i := 0; i < len(alltasks); i++ {
   282  				if !doneset[i] {
   283  					t.Logf("task %d not done", i)
   284  				}
   285  			}
   286  			return
   287  		}
   288  	}
   289  }
   290  
   291  type taskgen struct {
   292  	newFunc  func(running int, peers map[discover.NodeID]*Peer) []task
   293  	doneFunc func(task)
   294  }
   295  
   296  func (tg taskgen) newTasks(running int, peers map[discover.NodeID]*Peer, now time.Time) []task {
   297  	return tg.newFunc(running, peers)
   298  }
   299  func (tg taskgen) taskDone(t task, now time.Time) {
   300  	tg.doneFunc(t)
   301  }
   302  func (tg taskgen) addStatic(*discover.Node) {
   303  }
   304  func (tg taskgen) removeStatic(*discover.Node) {
   305  }
   306  
   307  type testTask struct {
   308  	index  int
   309  	called bool
   310  }
   311  
   312  func (t *testTask) Do(srv *Server) {
   313  	t.called = true
   314  }
   315  
   316  // This test checks that connections are disconnected
   317  // just after the encryption handshake when the server is
   318  // at capacity. Trusted connections should still be accepted.
   319  func TestServerAtCap(t *testing.T) {
   320  	trustedID := randomID()
   321  	srv := &Server{
   322  		Config: Config{
   323  			PrivateKey:   newkey(),
   324  			MaxPeers:     10,
   325  			NoDial:       true,
   326  			TrustedNodes: []*discover.Node{{ID: trustedID}},
   327  		},
   328  	}
   329  	if err := srv.Start(); err != nil {
   330  		t.Fatalf("could not start: %v", err)
   331  	}
   332  	defer srv.Stop()
   333  
   334  	newconn := func(id discover.NodeID) *conn {
   335  		fd, _ := net.Pipe()
   336  		tx := newTestTransport(id, fd)
   337  		return &conn{fd: fd, transport: tx, flags: inboundConn, id: id, cont: make(chan error)}
   338  	}
   339  
   340  	// Inject a few connections to fill up the peer set.
   341  	for i := 0; i < 10; i++ {
   342  		c := newconn(randomID())
   343  		if err := srv.checkpoint(c, srv.addpeer); err != nil {
   344  			t.Fatalf("could not add conn %d: %v", i, err)
   345  		}
   346  	}
   347  	// Try inserting a non-trusted connection.
   348  	c := newconn(randomID())
   349  	if err := srv.checkpoint(c, srv.posthandshake); err != DiscTooManyPeers {
   350  		t.Error("wrong error for insert:", err)
   351  	}
   352  	// Try inserting a trusted connection.
   353  	c = newconn(trustedID)
   354  	if err := srv.checkpoint(c, srv.posthandshake); err != nil {
   355  		t.Error("unexpected error for trusted conn @posthandshake:", err)
   356  	}
   357  	if !c.is(trustedConn) {
   358  		t.Error("Server did not set trusted flag")
   359  	}
   360  
   361  }
   362  
   363  func TestServerSetupConn(t *testing.T) {
   364  	id := randomID()
   365  	srvkey := newkey()
   366  	srvid := discover.PubkeyID(&srvkey.PublicKey)
   367  	tests := []struct {
   368  		dontstart bool
   369  		tt        *setupTransport
   370  		flags     connFlag
   371  		dialDest  *discover.Node
   372  
   373  		wantCloseErr error
   374  		wantCalls    string
   375  	}{
   376  		{
   377  			dontstart:    true,
   378  			tt:           &setupTransport{id: id},
   379  			wantCalls:    "close,",
   380  			wantCloseErr: errServerStopped,
   381  		},
   382  		{
   383  			tt:           &setupTransport{id: id, encHandshakeErr: errors.New("read error")},
   384  			flags:        inboundConn,
   385  			wantCalls:    "doEncHandshake,close,",
   386  			wantCloseErr: errors.New("read error"),
   387  		},
   388  		{
   389  			tt:           &setupTransport{id: id},
   390  			dialDest:     &discover.Node{ID: randomID()},
   391  			flags:        dynDialedConn,
   392  			wantCalls:    "doEncHandshake,close,",
   393  			wantCloseErr: DiscUnexpectedIdentity,
   394  		},
   395  		{
   396  			tt:           &setupTransport{id: id, phs: &protoHandshake{ID: randomID()}},
   397  			dialDest:     &discover.Node{ID: id},
   398  			flags:        dynDialedConn,
   399  			wantCalls:    "doEncHandshake,doProtoHandshake,close,",
   400  			wantCloseErr: DiscUnexpectedIdentity,
   401  		},
   402  		{
   403  			tt:           &setupTransport{id: id, protoHandshakeErr: errors.New("foo")},
   404  			dialDest:     &discover.Node{ID: id},
   405  			flags:        dynDialedConn,
   406  			wantCalls:    "doEncHandshake,doProtoHandshake,close,",
   407  			wantCloseErr: errors.New("foo"),
   408  		},
   409  		{
   410  			tt:           &setupTransport{id: srvid, phs: &protoHandshake{ID: srvid}},
   411  			flags:        inboundConn,
   412  			wantCalls:    "doEncHandshake,close,",
   413  			wantCloseErr: DiscSelf,
   414  		},
   415  		{
   416  			tt:           &setupTransport{id: id, phs: &protoHandshake{ID: id}},
   417  			flags:        inboundConn,
   418  			wantCalls:    "doEncHandshake,doProtoHandshake,close,",
   419  			wantCloseErr: DiscUselessPeer,
   420  		},
   421  	}
   422  
   423  	for i, test := range tests {
   424  		srv := &Server{
   425  			Config: Config{
   426  				PrivateKey: srvkey,
   427  				MaxPeers:   10,
   428  				NoDial:     true,
   429  				Protocols:  []Protocol{discard},
   430  			},
   431  			newTransport: func(fd net.Conn) transport { return test.tt },
   432  		}
   433  		if !test.dontstart {
   434  			if err := srv.Start(); err != nil {
   435  				t.Fatalf("couldn't start server: %v", err)
   436  			}
   437  		}
   438  		p1, _ := net.Pipe()
   439  		srv.setupConn(p1, test.flags, test.dialDest)
   440  		if !reflect.DeepEqual(test.tt.closeErr, test.wantCloseErr) {
   441  			t.Errorf("test %d: close error mismatch: got %q, want %q", i, test.tt.closeErr, test.wantCloseErr)
   442  		}
   443  		if test.tt.calls != test.wantCalls {
   444  			t.Errorf("test %d: calls mismatch: got %q, want %q", i, test.tt.calls, test.wantCalls)
   445  		}
   446  	}
   447  }
   448  
   449  type setupTransport struct {
   450  	id              discover.NodeID
   451  	encHandshakeErr error
   452  
   453  	phs               *protoHandshake
   454  	protoHandshakeErr error
   455  
   456  	calls    string
   457  	closeErr error
   458  }
   459  
   460  func (c *setupTransport) doEncHandshake(prv *ecdsa.PrivateKey, dialDest *discover.Node) (discover.NodeID, error) {
   461  	c.calls += "doEncHandshake,"
   462  	return c.id, c.encHandshakeErr
   463  }
   464  func (c *setupTransport) doProtoHandshake(our *protoHandshake) (*protoHandshake, error) {
   465  	c.calls += "doProtoHandshake,"
   466  	if c.protoHandshakeErr != nil {
   467  		return nil, c.protoHandshakeErr
   468  	}
   469  	return c.phs, nil
   470  }
   471  func (c *setupTransport) close(err error) {
   472  	c.calls += "close,"
   473  	c.closeErr = err
   474  }
   475  
   476  // setupConn shouldn't write to/read from the connection.
   477  func (c *setupTransport) WriteMsg(Msg) error {
   478  	panic("WriteMsg called on setupTransport")
   479  }
   480  func (c *setupTransport) ReadMsg() (Msg, error) {
   481  	panic("ReadMsg called on setupTransport")
   482  }
   483  
   484  func newkey() *ecdsa.PrivateKey {
   485  	key, err := crypto.GenerateKey()
   486  	if err != nil {
   487  		panic("couldn't generate key: " + err.Error())
   488  	}
   489  	return key
   490  }
   491  
   492  func randomID() (id discover.NodeID) {
   493  	for i := range id {
   494  		id[i] = byte(rand.Intn(255))
   495  	}
   496  	return id
   497  }