protocol_test.go 7.59 KB
Newer Older
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 6 7 8
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
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 13 14
// GNU Lesser General Public License for more details.
//
// 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 18
package eth

Felix Lange's avatar
Felix Lange committed
19
import (
20
	"fmt"
Felix Lange's avatar
Felix Lange committed
21 22 23 24 25 26 27 28
	"sync"
	"testing"
	"time"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/p2p"
29
	"github.com/ethereum/go-ethereum/rlp"
Felix Lange's avatar
Felix Lange committed
30 31 32 33 34 35 36
)

func init() {
	// glog.SetToStderr(true)
	// glog.SetV(6)
}

37
var testAccount, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
38

39 40 41 42 43 44
// Tests that handshake failures are detected and reported correctly.
func TestStatusMsgErrors61(t *testing.T) { testStatusMsgErrors(t, 61) }
func TestStatusMsgErrors62(t *testing.T) { testStatusMsgErrors(t, 62) }
func TestStatusMsgErrors63(t *testing.T) { testStatusMsgErrors(t, 63) }

func testStatusMsgErrors(t *testing.T, protocol int) {
45
	pm := newTestProtocolManagerMust(t, false, 0, nil, nil)
46
	td, currentBlock, genesis := pm.blockchain.Status()
Felix Lange's avatar
Felix Lange committed
47
	defer pm.Stop()
obscuren's avatar
obscuren committed
48

49
	tests := []struct {
Felix Lange's avatar
Felix Lange committed
50 51 52
		code      uint64
		data      interface{}
		wantError error
53 54 55
	}{
		{
			code: TxMsg, data: []interface{}{},
Felix Lange's avatar
Felix Lange committed
56
			wantError: errResp(ErrNoStatusMsg, "first msg has code 2 (!= 0)"),
57 58
		},
		{
59
			code: StatusMsg, data: statusData{10, NetworkId, td, currentBlock, genesis},
60
			wantError: errResp(ErrProtocolVersionMismatch, "10 (!= %d)", protocol),
61 62
		},
		{
63
			code: StatusMsg, data: statusData{uint32(protocol), 999, td, currentBlock, genesis},
64
			wantError: errResp(ErrNetworkIdMismatch, "999 (!= 1)"),
65 66
		},
		{
67
			code: StatusMsg, data: statusData{uint32(protocol), NetworkId, td, currentBlock, common.Hash{3}},
Felix Lange's avatar
Felix Lange committed
68
			wantError: errResp(ErrGenesisBlockMismatch, "0300000000000000000000000000000000000000000000000000000000000000 (!= %x)", genesis),
69 70
		},
	}
Felix Lange's avatar
Felix Lange committed
71 72

	for i, test := range tests {
73
		p, errc := newTestPeer("peer", protocol, pm, false)
Felix Lange's avatar
Felix Lange committed
74
		// The send call might hang until reset because
75
		// the protocol might not read the payload.
76
		go p2p.Send(p.app, test.code, test.data)
obscuren's avatar
obscuren committed
77

Felix Lange's avatar
Felix Lange committed
78 79 80
		select {
		case err := <-errc:
			if err == nil {
Felix Lange's avatar
Felix Lange committed
81
				t.Errorf("test %d: protocol returned nil error, want %q", i, test.wantError)
Felix Lange's avatar
Felix Lange committed
82 83 84 85 86 87 88
			} else if err.Error() != test.wantError.Error() {
				t.Errorf("test %d: wrong error: got %q, want %q", i, err, test.wantError)
			}
		case <-time.After(2 * time.Second):
			t.Errorf("protocol did not shut down withing 2 seconds")
		}
		p.close()
89
	}
90
}
91

Felix Lange's avatar
Felix Lange committed
92
// This test checks that received transactions are added to the local pool.
93 94 95 96 97
func TestRecvTransactions61(t *testing.T) { testRecvTransactions(t, 61) }
func TestRecvTransactions62(t *testing.T) { testRecvTransactions(t, 62) }
func TestRecvTransactions63(t *testing.T) { testRecvTransactions(t, 63) }

func testRecvTransactions(t *testing.T, protocol int) {
Felix Lange's avatar
Felix Lange committed
98
	txAdded := make(chan []*types.Transaction)
99
	pm := newTestProtocolManagerMust(t, false, 0, nil, txAdded)
100
	pm.synced = 1 // mark synced to accept transactions
101
	p, _ := newTestPeer("peer", protocol, pm, true)
Felix Lange's avatar
Felix Lange committed
102 103
	defer pm.Stop()
	defer p.close()
104

105 106
	tx := newTestTransaction(testAccount, 0, 0)
	if err := p2p.Send(p.app, TxMsg, []interface{}{tx}); err != nil {
Felix Lange's avatar
Felix Lange committed
107
		t.Fatalf("send error: %v", err)
108 109
	}
	select {
Felix Lange's avatar
Felix Lange committed
110 111 112 113 114
	case added := <-txAdded:
		if len(added) != 1 {
			t.Errorf("wrong number of added transactions: got %d, want 1", len(added))
		} else if added[0].Hash() != tx.Hash() {
			t.Errorf("added wrong tx hash: got %v, want %v", added[0].Hash(), tx.Hash())
115
		}
Felix Lange's avatar
Felix Lange committed
116 117
	case <-time.After(2 * time.Second):
		t.Errorf("no TxPreEvent received within 2 seconds")
118 119
	}
}
120

