protocol_test.go 13.2 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"
21
	"math/big"
Felix Lange's avatar
Felix Lange committed
22 23 24 25 26
	"sync"
	"testing"
	"time"

	"github.com/ethereum/go-ethereum/common"
27 28 29 30
	"github.com/ethereum/go-ethereum/consensus/ethash"
	"github.com/ethereum/go-ethereum/core"
	"github.com/ethereum/go-ethereum/core/forkid"
	"github.com/ethereum/go-ethereum/core/rawdb"
Felix Lange's avatar
Felix Lange committed
31
	"github.com/ethereum/go-ethereum/core/types"
32
	"github.com/ethereum/go-ethereum/core/vm"
Felix Lange's avatar
Felix Lange committed
33
	"github.com/ethereum/go-ethereum/crypto"
34
	"github.com/ethereum/go-ethereum/eth/downloader"
35
	"github.com/ethereum/go-ethereum/event"
Felix Lange's avatar
Felix Lange committed
36
	"github.com/ethereum/go-ethereum/p2p"
37 38
	"github.com/ethereum/go-ethereum/p2p/enode"
	"github.com/ethereum/go-ethereum/params"
39
	"github.com/ethereum/go-ethereum/rlp"
Felix Lange's avatar
Felix Lange committed
40 41 42
)

func init() {
43
	// log.Root().SetHandler(log.LvlFilterHandler(log.LvlTrace, log.StreamHandler(os.Stderr, log.TerminalFormat(false))))
Felix Lange's avatar
Felix Lange committed
44 45
}

46
var testAccount, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
47

48
// Tests that handshake failures are detected and reported correctly.
49
func TestStatusMsgErrors63(t *testing.T) {
50
	pm, _ := newTestProtocolManagerMust(t, downloader.FullSync, 0, nil, nil)
51 52 53 54 55
	var (
		genesis = pm.blockchain.Genesis()
		head    = pm.blockchain.CurrentHeader()
		td      = pm.blockchain.GetTd(head.Hash(), head.Number.Uint64())
	)
Felix Lange's avatar
Felix Lange committed
56
	defer pm.Stop()
obscuren's avatar
obscuren committed
57

58
	tests := []struct {
Felix Lange's avatar
Felix Lange committed
59 60 61
		code      uint64
		data      interface{}
		wantError error
62 63 64
	}{
		{
			code: TxMsg, data: []interface{}{},
Felix Lange's avatar
Felix Lange committed
65
			wantError: errResp(ErrNoStatusMsg, "first msg has code 2 (!= 0)"),
66 67
		},
		{
68 69
			code: StatusMsg, data: statusData63{10, DefaultConfig.NetworkId, td, head.Hash(), genesis.Hash()},
			wantError: errResp(ErrProtocolVersionMismatch, "10 (!= %d)", 63),
70 71
		},
		{
72 73
			code: StatusMsg, data: statusData63{63, 999, td, head.Hash(), genesis.Hash()},
			wantError: errResp(ErrNetworkIDMismatch, "999 (!= %d)", DefaultConfig.NetworkId),
74 75
		},
		{
76 77
			code: StatusMsg, data: statusData63{63, DefaultConfig.NetworkId, td, head.Hash(), common.Hash{3}},
			wantError: errResp(ErrGenesisMismatch, "0300000000000000 (!= %x)", genesis.Hash().Bytes()[:8]),
78 79
		},
	}
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
	for i, test := range tests {
		p, errc := newTestPeer("peer", 63, pm, false)
		// The send call might hang until reset because
		// the protocol might not read the payload.
		go p2p.Send(p.app, test.code, test.data)

		select {
		case err := <-errc:
			if err == nil {
				t.Errorf("test %d: protocol returned nil error, want %q", i, test.wantError)
			} 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 within 2 seconds")
		}
		p.close()
	}
}

