github.com/luckypickle/go-ethereum-vet@v1.14.2/eth/protocol_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 eth
    18  
    19  import (
    20  	"fmt"
    21  	"sync"
    22  	"testing"
    23  	"time"
    24  
    25  	"github.com/luckypickle/go-ethereum-vet/common"
    26  	"github.com/luckypickle/go-ethereum-vet/core/types"
    27  	"github.com/luckypickle/go-ethereum-vet/crypto"
    28  	"github.com/luckypickle/go-ethereum-vet/eth/downloader"
    29  	"github.com/luckypickle/go-ethereum-vet/p2p"
    30  	"github.com/luckypickle/go-ethereum-vet/rlp"
    31  )
    32  
    33  func init() {
    34  	// log.Root().SetHandler(log.LvlFilterHandler(log.LvlTrace, log.StreamHandler(os.Stderr, log.TerminalFormat(false))))
    35  }
    36  
    37  var testAccount, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
    38  
    39  // Tests that handshake failures are detected and reported correctly.
    40  func TestStatusMsgErrors62(t *testing.T) { testStatusMsgErrors(t, 62) }
    41  func TestStatusMsgErrors63(t *testing.T) { testStatusMsgErrors(t, 63) }
    42  
    43  func testStatusMsgErrors(t *testing.T, protocol int) {
    44  	pm, _ := newTestProtocolManagerMust(t, downloader.FullSync, 0, nil, nil)
    45  	var (
    46  		genesis = pm.blockchain.Genesis()
    47  		head    = pm.blockchain.CurrentHeader()
    48  		td      = pm.blockchain.GetTd(head.Hash(), head.Number.Uint64())
    49  	)
    50  	defer pm.Stop()
    51  
    52  	tests := []struct {
    53  		code      uint64
    54  		data      interface{}
    55  		wantError error
    56  	}{
    57  		{
    58  			code: TxMsg, data: []interface{}{},
    59  			wantError: errResp(ErrNoStatusMsg, "first msg has code 2 (!= 0)"),
    60  		},
    61  		{
    62  			code: StatusMsg, data: statusData{10, DefaultConfig.NetworkId, td, head.Hash(), genesis.Hash()},
    63  			wantError: errResp(ErrProtocolVersionMismatch, "10 (!= %d)", protocol),
    64  		},
    65  		{
    66  			code: StatusMsg, data: statusData{uint32(protocol), 999, td, head.Hash(), genesis.Hash()},
    67  			wantError: errResp(ErrNetworkIdMismatch, "999 (!= 1)"),
    68  		},
    69  		{
    70  			code: StatusMsg, data: statusData{uint32(protocol), DefaultConfig.NetworkId, td, head.Hash(), common.Hash{3}},
    71  			wantError: errResp(ErrGenesisBlockMismatch, "0300000000000000 (!= %x)", genesis.Hash().Bytes()[:8]),
    72  		},
    73  	}
    74  
    75  	for i, test := range tests {
    76  		p, errc := newTestPeer("peer", protocol, pm, false)
    77  		// The send call might hang until reset because
    78  		// the protocol might not read the payload.
    79  		go p2p.Send(p.app, test.code, test.data)
    80  
    81  		select {
    82  		case err := <-errc:
    83  			if err == nil {
    84  				t.Errorf("test %d: protocol returned nil error, want %q", i, test.wantError)
    85  			} else if err.Error() != test.wantError.Error() {
    86  				t.Errorf("test %d: wrong error: got %q, want %q", i, err, test.wantError)
    87  			}
    88  		case <-time.After(2 * time.Second):
    89  			t.Errorf("protocol did not shut down within 2 seconds")
    90  		}
    91  		p.close()
    92  	}
    93  }
    94  
    95  // This test checks that received transactions are added to the local pool.
    96  func TestRecvTransactions62(t *testing.T) { testRecvTransactions(t, 62) }
    97  func TestRecvTransactions63(t *testing.T) { testRecvTransactions(t, 63) }
    98  
    99  func testRecvTransactions(t *testing.T, protocol int) {
   100  	txAdded := make(chan []*types.Transaction)
   101  	pm, _ := newTestProtocolManagerMust(t, downloader.FullSync, 0, nil, txAdded)
   102  	pm.acceptTxs = 1 // mark synced to accept transactions
   103  	p, _ := newTestPeer("peer", protocol, pm, true)
   104  	defer pm.Stop()
   105  	defer p.close()
   106  
   107  	tx := newTestTransaction(testAccount, 0, 0)
   108  	if err := p2p.Send(p.app, TxMsg, []interface{}{tx}); err != nil {
   109  		t.Fatalf("send error: %v", err)
   110  	}
   111  	select {
   112  	case added := <-txAdded:
   113  		if len(added) != 1 {
   114  			t.Errorf("wrong number of added transactions: got %d, want 1", len(added))
   115  		} else if added[0].Hash() != tx.Hash() {
   116  			t.Errorf("added wrong tx hash: got %v, want %v", added[0].Hash(), tx.Hash())
   117  		}
   118  	case <-time.After(2 * time.Second):
   119  		t.Errorf("no NewTxsEvent received within 2 seconds")
   120  	}
   121  }
   122  
   123  // This test checks that pending transactions are sent.
   124  func TestSendTransactions62(t *testing.T) { testSendTransactions(t, 62) }
   125  func TestSendTransactions63(t *testing.T) { testSendTransactions(t, 63) }
   126  
   127  func testSendTransactions(t *testing.T, protocol int) {
   128  	pm, _ := newTestProtocolManagerMust(t, downloader.FullSync, 0, nil, nil)
   129  	defer pm.Stop()
   130  
   131  	// Fill the pool with big transactions.
   132  	const txsize = txsyncPackSize / 10
   133  	alltxs := make([]*types.Transaction, 100)
   134  	for nonce := range alltxs {
   135  		alltxs[nonce] = newTestTransaction(testAccount, uint64(nonce), txsize)
   136  	}
   137  	pm.txpool.AddRemotes(alltxs)
   138  
   139  	// Connect several peers. They should all receive the pending transactions.
   140  	var wg sync.WaitGroup
   141  	checktxs := func(p *testPeer) {
   142  		defer wg.Done()
   143  		defer p.close()
   144  		seen := make(map[common.Hash]bool)
   145  		for _, tx := range alltxs {
   146  			seen[tx.Hash()] = false
   147  		}
   148  		for n := 0; n < len(alltxs) && !t.Failed(); {
   149  			var txs []*types.Transaction
   150  			msg, err := p.app.ReadMsg()
   151  			if err != nil {
   152  				t.Errorf("%v: read error: %v", p.Peer, err)
   153  			} else if msg.Code != TxMsg {
   154  				t.Errorf("%v: got code %d, want TxMsg", p.Peer, msg.Code)
   155  			}
   156  			if err := msg.Decode(&txs); err != nil {
   157  				t.Errorf("%v: %v", p.Peer, err)
   158  			}
   159  			for _, tx := range txs {
   160  				hash := tx.Hash()
   161  				seentx, want := seen[hash]
   162  				if seentx {
   163  					t.Errorf("%v: got tx more than once: %x", p.Peer, hash)
   164  				}
   165  				if !want {
   166  					t.Errorf("%v: got unexpected tx: %x", p.Peer, hash)
   167  				}
   168  				seen[hash] = true
   169  				n++
   170  			}
   171  		}
   172  	}
   173  	for i := 0; i < 3; i++ {
   174  		p, _ := newTestPeer(fmt.Sprintf("peer #%d", i), protocol, pm, true)
   175  		wg.Add(1)
   176  		go checktxs(p)
   177  	}
   178  	wg.Wait()
   179  }
   180  
   181  // Tests that the custom union field encoder and decoder works correctly.
   182  func TestGetBlockHeadersDataEncodeDecode(t *testing.T) {
   183  	// Create a "random" hash for testing
   184  	var hash common.Hash
   185  	for i := range hash {
   186  		hash[i] = byte(i)
   187  	}
   188  	// Assemble some table driven tests
   189  	tests := []struct {
   190  		packet *getBlockHeadersData
   191  		fail   bool
   192  	}{
   193  		// Providing the origin as either a hash or a number should both work
   194  		{fail: false, packet: &getBlockHeadersData{Origin: hashOrNumber{Number: 314}}},
   195  		{fail: false, packet: &getBlockHeadersData{Origin: hashOrNumber{Hash: hash}}},
   196  
   197  		// Providing arbitrary query field should also work
   198  		{fail: false, packet: &getBlockHeadersData{Origin: hashOrNumber{Number: 314}, Amount: 314, Skip: 1, Reverse: true}},
   199  		{fail: false, packet: &getBlockHeadersData{Origin: hashOrNumber{Hash: hash}, Amount: 314, Skip: 1, Reverse: true}},
   200  
   201  		// Providing both the origin hash and origin number must fail
   202  		{fail: true, packet: &getBlockHeadersData{Origin: hashOrNumber{Hash: hash, Number: 314}}},
   203  	}
   204  	// Iterate over each of the tests and try to encode and then decode
   205  	for i, tt := range tests {
   206  		bytes, err := rlp.EncodeToBytes(tt.packet)
   207  		if err != nil && !tt.fail {
   208  			t.Fatalf("test %d: failed to encode packet: %v", i, err)
   209  		} else if err == nil && tt.fail {
   210  			t.Fatalf("test %d: encode should have failed", i)
   211  		}
   212  		if !tt.fail {
   213  			packet := new(getBlockHeadersData)
   214  			if err := rlp.DecodeBytes(bytes, packet); err != nil {
   215  				t.Fatalf("test %d: failed to decode packet: %v", i, err)
   216  			}
   217  			if packet.Origin.Hash != tt.packet.Origin.Hash || packet.Origin.Number != tt.packet.Origin.Number || packet.Amount != tt.packet.Amount ||
   218  				packet.Skip != tt.packet.Skip || packet.Reverse != tt.packet.Reverse {
   219  				t.Fatalf("test %d: encode decode mismatch: have %+v, want %+v", i, packet, tt.packet)
   220  			}
   221  		}
   222  	}
   223  }