github.com/Debrief-BC/go-debrief@v0.0.0-20200420203408-0c26ca968123/p2p/peer_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  	"encoding/binary"
    21  	"errors"
    22  	"fmt"
    23  	"math/rand"
    24  	"net"
    25  	"reflect"
    26  	"strconv"
    27  	"strings"
    28  	"testing"
    29  	"time"
    30  
    31  	"github.com/Debrief-BC/go-debrief/log"
    32  	"github.com/Debrief-BC/go-debrief/p2p/enode"
    33  	"github.com/Debrief-BC/go-debrief/p2p/enr"
    34  )
    35  
    36  var discard = Protocol{
    37  	Name:   "discard",
    38  	Length: 1,
    39  	Run: func(p *Peer, rw MsgReadWriter) error {
    40  		for {
    41  			msg, err := rw.ReadMsg()
    42  			if err != nil {
    43  				return err
    44  			}
    45  			fmt.Printf("discarding %d\n", msg.Code)
    46  			if err = msg.Discard(); err != nil {
    47  				return err
    48  			}
    49  		}
    50  	},
    51  }
    52  
    53  // uintID encodes i into a node ID.
    54  func uintID(i uint16) enode.ID {
    55  	var id enode.ID
    56  	binary.BigEndian.PutUint16(id[:], i)
    57  	return id
    58  }
    59  
    60  // newNode creates a node record with the given address.
    61  func newNode(id enode.ID, addr string) *enode.Node {
    62  	var r enr.Record
    63  	if addr != "" {
    64  		// Set the port if present.
    65  		if strings.Contains(addr, ":") {
    66  			hs, ps, err := net.SplitHostPort(addr)
    67  			if err != nil {
    68  				panic(fmt.Errorf("invalid address %q", addr))
    69  			}
    70  			port, err := strconv.Atoi(ps)
    71  			if err != nil {
    72  				panic(fmt.Errorf("invalid port in %q", addr))
    73  			}
    74  			r.Set(enr.TCP(port))
    75  			r.Set(enr.UDP(port))
    76  			addr = hs
    77  		}
    78  		// Set the IP.
    79  		ip := net.ParseIP(addr)
    80  		if ip == nil {
    81  			panic(fmt.Errorf("invalid IP %q", addr))
    82  		}
    83  		r.Set(enr.IP(ip))
    84  	}
    85  	return enode.SignNull(&r, id)
    86  }
    87  
    88  func testPeer(protos []Protocol) (func(), *conn, *Peer, <-chan error) {
    89  	fd1, fd2 := net.Pipe()
    90  	c1 := &conn{fd: fd1, node: newNode(randomID(), ""), transport: newTestTransport(&newkey().PublicKey, fd1)}
    91  	c2 := &conn{fd: fd2, node: newNode(randomID(), ""), transport: newTestTransport(&newkey().PublicKey, fd2)}
    92  	for _, p := range protos {
    93  		c1.caps = append(c1.caps, p.cap())
    94  		c2.caps = append(c2.caps, p.cap())
    95  	}
    96  
    97  	peer := newPeer(log.Root(), c1, protos)
    98  	errc := make(chan error, 1)
    99  	go func() {
   100  		_, err := peer.run()
   101  		errc <- err
   102  	}()
   103  
   104  	closer := func() { c2.close(errors.New("close func called")) }
   105  	return closer, c2, peer, errc
   106  }
   107  
   108  func TestPeerProtoReadMsg(t *testing.T) {
   109  	proto := Protocol{
   110  		Name:   "a",
   111  		Length: 5,
   112  		Run: func(peer *Peer, rw MsgReadWriter) error {
   113  			if err := ExpectMsg(rw, 2, []uint{1}); err != nil {
   114  				t.Error(err)
   115  			}
   116  			if err := ExpectMsg(rw, 3, []uint{2}); err != nil {
   117  				t.Error(err)
   118  			}
   119  			if err := ExpectMsg(rw, 4, []uint{3}); err != nil {
   120  				t.Error(err)
   121  			}
   122  			return nil
   123  		},
   124  	}
   125  
   126  	closer, rw, _, errc := testPeer([]Protocol{proto})
   127  	defer closer()
   128  
   129  	Send(rw, baseProtocolLength+2, []uint{1})
   130  	Send(rw, baseProtocolLength+3, []uint{2})
   131  	Send(rw, baseProtocolLength+4, []uint{3})
   132  
   133  	select {
   134  	case err := <-errc:
   135  		if err != errProtocolReturned {
   136  			t.Errorf("peer returned error: %v", err)
   137  		}
   138  	case <-time.After(2 * time.Second):
   139  		t.Errorf("receive timeout")
   140  	}
   141  }
   142  
   143  func TestPeerProtoEncodeMsg(t *testing.T) {
   144  	proto := Protocol{
   145  		Name:   "a",
   146  		Length: 2,
   147  		Run: func(peer *Peer, rw MsgReadWriter) error {
   148  			if err := SendItems(rw, 2); err == nil {
   149  				t.Error("expected error for out-of-range msg code, got nil")
   150  			}
   151  			if err := SendItems(rw, 1, "foo", "bar"); err != nil {
   152  				t.Errorf("write error: %v", err)
   153  			}
   154  			return nil
   155  		},
   156  	}
   157  	closer, rw, _, _ := testPeer([]Protocol{proto})
   158  	defer closer()
   159  
   160  	if err := ExpectMsg(rw, 17, []string{"foo", "bar"}); err != nil {
   161  		t.Error(err)
   162  	}
   163  }
   164  
   165  func TestPeerPing(t *testing.T) {
   166  	closer, rw, _, _ := testPeer(nil)
   167  	defer closer()
   168  	if err := SendItems(rw, pingMsg); err != nil {
   169  		t.Fatal(err)
   170  	}
   171  	if err := ExpectMsg(rw, pongMsg, nil); err != nil {
   172  		t.Error(err)
   173  	}
   174  }
   175  
   176  func TestPeerDisconnect(t *testing.T) {
   177  	closer, rw, _, disc := testPeer(nil)
   178  	defer closer()
   179  	if err := SendItems(rw, discMsg, DiscQuitting); err != nil {
   180  		t.Fatal(err)
   181  	}
   182  	select {
   183  	case reason := <-disc:
   184  		if reason != DiscQuitting {
   185  			t.Errorf("run returned wrong reason: got %v, want %v", reason, DiscQuitting)
   186  		}
   187  	case <-time.After(500 * time.Millisecond):
   188  		t.Error("peer did not return")
   189  	}
   190  }
   191  
   192  // This test is supposed to verify that Peer can reliably handle
   193  // multiple causes of disconnection occurring at the same time.
   194  func TestPeerDisconnectRace(t *testing.T) {
   195  	maybe := func() bool { return rand.Intn(2) == 1 }
   196  
   197  	for i := 0; i < 1000; i++ {
   198  		protoclose := make(chan error)
   199  		protodisc := make(chan DiscReason)
   200  		closer, rw, p, disc := testPeer([]Protocol{
   201  			{
   202  				Name:   "closereq",
   203  				Run:    func(p *Peer, rw MsgReadWriter) error { return <-protoclose },
   204  				Length: 1,
   205  			},
   206  			{
   207  				Name:   "disconnect",
   208  				Run:    func(p *Peer, rw MsgReadWriter) error { p.Disconnect(<-protodisc); return nil },
   209  				Length: 1,
   210  			},
   211  		})
   212  
   213  		// Simulate incoming messages.
   214  		go SendItems(rw, baseProtocolLength+1)
   215  		go SendItems(rw, baseProtocolLength+2)
   216  		// Close the network connection.
   217  		go closer()
   218  		// Make protocol "closereq" return.
   219  		protoclose <- errors.New("protocol closed")
   220  		// Make protocol "disconnect" call peer.Disconnect
   221  		protodisc <- DiscAlreadyConnected
   222  		// In some cases, simulate something else calling peer.Disconnect.
   223  		if maybe() {
   224  			go p.Disconnect(DiscInvalidIdentity)
   225  		}
   226  		// In some cases, simulate remote requesting a disconnect.
   227  		if maybe() {
   228  			go SendItems(rw, discMsg, DiscQuitting)
   229  		}
   230  
   231  		select {
   232  		case <-disc:
   233  		case <-time.After(2 * time.Second):
   234  			// Peer.run should return quickly. If it doesn't the Peer
   235  			// goroutines are probably deadlocked. Call panic in order to
   236  			// show the stacks.
   237  			panic("Peer.run took to long to return.")
   238  		}
   239  	}
   240  }
   241  
   242  func TestNewPeer(t *testing.T) {
   243  	name := "nodename"
   244  	caps := []Cap{{"foo", 2}, {"bar", 3}}
   245  	id := randomID()
   246  	p := NewPeer(id, name, caps)
   247  	if p.ID() != id {
   248  		t.Errorf("ID mismatch: got %v, expected %v", p.ID(), id)
   249  	}
   250  	if p.Name() != name {
   251  		t.Errorf("Name mismatch: got %v, expected %v", p.Name(), name)
   252  	}
   253  	if !reflect.DeepEqual(p.Caps(), caps) {
   254  		t.Errorf("Caps mismatch: got %v, expected %v", p.Caps(), caps)
   255  	}
   256  
   257  	p.Disconnect(DiscAlreadyConnected) // Should not hang
   258  }
   259  
   260  func TestMatchProtocols(t *testing.T) {
   261  	tests := []struct {
   262  		Remote []Cap
   263  		Local  []Protocol
   264  		Match  map[string]protoRW
   265  	}{
   266  		{
   267  			// No remote capabilities
   268  			Local: []Protocol{{Name: "a"}},
   269  		},
   270  		{
   271  			// No local protocols
   272  			Remote: []Cap{{Name: "a"}},
   273  		},
   274  		{
   275  			// No mutual protocols
   276  			Remote: []Cap{{Name: "a"}},
   277  			Local:  []Protocol{{Name: "b"}},
   278  		},
   279  		{
   280  			// Some matches, some differences
   281  			Remote: []Cap{{Name: "local"}, {Name: "match1"}, {Name: "match2"}},
   282  			Local:  []Protocol{{Name: "match1"}, {Name: "match2"}, {Name: "remote"}},
   283  			Match:  map[string]protoRW{"match1": {Protocol: Protocol{Name: "match1"}}, "match2": {Protocol: Protocol{Name: "match2"}}},
   284  		},
   285  		{
   286  			// Various alphabetical ordering
   287  			Remote: []Cap{{Name: "aa"}, {Name: "ab"}, {Name: "bb"}, {Name: "ba"}},
   288  			Local:  []Protocol{{Name: "ba"}, {Name: "bb"}, {Name: "ab"}, {Name: "aa"}},
   289  			Match:  map[string]protoRW{"aa": {Protocol: Protocol{Name: "aa"}}, "ab": {Protocol: Protocol{Name: "ab"}}, "ba": {Protocol: Protocol{Name: "ba"}}, "bb": {Protocol: Protocol{Name: "bb"}}},
   290  		},
   291  		{
   292  			// No mutual versions
   293  			Remote: []Cap{{Version: 1}},
   294  			Local:  []Protocol{{Version: 2}},
   295  		},
   296  		{
   297  			// Multiple versions, single common
   298  			Remote: []Cap{{Version: 1}, {Version: 2}},
   299  			Local:  []Protocol{{Version: 2}, {Version: 3}},
   300  			Match:  map[string]protoRW{"": {Protocol: Protocol{Version: 2}}},
   301  		},
   302  		{
   303  			// Multiple versions, multiple common
   304  			Remote: []Cap{{Version: 1}, {Version: 2}, {Version: 3}, {Version: 4}},
   305  			Local:  []Protocol{{Version: 2}, {Version: 3}},
   306  			Match:  map[string]protoRW{"": {Protocol: Protocol{Version: 3}}},
   307  		},
   308  		{
   309  			// Various version orderings
   310  			Remote: []Cap{{Version: 4}, {Version: 1}, {Version: 3}, {Version: 2}},
   311  			Local:  []Protocol{{Version: 2}, {Version: 3}, {Version: 1}},
   312  			Match:  map[string]protoRW{"": {Protocol: Protocol{Version: 3}}},
   313  		},
   314  		{
   315  			// Versions overriding sub-protocol lengths
   316  			Remote: []Cap{{Version: 1}, {Version: 2}, {Version: 3}, {Name: "a"}},
   317  			Local:  []Protocol{{Version: 1, Length: 1}, {Version: 2, Length: 2}, {Version: 3, Length: 3}, {Name: "a"}},
   318  			Match:  map[string]protoRW{"": {Protocol: Protocol{Version: 3}}, "a": {Protocol: Protocol{Name: "a"}, offset: 3}},
   319  		},
   320  	}
   321  
   322  	for i, tt := range tests {
   323  		result := matchProtocols(tt.Local, tt.Remote, nil)
   324  		if len(result) != len(tt.Match) {
   325  			t.Errorf("test %d: negotiation mismatch: have %v, want %v", i, len(result), len(tt.Match))
   326  			continue
   327  		}
   328  		// Make sure all negotiated protocols are needed and correct
   329  		for name, proto := range result {
   330  			match, ok := tt.Match[name]
   331  			if !ok {
   332  				t.Errorf("test %d, proto '%s': negotiated but shouldn't have", i, name)
   333  				continue
   334  			}
   335  			if proto.Name != match.Name {
   336  				t.Errorf("test %d, proto '%s': name mismatch: have %v, want %v", i, name, proto.Name, match.Name)
   337  			}
   338  			if proto.Version != match.Version {
   339  				t.Errorf("test %d, proto '%s': version mismatch: have %v, want %v", i, name, proto.Version, match.Version)
   340  			}
   341  			if proto.offset-baseProtocolLength != match.offset {
   342  				t.Errorf("test %d, proto '%s': offset mismatch: have %v, want %v", i, name, proto.offset-baseProtocolLength, match.offset)
   343  			}
   344  		}
   345  		// Make sure no protocols missed negotiation
   346  		for name := range tt.Match {
   347  			if _, ok := result[name]; !ok {
   348  				t.Errorf("test %d, proto '%s': not negotiated, should have", i, name)
   349  				continue
   350  			}
   351  		}
   352  	}
   353  }