func TestStatusMsgErrors64(t *testing.T) {
	pm, _ := newTestProtocolManagerMust(t, downloader.FullSync, 0, nil, nil)
	var (
		genesis = pm.blockchain.Genesis()
		head    = pm.blockchain.CurrentHeader()
		td      = pm.blockchain.GetTd(head.Hash(), head.Number.Uint64())
		forkID  = forkid.NewID(pm.blockchain)
	)
	defer pm.Stop()
Felix Lange's avatar
Felix Lange committed
109

110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
	tests := []struct {
		code      uint64
		data      interface{}
		wantError error
	}{
		{
			code: TxMsg, data: []interface{}{},
			wantError: errResp(ErrNoStatusMsg, "first msg has code 2 (!= 0)"),
		},
		{
			code: StatusMsg, data: statusData{10, DefaultConfig.NetworkId, td, head.Hash(), genesis.Hash(), forkID},
			wantError: errResp(ErrProtocolVersionMismatch, "10 (!= %d)", 64),
		},
		{
			code: StatusMsg, data: statusData{64, 999, td, head.Hash(), genesis.Hash(), forkID},
			wantError: errResp(ErrNetworkIDMismatch, "999 (!= %d)", DefaultConfig.NetworkId),
		},
		{
			code: StatusMsg, data: statusData{64, DefaultConfig.NetworkId, td, head.Hash(), common.Hash{3}, forkID},
			wantError: errResp(ErrGenesisMismatch, "0300000000000000000000000000000000000000000000000000000000000000 (!= %x)", genesis.Hash()),
		},
		{
			code: StatusMsg, data: statusData{64, DefaultConfig.NetworkId, td, head.Hash(), genesis.Hash(), forkid.ID{Hash: [4]byte{0x00, 0x01, 0x02, 0x03}}},
			wantError: errResp(ErrForkIDRejected, forkid.ErrLocalIncompatibleOrStale.Error()),
		},
	}
Felix Lange's avatar
Felix Lange committed
136
	for i, test := range tests {
137
		p, errc := newTestPeer("peer", 64, pm, false)
Felix Lange's avatar
Felix Lange committed
138
		// The send call might hang until reset because
139
		// the protocol might not read the payload.
140
		go p2p.Send(p.app, test.code, test.data)
obscuren's avatar
obscuren committed
141

Felix Lange's avatar
Felix Lange committed
142 143 144
		select {
		case err := <-errc:
			if err == nil {
Felix Lange's avatar
Felix Lange committed
145
				t.Errorf("test %d: protocol returned nil error, want %q", i, test.wantError)
Felix Lange's avatar
Felix Lange committed
146 147 148 149
			} 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):
150
			t.Errorf("protocol did not shut down within 2 seconds")
Felix Lange's avatar
Felix Lange committed
151 152
		}
		p.close()
153
	}
154
}
155

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
func TestForkIDSplit(t *testing.T) {
	var (
		engine = ethash.NewFaker()

		configNoFork  = &params.ChainConfig{HomesteadBlock: big.NewInt(1)}
		configProFork = &params.ChainConfig{
			HomesteadBlock: big.NewInt(1),
			EIP150Block:    big.NewInt(2),
			EIP155Block:    big.NewInt(2),
			EIP158Block:    big.NewInt(2),
			ByzantiumBlock: big.NewInt(3),
		}
		dbNoFork  = rawdb.NewMemoryDatabase()
		dbProFork = rawdb.NewMemoryDatabase()

		gspecNoFork  = &core.Genesis{Config: configNoFork}
		gspecProFork = &core.Genesis{Config: configProFork}

		genesisNoFork  = gspecNoFork.MustCommit(dbNoFork)
		genesisProFork = gspecProFork.MustCommit(dbProFork)

		chainNoFork, _  = core.NewBlockChain(dbNoFork, nil, configNoFork, engine, vm.Config{}, nil)
		chainProFork, _ = core.NewBlockChain(dbProFork, nil, configProFork, engine, vm.Config{}, nil)

		blocksNoFork, _  = core.GenerateChain(configNoFork, genesisNoFork, engine, dbNoFork, 2, nil)
		blocksProFork, _ = core.GenerateChain(configProFork, genesisProFork, engine, dbProFork, 2, nil)

		ethNoFork, _  = NewProtocolManager(configNoFork, nil, downloader.FullSync, 1, new(event.TypeMux), new(testTxPool), engine, chainNoFork, dbNoFork, 1, nil)
		ethProFork, _ = NewProtocolManager(configProFork, nil, downloader.FullSync, 1, new(event.TypeMux), new(testTxPool), engine, chainProFork, dbProFork, 1, nil)
	)
	ethNoFork.Start(1000)
	ethProFork.Start(1000)

	// Both nodes should allow the other to connect (same genesis, next fork is the same)
	p2pNoFork, p2pProFork := p2p.MsgPipe()
	peerNoFork := newPeer(64, p2p.NewPeer(enode.ID{1}, "", nil), p2pNoFork)
	peerProFork := newPeer(64, p2p.NewPeer(enode.ID{2}, "", nil), p2pProFork)

	errc := make(chan error, 2)
	go func() { errc <- ethNoFork.handle(peerProFork) }()
	go func() { errc <- ethProFork.handle(peerNoFork) }()

	select {
	case err := <-errc:
		t.Fatalf("frontier nofork <-> profork failed: %v", err)
	case <-time.After(250 * time.Millisecond):
		p2pNoFork.Close()
		p2pProFork.Close()
	}
	// Progress into Homestead. Fork's match, so we don't care what the future holds
	chainNoFork.InsertChain(blocksNoFork[:1])
	chainProFork.InsertChain(blocksProFork[:1])

	p2pNoFork, p2pProFork = p2p.MsgPipe()
	peerNoFork = newPeer(64, p2p.NewPeer(enode.ID{1}, "", nil), p2pNoFork)
	peerProFork = newPeer(64, p2p.NewPeer(enode.ID{2}, "", nil), p2pProFork)

	errc = make(chan error, 2)
	go func() { errc <- ethNoFork.handle(peerProFork) }()
	go func() { errc <- ethProFork.handle(peerNoFork) }()

	select {
	case err := <-errc:
		t.Fatalf("homestead nofork <-> profork failed: %v", err)
	case <-time.After(250 * time.Millisecond):
		p2pNoFork.Close()
		p2pProFork.Close()
	}
	// Progress into Spurious. Forks mismatch, signalling differing chains, reject
	chainNoFork.InsertChain(blocksNoFork[1:2])
	chainProFork.InsertChain(blocksProFork[1:2])

	p2pNoFork, p2pProFork = p2p.MsgPipe()
	peerNoFork = newPeer(64, p2p.NewPeer(enode.ID{1}, "", nil), p2pNoFork)
	peerProFork = newPeer(64, p2p.NewPeer(enode.ID{2}, "", nil), p2pProFork)

	errc = make(chan error, 2)
	go func() { errc <- ethNoFork.handle(peerProFork) }()
	go func() { errc <- ethProFork.handle(peerNoFork) }()

	select {
	case err := <-errc:
		if want := errResp(ErrForkIDRejected, forkid.ErrLocalIncompatibleOrStale.Error()); err.Error() != want.Error() {
			t.Fatalf("fork ID rejection error mismatch: have %v, want %v", err, want)
		}
	case <-time.After(250 * time.Millisecond):
		t.Fatalf("split peers not rejected")
	}
}

