handler_eth_test.go 26 KB

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