github.com/ethereum/go-ethereum@v1.10.9/eth/handler_eth_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  	"math/big"
    22  	"math/rand"
    23  	"sync/atomic"
    24  	"testing"
    25  	"time"
    26  
    27  	"github.com/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/consensus/ethash"
    29  	"github.com/ethereum/go-ethereum/core"
    30  	"github.com/ethereum/go-ethereum/core/forkid"
    31  	"github.com/ethereum/go-ethereum/core/rawdb"
    32  	"github.com/ethereum/go-ethereum/core/types"
    33  	"github.com/ethereum/go-ethereum/core/vm"
    34  	"github.com/ethereum/go-ethereum/eth/downloader"
    35  	"github.com/ethereum/go-ethereum/eth/protocols/eth"
    36  	"github.com/ethereum/go-ethereum/event"
    37  	"github.com/ethereum/go-ethereum/p2p"
    38  	"github.com/ethereum/go-ethereum/p2p/enode"
    39  	"github.com/ethereum/go-ethereum/params"
    40  	"github.com/ethereum/go-ethereum/trie"
    41  )
    42  
    43  // testEthHandler is a mock event handler to listen for inbound network requests
    44  // on the `eth` protocol and convert them into a more easily testable form.
    45  type testEthHandler struct {
    46  	blockBroadcasts event.Feed
    47  	txAnnounces     event.Feed
    48  	txBroadcasts    event.Feed
    49  }
    50  
    51  func (h *testEthHandler) Chain() *core.BlockChain              { panic("no backing chain") }
    52  func (h *testEthHandler) StateBloom() *trie.SyncBloom          { panic("no backing state bloom") }
    53  func (h *testEthHandler) TxPool() eth.TxPool                   { panic("no backing tx pool") }
    54  func (h *testEthHandler) AcceptTxs() bool                      { return true }
    55  func (h *testEthHandler) RunPeer(*eth.Peer, eth.Handler) error { panic("not used in tests") }
    56  func (h *testEthHandler) PeerInfo(enode.ID) interface{}        { panic("not used in tests") }
    57  
    58  func (h *testEthHandler) Handle(peer *eth.Peer, packet eth.Packet) error {
    59  	switch packet := packet.(type) {
    60  	case *eth.NewBlockPacket:
    61  		h.blockBroadcasts.Send(packet.Block)
    62  		return nil
    63  
    64  	case *eth.NewPooledTransactionHashesPacket:
    65  		h.txAnnounces.Send(([]common.Hash)(*packet))
    66  		return nil
    67  
    68  	case *eth.TransactionsPacket:
    69  		h.txBroadcasts.Send(([]*types.Transaction)(*packet))
    70  		return nil
    71  
    72  	case *eth.PooledTransactionsPacket:
    73  		h.txBroadcasts.Send(([]*types.Transaction)(*packet))
    74  		return nil
    75  
    76  	default:
    77  		panic(fmt.Sprintf("unexpected eth packet type in tests: %T", packet))
    78  	}
    79  }
    80  
    81  // Tests that peers are correctly accepted (or rejected) based on the advertised
    82  // fork IDs in the protocol handshake.
    83  func TestForkIDSplit66(t *testing.T) { testForkIDSplit(t, eth.ETH66) }
    84  
    85  func testForkIDSplit(t *testing.T, protocol uint) {
    86  	t.Parallel()
    87  
    88  	var (
    89  		engine = ethash.NewFaker()
    90  
    91  		configNoFork  = &params.ChainConfig{HomesteadBlock: big.NewInt(1)}
    92  		configProFork = &params.ChainConfig{
    93  			HomesteadBlock: big.NewInt(1),
    94  			EIP150Block:    big.NewInt(2),
    95  			EIP155Block:    big.NewInt(2),
    96  			EIP158Block:    big.NewInt(2),
    97  			ByzantiumBlock: big.NewInt(3),
    98  		}
    99  		dbNoFork  = rawdb.NewMemoryDatabase()
   100  		dbProFork = rawdb.NewMemoryDatabase()
   101  
   102  		gspecNoFork  = &core.Genesis{Config: configNoFork}
   103  		gspecProFork = &core.Genesis{Config: configProFork}
   104  
   105  		genesisNoFork  = gspecNoFork.MustCommit(dbNoFork)
   106  		genesisProFork = gspecProFork.MustCommit(dbProFork)
   107  
   108  		chainNoFork, _  = core.NewBlockChain(dbNoFork, nil, configNoFork, engine, vm.Config{}, nil, nil)
   109  		chainProFork, _ = core.NewBlockChain(dbProFork, nil, configProFork, engine, vm.Config{}, nil, nil)
   110  
   111  		blocksNoFork, _  = core.GenerateChain(configNoFork, genesisNoFork, engine, dbNoFork, 2, nil)
   112  		blocksProFork, _ = core.GenerateChain(configProFork, genesisProFork, engine, dbProFork, 2, nil)
   113  
   114  		ethNoFork, _ = newHandler(&handlerConfig{
   115  			Database:   dbNoFork,
   116  			Chain:      chainNoFork,
   117  			TxPool:     newTestTxPool(),
   118  			Network:    1,
   119  			Sync:       downloader.FullSync,
   120  			BloomCache: 1,
   121  		})
   122  		ethProFork, _ = newHandler(&handlerConfig{
   123  			Database:   dbProFork,
   124  			Chain:      chainProFork,
   125  			TxPool:     newTestTxPool(),
   126  			Network:    1,
   127  			Sync:       downloader.FullSync,
   128  			BloomCache: 1,
   129  		})
   130  	)
   131  	ethNoFork.Start(1000)
   132  	ethProFork.Start(1000)
   133  
   134  	// Clean up everything after ourselves
   135  	defer chainNoFork.Stop()
   136  	defer chainProFork.Stop()
   137  
   138  	defer ethNoFork.Stop()
   139  	defer ethProFork.Stop()
   140  
   141  	// Both nodes should allow the other to connect (same genesis, next fork is the same)
   142  	p2pNoFork, p2pProFork := p2p.MsgPipe()
   143  	defer p2pNoFork.Close()
   144  	defer p2pProFork.Close()
   145  
   146  	peerNoFork := eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{1}, "", nil, p2pNoFork), p2pNoFork, nil)
   147  	peerProFork := eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{2}, "", nil, p2pProFork), p2pProFork, nil)
   148  	defer peerNoFork.Close()
   149  	defer peerProFork.Close()
   150  
   151  	errc := make(chan error, 2)
   152  	go func(errc chan error) {
   153  		errc <- ethNoFork.runEthPeer(peerProFork, func(peer *eth.Peer) error { return nil })
   154  	}(errc)
   155  	go func(errc chan error) {
   156  		errc <- ethProFork.runEthPeer(peerNoFork, func(peer *eth.Peer) error { return nil })
   157  	}(errc)
   158  
   159  	for i := 0; i < 2; i++ {
   160  		select {
   161  		case err := <-errc:
   162  			if err != nil {
   163  				t.Fatalf("frontier nofork <-> profork failed: %v", err)
   164  			}
   165  		case <-time.After(250 * time.Millisecond):
   166  			t.Fatalf("frontier nofork <-> profork handler timeout")
   167  		}
   168  	}
   169  	// Progress into Homestead. Fork's match, so we don't care what the future holds
   170  	chainNoFork.InsertChain(blocksNoFork[:1])
   171  	chainProFork.InsertChain(blocksProFork[:1])
   172  
   173  	p2pNoFork, p2pProFork = p2p.MsgPipe()
   174  	defer p2pNoFork.Close()
   175  	defer p2pProFork.Close()
   176  
   177  	peerNoFork = eth.NewPeer(protocol, p2p.NewPeer(enode.ID{1}, "", nil), p2pNoFork, nil)
   178  	peerProFork = eth.NewPeer(protocol, p2p.NewPeer(enode.ID{2}, "", nil), p2pProFork, nil)
   179  	defer peerNoFork.Close()
   180  	defer peerProFork.Close()
   181  
   182  	errc = make(chan error, 2)
   183  	go func(errc chan error) {
   184  		errc <- ethNoFork.runEthPeer(peerProFork, func(peer *eth.Peer) error { return nil })
   185  	}(errc)
   186  	go func(errc chan error) {
   187  		errc <- ethProFork.runEthPeer(peerNoFork, func(peer *eth.Peer) error { return nil })
   188  	}(errc)
   189  
   190  	for i := 0; i < 2; i++ {
   191  		select {
   192  		case err := <-errc:
   193  			if err != nil {
   194  				t.Fatalf("homestead nofork <-> profork failed: %v", err)
   195  			}
   196  		case <-time.After(250 * time.Millisecond):
   197  			t.Fatalf("homestead nofork <-> profork handler timeout")
   198  		}
   199  	}
   200  	// Progress into Spurious. Forks mismatch, signalling differing chains, reject
   201  	chainNoFork.InsertChain(blocksNoFork[1:2])
   202  	chainProFork.InsertChain(blocksProFork[1:2])
   203  
   204  	p2pNoFork, p2pProFork = p2p.MsgPipe()
   205  	defer p2pNoFork.Close()
   206  	defer p2pProFork.Close()
   207  
   208  	peerNoFork = eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{1}, "", nil, p2pNoFork), p2pNoFork, nil)
   209  	peerProFork = eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{2}, "", nil, p2pProFork), p2pProFork, nil)
   210  	defer peerNoFork.Close()
   211  	defer peerProFork.Close()
   212  
   213  	errc = make(chan error, 2)
   214  	go func(errc chan error) {
   215  		errc <- ethNoFork.runEthPeer(peerProFork, func(peer *eth.Peer) error { return nil })
   216  	}(errc)
   217  	go func(errc chan error) {
   218  		errc <- ethProFork.runEthPeer(peerNoFork, func(peer *eth.Peer) error { return nil })
   219  	}(errc)
   220  
   221  	var successes int
   222  	for i := 0; i < 2; i++ {
   223  		select {
   224  		case err := <-errc:
   225  			if err == nil {
   226  				successes++
   227  				if successes == 2 { // Only one side disconnects
   228  					t.Fatalf("fork ID rejection didn't happen")
   229  				}
   230  			}
   231  		case <-time.After(250 * time.Millisecond):
   232  			t.Fatalf("split peers not rejected")
   233  		}
   234  	}
   235  }
   236  
   237  // Tests that received transactions are added to the local pool.
   238  func TestRecvTransactions66(t *testing.T) { testRecvTransactions(t, eth.ETH66) }
   239  
   240  func testRecvTransactions(t *testing.T, protocol uint) {
   241  	t.Parallel()
   242  
   243  	// Create a message handler, configure it to accept transactions and watch them
   244  	handler := newTestHandler()
   245  	defer handler.close()
   246  
   247  	handler.handler.acceptTxs = 1 // mark synced to accept transactions
   248  
   249  	txs := make(chan core.NewTxsEvent)
   250  	sub := handler.txpool.SubscribeNewTxsEvent(txs)
   251  	defer sub.Unsubscribe()
   252  
   253  	// Create a source peer to send messages through and a sink handler to receive them
   254  	p2pSrc, p2pSink := p2p.MsgPipe()
   255  	defer p2pSrc.Close()
   256  	defer p2pSink.Close()
   257  
   258  	src := eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{1}, "", nil, p2pSrc), p2pSrc, handler.txpool)
   259  	sink := eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{2}, "", nil, p2pSink), p2pSink, handler.txpool)
   260  	defer src.Close()
   261  	defer sink.Close()
   262  
   263  	go handler.handler.runEthPeer(sink, func(peer *eth.Peer) error {
   264  		return eth.Handle((*ethHandler)(handler.handler), peer)
   265  	})
   266  	// Run the handshake locally to avoid spinning up a source handler
   267  	var (
   268  		genesis = handler.chain.Genesis()
   269  		head    = handler.chain.CurrentBlock()
   270  		td      = handler.chain.GetTd(head.Hash(), head.NumberU64())
   271  	)
   272  	if err := src.Handshake(1, td, head.Hash(), genesis.Hash(), forkid.NewIDWithChain(handler.chain), forkid.NewFilter(handler.chain)); err != nil {
   273  		t.Fatalf("failed to run protocol handshake")
   274  	}
   275  	// Send the transaction to the sink and verify that it's added to the tx pool
   276  	tx := types.NewTransaction(0, common.Address{}, big.NewInt(0), 100000, big.NewInt(0), nil)
   277  	tx, _ = types.SignTx(tx, types.HomesteadSigner{}, testKey)
   278  
   279  	if err := src.SendTransactions([]*types.Transaction{tx}); err != nil {
   280  		t.Fatalf("failed to send transaction: %v", err)
   281  	}
   282  	select {
   283  	case event := <-txs:
   284  		if len(event.Txs) != 1 {
   285  			t.Errorf("wrong number of added transactions: got %d, want 1", len(event.Txs))
   286  		} else if event.Txs[0].Hash() != tx.Hash() {
   287  			t.Errorf("added wrong tx hash: got %v, want %v", event.Txs[0].Hash(), tx.Hash())
   288  		}
   289  	case <-time.After(2 * time.Second):
   290  		t.Errorf("no NewTxsEvent received within 2 seconds")
   291  	}
   292  }
   293  
   294  // This test checks that pending transactions are sent.
   295  func TestSendTransactions66(t *testing.T) { testSendTransactions(t, eth.ETH66) }
   296  
   297  func testSendTransactions(t *testing.T, protocol uint) {
   298  	t.Parallel()
   299  
   300  	// Create a message handler and fill the pool with big transactions
   301  	handler := newTestHandler()
   302  	defer handler.close()
   303  
   304  	insert := make([]*types.Transaction, 100)
   305  	for nonce := range insert {
   306  		tx := types.NewTransaction(uint64(nonce), common.Address{}, big.NewInt(0), 100000, big.NewInt(0), make([]byte, 10240))
   307  		tx, _ = types.SignTx(tx, types.HomesteadSigner{}, testKey)
   308  
   309  		insert[nonce] = tx
   310  	}
   311  	go handler.txpool.AddRemotes(insert) // Need goroutine to not block on feed
   312  	time.Sleep(250 * time.Millisecond)   // Wait until tx events get out of the system (can't use events, tx broadcaster races with peer join)
   313  
   314  	// Create a source handler to send messages through and a sink peer to receive them
   315  	p2pSrc, p2pSink := p2p.MsgPipe()
   316  	defer p2pSrc.Close()
   317  	defer p2pSink.Close()
   318  
   319  	src := eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{1}, "", nil, p2pSrc), p2pSrc, handler.txpool)
   320  	sink := eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{2}, "", nil, p2pSink), p2pSink, handler.txpool)
   321  	defer src.Close()
   322  	defer sink.Close()
   323  
   324  	go handler.handler.runEthPeer(src, func(peer *eth.Peer) error {
   325  		return eth.Handle((*ethHandler)(handler.handler), peer)
   326  	})
   327  	// Run the handshake locally to avoid spinning up a source handler
   328  	var (
   329  		genesis = handler.chain.Genesis()
   330  		head    = handler.chain.CurrentBlock()
   331  		td      = handler.chain.GetTd(head.Hash(), head.NumberU64())
   332  	)
   333  	if err := sink.Handshake(1, td, head.Hash(), genesis.Hash(), forkid.NewIDWithChain(handler.chain), forkid.NewFilter(handler.chain)); err != nil {
   334  		t.Fatalf("failed to run protocol handshake")
   335  	}
   336  	// After the handshake completes, the source handler should stream the sink
   337  	// the transactions, subscribe to all inbound network events
   338  	backend := new(testEthHandler)
   339  
   340  	anns := make(chan []common.Hash)
   341  	annSub := backend.txAnnounces.Subscribe(anns)
   342  	defer annSub.Unsubscribe()
   343  
   344  	bcasts := make(chan []*types.Transaction)
   345  	bcastSub := backend.txBroadcasts.Subscribe(bcasts)
   346  	defer bcastSub.Unsubscribe()
   347  
   348  	go eth.Handle(backend, sink)
   349  
   350  	// Make sure we get all the transactions on the correct channels
   351  	seen := make(map[common.Hash]struct{})
   352  	for len(seen) < len(insert) {
   353  		switch protocol {
   354  		case 65, 66:
   355  			select {
   356  			case hashes := <-anns:
   357  				for _, hash := range hashes {
   358  					if _, ok := seen[hash]; ok {
   359  						t.Errorf("duplicate transaction announced: %x", hash)
   360  					}
   361  					seen[hash] = struct{}{}
   362  				}
   363  			case <-bcasts:
   364  				t.Errorf("initial tx broadcast received on post eth/65")
   365  			}
   366  
   367  		default:
   368  			panic("unsupported protocol, please extend test")
   369  		}
   370  	}
   371  	for _, tx := range insert {
   372  		if _, ok := seen[tx.Hash()]; !ok {
   373  			t.Errorf("missing transaction: %x", tx.Hash())
   374  		}
   375  	}
   376  }
   377  
   378  // Tests that transactions get propagated to all attached peers, either via direct
   379  // broadcasts or via announcements/retrievals.
   380  func TestTransactionPropagation66(t *testing.T) { testTransactionPropagation(t, eth.ETH66) }
   381  
   382  func testTransactionPropagation(t *testing.T, protocol uint) {
   383  	t.Parallel()
   384  
   385  	// Create a source handler to send transactions from and a number of sinks
   386  	// to receive them. We need multiple sinks since a one-to-one peering would
   387  	// broadcast all transactions without announcement.
   388  	source := newTestHandler()
   389  	defer source.close()
   390  
   391  	sinks := make([]*testHandler, 10)
   392  	for i := 0; i < len(sinks); i++ {
   393  		sinks[i] = newTestHandler()
   394  		defer sinks[i].close()
   395  
   396  		sinks[i].handler.acceptTxs = 1 // mark synced to accept transactions
   397  	}
   398  	// Interconnect all the sink handlers with the source handler
   399  	for i, sink := range sinks {
   400  		sink := sink // Closure for gorotuine below
   401  
   402  		sourcePipe, sinkPipe := p2p.MsgPipe()
   403  		defer sourcePipe.Close()
   404  		defer sinkPipe.Close()
   405  
   406  		sourcePeer := eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{byte(i)}, "", nil, sourcePipe), sourcePipe, source.txpool)
   407  		sinkPeer := eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{0}, "", nil, sinkPipe), sinkPipe, sink.txpool)
   408  		defer sourcePeer.Close()
   409  		defer sinkPeer.Close()
   410  
   411  		go source.handler.runEthPeer(sourcePeer, func(peer *eth.Peer) error {
   412  			return eth.Handle((*ethHandler)(source.handler), peer)
   413  		})
   414  		go sink.handler.runEthPeer(sinkPeer, func(peer *eth.Peer) error {
   415  			return eth.Handle((*ethHandler)(sink.handler), peer)
   416  		})
   417  	}
   418  	// Subscribe to all the transaction pools
   419  	txChs := make([]chan core.NewTxsEvent, len(sinks))
   420  	for i := 0; i < len(sinks); i++ {
   421  		txChs[i] = make(chan core.NewTxsEvent, 1024)
   422  
   423  		sub := sinks[i].txpool.SubscribeNewTxsEvent(txChs[i])
   424  		defer sub.Unsubscribe()
   425  	}
   426  	// Fill the source pool with transactions and wait for them at the sinks
   427  	txs := make([]*types.Transaction, 1024)
   428  	for nonce := range txs {
   429  		tx := types.NewTransaction(uint64(nonce), common.Address{}, big.NewInt(0), 100000, big.NewInt(0), nil)
   430  		tx, _ = types.SignTx(tx, types.HomesteadSigner{}, testKey)
   431  
   432  		txs[nonce] = tx
   433  	}
   434  	source.txpool.AddRemotes(txs)
   435  
   436  	// Iterate through all the sinks and ensure they all got the transactions
   437  	for i := range sinks {
   438  		for arrived := 0; arrived < len(txs); {
   439  			select {
   440  			case event := <-txChs[i]:
   441  				arrived += len(event.Txs)
   442  			case <-time.NewTimer(time.Second).C:
   443  				t.Errorf("sink %d: transaction propagation timed out: have %d, want %d", i, arrived, len(txs))
   444  			}
   445  		}
   446  	}
   447  }
   448  
   449  // Tests that post eth protocol handshake, clients perform a mutual checkpoint
   450  // challenge to validate each other's chains. Hash mismatches, or missing ones
   451  // during a fast sync should lead to the peer getting dropped.
   452  func TestCheckpointChallenge(t *testing.T) {
   453  	tests := []struct {
   454  		syncmode   downloader.SyncMode
   455  		checkpoint bool
   456  		timeout    bool
   457  		empty      bool
   458  		match      bool
   459  		drop       bool
   460  	}{
   461  		// If checkpointing is not enabled locally, don't challenge and don't drop
   462  		{downloader.FullSync, false, false, false, false, false},
   463  		{downloader.FastSync, false, false, false, false, false},
   464  
   465  		// If checkpointing is enabled locally and remote response is empty, only drop during fast sync
   466  		{downloader.FullSync, true, false, true, false, false},
   467  		{downloader.FastSync, true, false, true, false, true}, // Special case, fast sync, unsynced peer
   468  
   469  		// If checkpointing is enabled locally and remote response mismatches, always drop
   470  		{downloader.FullSync, true, false, false, false, true},
   471  		{downloader.FastSync, true, false, false, false, true},
   472  
   473  		// If checkpointing is enabled locally and remote response matches, never drop
   474  		{downloader.FullSync, true, false, false, true, false},
   475  		{downloader.FastSync, true, false, false, true, false},
   476  
   477  		// If checkpointing is enabled locally and remote times out, always drop
   478  		{downloader.FullSync, true, true, false, true, true},
   479  		{downloader.FastSync, true, true, false, true, true},
   480  	}
   481  	for _, tt := range tests {
   482  		t.Run(fmt.Sprintf("sync %v checkpoint %v timeout %v empty %v match %v", tt.syncmode, tt.checkpoint, tt.timeout, tt.empty, tt.match), func(t *testing.T) {
   483  			testCheckpointChallenge(t, tt.syncmode, tt.checkpoint, tt.timeout, tt.empty, tt.match, tt.drop)
   484  		})
   485  	}
   486  }
   487  
   488  func testCheckpointChallenge(t *testing.T, syncmode downloader.SyncMode, checkpoint bool, timeout bool, empty bool, match bool, drop bool) {
   489  	t.Parallel()
   490  
   491  	// Reduce the checkpoint handshake challenge timeout
   492  	defer func(old time.Duration) { syncChallengeTimeout = old }(syncChallengeTimeout)
   493  	syncChallengeTimeout = 250 * time.Millisecond
   494  
   495  	// Create a test handler and inject a CHT into it. The injection is a bit
   496  	// ugly, but it beats creating everything manually just to avoid reaching
   497  	// into the internals a bit.
   498  	handler := newTestHandler()
   499  	defer handler.close()
   500  
   501  	if syncmode == downloader.FastSync {
   502  		atomic.StoreUint32(&handler.handler.fastSync, 1)
   503  	} else {
   504  		atomic.StoreUint32(&handler.handler.fastSync, 0)
   505  	}
   506  	var response *types.Header
   507  	if checkpoint {
   508  		number := (uint64(rand.Intn(500))+1)*params.CHTFrequency - 1
   509  		response = &types.Header{Number: big.NewInt(int64(number)), Extra: []byte("valid")}
   510  
   511  		handler.handler.checkpointNumber = number
   512  		handler.handler.checkpointHash = response.Hash()
   513  	}
   514  
   515  	// Create a challenger peer and a challenged one.
   516  	p2pLocal, p2pRemote := p2p.MsgPipe()
   517  	defer p2pLocal.Close()
   518  	defer p2pRemote.Close()
   519  
   520  	local := eth.NewPeer(eth.ETH66, p2p.NewPeerPipe(enode.ID{1}, "", nil, p2pLocal), p2pLocal, handler.txpool)
   521  	remote := eth.NewPeer(eth.ETH66, p2p.NewPeerPipe(enode.ID{2}, "", nil, p2pRemote), p2pRemote, handler.txpool)
   522  	defer local.Close()
   523  	defer remote.Close()
   524  
   525  	handlerDone := make(chan struct{})
   526  	go func() {
   527  		defer close(handlerDone)
   528  		handler.handler.runEthPeer(local, func(peer *eth.Peer) error {
   529  			return eth.Handle((*ethHandler)(handler.handler), peer)
   530  		})
   531  	}()
   532  
   533  	// Run the handshake locally to avoid spinning up a remote handler.
   534  	var (
   535  		genesis = handler.chain.Genesis()
   536  		head    = handler.chain.CurrentBlock()
   537  		td      = handler.chain.GetTd(head.Hash(), head.NumberU64())
   538  	)
   539  	if err := remote.Handshake(1, td, head.Hash(), genesis.Hash(), forkid.NewIDWithChain(handler.chain), forkid.NewFilter(handler.chain)); err != nil {
   540  		t.Fatalf("failed to run protocol handshake")
   541  	}
   542  	// Connect a new peer and check that we receive the checkpoint challenge.
   543  	if checkpoint {
   544  		msg, err := p2pRemote.ReadMsg()
   545  		if err != nil {
   546  			t.Fatalf("failed to read checkpoint challenge: %v", err)
   547  		}
   548  		request := new(eth.GetBlockHeadersPacket66)
   549  		if err := msg.Decode(request); err != nil {
   550  			t.Fatalf("failed to decode checkpoint challenge: %v", err)
   551  		}
   552  		query := request.GetBlockHeadersPacket
   553  		if query.Origin.Number != response.Number.Uint64() || query.Amount != 1 || query.Skip != 0 || query.Reverse {
   554  			t.Fatalf("challenge mismatch: have [%d, %d, %d, %v] want [%d, %d, %d, %v]",
   555  				query.Origin.Number, query.Amount, query.Skip, query.Reverse,
   556  				response.Number.Uint64(), 1, 0, false)
   557  		}
   558  		// Create a block to reply to the challenge if no timeout is simulated.
   559  		if !timeout {
   560  			if empty {
   561  				if err := remote.ReplyBlockHeaders(request.RequestId, []*types.Header{}); err != nil {
   562  					t.Fatalf("failed to answer challenge: %v", err)
   563  				}
   564  			} else if match {
   565  				if err := remote.ReplyBlockHeaders(request.RequestId, []*types.Header{response}); err != nil {
   566  					t.Fatalf("failed to answer challenge: %v", err)
   567  				}
   568  			} else {
   569  				if err := remote.ReplyBlockHeaders(request.RequestId, []*types.Header{{Number: response.Number}}); err != nil {
   570  					t.Fatalf("failed to answer challenge: %v", err)
   571  				}
   572  			}
   573  		}
   574  	}
   575  	// Wait until the test timeout passes to ensure proper cleanup
   576  	time.Sleep(syncChallengeTimeout + 300*time.Millisecond)
   577  
   578  	// Verify that the remote peer is maintained or dropped.
   579  	if drop {
   580  		<-handlerDone
   581  		if peers := handler.handler.peers.len(); peers != 0 {
   582  			t.Fatalf("peer count mismatch: have %d, want %d", peers, 0)
   583  		}
   584  	} else {
   585  		if peers := handler.handler.peers.len(); peers != 1 {
   586  			t.Fatalf("peer count mismatch: have %d, want %d", peers, 1)
   587  		}
   588  	}
   589  }
   590  
   591  // Tests that blocks are broadcast to a sqrt number of peers only.
   592  func TestBroadcastBlock1Peer(t *testing.T)    { testBroadcastBlock(t, 1, 1) }
   593  func TestBroadcastBlock2Peers(t *testing.T)   { testBroadcastBlock(t, 2, 1) }
   594  func TestBroadcastBlock3Peers(t *testing.T)   { testBroadcastBlock(t, 3, 1) }
   595  func TestBroadcastBlock4Peers(t *testing.T)   { testBroadcastBlock(t, 4, 2) }
   596  func TestBroadcastBlock5Peers(t *testing.T)   { testBroadcastBlock(t, 5, 2) }
   597  func TestBroadcastBlock8Peers(t *testing.T)   { testBroadcastBlock(t, 9, 3) }
   598  func TestBroadcastBlock12Peers(t *testing.T)  { testBroadcastBlock(t, 12, 3) }
   599  func TestBroadcastBlock16Peers(t *testing.T)  { testBroadcastBlock(t, 16, 4) }
   600  func TestBroadcastBloc26Peers(t *testing.T)   { testBroadcastBlock(t, 26, 5) }
   601  func TestBroadcastBlock100Peers(t *testing.T) { testBroadcastBlock(t, 100, 10) }
   602  
   603  func testBroadcastBlock(t *testing.T, peers, bcasts int) {
   604  	t.Parallel()
   605  
   606  	// Create a source handler to broadcast blocks from and a number of sinks
   607  	// to receive them.
   608  	source := newTestHandlerWithBlocks(1)
   609  	defer source.close()
   610  
   611  	sinks := make([]*testEthHandler, peers)
   612  	for i := 0; i < len(sinks); i++ {
   613  		sinks[i] = new(testEthHandler)
   614  	}
   615  	// Interconnect all the sink handlers with the source handler
   616  	var (
   617  		genesis = source.chain.Genesis()
   618  		td      = source.chain.GetTd(genesis.Hash(), genesis.NumberU64())
   619  	)
   620  	for i, sink := range sinks {
   621  		sink := sink // Closure for gorotuine below
   622  
   623  		sourcePipe, sinkPipe := p2p.MsgPipe()
   624  		defer sourcePipe.Close()
   625  		defer sinkPipe.Close()
   626  
   627  		sourcePeer := eth.NewPeer(eth.ETH66, p2p.NewPeerPipe(enode.ID{byte(i)}, "", nil, sourcePipe), sourcePipe, nil)
   628  		sinkPeer := eth.NewPeer(eth.ETH66, p2p.NewPeerPipe(enode.ID{0}, "", nil, sinkPipe), sinkPipe, nil)
   629  		defer sourcePeer.Close()
   630  		defer sinkPeer.Close()
   631  
   632  		go source.handler.runEthPeer(sourcePeer, func(peer *eth.Peer) error {
   633  			return eth.Handle((*ethHandler)(source.handler), peer)
   634  		})
   635  		if err := sinkPeer.Handshake(1, td, genesis.Hash(), genesis.Hash(), forkid.NewIDWithChain(source.chain), forkid.NewFilter(source.chain)); err != nil {
   636  			t.Fatalf("failed to run protocol handshake")
   637  		}
   638  		go eth.Handle(sink, sinkPeer)
   639  	}
   640  	// Subscribe to all the transaction pools
   641  	blockChs := make([]chan *types.Block, len(sinks))
   642  	for i := 0; i < len(sinks); i++ {
   643  		blockChs[i] = make(chan *types.Block, 1)
   644  		defer close(blockChs[i])
   645  
   646  		sub := sinks[i].blockBroadcasts.Subscribe(blockChs[i])
   647  		defer sub.Unsubscribe()
   648  	}
   649  	// Initiate a block propagation across the peers
   650  	time.Sleep(100 * time.Millisecond)
   651  	source.handler.BroadcastBlock(source.chain.CurrentBlock(), true)
   652  
   653  	// Iterate through all the sinks and ensure the correct number got the block
   654  	done := make(chan struct{}, peers)
   655  	for _, ch := range blockChs {
   656  		ch := ch
   657  		go func() {
   658  			<-ch
   659  			done <- struct{}{}
   660  		}()
   661  	}
   662  	var received int
   663  	for {
   664  		select {
   665  		case <-done:
   666  			received++
   667  
   668  		case <-time.After(100 * time.Millisecond):
   669  			if received != bcasts {
   670  				t.Errorf("broadcast count mismatch: have %d, want %d", received, bcasts)
   671  			}
   672  			return
   673  		}
   674  	}
   675  }
   676  
   677  // Tests that a propagated malformed block (uncles or transactions don't match
   678  // with the hashes in the header) gets discarded and not broadcast forward.
   679  func TestBroadcastMalformedBlock66(t *testing.T) { testBroadcastMalformedBlock(t, eth.ETH66) }
   680  
   681  func testBroadcastMalformedBlock(t *testing.T, protocol uint) {
   682  	t.Parallel()
   683  
   684  	// Create a source handler to broadcast blocks from and a number of sinks
   685  	// to receive them.
   686  	source := newTestHandlerWithBlocks(1)
   687  	defer source.close()
   688  
   689  	// Create a source handler to send messages through and a sink peer to receive them
   690  	p2pSrc, p2pSink := p2p.MsgPipe()
   691  	defer p2pSrc.Close()
   692  	defer p2pSink.Close()
   693  
   694  	src := eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{1}, "", nil, p2pSrc), p2pSrc, source.txpool)
   695  	sink := eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{2}, "", nil, p2pSink), p2pSink, source.txpool)
   696  	defer src.Close()
   697  	defer sink.Close()
   698  
   699  	go source.handler.runEthPeer(src, func(peer *eth.Peer) error {
   700  		return eth.Handle((*ethHandler)(source.handler), peer)
   701  	})
   702  	// Run the handshake locally to avoid spinning up a sink handler
   703  	var (
   704  		genesis = source.chain.Genesis()
   705  		td      = source.chain.GetTd(genesis.Hash(), genesis.NumberU64())
   706  	)
   707  	if err := sink.Handshake(1, td, genesis.Hash(), genesis.Hash(), forkid.NewIDWithChain(source.chain), forkid.NewFilter(source.chain)); err != nil {
   708  		t.Fatalf("failed to run protocol handshake")
   709  	}
   710  	// After the handshake completes, the source handler should stream the sink
   711  	// the blocks, subscribe to inbound network events
   712  	backend := new(testEthHandler)
   713  
   714  	blocks := make(chan *types.Block, 1)
   715  	sub := backend.blockBroadcasts.Subscribe(blocks)
   716  	defer sub.Unsubscribe()
   717  
   718  	go eth.Handle(backend, sink)
   719  
   720  	// Create various combinations of malformed blocks
   721  	head := source.chain.CurrentBlock()
   722  
   723  	malformedUncles := head.Header()
   724  	malformedUncles.UncleHash[0]++
   725  	malformedTransactions := head.Header()
   726  	malformedTransactions.TxHash[0]++
   727  	malformedEverything := head.Header()
   728  	malformedEverything.UncleHash[0]++
   729  	malformedEverything.TxHash[0]++
   730  
   731  	// Try to broadcast all malformations and ensure they all get discarded
   732  	for _, header := range []*types.Header{malformedUncles, malformedTransactions, malformedEverything} {
   733  		block := types.NewBlockWithHeader(header).WithBody(head.Transactions(), head.Uncles())
   734  		if err := src.SendNewBlock(block, big.NewInt(131136)); err != nil {
   735  			t.Fatalf("failed to broadcast block: %v", err)
   736  		}
   737  		select {
   738  		case <-blocks:
   739  			t.Fatalf("malformed block forwarded")
   740  		case <-time.After(100 * time.Millisecond):
   741  		}
   742  	}
   743  }