Felix Lange's avatar
Felix Lange committed
121
// This test checks that pending transactions are sent.
122 123 124 125 126
func TestSendTransactions61(t *testing.T) { testSendTransactions(t, 61) }
func TestSendTransactions62(t *testing.T) { testSendTransactions(t, 62) }
func TestSendTransactions63(t *testing.T) { testSendTransactions(t, 63) }

func testSendTransactions(t *testing.T, protocol int) {
127
	pm := newTestProtocolManagerMust(t, false, 0, nil, nil)
Felix Lange's avatar
Felix Lange committed
128
	defer pm.Stop()
129

Felix Lange's avatar
Felix Lange committed
130 131 132 133
	// Fill the pool with big transactions.
	const txsize = txsyncPackSize / 10
	alltxs := make([]*types.Transaction, 100)
	for nonce := range alltxs {
134
		alltxs[nonce] = newTestTransaction(testAccount, uint64(nonce), txsize)
135
	}
Felix Lange's avatar
Felix Lange committed
136
	pm.txpool.AddTransactions(alltxs)
137

Felix Lange's avatar
Felix Lange committed
138 139 140 141 142 143 144 145 146 147 148
	// Connect several peers. They should all receive the pending transactions.
	var wg sync.WaitGroup
	checktxs := func(p *testPeer) {
		defer wg.Done()
		defer p.close()
		seen := make(map[common.Hash]bool)
		for _, tx := range alltxs {
			seen[tx.Hash()] = false
		}
		for n := 0; n < len(alltxs) && !t.Failed(); {
			var txs []*types.Transaction
149
			msg, err := p.app.ReadMsg()
Felix Lange's avatar
Felix Lange committed
150 151 152 153 154 155 156
			if err != nil {
				t.Errorf("%v: read error: %v", p.Peer, err)
			} else if msg.Code != TxMsg {
				t.Errorf("%v: got code %d, want TxMsg", p.Peer, msg.Code)
			}
			if err := msg.Decode(&txs); err != nil {
				t.Errorf("%v: %v", p.Peer, err)
157
			}
Felix Lange's avatar
Felix Lange committed
158 159 160 161 162 163 164 165 166 167 168
			for _, tx := range txs {
				hash := tx.Hash()
				seentx, want := seen[hash]
				if seentx {
					t.Errorf("%v: got tx more than once: %x", p.Peer, hash)
				}
				if !want {
					t.Errorf("%v: got unexpected tx: %x", p.Peer, hash)
				}
				seen[hash] = true
				n++
169
			}
170 171
		}
	}
Felix Lange's avatar
Felix Lange committed
172
	for i := 0; i < 3; i++ {
173
		p, _ := newTestPeer(fmt.Sprintf("peer #%d", i), protocol, pm, true)
Felix Lange's avatar
Felix Lange committed
174 175
		wg.Add(1)
		go checktxs(p)
176
	}
Felix Lange's avatar
Felix Lange committed
177 178
	wg.Wait()
}
179

180 181 182 183 184 185
// Tests that the custom union field encoder and decoder works correctly.
func TestGetBlockHeadersDataEncodeDecode(t *testing.T) {
	// Create a "random" hash for testing
	var hash common.Hash
	for i, _ := range hash {
		hash[i] = byte(i)
Felix Lange's avatar
Felix Lange committed
186
	}
187 188 189 190 191 192 193 194
	// Assemble some table driven tests
	tests := []struct {
		packet *getBlockHeadersData
		fail   bool
	}{
		// Providing the origin as either a hash or a number should both work
		{fail: false, packet: &getBlockHeadersData{Origin: hashOrNumber{Number: 314}}},
		{fail: false, packet: &getBlockHeadersData{Origin: hashOrNumber{Hash: hash}}},
zelig's avatar
zelig committed
195

196 197 198
		// Providing arbitrary query field should also work
		{fail: false, packet: &getBlockHeadersData{Origin: hashOrNumber{Number: 314}, Amount: 314, Skip: 1, Reverse: true}},
		{fail: false, packet: &getBlockHeadersData{Origin: hashOrNumber{Hash: hash}, Amount: 314, Skip: 1, Reverse: true}},
Felix Lange's avatar
Felix Lange committed
199

200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
		// Providing both the origin hash and origin number must fail
		{fail: true, packet: &getBlockHeadersData{Origin: hashOrNumber{Hash: hash, Number: 314}}},
	}
	// Iterate over each of the tests and try to encode and then decode
	for i, tt := range tests {
		bytes, err := rlp.EncodeToBytes(tt.packet)
		if err != nil && !tt.fail {
			t.Fatalf("test %d: failed to encode packet: %v", i, err)
		} else if err == nil && tt.fail {
			t.Fatalf("test %d: encode should have failed", i)
		}
		if !tt.fail {
			packet := new(getBlockHeadersData)
			if err := rlp.DecodeBytes(bytes, packet); err != nil {
				t.Fatalf("test %d: failed to decode packet: %v", i, err)
			}
			if packet.Origin.Hash != tt.packet.Origin.Hash || packet.Origin.Number != tt.packet.Origin.Number || packet.Amount != tt.packet.Amount ||
				packet.Skip != tt.packet.Skip || packet.Reverse != tt.packet.Reverse {
				t.Fatalf("test %d: encode decode mismatch: have %+v, want %+v", i, packet, tt.packet)
			}
		}
zelig's avatar
zelig committed
221 222
	}
}