handler_eth_test.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  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 TestWaitDiffExtensionTimout(t *testing.T) {
  208. t.Parallel()
  209. // Create a message handler, configure it to accept transactions and watch them
  210. handler := newTestHandler()
  211. defer handler.close()
  212. // Create a source peer to send messages through and a sink handler to receive them
  213. _, p2pSink := p2p.MsgPipe()
  214. defer p2pSink.Close()
  215. protos := []p2p.Protocol{
  216. {
  217. Name: "diff",
  218. Version: 1,
  219. },
  220. }
  221. sink := eth.NewPeer(eth.ETH67, p2p.NewPeerWithProtocols(enode.ID{2}, protos, "", []p2p.Cap{
  222. {
  223. Name: "diff",
  224. Version: 1,
  225. },
  226. }), p2pSink, nil)
  227. defer sink.Close()
  228. err := handler.handler.runEthPeer(sink, func(peer *eth.Peer) error {
  229. return eth.Handle((*ethHandler)(handler.handler), peer)
  230. })
  231. if err == nil || err.Error() != "peer wait timeout" {
  232. t.Fatalf("error should be `peer wait timeout`")
  233. }
  234. }
  235. func TestWaitSnapExtensionTimout(t *testing.T) {
  236. t.Parallel()
  237. // Create a message handler, configure it to accept transactions and watch them
  238. handler := newTestHandler()
  239. defer handler.close()
  240. // Create a source peer to send messages through and a sink handler to receive them
  241. _, p2pSink := p2p.MsgPipe()
  242. defer p2pSink.Close()
  243. protos := []p2p.Protocol{
  244. {
  245. Name: "snap",
  246. Version: 1,
  247. },
  248. }
  249. sink := eth.NewPeer(eth.ETH67, p2p.NewPeerWithProtocols(enode.ID{2}, protos, "", []p2p.Cap{
  250. {
  251. Name: "snap",
  252. Version: 1,
  253. },
  254. }), p2pSink, nil)
  255. defer sink.Close()
  256. err := handler.handler.runEthPeer(sink, func(peer *eth.Peer) error {
  257. return eth.Handle((*ethHandler)(handler.handler), peer)
  258. })
  259. if err == nil || err.Error() != "peer wait timeout" {
  260. t.Fatalf("error should be `peer wait timeout`")
  261. }
  262. }
  263. func testRecvTransactions(t *testing.T, protocol uint) {
  264. t.Parallel()
  265. // Create a message handler, configure it to accept transactions and watch them
  266. handler := newTestHandler()
  267. defer handler.close()
  268. handler.handler.acceptTxs = 1 // mark synced to accept transactions
  269. txs := make(chan core.NewTxsEvent)
  270. sub := handler.txpool.SubscribeNewTxsEvent(txs)
  271. defer sub.Unsubscribe()
  272. // Create a source peer to send messages through and a sink handler 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(sink, 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 := src.Handshake(1, td, head.Hash(), genesis.Hash(), forkid.NewIDWithChain(handler.chain), forkid.NewFilter(handler.chain), nil); err != nil {
  290. t.Fatalf("failed to run protocol handshake")
  291. }
  292. // Send the transaction to the sink and verify that it's added to the tx pool
  293. tx := types.NewTransaction(0, common.Address{}, big.NewInt(0), 100000, big.NewInt(0), nil)
  294. tx, _ = types.SignTx(tx, types.HomesteadSigner{}, testKey)
  295. if err := src.SendTransactions([]*types.Transaction{tx}); err != nil {
  296. t.Fatalf("failed to send transaction: %v", err)
  297. }
  298. select {
  299. case event := <-txs:
  300. if len(event.Txs) != 1 {
  301. t.Errorf("wrong number of added transactions: got %d, want 1", len(event.Txs))
  302. } else if event.Txs[0].Hash() != tx.Hash() {
  303. t.Errorf("added wrong tx hash: got %v, want %v", event.Txs[0].Hash(), tx.Hash())
  304. }
  305. case <-time.After(2 * time.Second):
  306. t.Errorf("no NewTxsEvent received within 2 seconds")
  307. }
  308. }
  309. // This test checks that pending transactions are sent.
  310. func TestSendTransactions65(t *testing.T) { testSendTransactions(t, eth.ETH65) }
  311. func TestSendTransactions66(t *testing.T) { testSendTransactions(t, eth.ETH66) }
  312. func testSendTransactions(t *testing.T, protocol uint) {
  313. t.Parallel()
  314. // Create a message handler and fill the pool with big transactions
  315. handler := newTestHandler()
  316. defer handler.close()
  317. insert := make([]*types.Transaction, 100)
  318. for nonce := range insert {
  319. tx := types.NewTransaction(uint64(nonce), common.Address{}, big.NewInt(0), 100000, big.NewInt(0), make([]byte, txsyncPackSize/10))
  320. tx, _ = types.SignTx(tx, types.HomesteadSigner{}, testKey)
  321. insert[nonce] = tx
  322. }
  323. go handler.txpool.AddRemotes(insert) // Need goroutine to not block on feed
  324. time.Sleep(250 * time.Millisecond) // Wait until tx events get out of the system (can't use events, tx broadcaster races with peer join)
  325. // Create a source handler to send messages through and a sink peer to receive them
  326. p2pSrc, p2pSink := p2p.MsgPipe()
  327. defer p2pSrc.Close()
  328. defer p2pSink.Close()
  329. src := eth.NewPeer(protocol, p2p.NewPeer(enode.ID{1}, "", nil), p2pSrc, handler.txpool)
  330. sink := eth.NewPeer(protocol, p2p.NewPeer(enode.ID{2}, "", nil), p2pSink, handler.txpool)
  331. defer src.Close()
  332. defer sink.Close()
  333. go handler.handler.runEthPeer(src, func(peer *eth.Peer) error {
  334. return eth.Handle((*ethHandler)(handler.handler), peer)
  335. })
  336. // Run the handshake locally to avoid spinning up a source handler
  337. var (
  338. genesis = handler.chain.Genesis()
  339. head = handler.chain.CurrentBlock()
  340. td = handler.chain.GetTd(head.Hash(), head.NumberU64())
  341. )
  342. if err := sink.Handshake(1, td, head.Hash(), genesis.Hash(), forkid.NewIDWithChain(handler.chain), forkid.NewFilter(handler.chain), nil); err != nil {
  343. t.Fatalf("failed to run protocol handshake")
  344. }
  345. // After the handshake completes, the source handler should stream the sink
  346. // the transactions, subscribe to all inbound network events
  347. backend := new(testEthHandler)
  348. anns := make(chan []common.Hash)
  349. annSub := backend.txAnnounces.Subscribe(anns)
  350. defer annSub.Unsubscribe()
  351. bcasts := make(chan []*types.Transaction)
  352. bcastSub := backend.txBroadcasts.Subscribe(bcasts)
  353. defer bcastSub.Unsubscribe()
  354. go eth.Handle(backend, sink)
  355. // Make sure we get all the transactions on the correct channels
  356. seen := make(map[common.Hash]struct{})
  357. for len(seen) < len(insert) {
  358. switch protocol {
  359. case 65, 66:
  360. select {
  361. case hashes := <-anns:
  362. for _, hash := range hashes {
  363. if _, ok := seen[hash]; ok {
  364. t.Errorf("duplicate transaction announced: %x", hash)
  365. }
  366. seen[hash] = struct{}{}
  367. }
  368. case <-bcasts:
  369. t.Errorf("initial tx broadcast received on post eth/65")
  370. }
  371. default:
  372. panic("unsupported protocol, please extend test")
  373. }
  374. }
  375. for _, tx := range insert {
  376. if _, ok := seen[tx.Hash()]; !ok {
  377. t.Errorf("missing transaction: %x", tx.Hash())
  378. }
  379. }
  380. }
  381. // Tests that transactions get propagated to all attached peers, either via direct
  382. // broadcasts or via announcements/retrievals.
  383. func TestTransactionPropagation65(t *testing.T) { testTransactionPropagation(t, eth.ETH65) }
  384. func TestTransactionPropagation66(t *testing.T) { testTransactionPropagation(t, eth.ETH66) }
  385. func testTransactionPropagation(t *testing.T, protocol uint) {
  386. t.Parallel()
  387. // Create a source handler to send transactions from and a number of sinks
  388. // to receive them. We need multiple sinks since a one-to-one peering would
  389. // broadcast all transactions without announcement.
  390. source := newTestHandler()
  391. defer source.close()
  392. sinks := make([]*testHandler, 10)
  393. for i := 0; i < len(sinks); i++ {
  394. sinks[i] = newTestHandler()
  395. defer sinks[i].close()
  396. sinks[i].handler.acceptTxs = 1 // mark synced to accept transactions
  397. }
  398. // Interconnect all the sink handlers with the source handler
  399. for i, sink := range sinks {
  400. sink := sink // Closure for gorotuine below
  401. sourcePipe, sinkPipe := p2p.MsgPipe()
  402. defer sourcePipe.Close()
  403. defer sinkPipe.Close()
  404. sourcePeer := eth.NewPeer(protocol, p2p.NewPeer(enode.ID{byte(i)}, "", nil), sourcePipe, source.txpool)
  405. sinkPeer := eth.NewPeer(protocol, p2p.NewPeer(enode.ID{0}, "", nil), sinkPipe, sink.txpool)
  406. defer sourcePeer.Close()
  407. defer sinkPeer.Close()
  408. go source.handler.runEthPeer(sourcePeer, func(peer *eth.Peer) error {
  409. return eth.Handle((*ethHandler)(source.handler), peer)
  410. })
  411. go sink.handler.runEthPeer(sinkPeer, func(peer *eth.Peer) error {
  412. return eth.Handle((*ethHandler)(sink.handler), peer)
  413. })
  414. }
  415. // Subscribe to all the transaction pools
  416. txChs := make([]chan core.NewTxsEvent, len(sinks))
  417. for i := 0; i < len(sinks); i++ {
  418. txChs[i] = make(chan core.NewTxsEvent, 1024)
  419. sub := sinks[i].txpool.SubscribeNewTxsEvent(txChs[i])
  420. defer sub.Unsubscribe()
  421. }
  422. // Fill the source pool with transactions and wait for them at the sinks
  423. txs := make([]*types.Transaction, 1024)
  424. for nonce := range txs {
  425. tx := types.NewTransaction(uint64(nonce), common.Address{}, big.NewInt(0), 100000, big.NewInt(0), nil)
  426. tx, _ = types.SignTx(tx, types.HomesteadSigner{}, testKey)
  427. txs[nonce] = tx
  428. }
  429. source.txpool.AddRemotes(txs)
  430. // Iterate through all the sinks and ensure they all got the transactions
  431. for i := range sinks {
  432. for arrived := 0; arrived < len(txs); {
  433. select {
  434. case event := <-txChs[i]:
  435. arrived += len(event.Txs)
  436. case <-time.NewTimer(time.Second).C:
  437. t.Errorf("sink %d: transaction propagation timed out: have %d, want %d", i, arrived, len(txs))
  438. }
  439. }
  440. }
  441. }
  442. // Tests that local pending transactions get propagated to peers.
  443. func TestTransactionPendingReannounce(t *testing.T) {
  444. t.Parallel()
  445. // Create a source handler to announce transactions from and a sink handler
  446. // to receive them.
  447. source := newTestHandler()
  448. defer source.close()
  449. sink := newTestHandler()
  450. defer sink.close()
  451. sink.handler.acceptTxs = 1 // mark synced to accept transactions
  452. sourcePipe, sinkPipe := p2p.MsgPipe()
  453. defer sourcePipe.Close()
  454. defer sinkPipe.Close()
  455. sourcePeer := eth.NewPeer(eth.ETH65, p2p.NewPeer(enode.ID{0}, "", nil), sourcePipe, source.txpool)
  456. sinkPeer := eth.NewPeer(eth.ETH65, p2p.NewPeer(enode.ID{0}, "", nil), sinkPipe, sink.txpool)
  457. defer sourcePeer.Close()
  458. defer sinkPeer.Close()
  459. go source.handler.runEthPeer(sourcePeer, func(peer *eth.Peer) error {
  460. return eth.Handle((*ethHandler)(source.handler), peer)
  461. })
  462. go sink.handler.runEthPeer(sinkPeer, func(peer *eth.Peer) error {
  463. return eth.Handle((*ethHandler)(sink.handler), peer)
  464. })
  465. // Subscribe transaction pools
  466. txCh := make(chan core.NewTxsEvent, 1024)
  467. sub := sink.txpool.SubscribeNewTxsEvent(txCh)
  468. defer sub.Unsubscribe()
  469. txs := make([]*types.Transaction, 64)
  470. for nonce := range txs {
  471. tx := types.NewTransaction(uint64(nonce), common.Address{}, big.NewInt(0), 100000, big.NewInt(0), nil)
  472. tx, _ = types.SignTx(tx, types.HomesteadSigner{}, testKey)
  473. txs[nonce] = tx
  474. }
  475. source.txpool.ReannouceTransactions(txs)
  476. for arrived := 0; arrived < len(txs); {
  477. select {
  478. case event := <-txCh:
  479. arrived += len(event.Txs)
  480. case <-time.NewTimer(time.Second).C:
  481. t.Errorf("sink: transaction propagation timed out: have %d, want %d", arrived, len(txs))
  482. }
  483. }
  484. }
  485. // Tests that post eth protocol handshake, clients perform a mutual checkpoint
  486. // challenge to validate each other's chains. Hash mismatches, or missing ones
  487. // during a fast sync should lead to the peer getting dropped.
  488. func TestCheckpointChallenge(t *testing.T) {
  489. tests := []struct {
  490. syncmode downloader.SyncMode
  491. checkpoint bool
  492. timeout bool
  493. empty bool
  494. match bool
  495. drop bool
  496. }{
  497. // If checkpointing is not enabled locally, don't challenge and don't drop
  498. {downloader.FullSync, false, false, false, false, false},
  499. {downloader.FastSync, false, false, false, false, false},
  500. // If checkpointing is enabled locally and remote response is empty, only drop during fast sync
  501. {downloader.FullSync, true, false, true, false, false},
  502. {downloader.FastSync, true, false, true, false, true}, // Special case, fast sync, unsynced peer
  503. // If checkpointing is enabled locally and remote response mismatches, always drop
  504. {downloader.FullSync, true, false, false, false, true},
  505. {downloader.FastSync, true, false, false, false, true},
  506. // If checkpointing is enabled locally and remote response matches, never drop
  507. {downloader.FullSync, true, false, false, true, false},
  508. {downloader.FastSync, true, false, false, true, false},
  509. // If checkpointing is enabled locally and remote times out, always drop
  510. {downloader.FullSync, true, true, false, true, true},
  511. {downloader.FastSync, true, true, false, true, true},
  512. }
  513. for _, tt := range tests {
  514. 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) {
  515. testCheckpointChallenge(t, tt.syncmode, tt.checkpoint, tt.timeout, tt.empty, tt.match, tt.drop)
  516. })
  517. }
  518. }
  519. func testCheckpointChallenge(t *testing.T, syncmode downloader.SyncMode, checkpoint bool, timeout bool, empty bool, match bool, drop bool) {
  520. // Reduce the checkpoint handshake challenge timeout
  521. defer func(old time.Duration) { syncChallengeTimeout = old }(syncChallengeTimeout)
  522. syncChallengeTimeout = 250 * time.Millisecond
  523. // Create a test handler and inject a CHT into it. The injection is a bit
  524. // ugly, but it beats creating everything manually just to avoid reaching
  525. // into the internals a bit.
  526. handler := newTestHandler()
  527. defer handler.close()
  528. if syncmode == downloader.FastSync {
  529. atomic.StoreUint32(&handler.handler.fastSync, 1)
  530. } else {
  531. atomic.StoreUint32(&handler.handler.fastSync, 0)
  532. }
  533. var response *types.Header
  534. if checkpoint {
  535. number := (uint64(rand.Intn(500))+1)*params.CHTFrequency - 1
  536. response = &types.Header{Number: big.NewInt(int64(number)), Extra: []byte("valid")}
  537. handler.handler.checkpointNumber = number
  538. handler.handler.checkpointHash = response.Hash()
  539. }
  540. // Create a challenger peer and a challenged one
  541. p2pLocal, p2pRemote := p2p.MsgPipe()
  542. defer p2pLocal.Close()
  543. defer p2pRemote.Close()
  544. local := eth.NewPeer(eth.ETH65, p2p.NewPeer(enode.ID{1}, "", nil), p2pLocal, handler.txpool)
  545. remote := eth.NewPeer(eth.ETH65, p2p.NewPeer(enode.ID{2}, "", nil), p2pRemote, handler.txpool)
  546. defer local.Close()
  547. defer remote.Close()
  548. go handler.handler.runEthPeer(local, func(peer *eth.Peer) error {
  549. return eth.Handle((*ethHandler)(handler.handler), peer)
  550. })
  551. // Run the handshake locally to avoid spinning up a remote handler
  552. var (
  553. genesis = handler.chain.Genesis()
  554. head = handler.chain.CurrentBlock()
  555. td = handler.chain.GetTd(head.Hash(), head.NumberU64())
  556. )
  557. if err := remote.Handshake(1, td, head.Hash(), genesis.Hash(), forkid.NewIDWithChain(handler.chain), forkid.NewFilter(handler.chain), nil); err != nil {
  558. t.Fatalf("failed to run protocol handshake")
  559. }
  560. // Connect a new peer and check that we receive the checkpoint challenge
  561. if checkpoint {
  562. if err := remote.ExpectRequestHeadersByNumber(response.Number.Uint64(), 1, 0, false); err != nil {
  563. t.Fatalf("challenge mismatch: %v", err)
  564. }
  565. // Create a block to reply to the challenge if no timeout is simulated
  566. if !timeout {
  567. if empty {
  568. if err := remote.SendBlockHeaders([]*types.Header{}); err != nil {
  569. t.Fatalf("failed to answer challenge: %v", err)
  570. }
  571. } else if match {
  572. if err := remote.SendBlockHeaders([]*types.Header{response}); err != nil {
  573. t.Fatalf("failed to answer challenge: %v", err)
  574. }
  575. } else {
  576. if err := remote.SendBlockHeaders([]*types.Header{{Number: response.Number}}); err != nil {
  577. t.Fatalf("failed to answer challenge: %v", err)
  578. }
  579. }
  580. }
  581. }
  582. // Wait until the test timeout passes to ensure proper cleanup
  583. time.Sleep(syncChallengeTimeout + 300*time.Millisecond)
  584. // Verify that the remote peer is maintained or dropped
  585. if drop {
  586. if peers := handler.handler.peers.len(); peers != 0 {
  587. t.Fatalf("peer count mismatch: have %d, want %d", peers, 0)
  588. }
  589. } else {
  590. if peers := handler.handler.peers.len(); peers != 1 {
  591. t.Fatalf("peer count mismatch: have %d, want %d", peers, 1)
  592. }
  593. }
  594. }
  595. // Tests that blocks are broadcast to a sqrt number of peers only.
  596. func TestBroadcastBlock1Peer(t *testing.T) { testBroadcastBlock(t, 1, 1) }
  597. func TestBroadcastBlock2Peers(t *testing.T) { testBroadcastBlock(t, 2, 1) }
  598. func TestBroadcastBlock3Peers(t *testing.T) { testBroadcastBlock(t, 3, 1) }
  599. func TestBroadcastBlock4Peers(t *testing.T) { testBroadcastBlock(t, 4, 2) }
  600. func TestBroadcastBlock5Peers(t *testing.T) { testBroadcastBlock(t, 5, 2) }
  601. func TestBroadcastBlock8Peers(t *testing.T) { testBroadcastBlock(t, 9, 3) }
  602. func TestBroadcastBlock12Peers(t *testing.T) { testBroadcastBlock(t, 12, 3) }
  603. func TestBroadcastBlock16Peers(t *testing.T) { testBroadcastBlock(t, 16, 4) }
  604. func TestBroadcastBloc26Peers(t *testing.T) { testBroadcastBlock(t, 26, 5) }
  605. func TestBroadcastBlock100Peers(t *testing.T) { testBroadcastBlock(t, 100, 10) }
  606. func testBroadcastBlock(t *testing.T, peers, bcasts int) {
  607. t.Parallel()
  608. // Create a source handler to broadcast blocks from and a number of sinks
  609. // to receive them.
  610. source := newTestHandlerWithBlocks(1)
  611. defer source.close()
  612. sinks := make([]*testEthHandler, peers)
  613. for i := 0; i < len(sinks); i++ {
  614. sinks[i] = new(testEthHandler)
  615. }
  616. // Interconnect all the sink handlers with the source handler
  617. var (
  618. genesis = source.chain.Genesis()
  619. td = source.chain.GetTd(genesis.Hash(), genesis.NumberU64())
  620. )
  621. for i, sink := range sinks {
  622. sink := sink // Closure for gorotuine below
  623. sourcePipe, sinkPipe := p2p.MsgPipe()
  624. defer sourcePipe.Close()
  625. defer sinkPipe.Close()
  626. sourcePeer := eth.NewPeer(eth.ETH65, p2p.NewPeer(enode.ID{byte(i)}, "", nil), sourcePipe, nil)
  627. sinkPeer := eth.NewPeer(eth.ETH65, p2p.NewPeer(enode.ID{0}, "", nil), sinkPipe, nil)
  628. defer sourcePeer.Close()
  629. defer sinkPeer.Close()
  630. go source.handler.runEthPeer(sourcePeer, func(peer *eth.Peer) error {
  631. return eth.Handle((*ethHandler)(source.handler), peer)
  632. })
  633. if err := sinkPeer.Handshake(1, td, genesis.Hash(), genesis.Hash(), forkid.NewIDWithChain(source.chain), forkid.NewFilter(source.chain), nil); err != nil {
  634. t.Fatalf("failed to run protocol handshake")
  635. }
  636. go eth.Handle(sink, sinkPeer)
  637. }
  638. // Subscribe to all the transaction pools
  639. blockChs := make([]chan *types.Block, len(sinks))
  640. for i := 0; i < len(sinks); i++ {
  641. blockChs[i] = make(chan *types.Block, 1)
  642. defer close(blockChs[i])
  643. sub := sinks[i].blockBroadcasts.Subscribe(blockChs[i])
  644. defer sub.Unsubscribe()
  645. }
  646. // Initiate a block propagation across the peers
  647. time.Sleep(100 * time.Millisecond)
  648. source.handler.BroadcastBlock(source.chain.CurrentBlock(), true)
  649. // Iterate through all the sinks and ensure the correct number got the block
  650. done := make(chan struct{}, peers)
  651. for _, ch := range blockChs {
  652. ch := ch
  653. go func() {
  654. <-ch
  655. done <- struct{}{}
  656. }()
  657. }
  658. var received int
  659. for {
  660. select {
  661. case <-done:
  662. received++
  663. case <-time.After(100 * time.Millisecond):
  664. if received != bcasts {
  665. t.Errorf("broadcast count mismatch: have %d, want %d", received, bcasts)
  666. }
  667. return
  668. }
  669. }
  670. }
  671. // Tests that a propagated malformed block (uncles or transactions don't match
  672. // with the hashes in the header) gets discarded and not broadcast forward.
  673. func TestBroadcastMalformedBlock65(t *testing.T) { testBroadcastMalformedBlock(t, eth.ETH65) }
  674. func TestBroadcastMalformedBlock66(t *testing.T) { testBroadcastMalformedBlock(t, eth.ETH66) }
  675. func testBroadcastMalformedBlock(t *testing.T, protocol uint) {
  676. t.Parallel()
  677. // Create a source handler to broadcast blocks from and a number of sinks
  678. // to receive them.
  679. source := newTestHandlerWithBlocks(1)
  680. defer source.close()
  681. // Create a source handler to send messages through and a sink peer to receive them
  682. p2pSrc, p2pSink := p2p.MsgPipe()
  683. defer p2pSrc.Close()
  684. defer p2pSink.Close()
  685. src := eth.NewPeer(protocol, p2p.NewPeer(enode.ID{1}, "", nil), p2pSrc, source.txpool)
  686. sink := eth.NewPeer(protocol, p2p.NewPeer(enode.ID{2}, "", nil), p2pSink, source.txpool)
  687. defer src.Close()
  688. defer sink.Close()
  689. go source.handler.runEthPeer(src, func(peer *eth.Peer) error {
  690. return eth.Handle((*ethHandler)(source.handler), peer)
  691. })
  692. // Run the handshake locally to avoid spinning up a sink handler
  693. var (
  694. genesis = source.chain.Genesis()
  695. td = source.chain.GetTd(genesis.Hash(), genesis.NumberU64())
  696. )
  697. if err := sink.Handshake(1, td, genesis.Hash(), genesis.Hash(), forkid.NewIDWithChain(source.chain), forkid.NewFilter(source.chain), nil); err != nil {
  698. t.Fatalf("failed to run protocol handshake")
  699. }
  700. // After the handshake completes, the source handler should stream the sink
  701. // the blocks, subscribe to inbound network events
  702. backend := new(testEthHandler)
  703. blocks := make(chan *types.Block, 1)
  704. sub := backend.blockBroadcasts.Subscribe(blocks)
  705. defer sub.Unsubscribe()
  706. go eth.Handle(backend, sink)
  707. // Create various combinations of malformed blocks
  708. head := source.chain.CurrentBlock()
  709. malformedUncles := head.Header()
  710. malformedUncles.UncleHash[0]++
  711. malformedTransactions := head.Header()
  712. malformedTransactions.TxHash[0]++
  713. malformedEverything := head.Header()
  714. malformedEverything.UncleHash[0]++
  715. malformedEverything.TxHash[0]++
  716. // Try to broadcast all malformations and ensure they all get discarded
  717. for _, header := range []*types.Header{malformedUncles, malformedTransactions, malformedEverything} {
  718. block := types.NewBlockWithHeader(header).WithBody(head.Transactions(), head.Uncles())
  719. if err := src.SendNewBlock(block, big.NewInt(131136)); err != nil {
  720. t.Fatalf("failed to broadcast block: %v", err)
  721. }
  722. select {
  723. case <-blocks:
  724. t.Fatalf("malformed block forwarded")
  725. case <-time.After(100 * time.Millisecond):
  726. }
  727. }
  728. }