Felix Lange's avatar
Felix Lange committed
246
// This test checks that received transactions are added to the local pool.
247
func TestRecvTransactions63(t *testing.T) { testRecvTransactions(t, 63) }
248
func TestRecvTransactions64(t *testing.T) { testRecvTransactions(t, 64) }
249 250

func testRecvTransactions(t *testing.T, protocol int) {
Felix Lange's avatar
Felix Lange committed
251
	txAdded := make(chan []*types.Transaction)
252
	pm, _ := newTestProtocolManagerMust(t, downloader.FullSync, 0, nil, txAdded)
253
	pm.acceptTxs = 1 // mark synced to accept transactions
254
	p, _ := newTestPeer("peer", protocol, pm, true)
Felix Lange's avatar
Felix Lange committed
255 256
	defer pm.Stop()
	defer p.close()
257

258 259
	tx := newTestTransaction(testAccount, 0, 0)
	if err := p2p.Send(p.app, TxMsg, []interface{}{tx}); err != nil {
Felix Lange's avatar
Felix Lange committed
260
		t.Fatalf("send error: %v", err)
261 262
	}
	select {
Felix Lange's avatar
Felix Lange committed
263 264 265 266 267
	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())
268
		}
Felix Lange's avatar
Felix Lange committed
269
	case <-time.After(2 * time.Second):
270
		t.Errorf("no NewTxsEvent received within 2 seconds")
271 272
	}
}
273

Felix Lange's avatar
Felix Lange committed
274
// This test checks that pending transactions are sent.
275
func TestSendTransactions63(t *testing.T) { testSendTransactions(t, 63) }
276
func TestSendTransactions64(t *testing.T) { testSendTransactions(t, 64) }
277 278

func testSendTransactions(t *testing.T, protocol int) {
279
	pm, _ := newTestProtocolManagerMust(t, downloader.FullSync, 0, nil, nil)
Felix Lange's avatar
Felix Lange committed
280
	defer pm.Stop()
281

Felix Lange's avatar
Felix Lange committed
282 283 284 285
	// Fill the pool with big transactions.
	const txsize = txsyncPackSize / 10
	alltxs := make([]*types.Transaction, 100)
	for nonce := range alltxs {
286
		alltxs[nonce] = newTestTransaction(testAccount, uint64(nonce), txsize)
287
	}
288
	pm.txpool.AddRemotes(alltxs)
289

Felix Lange's avatar
Felix Lange committed
290 291 292 293 294 295 296 297 298 299 300
	// 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
301
			msg, err := p.app.ReadMsg()
Felix Lange's avatar
Felix Lange committed
302 303 304 305 306 307 308
			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)
309
			}
Felix Lange's avatar
Felix Lange committed
310 311 312 313 314 315 316 317 318 319 320
			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++
321
			}
322 323
		}
	}
Felix Lange's avatar
Felix Lange committed
324
	for i := 0; i < 3; i++ {
325
		p, _ := newTestPeer(fmt.Sprintf("peer #%d", i), protocol, pm, true)
Felix Lange's avatar
Felix Lange committed
326 327
		wg.Add(1)
		go checktxs(p)
328
	}
Felix Lange's avatar
Felix Lange committed
329 330
	wg.Wait()
}
331

332 333 334 335
// 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
Felix Lange's avatar
Felix Lange committed
336
	for i := range hash {
337
		hash[i] = byte(i)
Felix Lange's avatar
Felix Lange committed
338
	}
339 340 341 342 343 344 345 346
	// 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
347

348 349 350
		// 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
351

352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
		// 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
373 374
	}
}