handler_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. // Copyright 2015 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"
  20. "math/big"
  21. "math/rand"
  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/rawdb"
  28. "github.com/ethereum/go-ethereum/core/state"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/core/vm"
  31. "github.com/ethereum/go-ethereum/crypto"
  32. "github.com/ethereum/go-ethereum/eth/downloader"
  33. "github.com/ethereum/go-ethereum/event"
  34. "github.com/ethereum/go-ethereum/p2p"
  35. "github.com/ethereum/go-ethereum/params"
  36. )
  37. // Tests that block headers can be retrieved from a remote chain based on user queries.
  38. func TestGetBlockHeaders63(t *testing.T) { testGetBlockHeaders(t, 63) }
  39. func TestGetBlockHeaders64(t *testing.T) { testGetBlockHeaders(t, 64) }
  40. func testGetBlockHeaders(t *testing.T, protocol int) {
  41. pm, _ := newTestProtocolManagerMust(t, downloader.FullSync, downloader.MaxHashFetch+15, nil, nil)
  42. peer, _ := newTestPeer("peer", protocol, pm, true)
  43. defer peer.close()
  44. // Create a "random" unknown hash for testing
  45. var unknown common.Hash
  46. for i := range unknown {
  47. unknown[i] = byte(i)
  48. }
  49. // Create a batch of tests for various scenarios
  50. limit := uint64(downloader.MaxHeaderFetch)
  51. tests := []struct {
  52. query *getBlockHeadersData // The query to execute for header retrieval
  53. expect []common.Hash // The hashes of the block whose headers are expected
  54. }{
  55. // A single random block should be retrievable by hash and number too
  56. {
  57. &getBlockHeadersData{Origin: hashOrNumber{Hash: pm.blockchain.GetBlockByNumber(limit / 2).Hash()}, Amount: 1},
  58. []common.Hash{pm.blockchain.GetBlockByNumber(limit / 2).Hash()},
  59. }, {
  60. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 1},
  61. []common.Hash{pm.blockchain.GetBlockByNumber(limit / 2).Hash()},
  62. },
  63. // Multiple headers should be retrievable in both directions
  64. {
  65. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 3},
  66. []common.Hash{
  67. pm.blockchain.GetBlockByNumber(limit / 2).Hash(),
  68. pm.blockchain.GetBlockByNumber(limit/2 + 1).Hash(),
  69. pm.blockchain.GetBlockByNumber(limit/2 + 2).Hash(),
  70. },
  71. }, {
  72. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 3, Reverse: true},
  73. []common.Hash{
  74. pm.blockchain.GetBlockByNumber(limit / 2).Hash(),
  75. pm.blockchain.GetBlockByNumber(limit/2 - 1).Hash(),
  76. pm.blockchain.GetBlockByNumber(limit/2 - 2).Hash(),
  77. },
  78. },
  79. // Multiple headers with skip lists should be retrievable
  80. {
  81. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Skip: 3, Amount: 3},
  82. []common.Hash{
  83. pm.blockchain.GetBlockByNumber(limit / 2).Hash(),
  84. pm.blockchain.GetBlockByNumber(limit/2 + 4).Hash(),
  85. pm.blockchain.GetBlockByNumber(limit/2 + 8).Hash(),
  86. },
  87. }, {
  88. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Skip: 3, Amount: 3, Reverse: true},
  89. []common.Hash{
  90. pm.blockchain.GetBlockByNumber(limit / 2).Hash(),
  91. pm.blockchain.GetBlockByNumber(limit/2 - 4).Hash(),
  92. pm.blockchain.GetBlockByNumber(limit/2 - 8).Hash(),
  93. },
  94. },
  95. // The chain endpoints should be retrievable
  96. {
  97. &getBlockHeadersData{Origin: hashOrNumber{Number: 0}, Amount: 1},
  98. []common.Hash{pm.blockchain.GetBlockByNumber(0).Hash()},
  99. }, {
  100. &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64()}, Amount: 1},
  101. []common.Hash{pm.blockchain.CurrentBlock().Hash()},
  102. },
  103. // Ensure protocol limits are honored
  104. {
  105. &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64() - 1}, Amount: limit + 10, Reverse: true},
  106. pm.blockchain.GetBlockHashesFromHash(pm.blockchain.CurrentBlock().Hash(), limit),
  107. },
  108. // Check that requesting more than available is handled gracefully
  109. {
  110. &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64() - 4}, Skip: 3, Amount: 3},
  111. []common.Hash{
  112. pm.blockchain.GetBlockByNumber(pm.blockchain.CurrentBlock().NumberU64() - 4).Hash(),
  113. pm.blockchain.GetBlockByNumber(pm.blockchain.CurrentBlock().NumberU64()).Hash(),
  114. },
  115. }, {
  116. &getBlockHeadersData{Origin: hashOrNumber{Number: 4}, Skip: 3, Amount: 3, Reverse: true},
  117. []common.Hash{
  118. pm.blockchain.GetBlockByNumber(4).Hash(),
  119. pm.blockchain.GetBlockByNumber(0).Hash(),
  120. },
  121. },
  122. // Check that requesting more than available is handled gracefully, even if mid skip
  123. {
  124. &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64() - 4}, Skip: 2, Amount: 3},
  125. []common.Hash{
  126. pm.blockchain.GetBlockByNumber(pm.blockchain.CurrentBlock().NumberU64() - 4).Hash(),
  127. pm.blockchain.GetBlockByNumber(pm.blockchain.CurrentBlock().NumberU64() - 1).Hash(),
  128. },
  129. }, {
  130. &getBlockHeadersData{Origin: hashOrNumber{Number: 4}, Skip: 2, Amount: 3, Reverse: true},
  131. []common.Hash{
  132. pm.blockchain.GetBlockByNumber(4).Hash(),
  133. pm.blockchain.GetBlockByNumber(1).Hash(),
  134. },
  135. },
  136. // Check a corner case where requesting more can iterate past the endpoints
  137. {
  138. &getBlockHeadersData{Origin: hashOrNumber{Number: 2}, Amount: 5, Reverse: true},
  139. []common.Hash{
  140. pm.blockchain.GetBlockByNumber(2).Hash(),
  141. pm.blockchain.GetBlockByNumber(1).Hash(),
  142. pm.blockchain.GetBlockByNumber(0).Hash(),
  143. },
  144. },
  145. // Check a corner case where skipping overflow loops back into the chain start
  146. {
  147. &getBlockHeadersData{Origin: hashOrNumber{Hash: pm.blockchain.GetBlockByNumber(3).Hash()}, Amount: 2, Reverse: false, Skip: math.MaxUint64 - 1},
  148. []common.Hash{
  149. pm.blockchain.GetBlockByNumber(3).Hash(),
  150. },
  151. },
  152. // Check a corner case where skipping overflow loops back to the same header
  153. {
  154. &getBlockHeadersData{Origin: hashOrNumber{Hash: pm.blockchain.GetBlockByNumber(1).Hash()}, Amount: 2, Reverse: false, Skip: math.MaxUint64},
  155. []common.Hash{
  156. pm.blockchain.GetBlockByNumber(1).Hash(),
  157. },
  158. },
  159. // Check that non existing headers aren't returned
  160. {
  161. &getBlockHeadersData{Origin: hashOrNumber{Hash: unknown}, Amount: 1},
  162. []common.Hash{},
  163. }, {
  164. &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64() + 1}, Amount: 1},
  165. []common.Hash{},
  166. },
  167. }
  168. // Run each of the tests and verify the results against the chain
  169. for i, tt := range tests {
  170. // Collect the headers to expect in the response
  171. headers := []*types.Header{}
  172. for _, hash := range tt.expect {
  173. headers = append(headers, pm.blockchain.GetBlockByHash(hash).Header())
  174. }
  175. // Send the hash request and verify the response
  176. p2p.Send(peer.app, 0x03, tt.query)
  177. if err := p2p.ExpectMsg(peer.app, 0x04, headers); err != nil {
  178. t.Errorf("test %d: headers mismatch: %v", i, err)
  179. }
  180. // If the test used number origins, repeat with hashes as the too
  181. if tt.query.Origin.Hash == (common.Hash{}) {
  182. if origin := pm.blockchain.GetBlockByNumber(tt.query.Origin.Number); origin != nil {
  183. tt.query.Origin.Hash, tt.query.Origin.Number = origin.Hash(), 0
  184. p2p.Send(peer.app, 0x03, tt.query)
  185. if err := p2p.ExpectMsg(peer.app, 0x04, headers); err != nil {
  186. t.Errorf("test %d: headers mismatch: %v", i, err)
  187. }
  188. }
  189. }
  190. }
  191. }
  192. // Tests that block contents can be retrieved from a remote chain based on their hashes.
  193. func TestGetBlockBodies63(t *testing.T) { testGetBlockBodies(t, 63) }
  194. func TestGetBlockBodies64(t *testing.T) { testGetBlockBodies(t, 64) }
  195. func testGetBlockBodies(t *testing.T, protocol int) {
  196. pm, _ := newTestProtocolManagerMust(t, downloader.FullSync, downloader.MaxBlockFetch+15, nil, nil)
  197. peer, _ := newTestPeer("peer", protocol, pm, true)
  198. defer peer.close()
  199. // Create a batch of tests for various scenarios
  200. limit := downloader.MaxBlockFetch
  201. tests := []struct {
  202. random int // Number of blocks to fetch randomly from the chain
  203. explicit []common.Hash // Explicitly requested blocks
  204. available []bool // Availability of explicitly requested blocks
  205. expected int // Total number of existing blocks to expect
  206. }{
  207. {1, nil, nil, 1}, // A single random block should be retrievable
  208. {10, nil, nil, 10}, // Multiple random blocks should be retrievable
  209. {limit, nil, nil, limit}, // The maximum possible blocks should be retrievable
  210. {limit + 1, nil, nil, limit}, // No more than the possible block count should be returned
  211. {0, []common.Hash{pm.blockchain.Genesis().Hash()}, []bool{true}, 1}, // The genesis block should be retrievable
  212. {0, []common.Hash{pm.blockchain.CurrentBlock().Hash()}, []bool{true}, 1}, // The chains head block should be retrievable
  213. {0, []common.Hash{{}}, []bool{false}, 0}, // A non existent block should not be returned
  214. // Existing and non-existing blocks interleaved should not cause problems
  215. {0, []common.Hash{
  216. {},
  217. pm.blockchain.GetBlockByNumber(1).Hash(),
  218. {},
  219. pm.blockchain.GetBlockByNumber(10).Hash(),
  220. {},
  221. pm.blockchain.GetBlockByNumber(100).Hash(),
  222. {},
  223. }, []bool{false, true, false, true, false, true, false}, 3},
  224. }
  225. // Run each of the tests and verify the results against the chain
  226. for i, tt := range tests {
  227. // Collect the hashes to request, and the response to expect
  228. hashes, seen := []common.Hash{}, make(map[int64]bool)
  229. bodies := []*blockBody{}
  230. for j := 0; j < tt.random; j++ {
  231. for {
  232. num := rand.Int63n(int64(pm.blockchain.CurrentBlock().NumberU64()))
  233. if !seen[num] {
  234. seen[num] = true
  235. block := pm.blockchain.GetBlockByNumber(uint64(num))
  236. hashes = append(hashes, block.Hash())
  237. if len(bodies) < tt.expected {
  238. bodies = append(bodies, &blockBody{Transactions: block.Transactions(), Uncles: block.Uncles()})
  239. }
  240. break
  241. }
  242. }
  243. }
  244. for j, hash := range tt.explicit {
  245. hashes = append(hashes, hash)
  246. if tt.available[j] && len(bodies) < tt.expected {
  247. block := pm.blockchain.GetBlockByHash(hash)
  248. bodies = append(bodies, &blockBody{Transactions: block.Transactions(), Uncles: block.Uncles()})
  249. }
  250. }
  251. // Send the hash request and verify the response
  252. p2p.Send(peer.app, 0x05, hashes)
  253. if err := p2p.ExpectMsg(peer.app, 0x06, bodies); err != nil {
  254. t.Errorf("test %d: bodies mismatch: %v", i, err)
  255. }
  256. }
  257. }
  258. // Tests that the node state database can be retrieved based on hashes.
  259. func TestGetNodeData63(t *testing.T) { testGetNodeData(t, 63) }
  260. func TestGetNodeData64(t *testing.T) { testGetNodeData(t, 64) }
  261. func testGetNodeData(t *testing.T, protocol int) {
  262. // Define three accounts to simulate transactions with
  263. acc1Key, _ := crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
  264. acc2Key, _ := crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
  265. acc1Addr := crypto.PubkeyToAddress(acc1Key.PublicKey)
  266. acc2Addr := crypto.PubkeyToAddress(acc2Key.PublicKey)
  267. signer := types.HomesteadSigner{}
  268. // Create a chain generator with some simple transactions (blatantly stolen from @fjl/chain_markets_test)
  269. generator := func(i int, block *core.BlockGen) {
  270. switch i {
  271. case 0:
  272. // In block 1, the test bank sends account #1 some ether.
  273. tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBank), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, testBankKey)
  274. block.AddTx(tx)
  275. case 1:
  276. // In block 2, the test bank sends some more ether to account #1.
  277. // acc1Addr passes it on to account #2.
  278. tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBank), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, testBankKey)
  279. tx2, _ := types.SignTx(types.NewTransaction(block.TxNonce(acc1Addr), acc2Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, acc1Key)
  280. block.AddTx(tx1)
  281. block.AddTx(tx2)
  282. case 2:
  283. // Block 3 is empty but was mined by account #2.
  284. block.SetCoinbase(acc2Addr)
  285. block.SetExtra([]byte("yeehaw"))
  286. case 3:
  287. // Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
  288. b2 := block.PrevBlock(1).Header()
  289. b2.Extra = []byte("foo")
  290. block.AddUncle(b2)
  291. b3 := block.PrevBlock(2).Header()
  292. b3.Extra = []byte("foo")
  293. block.AddUncle(b3)
  294. }
  295. }
  296. // Assemble the test environment
  297. pm, db := newTestProtocolManagerMust(t, downloader.FullSync, 4, generator, nil)
  298. peer, _ := newTestPeer("peer", protocol, pm, true)
  299. defer peer.close()
  300. // Fetch for now the entire chain db
  301. hashes := []common.Hash{}
  302. it := db.NewIterator()
  303. for it.Next() {
  304. if key := it.Key(); len(key) == common.HashLength {
  305. hashes = append(hashes, common.BytesToHash(key))
  306. }
  307. }
  308. it.Release()
  309. p2p.Send(peer.app, 0x0d, hashes)
  310. msg, err := peer.app.ReadMsg()
  311. if err != nil {
  312. t.Fatalf("failed to read node data response: %v", err)
  313. }
  314. if msg.Code != 0x0e {
  315. t.Fatalf("response packet code mismatch: have %x, want %x", msg.Code, 0x0c)
  316. }
  317. var data [][]byte
  318. if err := msg.Decode(&data); err != nil {
  319. t.Fatalf("failed to decode response node data: %v", err)
  320. }
  321. // Verify that all hashes correspond to the requested data, and reconstruct a state tree
  322. for i, want := range hashes {
  323. if hash := crypto.Keccak256Hash(data[i]); hash != want {
  324. t.Errorf("data hash mismatch: have %x, want %x", hash, want)
  325. }
  326. }
  327. statedb := rawdb.NewMemoryDatabase()
  328. for i := 0; i < len(data); i++ {
  329. statedb.Put(hashes[i].Bytes(), data[i])
  330. }
  331. accounts := []common.Address{testBank, acc1Addr, acc2Addr}
  332. for i := uint64(0); i <= pm.blockchain.CurrentBlock().NumberU64(); i++ {
  333. trie, _ := state.New(pm.blockchain.GetBlockByNumber(i).Root(), state.NewDatabase(statedb))
  334. for j, acc := range accounts {
  335. state, _ := pm.blockchain.State()
  336. bw := state.GetBalance(acc)
  337. bh := trie.GetBalance(acc)
  338. if (bw != nil && bh == nil) || (bw == nil && bh != nil) {
  339. t.Errorf("test %d, account %d: balance mismatch: have %v, want %v", i, j, bh, bw)
  340. }
  341. if bw != nil && bh != nil && bw.Cmp(bw) != 0 {
  342. t.Errorf("test %d, account %d: balance mismatch: have %v, want %v", i, j, bh, bw)
  343. }
  344. }
  345. }
  346. }
  347. // Tests that the transaction receipts can be retrieved based on hashes.
  348. func TestGetReceipt63(t *testing.T) { testGetReceipt(t, 63) }
  349. func TestGetReceipt64(t *testing.T) { testGetReceipt(t, 64) }
  350. func testGetReceipt(t *testing.T, protocol int) {
  351. // Define three accounts to simulate transactions with
  352. acc1Key, _ := crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
  353. acc2Key, _ := crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
  354. acc1Addr := crypto.PubkeyToAddress(acc1Key.PublicKey)
  355. acc2Addr := crypto.PubkeyToAddress(acc2Key.PublicKey)
  356. signer := types.HomesteadSigner{}
  357. // Create a chain generator with some simple transactions (blatantly stolen from @fjl/chain_markets_test)
  358. generator := func(i int, block *core.BlockGen) {
  359. switch i {
  360. case 0:
  361. // In block 1, the test bank sends account #1 some ether.
  362. tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBank), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, testBankKey)
  363. block.AddTx(tx)
  364. case 1:
  365. // In block 2, the test bank sends some more ether to account #1.
  366. // acc1Addr passes it on to account #2.
  367. tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBank), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, testBankKey)
  368. tx2, _ := types.SignTx(types.NewTransaction(block.TxNonce(acc1Addr), acc2Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, acc1Key)
  369. block.AddTx(tx1)
  370. block.AddTx(tx2)
  371. case 2:
  372. // Block 3 is empty but was mined by account #2.
  373. block.SetCoinbase(acc2Addr)
  374. block.SetExtra([]byte("yeehaw"))
  375. case 3:
  376. // Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
  377. b2 := block.PrevBlock(1).Header()
  378. b2.Extra = []byte("foo")
  379. block.AddUncle(b2)
  380. b3 := block.PrevBlock(2).Header()
  381. b3.Extra = []byte("foo")
  382. block.AddUncle(b3)
  383. }
  384. }
  385. // Assemble the test environment
  386. pm, _ := newTestProtocolManagerMust(t, downloader.FullSync, 4, generator, nil)
  387. peer, _ := newTestPeer("peer", protocol, pm, true)
  388. defer peer.close()
  389. // Collect the hashes to request, and the response to expect
  390. hashes, receipts := []common.Hash{}, []types.Receipts{}
  391. for i := uint64(0); i <= pm.blockchain.CurrentBlock().NumberU64(); i++ {
  392. block := pm.blockchain.GetBlockByNumber(i)
  393. hashes = append(hashes, block.Hash())
  394. receipts = append(receipts, pm.blockchain.GetReceiptsByHash(block.Hash()))
  395. }
  396. // Send the hash request and verify the response
  397. p2p.Send(peer.app, 0x0f, hashes)
  398. if err := p2p.ExpectMsg(peer.app, 0x10, receipts); err != nil {
  399. t.Errorf("receipts mismatch: %v", err)
  400. }
  401. }
  402. // Tests that post eth protocol handshake, clients perform a mutual checkpoint
  403. // challenge to validate each other's chains. Hash mismatches, or missing ones
  404. // during a fast sync should lead to the peer getting dropped.
  405. func TestCheckpointChallenge(t *testing.T) {
  406. tests := []struct {
  407. syncmode downloader.SyncMode
  408. checkpoint bool
  409. timeout bool
  410. empty bool
  411. match bool
  412. drop bool
  413. }{
  414. // If checkpointing is not enabled locally, don't challenge and don't drop
  415. {downloader.FullSync, false, false, false, false, false},
  416. {downloader.FastSync, false, false, false, false, false},
  417. // If checkpointing is enabled locally and remote response is empty, only drop during fast sync
  418. {downloader.FullSync, true, false, true, false, false},
  419. {downloader.FastSync, true, false, true, false, true}, // Special case, fast sync, unsynced peer
  420. // If checkpointing is enabled locally and remote response mismatches, always drop
  421. {downloader.FullSync, true, false, false, false, true},
  422. {downloader.FastSync, true, false, false, false, true},
  423. // If checkpointing is enabled locally and remote response matches, never drop
  424. {downloader.FullSync, true, false, false, true, false},
  425. {downloader.FastSync, true, false, false, true, false},
  426. // If checkpointing is enabled locally and remote times out, always drop
  427. {downloader.FullSync, true, true, false, true, true},
  428. {downloader.FastSync, true, true, false, true, true},
  429. }
  430. for _, tt := range tests {
  431. 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) {
  432. testCheckpointChallenge(t, tt.syncmode, tt.checkpoint, tt.timeout, tt.empty, tt.match, tt.drop)
  433. })
  434. }
  435. }
  436. func testCheckpointChallenge(t *testing.T, syncmode downloader.SyncMode, checkpoint bool, timeout bool, empty bool, match bool, drop bool) {
  437. // Reduce the checkpoint handshake challenge timeout
  438. defer func(old time.Duration) { syncChallengeTimeout = old }(syncChallengeTimeout)
  439. syncChallengeTimeout = 250 * time.Millisecond
  440. // Initialize a chain and generate a fake CHT if checkpointing is enabled
  441. var (
  442. db = rawdb.NewMemoryDatabase()
  443. config = new(params.ChainConfig)
  444. )
  445. (&core.Genesis{Config: config}).MustCommit(db) // Commit genesis block
  446. // If checkpointing is enabled, create and inject a fake CHT and the corresponding
  447. // chllenge response.
  448. var response *types.Header
  449. var cht *params.TrustedCheckpoint
  450. if checkpoint {
  451. index := uint64(rand.Intn(500))
  452. number := (index+1)*params.CHTFrequency - 1
  453. response = &types.Header{Number: big.NewInt(int64(number)), Extra: []byte("valid")}
  454. cht = &params.TrustedCheckpoint{
  455. SectionIndex: index,
  456. SectionHead: response.Hash(),
  457. }
  458. }
  459. // Create a checkpoint aware protocol manager
  460. blockchain, err := core.NewBlockChain(db, nil, config, ethash.NewFaker(), vm.Config{}, nil)
  461. if err != nil {
  462. t.Fatalf("failed to create new blockchain: %v", err)
  463. }
  464. pm, err := NewProtocolManager(config, cht, syncmode, DefaultConfig.NetworkId, new(event.TypeMux), &testTxPool{pool: make(map[common.Hash]*types.Transaction)}, ethash.NewFaker(), blockchain, db, 1, nil)
  465. if err != nil {
  466. t.Fatalf("failed to start test protocol manager: %v", err)
  467. }
  468. pm.Start(1000)
  469. defer pm.Stop()
  470. // Connect a new peer and check that we receive the checkpoint challenge
  471. peer, _ := newTestPeer("peer", eth63, pm, true)
  472. defer peer.close()
  473. if checkpoint {
  474. challenge := &getBlockHeadersData{
  475. Origin: hashOrNumber{Number: response.Number.Uint64()},
  476. Amount: 1,
  477. Skip: 0,
  478. Reverse: false,
  479. }
  480. if err := p2p.ExpectMsg(peer.app, GetBlockHeadersMsg, challenge); err != nil {
  481. t.Fatalf("challenge mismatch: %v", err)
  482. }
  483. // Create a block to reply to the challenge if no timeout is simulated
  484. if !timeout {
  485. if empty {
  486. if err := p2p.Send(peer.app, BlockHeadersMsg, []*types.Header{}); err != nil {
  487. t.Fatalf("failed to answer challenge: %v", err)
  488. }
  489. } else if match {
  490. if err := p2p.Send(peer.app, BlockHeadersMsg, []*types.Header{response}); err != nil {
  491. t.Fatalf("failed to answer challenge: %v", err)
  492. }
  493. } else {
  494. if err := p2p.Send(peer.app, BlockHeadersMsg, []*types.Header{{Number: response.Number}}); 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. if peers := pm.peers.Len(); peers != 0 {
  505. t.Fatalf("peer count mismatch: have %d, want %d", peers, 0)
  506. }
  507. } else {
  508. if peers := pm.peers.Len(); peers != 1 {
  509. t.Fatalf("peer count mismatch: have %d, want %d", peers, 1)
  510. }
  511. }
  512. }
  513. func TestBroadcastBlock(t *testing.T) {
  514. var tests = []struct {
  515. totalPeers int
  516. broadcastExpected int
  517. }{
  518. {1, 1},
  519. {2, 1},
  520. {3, 1},
  521. {4, 2},
  522. {5, 2},
  523. {9, 3},
  524. {12, 3},
  525. {16, 4},
  526. {26, 5},
  527. {100, 10},
  528. }
  529. for _, test := range tests {
  530. testBroadcastBlock(t, test.totalPeers, test.broadcastExpected)
  531. }
  532. }
  533. func testBroadcastBlock(t *testing.T, totalPeers, broadcastExpected int) {
  534. var (
  535. evmux = new(event.TypeMux)
  536. pow = ethash.NewFaker()
  537. db = rawdb.NewMemoryDatabase()
  538. config = &params.ChainConfig{}
  539. gspec = &core.Genesis{Config: config}
  540. genesis = gspec.MustCommit(db)
  541. )
  542. blockchain, err := core.NewBlockChain(db, nil, config, pow, vm.Config{}, nil)
  543. if err != nil {
  544. t.Fatalf("failed to create new blockchain: %v", err)
  545. }
  546. pm, err := NewProtocolManager(config, nil, downloader.FullSync, DefaultConfig.NetworkId, evmux, &testTxPool{pool: make(map[common.Hash]*types.Transaction)}, pow, blockchain, db, 1, nil)
  547. if err != nil {
  548. t.Fatalf("failed to start test protocol manager: %v", err)
  549. }
  550. pm.Start(1000)
  551. defer pm.Stop()
  552. var peers []*testPeer
  553. for i := 0; i < totalPeers; i++ {
  554. peer, _ := newTestPeer(fmt.Sprintf("peer %d", i), eth63, pm, true)
  555. defer peer.close()
  556. peers = append(peers, peer)
  557. }
  558. chain, _ := core.GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 1, func(i int, gen *core.BlockGen) {})
  559. pm.BroadcastBlock(chain[0], true /*propagate*/)
  560. errCh := make(chan error, totalPeers)
  561. doneCh := make(chan struct{}, totalPeers)
  562. for _, peer := range peers {
  563. go func(p *testPeer) {
  564. if err := p2p.ExpectMsg(p.app, NewBlockMsg, &newBlockData{Block: chain[0], TD: big.NewInt(131136)}); err != nil {
  565. errCh <- err
  566. } else {
  567. doneCh <- struct{}{}
  568. }
  569. }(peer)
  570. }
  571. var received int
  572. for {
  573. select {
  574. case <-doneCh:
  575. received++
  576. case <-time.After(100 * time.Millisecond):
  577. if received != broadcastExpected {
  578. t.Errorf("broadcast count mismatch: have %d, want %d", received, broadcastExpected)
  579. }
  580. return
  581. case err = <-errCh:
  582. t.Fatalf("broadcast failed: %v", err)
  583. }
  584. }
  585. }
  586. // Tests that a propagated malformed block (uncles or transactions don't match
  587. // with the hashes in the header) gets discarded and not broadcast forward.
  588. func TestBroadcastMalformedBlock(t *testing.T) {
  589. // Create a live node to test propagation with
  590. var (
  591. engine = ethash.NewFaker()
  592. db = rawdb.NewMemoryDatabase()
  593. config = &params.ChainConfig{}
  594. gspec = &core.Genesis{Config: config}
  595. genesis = gspec.MustCommit(db)
  596. )
  597. blockchain, err := core.NewBlockChain(db, nil, config, engine, vm.Config{}, nil)
  598. if err != nil {
  599. t.Fatalf("failed to create new blockchain: %v", err)
  600. }
  601. pm, err := NewProtocolManager(config, nil, downloader.FullSync, DefaultConfig.NetworkId, new(event.TypeMux), new(testTxPool), engine, blockchain, db, 1, nil)
  602. if err != nil {
  603. t.Fatalf("failed to start test protocol manager: %v", err)
  604. }
  605. pm.Start(2)
  606. defer pm.Stop()
  607. // Create two peers, one to send the malformed block with and one to check
  608. // propagation
  609. source, _ := newTestPeer("source", eth63, pm, true)
  610. defer source.close()
  611. sink, _ := newTestPeer("sink", eth63, pm, true)
  612. defer sink.close()
  613. // Create various combinations of malformed blocks
  614. chain, _ := core.GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 1, func(i int, gen *core.BlockGen) {})
  615. malformedUncles := chain[0].Header()
  616. malformedUncles.UncleHash[0]++
  617. malformedTransactions := chain[0].Header()
  618. malformedTransactions.TxHash[0]++
  619. malformedEverything := chain[0].Header()
  620. malformedEverything.UncleHash[0]++
  621. malformedEverything.TxHash[0]++
  622. // Keep listening to broadcasts and notify if any arrives
  623. notify := make(chan struct{}, 1)
  624. go func() {
  625. if _, err := sink.app.ReadMsg(); err == nil {
  626. notify <- struct{}{}
  627. }
  628. }()
  629. // Try to broadcast all malformations and ensure they all get discarded
  630. for _, header := range []*types.Header{malformedUncles, malformedTransactions, malformedEverything} {
  631. block := types.NewBlockWithHeader(header).WithBody(chain[0].Transactions(), chain[0].Uncles())
  632. if err := p2p.Send(source.app, NewBlockMsg, []interface{}{block, big.NewInt(131136)}); err != nil {
  633. t.Fatalf("failed to broadcast block: %v", err)
  634. }
  635. select {
  636. case <-notify:
  637. t.Fatalf("malformed block forwarded")
  638. case <-time.After(100 * time.Millisecond):
  639. }
  640. }
  641. }