handler_eth_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. // Copyright 2020 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"
  26. "github.com/ethereum/go-ethereum/consensus/ethash"
  27. "github.com/ethereum/go-ethereum/core"
  28. "github.com/ethereum/go-ethereum/core/forkid"
  29. "github.com/ethereum/go-ethereum/core/rawdb"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/core/vm"
  32. "github.com/ethereum/go-ethereum/eth/downloader"
  33. "github.com/ethereum/go-ethereum/eth/protocols/eth"
  34. "github.com/ethereum/go-ethereum/event"
  35. "github.com/ethereum/go-ethereum/p2p"
  36. "github.com/ethereum/go-ethereum/p2p/enode"
  37. "github.com/ethereum/go-ethereum/params"
  38. "github.com/ethereum/go-ethereum/rlp"
  39. )
  40. // testEthHandler is a mock event handler to listen for inbound network requests
  41. // on the `eth` protocol and convert them into a more easily testable form.
  42. type testEthHandler struct {
  43. blockBroadcasts event.Feed
  44. txAnnounces event.Feed
  45. txBroadcasts event.Feed
  46. }
  47. func (h *testEthHandler) Chain() *core.BlockChain { panic("no backing chain") }
  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 TestForkIDSplit66(t *testing.T) { testForkIDSplit(t, eth.ETH66) }
  73. func testForkIDSplit(t *testing.T, protocol uint) {
  74. t.Parallel()
  75. var (
  76. engine = ethash.NewFaker()
  77. configNoFork = &params.ChainConfig{HomesteadBlock: big.NewInt(1)}
  78. configProFork = &params.ChainConfig{
  79. HomesteadBlock: big.NewInt(1),
  80. EIP150Block: big.NewInt(2),
  81. EIP155Block: big.NewInt(2),
  82. EIP158Block: big.NewInt(2),
  83. ByzantiumBlock: big.NewInt(3),
  84. }
  85. dbNoFork = rawdb.NewMemoryDatabase()
  86. dbProFork = rawdb.NewMemoryDatabase()
  87. gspecNoFork = &core.Genesis{Config: configNoFork}
  88. gspecProFork = &core.Genesis{Config: configProFork}
  89. genesisNoFork = gspecNoFork.MustCommit(dbNoFork)
  90. genesisProFork = gspecProFork.MustCommit(dbProFork)
  91. chainNoFork, _ = core.NewBlockChain(dbNoFork, nil, configNoFork, engine, vm.Config{}, nil, nil)
  92. chainProFork, _ = core.NewBlockChain(dbProFork, nil, configProFork, engine, vm.Config{}, nil, nil)
  93. blocksNoFork, _ = core.GenerateChain(configNoFork, genesisNoFork, engine, dbNoFork, 2, nil)
  94. blocksProFork, _ = core.GenerateChain(configProFork, genesisProFork, engine, dbProFork, 2, nil)
  95. ethNoFork, _ = newHandler(&handlerConfig{
  96. Database: dbNoFork,
  97. Chain: chainNoFork,
  98. TxPool: newTestTxPool(),
  99. Merger: consensus.NewMerger(rawdb.NewMemoryDatabase()),
  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. Merger: consensus.NewMerger(rawdb.NewMemoryDatabase()),
  109. Network: 1,
  110. Sync: downloader.FullSync,
  111. BloomCache: 1,
  112. })
  113. )
  114. ethNoFork.Start(1000)
  115. ethProFork.Start(1000)
  116. // Clean up everything after ourselves
  117. defer chainNoFork.Stop()
  118. defer chainProFork.Stop()
  119. defer ethNoFork.Stop()
  120. defer ethProFork.Stop()
  121. // Both nodes should allow the other to connect (same genesis, next fork is the same)
  122. p2pNoFork, p2pProFork := p2p.MsgPipe()
  123. defer p2pNoFork.Close()
  124. defer p2pProFork.Close()
  125. peerNoFork := eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{1}, "", nil, p2pNoFork), p2pNoFork, nil)
  126. peerProFork := eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{2}, "", nil, p2pProFork), p2pProFork, nil)
  127. defer peerNoFork.Close()
  128. defer peerProFork.Close()
  129. errc := make(chan error, 2)
  130. go func(errc chan error) {
  131. errc <- ethNoFork.runEthPeer(peerProFork, func(peer *eth.Peer) error { return nil })
  132. }(errc)
  133. go func(errc chan error) {
  134. errc <- ethProFork.runEthPeer(peerNoFork, func(peer *eth.Peer) error { return nil })
  135. }(errc)
  136. for i := 0; i < 2; i++ {
  137. select {
  138. case err := <-errc:
  139. if err != nil {
  140. t.Fatalf("frontier nofork <-> profork failed: %v", err)
  141. }
  142. case <-time.After(250 * time.Millisecond):
  143. t.Fatalf("frontier nofork <-> profork handler timeout")
  144. }
  145. }
  146. // Progress into Homestead. Fork's match, so we don't care what the future holds
  147. chainNoFork.InsertChain(blocksNoFork[:1])
  148. chainProFork.InsertChain(blocksProFork[:1])
  149. p2pNoFork, p2pProFork = p2p.MsgPipe()
  150. defer p2pNoFork.Close()
  151. defer p2pProFork.Close()
  152. peerNoFork = eth.NewPeer(protocol, p2p.NewPeer(enode.ID{1}, "", nil), p2pNoFork, nil)
  153. peerProFork = eth.NewPeer(protocol, p2p.NewPeer(enode.ID{2}, "", nil), p2pProFork, nil)
  154. defer peerNoFork.Close()
  155. defer peerProFork.Close()
  156. errc = make(chan error, 2)
  157. go func(errc chan error) {
  158. errc <- ethNoFork.runEthPeer(peerProFork, func(peer *eth.Peer) error { return nil })
  159. }(errc)
  160. go func(errc chan error) {
  161. errc <- ethProFork.runEthPeer(peerNoFork, func(peer *eth.Peer) error { return nil })
  162. }(errc)
  163. for i := 0; i < 2; i++ {
  164. select {
  165. case err := <-errc:
  166. if err != nil {
  167. t.Fatalf("homestead nofork <-> profork failed: %v", err)
  168. }
  169. case <-time.After(250 * time.Millisecond):
  170. t.Fatalf("homestead nofork <-> profork handler timeout")
  171. }
  172. }
  173. // Progress into Spurious. Forks mismatch, signalling differing chains, reject
  174. chainNoFork.InsertChain(blocksNoFork[1:2])
  175. chainProFork.InsertChain(blocksProFork[1:2])
  176. p2pNoFork, p2pProFork = p2p.MsgPipe()
  177. defer p2pNoFork.Close()
  178. defer p2pProFork.Close()
  179. peerNoFork = eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{1}, "", nil, p2pNoFork), p2pNoFork, nil)
  180. peerProFork = eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{2}, "", nil, p2pProFork), p2pProFork, nil)
  181. defer peerNoFork.Close()
  182. defer peerProFork.Close()
  183. errc = make(chan error, 2)
  184. go func(errc chan error) {
  185. errc <- ethNoFork.runEthPeer(peerProFork, func(peer *eth.Peer) error { return nil })
  186. }(errc)
  187. go func(errc chan error) {
  188. errc <- ethProFork.runEthPeer(peerNoFork, func(peer *eth.Peer) error { return nil })
  189. }(errc)
  190. var successes int
  191. for i := 0; i < 2; i++ {
  192. select {
  193. case err := <-errc:
  194. if err == nil {
  195. successes++
  196. if successes == 2 { // Only one side disconnects
  197. t.Fatalf("fork ID rejection didn't happen")
  198. }
  199. }
  200. case <-time.After(250 * time.Millisecond):
  201. t.Fatalf("split peers not rejected")
  202. }
  203. }
  204. }
  205. // Tests that received transactions are added to the local pool.
  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.NewPeerPipe(enode.ID{1}, "", nil, p2pSrc), p2pSrc, handler.txpool)
  221. sink := eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{2}, "", nil, p2pSink), 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 TestSendTransactions66(t *testing.T) { testSendTransactions(t, eth.ETH66) }
  255. func testSendTransactions(t *testing.T, protocol uint) {
  256. t.Parallel()
  257. // Create a message handler and fill the pool with big transactions
  258. handler := newTestHandler()
  259. defer handler.close()
  260. insert := make([]*types.Transaction, 100)
  261. for nonce := range insert {
  262. tx := types.NewTransaction(uint64(nonce), common.Address{}, big.NewInt(0), 100000, big.NewInt(0), make([]byte, 10240))
  263. tx, _ = types.SignTx(tx, types.HomesteadSigner{}, testKey)
  264. insert[nonce] = tx
  265. }
  266. go handler.txpool.AddRemotes(insert) // Need goroutine to not block on feed
  267. time.Sleep(250 * time.Millisecond) // Wait until tx events get out of the system (can't use events, tx broadcaster races with peer join)
  268. // Create a source handler to send messages through and a sink peer to receive them
  269. p2pSrc, p2pSink := p2p.MsgPipe()
  270. defer p2pSrc.Close()
  271. defer p2pSink.Close()
  272. src := eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{1}, "", nil, p2pSrc), p2pSrc, handler.txpool)
  273. sink := eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{2}, "", nil, p2pSink), p2pSink, handler.txpool)
  274. defer src.Close()
  275. defer sink.Close()
  276. go handler.handler.runEthPeer(src, func(peer *eth.Peer) error {
  277. return eth.Handle((*ethHandler)(handler.handler), peer)
  278. })
  279. // Run the handshake locally to avoid spinning up a source handler
  280. var (
  281. genesis = handler.chain.Genesis()
  282. head = handler.chain.CurrentBlock()
  283. td = handler.chain.GetTd(head.Hash(), head.NumberU64())
  284. )
  285. if err := sink.Handshake(1, td, head.Hash(), genesis.Hash(), forkid.NewIDWithChain(handler.chain), forkid.NewFilter(handler.chain)); err != nil {
  286. t.Fatalf("failed to run protocol handshake")
  287. }
  288. // After the handshake completes, the source handler should stream the sink
  289. // the transactions, subscribe to all inbound network events
  290. backend := new(testEthHandler)
  291. anns := make(chan []common.Hash)
  292. annSub := backend.txAnnounces.Subscribe(anns)
  293. defer annSub.Unsubscribe()
  294. bcasts := make(chan []*types.Transaction)
  295. bcastSub := backend.txBroadcasts.Subscribe(bcasts)
  296. defer bcastSub.Unsubscribe()
  297. go eth.Handle(backend, sink)
  298. // Make sure we get all the transactions on the correct channels
  299. seen := make(map[common.Hash]struct{})
  300. for len(seen) < len(insert) {
  301. switch protocol {
  302. case 66:
  303. select {
  304. case hashes := <-anns:
  305. for _, hash := range hashes {
  306. if _, ok := seen[hash]; ok {
  307. t.Errorf("duplicate transaction announced: %x", hash)
  308. }
  309. seen[hash] = struct{}{}
  310. }
  311. case <-bcasts:
  312. t.Errorf("initial tx broadcast received on post eth/66")
  313. }
  314. default:
  315. panic("unsupported protocol, please extend test")
  316. }
  317. }
  318. for _, tx := range insert {
  319. if _, ok := seen[tx.Hash()]; !ok {
  320. t.Errorf("missing transaction: %x", tx.Hash())
  321. }
  322. }
  323. }
  324. // Tests that transactions get propagated to all attached peers, either via direct
  325. // broadcasts or via announcements/retrievals.
  326. func TestTransactionPropagation66(t *testing.T) { testTransactionPropagation(t, eth.ETH66) }
  327. func testTransactionPropagation(t *testing.T, protocol uint) {
  328. t.Parallel()
  329. // Create a source handler to send transactions from and a number of sinks
  330. // to receive them. We need multiple sinks since a one-to-one peering would
  331. // broadcast all transactions without announcement.
  332. source := newTestHandler()
  333. source.handler.snapSync = 0 // Avoid requiring snap, otherwise some will be dropped below
  334. defer source.close()
  335. sinks := make([]*testHandler, 10)
  336. for i := 0; i < len(sinks); i++ {
  337. sinks[i] = newTestHandler()
  338. defer sinks[i].close()
  339. sinks[i].handler.acceptTxs = 1 // mark synced to accept transactions
  340. }
  341. // Interconnect all the sink handlers with the source handler
  342. for i, sink := range sinks {
  343. sink := sink // Closure for gorotuine below
  344. sourcePipe, sinkPipe := p2p.MsgPipe()
  345. defer sourcePipe.Close()
  346. defer sinkPipe.Close()
  347. sourcePeer := eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{byte(i + 1)}, "", nil, sourcePipe), sourcePipe, source.txpool)
  348. sinkPeer := eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{0}, "", nil, sinkPipe), sinkPipe, sink.txpool)
  349. defer sourcePeer.Close()
  350. defer sinkPeer.Close()
  351. go source.handler.runEthPeer(sourcePeer, func(peer *eth.Peer) error {
  352. return eth.Handle((*ethHandler)(source.handler), peer)
  353. })
  354. go sink.handler.runEthPeer(sinkPeer, func(peer *eth.Peer) error {
  355. return eth.Handle((*ethHandler)(sink.handler), peer)
  356. })
  357. }
  358. // Subscribe to all the transaction pools
  359. txChs := make([]chan core.NewTxsEvent, len(sinks))
  360. for i := 0; i < len(sinks); i++ {
  361. txChs[i] = make(chan core.NewTxsEvent, 1024)
  362. sub := sinks[i].txpool.SubscribeNewTxsEvent(txChs[i])
  363. defer sub.Unsubscribe()
  364. }
  365. // Fill the source pool with transactions and wait for them at the sinks
  366. txs := make([]*types.Transaction, 1024)
  367. for nonce := range txs {
  368. tx := types.NewTransaction(uint64(nonce), common.Address{}, big.NewInt(0), 100000, big.NewInt(0), nil)
  369. tx, _ = types.SignTx(tx, types.HomesteadSigner{}, testKey)
  370. txs[nonce] = tx
  371. }
  372. source.txpool.AddRemotes(txs)
  373. // Iterate through all the sinks and ensure they all got the transactions
  374. for i := range sinks {
  375. for arrived, timeout := 0, false; arrived < len(txs) && !timeout; {
  376. select {
  377. case event := <-txChs[i]:
  378. arrived += len(event.Txs)
  379. case <-time.After(time.Second):
  380. t.Errorf("sink %d: transaction propagation timed out: have %d, want %d", i, arrived, len(txs))
  381. timeout = true
  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.SnapSync, 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.SnapSync, 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.SnapSync, 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.SnapSync, 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.SnapSync, 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.SnapSync {
  430. atomic.StoreUint32(&handler.handler.snapSync, 1)
  431. } else {
  432. atomic.StoreUint32(&handler.handler.snapSync, 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.ETH66, p2p.NewPeerPipe(enode.ID{1}, "", nil, p2pLocal), p2pLocal, handler.txpool)
  446. remote := eth.NewPeer(eth.ETH66, p2p.NewPeerPipe(enode.ID{2}, "", nil, p2pRemote), p2pRemote, handler.txpool)
  447. defer local.Close()
  448. defer remote.Close()
  449. handlerDone := make(chan struct{})
  450. go func() {
  451. defer close(handlerDone)
  452. handler.handler.runEthPeer(local, func(peer *eth.Peer) error {
  453. return eth.Handle((*ethHandler)(handler.handler), peer)
  454. })
  455. }()
  456. // Run the handshake locally to avoid spinning up a remote handler.
  457. var (
  458. genesis = handler.chain.Genesis()
  459. head = handler.chain.CurrentBlock()
  460. td = handler.chain.GetTd(head.Hash(), head.NumberU64())
  461. )
  462. if err := remote.Handshake(1, td, head.Hash(), genesis.Hash(), forkid.NewIDWithChain(handler.chain), forkid.NewFilter(handler.chain)); err != nil {
  463. t.Fatalf("failed to run protocol handshake")
  464. }
  465. // Connect a new peer and check that we receive the checkpoint challenge.
  466. if checkpoint {
  467. msg, err := p2pRemote.ReadMsg()
  468. if err != nil {
  469. t.Fatalf("failed to read checkpoint challenge: %v", err)
  470. }
  471. request := new(eth.GetBlockHeadersPacket66)
  472. if err := msg.Decode(request); err != nil {
  473. t.Fatalf("failed to decode checkpoint challenge: %v", err)
  474. }
  475. query := request.GetBlockHeadersPacket
  476. if query.Origin.Number != response.Number.Uint64() || query.Amount != 1 || query.Skip != 0 || query.Reverse {
  477. t.Fatalf("challenge mismatch: have [%d, %d, %d, %v] want [%d, %d, %d, %v]",
  478. query.Origin.Number, query.Amount, query.Skip, query.Reverse,
  479. response.Number.Uint64(), 1, 0, false)
  480. }
  481. // Create a block to reply to the challenge if no timeout is simulated.
  482. if !timeout {
  483. if empty {
  484. if err := remote.ReplyBlockHeadersRLP(request.RequestId, []rlp.RawValue{}); err != nil {
  485. t.Fatalf("failed to answer challenge: %v", err)
  486. }
  487. } else if match {
  488. responseRlp, _ := rlp.EncodeToBytes(response)
  489. if err := remote.ReplyBlockHeadersRLP(request.RequestId, []rlp.RawValue{responseRlp}); err != nil {
  490. t.Fatalf("failed to answer challenge: %v", err)
  491. }
  492. } else {
  493. responseRlp, _ := rlp.EncodeToBytes(&types.Header{Number: response.Number})
  494. if err := remote.ReplyBlockHeadersRLP(request.RequestId, []rlp.RawValue{responseRlp}); err != nil {
  495. t.Fatalf("failed to answer challenge: %v", err)
  496. }
  497. }
  498. }
  499. }
  500. // Wait until the test timeout passes to ensure proper cleanup
  501. time.Sleep(syncChallengeTimeout + 300*time.Millisecond)
  502. // Verify that the remote peer is maintained or dropped.
  503. if drop {
  504. <-handlerDone
  505. if peers := handler.handler.peers.len(); peers != 0 {
  506. t.Fatalf("peer count mismatch: have %d, want %d", peers, 0)
  507. }
  508. } else {
  509. if peers := handler.handler.peers.len(); peers != 1 {
  510. t.Fatalf("peer count mismatch: have %d, want %d", peers, 1)
  511. }
  512. }
  513. }
  514. // Tests that blocks are broadcast to a sqrt number of peers only.
  515. func TestBroadcastBlock1Peer(t *testing.T) { testBroadcastBlock(t, 1, 1) }
  516. func TestBroadcastBlock2Peers(t *testing.T) { testBroadcastBlock(t, 2, 1) }
  517. func TestBroadcastBlock3Peers(t *testing.T) { testBroadcastBlock(t, 3, 1) }
  518. func TestBroadcastBlock4Peers(t *testing.T) { testBroadcastBlock(t, 4, 2) }
  519. func TestBroadcastBlock5Peers(t *testing.T) { testBroadcastBlock(t, 5, 2) }
  520. func TestBroadcastBlock8Peers(t *testing.T) { testBroadcastBlock(t, 9, 3) }
  521. func TestBroadcastBlock12Peers(t *testing.T) { testBroadcastBlock(t, 12, 3) }
  522. func TestBroadcastBlock16Peers(t *testing.T) { testBroadcastBlock(t, 16, 4) }
  523. func TestBroadcastBloc26Peers(t *testing.T) { testBroadcastBlock(t, 26, 5) }
  524. func TestBroadcastBlock100Peers(t *testing.T) { testBroadcastBlock(t, 100, 10) }
  525. func testBroadcastBlock(t *testing.T, peers, bcasts int) {
  526. t.Parallel()
  527. // Create a source handler to broadcast blocks from and a number of sinks
  528. // to receive them.
  529. source := newTestHandlerWithBlocks(1)
  530. defer source.close()
  531. sinks := make([]*testEthHandler, peers)
  532. for i := 0; i < len(sinks); i++ {
  533. sinks[i] = new(testEthHandler)
  534. }
  535. // Interconnect all the sink handlers with the source handler
  536. var (
  537. genesis = source.chain.Genesis()
  538. td = source.chain.GetTd(genesis.Hash(), genesis.NumberU64())
  539. )
  540. for i, sink := range sinks {
  541. sink := sink // Closure for gorotuine below
  542. sourcePipe, sinkPipe := p2p.MsgPipe()
  543. defer sourcePipe.Close()
  544. defer sinkPipe.Close()
  545. sourcePeer := eth.NewPeer(eth.ETH66, p2p.NewPeerPipe(enode.ID{byte(i)}, "", nil, sourcePipe), sourcePipe, nil)
  546. sinkPeer := eth.NewPeer(eth.ETH66, p2p.NewPeerPipe(enode.ID{0}, "", nil, sinkPipe), sinkPipe, nil)
  547. defer sourcePeer.Close()
  548. defer sinkPeer.Close()
  549. go source.handler.runEthPeer(sourcePeer, func(peer *eth.Peer) error {
  550. return eth.Handle((*ethHandler)(source.handler), peer)
  551. })
  552. if err := sinkPeer.Handshake(1, td, genesis.Hash(), genesis.Hash(), forkid.NewIDWithChain(source.chain), forkid.NewFilter(source.chain)); err != nil {
  553. t.Fatalf("failed to run protocol handshake")
  554. }
  555. go eth.Handle(sink, sinkPeer)
  556. }
  557. // Subscribe to all the transaction pools
  558. blockChs := make([]chan *types.Block, len(sinks))
  559. for i := 0; i < len(sinks); i++ {
  560. blockChs[i] = make(chan *types.Block, 1)
  561. defer close(blockChs[i])
  562. sub := sinks[i].blockBroadcasts.Subscribe(blockChs[i])
  563. defer sub.Unsubscribe()
  564. }
  565. // Initiate a block propagation across the peers
  566. time.Sleep(100 * time.Millisecond)
  567. source.handler.BroadcastBlock(source.chain.CurrentBlock(), true)
  568. // Iterate through all the sinks and ensure the correct number got the block
  569. done := make(chan struct{}, peers)
  570. for _, ch := range blockChs {
  571. ch := ch
  572. go func() {
  573. <-ch
  574. done <- struct{}{}
  575. }()
  576. }
  577. var received int
  578. for {
  579. select {
  580. case <-done:
  581. received++
  582. case <-time.After(100 * time.Millisecond):
  583. if received != bcasts {
  584. t.Errorf("broadcast count mismatch: have %d, want %d", received, bcasts)
  585. }
  586. return
  587. }
  588. }
  589. }
  590. // Tests that a propagated malformed block (uncles or transactions don't match
  591. // with the hashes in the header) gets discarded and not broadcast forward.
  592. func TestBroadcastMalformedBlock66(t *testing.T) { testBroadcastMalformedBlock(t, eth.ETH66) }
  593. func testBroadcastMalformedBlock(t *testing.T, protocol uint) {
  594. t.Parallel()
  595. // Create a source handler to broadcast blocks from and a number of sinks
  596. // to receive them.
  597. source := newTestHandlerWithBlocks(1)
  598. defer source.close()
  599. // Create a source handler to send messages through and a sink peer to receive them
  600. p2pSrc, p2pSink := p2p.MsgPipe()
  601. defer p2pSrc.Close()
  602. defer p2pSink.Close()
  603. src := eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{1}, "", nil, p2pSrc), p2pSrc, source.txpool)
  604. sink := eth.NewPeer(protocol, p2p.NewPeerPipe(enode.ID{2}, "", nil, p2pSink), p2pSink, source.txpool)
  605. defer src.Close()
  606. defer sink.Close()
  607. go source.handler.runEthPeer(src, func(peer *eth.Peer) error {
  608. return eth.Handle((*ethHandler)(source.handler), peer)
  609. })
  610. // Run the handshake locally to avoid spinning up a sink handler
  611. var (
  612. genesis = source.chain.Genesis()
  613. td = source.chain.GetTd(genesis.Hash(), genesis.NumberU64())
  614. )
  615. if err := sink.Handshake(1, td, genesis.Hash(), genesis.Hash(), forkid.NewIDWithChain(source.chain), forkid.NewFilter(source.chain)); err != nil {
  616. t.Fatalf("failed to run protocol handshake")
  617. }
  618. // After the handshake completes, the source handler should stream the sink
  619. // the blocks, subscribe to inbound network events
  620. backend := new(testEthHandler)
  621. blocks := make(chan *types.Block, 1)
  622. sub := backend.blockBroadcasts.Subscribe(blocks)
  623. defer sub.Unsubscribe()
  624. go eth.Handle(backend, sink)
  625. // Create various combinations of malformed blocks
  626. head := source.chain.CurrentBlock()
  627. malformedUncles := head.Header()
  628. malformedUncles.UncleHash[0]++
  629. malformedTransactions := head.Header()
  630. malformedTransactions.TxHash[0]++
  631. malformedEverything := head.Header()
  632. malformedEverything.UncleHash[0]++
  633. malformedEverything.TxHash[0]++
  634. // Try to broadcast all malformations and ensure they all get discarded
  635. for _, header := range []*types.Header{malformedUncles, malformedTransactions, malformedEverything} {
  636. block := types.NewBlockWithHeader(header).WithBody(head.Transactions(), head.Uncles())
  637. if err := src.SendNewBlock(block, big.NewInt(131136)); err != nil {
  638. t.Fatalf("failed to broadcast block: %v", err)
  639. }
  640. select {
  641. case <-blocks:
  642. t.Fatalf("malformed block forwarded")
  643. case <-time.After(100 * time.Millisecond):
  644. }
  645. }
  646. }