handler_eth_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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 TestForkIDSplit65(t *testing.T) { testForkIDSplit(t, eth.ETH65) }
  73. func TestForkIDSplit66(t *testing.T) { testForkIDSplit(t, eth.ETH66) }
  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 TestRecvTransactions65(t *testing.T) { testRecvTransactions(t, eth.ETH65) }
  206. func TestRecvTransactions66(t *testing.T) { testRecvTransactions(t, eth.ETH66) }
  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 TestSendTransactions65(t *testing.T) { testSendTransactions(t, eth.ETH65) }
  255. func TestSendTransactions66(t *testing.T) { testSendTransactions(t, eth.ETH66) }
  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 65, 66:
  304. select {
  305. case hashes := <-anns:
  306. for _, hash := range hashes {
  307. if _, ok := seen[hash]; ok {
  308. t.Errorf("duplicate transaction announced: %x", hash)
  309. }
  310. seen[hash] = struct{}{}
  311. }
  312. case <-bcasts:
  313. t.Errorf("initial tx broadcast received on post eth/65")
  314. }
  315. default:
  316. panic("unsupported protocol, please extend test")
  317. }
  318. }
  319. for _, tx := range insert {
  320. if _, ok := seen[tx.Hash()]; !ok {
  321. t.Errorf("missing transaction: %x", tx.Hash())
  322. }
  323. }
  324. }
  325. // Tests that transactions get propagated to all attached peers, either via direct
  326. // broadcasts or via announcements/retrievals.
  327. func TestTransactionPropagation65(t *testing.T) { testTransactionPropagation(t, eth.ETH65) }
  328. func TestTransactionPropagation66(t *testing.T) { testTransactionPropagation(t, eth.ETH66) }
  329. func testTransactionPropagation(t *testing.T, protocol uint) {
  330. t.Parallel()
  331. // Create a source handler to send transactions from and a number of sinks
  332. // to receive them. We need multiple sinks since a one-to-one peering would
  333. // broadcast all transactions without announcement.
  334. source := newTestHandler()
  335. defer source.close()
  336. sinks := make([]*testHandler, 10)
  337. for i := 0; i < len(sinks); i++ {
  338. sinks[i] = newTestHandler()
  339. defer sinks[i].close()
  340. sinks[i].handler.acceptTxs = 1 // mark synced to accept transactions
  341. }
  342. // Interconnect all the sink handlers with the source handler
  343. for i, sink := range sinks {
  344. sink := sink // Closure for gorotuine below
  345. sourcePipe, sinkPipe := p2p.MsgPipe()
  346. defer sourcePipe.Close()
  347. defer sinkPipe.Close()
  348. sourcePeer := eth.NewPeer(protocol, p2p.NewPeer(enode.ID{byte(i)}, "", nil), sourcePipe, source.txpool)
  349. sinkPeer := eth.NewPeer(protocol, p2p.NewPeer(enode.ID{0}, "", nil), sinkPipe, sink.txpool)
  350. defer sourcePeer.Close()
  351. defer sinkPeer.Close()
  352. go source.handler.runEthPeer(sourcePeer, func(peer *eth.Peer) error {
  353. return eth.Handle((*ethHandler)(source.handler), peer)
  354. })
  355. go sink.handler.runEthPeer(sinkPeer, func(peer *eth.Peer) error {
  356. return eth.Handle((*ethHandler)(sink.handler), peer)
  357. })
  358. }
  359. // Subscribe to all the transaction pools
  360. txChs := make([]chan core.NewTxsEvent, len(sinks))
  361. for i := 0; i < len(sinks); i++ {
  362. txChs[i] = make(chan core.NewTxsEvent, 1024)
  363. sub := sinks[i].txpool.SubscribeNewTxsEvent(txChs[i])
  364. defer sub.Unsubscribe()
  365. }
  366. // Fill the source pool with transactions and wait for them at the sinks
  367. txs := make([]*types.Transaction, 1024)
  368. for nonce := range txs {
  369. tx := types.NewTransaction(uint64(nonce), common.Address{}, big.NewInt(0), 100000, big.NewInt(0), nil)
  370. tx, _ = types.SignTx(tx, types.HomesteadSigner{}, testKey)
  371. txs[nonce] = tx
  372. }
  373. source.txpool.AddRemotes(txs)
  374. // Iterate through all the sinks and ensure they all got the transactions
  375. for i := range sinks {
  376. for arrived := 0; arrived < len(txs); {
  377. select {
  378. case event := <-txChs[i]:
  379. arrived += len(event.Txs)
  380. case <-time.NewTimer(time.Second).C:
  381. t.Errorf("sink %d: transaction propagation timed out: have %d, want %d", i, arrived, len(txs))
  382. }
  383. }
  384. }
  385. }
  386. // Tests that post eth protocol handshake, clients perform a mutual checkpoint
  387. // challenge to validate each other's chains. Hash mismatches, or missing ones
  388. // during a fast sync should lead to the peer getting dropped.
  389. func TestCheckpointChallenge(t *testing.T) {
  390. tests := []struct {
  391. syncmode downloader.SyncMode
  392. checkpoint bool
  393. timeout bool
  394. empty bool
  395. match bool
  396. drop bool
  397. }{
  398. // If checkpointing is not enabled locally, don't challenge and don't drop
  399. {downloader.FullSync, false, false, false, false, false},
  400. {downloader.FastSync, false, false, false, false, false},
  401. // If checkpointing is enabled locally and remote response is empty, only drop during fast sync
  402. {downloader.FullSync, true, false, true, false, false},
  403. {downloader.FastSync, true, false, true, false, true}, // Special case, fast sync, unsynced peer
  404. // If checkpointing is enabled locally and remote response mismatches, always drop
  405. {downloader.FullSync, true, false, false, false, true},
  406. {downloader.FastSync, true, false, false, false, true},
  407. // If checkpointing is enabled locally and remote response matches, never drop
  408. {downloader.FullSync, true, false, false, true, false},
  409. {downloader.FastSync, true, false, false, true, false},
  410. // If checkpointing is enabled locally and remote times out, always drop
  411. {downloader.FullSync, true, true, false, true, true},
  412. {downloader.FastSync, true, true, false, true, true},
  413. }
  414. for _, tt := range tests {
  415. 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) {
  416. testCheckpointChallenge(t, tt.syncmode, tt.checkpoint, tt.timeout, tt.empty, tt.match, tt.drop)
  417. })
  418. }
  419. }
  420. func testCheckpointChallenge(t *testing.T, syncmode downloader.SyncMode, checkpoint bool, timeout bool, empty bool, match bool, drop bool) {
  421. // Reduce the checkpoint handshake challenge timeout
  422. defer func(old time.Duration) { syncChallengeTimeout = old }(syncChallengeTimeout)
  423. syncChallengeTimeout = 250 * time.Millisecond
  424. // Create a test handler and inject a CHT into it. The injection is a bit
  425. // ugly, but it beats creating everything manually just to avoid reaching
  426. // into the internals a bit.
  427. handler := newTestHandler()
  428. defer handler.close()
  429. if syncmode == downloader.FastSync {
  430. atomic.StoreUint32(&handler.handler.fastSync, 1)
  431. } else {
  432. atomic.StoreUint32(&handler.handler.fastSync, 0)
  433. }
  434. var response *types.Header
  435. if checkpoint {
  436. number := (uint64(rand.Intn(500))+1)*params.CHTFrequency - 1
  437. response = &types.Header{Number: big.NewInt(int64(number)), Extra: []byte("valid")}
  438. handler.handler.checkpointNumber = number
  439. handler.handler.checkpointHash = response.Hash()
  440. }
  441. // Create a challenger peer and a challenged one
  442. p2pLocal, p2pRemote := p2p.MsgPipe()
  443. defer p2pLocal.Close()
  444. defer p2pRemote.Close()
  445. local := eth.NewPeer(eth.ETH65, p2p.NewPeer(enode.ID{1}, "", nil), p2pLocal, handler.txpool)
  446. remote := eth.NewPeer(eth.ETH65, p2p.NewPeer(enode.ID{2}, "", nil), p2pRemote, handler.txpool)
  447. defer local.Close()
  448. defer remote.Close()
  449. go handler.handler.runEthPeer(local, func(peer *eth.Peer) error {
  450. return eth.Handle((*ethHandler)(handler.handler), peer)
  451. })
  452. // Run the handshake locally to avoid spinning up a remote handler
  453. var (
  454. genesis = handler.chain.Genesis()
  455. head = handler.chain.CurrentBlock()
  456. td = handler.chain.GetTd(head.Hash(), head.NumberU64())
  457. )
  458. if err := remote.Handshake(1, td, head.Hash(), genesis.Hash(), forkid.NewIDWithChain(handler.chain), forkid.NewFilter(handler.chain)); err != nil {
  459. t.Fatalf("failed to run protocol handshake")
  460. }
  461. // Connect a new peer and check that we receive the checkpoint challenge
  462. if checkpoint {
  463. if err := remote.ExpectRequestHeadersByNumber(response.Number.Uint64(), 1, 0, false); err != nil {
  464. t.Fatalf("challenge mismatch: %v", err)
  465. }
  466. // Create a block to reply to the challenge if no timeout is simulated
  467. if !timeout {
  468. if empty {
  469. if err := remote.SendBlockHeaders([]*types.Header{}); err != nil {
  470. t.Fatalf("failed to answer challenge: %v", err)
  471. }
  472. } else if match {
  473. if err := remote.SendBlockHeaders([]*types.Header{response}); err != nil {
  474. t.Fatalf("failed to answer challenge: %v", err)
  475. }
  476. } else {
  477. if err := remote.SendBlockHeaders([]*types.Header{{Number: response.Number}}); err != nil {
  478. t.Fatalf("failed to answer challenge: %v", err)
  479. }
  480. }
  481. }
  482. }
  483. // Wait until the test timeout passes to ensure proper cleanup
  484. time.Sleep(syncChallengeTimeout + 300*time.Millisecond)
  485. // Verify that the remote peer is maintained or dropped
  486. if drop {
  487. if peers := handler.handler.peers.len(); peers != 0 {
  488. t.Fatalf("peer count mismatch: have %d, want %d", peers, 0)
  489. }
  490. } else {
  491. if peers := handler.handler.peers.len(); peers != 1 {
  492. t.Fatalf("peer count mismatch: have %d, want %d", peers, 1)
  493. }
  494. }
  495. }
  496. // Tests that blocks are broadcast to a sqrt number of peers only.
  497. func TestBroadcastBlock1Peer(t *testing.T) { testBroadcastBlock(t, 1, 1) }
  498. func TestBroadcastBlock2Peers(t *testing.T) { testBroadcastBlock(t, 2, 1) }
  499. func TestBroadcastBlock3Peers(t *testing.T) { testBroadcastBlock(t, 3, 1) }
  500. func TestBroadcastBlock4Peers(t *testing.T) { testBroadcastBlock(t, 4, 2) }
  501. func TestBroadcastBlock5Peers(t *testing.T) { testBroadcastBlock(t, 5, 2) }
  502. func TestBroadcastBlock8Peers(t *testing.T) { testBroadcastBlock(t, 9, 3) }
  503. func TestBroadcastBlock12Peers(t *testing.T) { testBroadcastBlock(t, 12, 3) }
  504. func TestBroadcastBlock16Peers(t *testing.T) { testBroadcastBlock(t, 16, 4) }
  505. func TestBroadcastBloc26Peers(t *testing.T) { testBroadcastBlock(t, 26, 5) }
  506. func TestBroadcastBlock100Peers(t *testing.T) { testBroadcastBlock(t, 100, 10) }
  507. func testBroadcastBlock(t *testing.T, peers, bcasts int) {
  508. t.Parallel()
  509. // Create a source handler to broadcast blocks from and a number of sinks
  510. // to receive them.
  511. source := newTestHandlerWithBlocks(1)
  512. defer source.close()
  513. sinks := make([]*testEthHandler, peers)
  514. for i := 0; i < len(sinks); i++ {
  515. sinks[i] = new(testEthHandler)
  516. }
  517. // Interconnect all the sink handlers with the source handler
  518. var (
  519. genesis = source.chain.Genesis()
  520. td = source.chain.GetTd(genesis.Hash(), genesis.NumberU64())
  521. )
  522. for i, sink := range sinks {
  523. sink := sink // Closure for gorotuine below
  524. sourcePipe, sinkPipe := p2p.MsgPipe()
  525. defer sourcePipe.Close()
  526. defer sinkPipe.Close()
  527. sourcePeer := eth.NewPeer(eth.ETH65, p2p.NewPeer(enode.ID{byte(i)}, "", nil), sourcePipe, nil)
  528. sinkPeer := eth.NewPeer(eth.ETH65, p2p.NewPeer(enode.ID{0}, "", nil), sinkPipe, nil)
  529. defer sourcePeer.Close()
  530. defer sinkPeer.Close()
  531. go source.handler.runEthPeer(sourcePeer, func(peer *eth.Peer) error {
  532. return eth.Handle((*ethHandler)(source.handler), peer)
  533. })
  534. if err := sinkPeer.Handshake(1, td, genesis.Hash(), genesis.Hash(), forkid.NewIDWithChain(source.chain), forkid.NewFilter(source.chain)); err != nil {
  535. t.Fatalf("failed to run protocol handshake")
  536. }
  537. go eth.Handle(sink, sinkPeer)
  538. }
  539. // Subscribe to all the transaction pools
  540. blockChs := make([]chan *types.Block, len(sinks))
  541. for i := 0; i < len(sinks); i++ {
  542. blockChs[i] = make(chan *types.Block, 1)
  543. defer close(blockChs[i])
  544. sub := sinks[i].blockBroadcasts.Subscribe(blockChs[i])
  545. defer sub.Unsubscribe()
  546. }
  547. // Initiate a block propagation across the peers
  548. time.Sleep(100 * time.Millisecond)
  549. source.handler.BroadcastBlock(source.chain.CurrentBlock(), true)
  550. // Iterate through all the sinks and ensure the correct number got the block
  551. done := make(chan struct{}, peers)
  552. for _, ch := range blockChs {
  553. ch := ch
  554. go func() {
  555. <-ch
  556. done <- struct{}{}
  557. }()
  558. }
  559. var received int
  560. for {
  561. select {
  562. case <-done:
  563. received++
  564. case <-time.After(100 * time.Millisecond):
  565. if received != bcasts {
  566. t.Errorf("broadcast count mismatch: have %d, want %d", received, bcasts)
  567. }
  568. return
  569. }
  570. }
  571. }
  572. // Tests that a propagated malformed block (uncles or transactions don't match
  573. // with the hashes in the header) gets discarded and not broadcast forward.
  574. func TestBroadcastMalformedBlock65(t *testing.T) { testBroadcastMalformedBlock(t, eth.ETH65) }
  575. func TestBroadcastMalformedBlock66(t *testing.T) { testBroadcastMalformedBlock(t, eth.ETH66) }
  576. func testBroadcastMalformedBlock(t *testing.T, protocol uint) {
  577. t.Parallel()
  578. // Create a source handler to broadcast blocks from and a number of sinks
  579. // to receive them.
  580. source := newTestHandlerWithBlocks(1)
  581. defer source.close()
  582. // Create a source handler to send messages through and a sink peer to receive them
  583. p2pSrc, p2pSink := p2p.MsgPipe()
  584. defer p2pSrc.Close()
  585. defer p2pSink.Close()
  586. src := eth.NewPeer(protocol, p2p.NewPeer(enode.ID{1}, "", nil), p2pSrc, source.txpool)
  587. sink := eth.NewPeer(protocol, p2p.NewPeer(enode.ID{2}, "", nil), p2pSink, source.txpool)
  588. defer src.Close()
  589. defer sink.Close()
  590. go source.handler.runEthPeer(src, func(peer *eth.Peer) error {
  591. return eth.Handle((*ethHandler)(source.handler), peer)
  592. })
  593. // Run the handshake locally to avoid spinning up a sink handler
  594. var (
  595. genesis = source.chain.Genesis()
  596. td = source.chain.GetTd(genesis.Hash(), genesis.NumberU64())
  597. )
  598. if err := sink.Handshake(1, td, genesis.Hash(), genesis.Hash(), forkid.NewIDWithChain(source.chain), forkid.NewFilter(source.chain)); err != nil {
  599. t.Fatalf("failed to run protocol handshake")
  600. }
  601. // After the handshake completes, the source handler should stream the sink
  602. // the blocks, subscribe to inbound network events
  603. backend := new(testEthHandler)
  604. blocks := make(chan *types.Block, 1)
  605. sub := backend.blockBroadcasts.Subscribe(blocks)
  606. defer sub.Unsubscribe()
  607. go eth.Handle(backend, sink)
  608. // Create various combinations of malformed blocks
  609. head := source.chain.CurrentBlock()
  610. malformedUncles := head.Header()
  611. malformedUncles.UncleHash[0]++
  612. malformedTransactions := head.Header()
  613. malformedTransactions.TxHash[0]++
  614. malformedEverything := head.Header()
  615. malformedEverything.UncleHash[0]++
  616. malformedEverything.TxHash[0]++
  617. // Try to broadcast all malformations and ensure they all get discarded
  618. for _, header := range []*types.Header{malformedUncles, malformedTransactions, malformedEverything} {
  619. block := types.NewBlockWithHeader(header).WithBody(head.Transactions(), head.Uncles())
  620. if err := src.SendNewBlock(block, big.NewInt(131136)); err != nil {
  621. t.Fatalf("failed to broadcast block: %v", err)
  622. }
  623. select {
  624. case <-blocks:
  625. t.Fatalf("malformed block forwarded")
  626. case <-time.After(100 * time.Millisecond):
  627. }
  628. }
  629. }