handler_eth_test.go 29 KB

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