handler_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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 TestGetBlockHeaders62(t *testing.T) { testGetBlockHeaders(t, 62) }
  39. func TestGetBlockHeaders63(t *testing.T) { testGetBlockHeaders(t, 63) }
  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 TestGetBlockBodies62(t *testing.T) { testGetBlockBodies(t, 62) }
  194. func TestGetBlockBodies63(t *testing.T) { testGetBlockBodies(t, 63) }
  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 testGetNodeData(t *testing.T, protocol int) {
  261. // Define three accounts to simulate transactions with
  262. acc1Key, _ := crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
  263. acc2Key, _ := crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
  264. acc1Addr := crypto.PubkeyToAddress(acc1Key.PublicKey)
  265. acc2Addr := crypto.PubkeyToAddress(acc2Key.PublicKey)
  266. signer := types.HomesteadSigner{}
  267. // Create a chain generator with some simple transactions (blatantly stolen from @fjl/chain_markets_test)
  268. generator := func(i int, block *core.BlockGen) {
  269. switch i {
  270. case 0:
  271. // In block 1, the test bank sends account #1 some ether.
  272. tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBank), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, testBankKey)
  273. block.AddTx(tx)
  274. case 1:
  275. // In block 2, the test bank sends some more ether to account #1.
  276. // acc1Addr passes it on to account #2.
  277. tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBank), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, testBankKey)
  278. tx2, _ := types.SignTx(types.NewTransaction(block.TxNonce(acc1Addr), acc2Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, acc1Key)
  279. block.AddTx(tx1)
  280. block.AddTx(tx2)
  281. case 2:
  282. // Block 3 is empty but was mined by account #2.
  283. block.SetCoinbase(acc2Addr)
  284. block.SetExtra([]byte("yeehaw"))
  285. case 3:
  286. // Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
  287. b2 := block.PrevBlock(1).Header()
  288. b2.Extra = []byte("foo")
  289. block.AddUncle(b2)
  290. b3 := block.PrevBlock(2).Header()
  291. b3.Extra = []byte("foo")
  292. block.AddUncle(b3)
  293. }
  294. }
  295. // Assemble the test environment
  296. pm, db := newTestProtocolManagerMust(t, downloader.FullSync, 4, generator, nil)
  297. peer, _ := newTestPeer("peer", protocol, pm, true)
  298. defer peer.close()
  299. // Fetch for now the entire chain db
  300. hashes := []common.Hash{}
  301. it := db.NewIterator()
  302. for it.Next() {
  303. if key := it.Key(); len(key) == common.HashLength {
  304. hashes = append(hashes, common.BytesToHash(key))
  305. }
  306. }
  307. it.Release()
  308. p2p.Send(peer.app, 0x0d, hashes)
  309. msg, err := peer.app.ReadMsg()
  310. if err != nil {
  311. t.Fatalf("failed to read node data response: %v", err)
  312. }
  313. if msg.Code != 0x0e {
  314. t.Fatalf("response packet code mismatch: have %x, want %x", msg.Code, 0x0c)
  315. }
  316. var data [][]byte
  317. if err := msg.Decode(&data); err != nil {
  318. t.Fatalf("failed to decode response node data: %v", err)
  319. }
  320. // Verify that all hashes correspond to the requested data, and reconstruct a state tree
  321. for i, want := range hashes {
  322. if hash := crypto.Keccak256Hash(data[i]); hash != want {
  323. t.Errorf("data hash mismatch: have %x, want %x", hash, want)
  324. }
  325. }
  326. statedb := rawdb.NewMemoryDatabase()
  327. for i := 0; i < len(data); i++ {
  328. statedb.Put(hashes[i].Bytes(), data[i])
  329. }
  330. accounts := []common.Address{testBank, acc1Addr, acc2Addr}
  331. for i := uint64(0); i <= pm.blockchain.CurrentBlock().NumberU64(); i++ {
  332. trie, _ := state.New(pm.blockchain.GetBlockByNumber(i).Root(), state.NewDatabase(statedb))
  333. for j, acc := range accounts {
  334. state, _ := pm.blockchain.State()
  335. bw := state.GetBalance(acc)
  336. bh := trie.GetBalance(acc)
  337. if (bw != nil && bh == nil) || (bw == nil && bh != nil) {
  338. t.Errorf("test %d, account %d: balance mismatch: have %v, want %v", i, j, bh, bw)
  339. }
  340. if bw != nil && bh != nil && bw.Cmp(bw) != 0 {
  341. t.Errorf("test %d, account %d: balance mismatch: have %v, want %v", i, j, bh, bw)
  342. }
  343. }
  344. }
  345. }
  346. // Tests that the transaction receipts can be retrieved based on hashes.
  347. func TestGetReceipt63(t *testing.T) { testGetReceipt(t, 63) }
  348. func testGetReceipt(t *testing.T, protocol int) {
  349. // Define three accounts to simulate transactions with
  350. acc1Key, _ := crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
  351. acc2Key, _ := crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
  352. acc1Addr := crypto.PubkeyToAddress(acc1Key.PublicKey)
  353. acc2Addr := crypto.PubkeyToAddress(acc2Key.PublicKey)
  354. signer := types.HomesteadSigner{}
  355. // Create a chain generator with some simple transactions (blatantly stolen from @fjl/chain_markets_test)
  356. generator := func(i int, block *core.BlockGen) {
  357. switch i {
  358. case 0:
  359. // In block 1, the test bank sends account #1 some ether.
  360. tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBank), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, testBankKey)
  361. block.AddTx(tx)
  362. case 1:
  363. // In block 2, the test bank sends some more ether to account #1.
  364. // acc1Addr passes it on to account #2.
  365. tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBank), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, testBankKey)
  366. tx2, _ := types.SignTx(types.NewTransaction(block.TxNonce(acc1Addr), acc2Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, acc1Key)
  367. block.AddTx(tx1)
  368. block.AddTx(tx2)
  369. case 2:
  370. // Block 3 is empty but was mined by account #2.
  371. block.SetCoinbase(acc2Addr)
  372. block.SetExtra([]byte("yeehaw"))
  373. case 3:
  374. // Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
  375. b2 := block.PrevBlock(1).Header()
  376. b2.Extra = []byte("foo")
  377. block.AddUncle(b2)
  378. b3 := block.PrevBlock(2).Header()
  379. b3.Extra = []byte("foo")
  380. block.AddUncle(b3)
  381. }
  382. }
  383. // Assemble the test environment
  384. pm, _ := newTestProtocolManagerMust(t, downloader.FullSync, 4, generator, nil)
  385. peer, _ := newTestPeer("peer", protocol, pm, true)
  386. defer peer.close()
  387. // Collect the hashes to request, and the response to expect
  388. hashes, receipts := []common.Hash{}, []types.Receipts{}
  389. for i := uint64(0); i <= pm.blockchain.CurrentBlock().NumberU64(); i++ {
  390. block := pm.blockchain.GetBlockByNumber(i)
  391. hashes = append(hashes, block.Hash())
  392. receipts = append(receipts, pm.blockchain.GetReceiptsByHash(block.Hash()))
  393. }
  394. // Send the hash request and verify the response
  395. p2p.Send(peer.app, 0x0f, hashes)
  396. if err := p2p.ExpectMsg(peer.app, 0x10, receipts); err != nil {
  397. t.Errorf("receipts mismatch: %v", err)
  398. }
  399. }
  400. // Tests that post eth protocol handshake, clients perform a mutual checkpoint
  401. // challenge to validate each other's chains. Hash mismatches, or missing ones
  402. // during a fast sync should lead to the peer getting dropped.
  403. func TestCheckpointChallenge(t *testing.T) {
  404. tests := []struct {
  405. syncmode downloader.SyncMode
  406. checkpoint bool
  407. timeout bool
  408. empty bool
  409. match bool
  410. drop bool
  411. }{
  412. // If checkpointing is not enabled locally, don't challenge and don't drop
  413. {downloader.FullSync, false, false, false, false, false},
  414. {downloader.FastSync, false, false, false, false, false},
  415. // If checkpointing is enabled locally and remote response is empty, only drop during fast sync
  416. {downloader.FullSync, true, false, true, false, false},
  417. {downloader.FastSync, true, false, true, false, true}, // Special case, fast sync, unsynced peer
  418. // If checkpointing is enabled locally and remote response mismatches, always drop
  419. {downloader.FullSync, true, false, false, false, true},
  420. {downloader.FastSync, true, false, false, false, true},
  421. // If checkpointing is enabled locally and remote response matches, never drop
  422. {downloader.FullSync, true, false, false, true, false},
  423. {downloader.FastSync, true, false, false, true, false},
  424. // If checkpointing is enabled locally and remote times out, always drop
  425. {downloader.FullSync, true, true, false, true, true},
  426. {downloader.FastSync, true, true, false, true, true},
  427. }
  428. for _, tt := range tests {
  429. 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) {
  430. testCheckpointChallenge(t, tt.syncmode, tt.checkpoint, tt.timeout, tt.empty, tt.match, tt.drop)
  431. })
  432. }
  433. }
  434. func testCheckpointChallenge(t *testing.T, syncmode downloader.SyncMode, checkpoint bool, timeout bool, empty bool, match bool, drop bool) {
  435. // Reduce the checkpoint handshake challenge timeout
  436. defer func(old time.Duration) { syncChallengeTimeout = old }(syncChallengeTimeout)
  437. syncChallengeTimeout = 250 * time.Millisecond
  438. // Initialize a chain and generate a fake CHT if checkpointing is enabled
  439. var (
  440. db = rawdb.NewMemoryDatabase()
  441. config = new(params.ChainConfig)
  442. )
  443. (&core.Genesis{Config: config}).MustCommit(db) // Commit genesis block
  444. // If checkpointing is enabled, create and inject a fake CHT and the corresponding
  445. // chllenge response.
  446. var response *types.Header
  447. var cht *params.TrustedCheckpoint
  448. if checkpoint {
  449. index := uint64(rand.Intn(500))
  450. number := (index+1)*params.CHTFrequency - 1
  451. response = &types.Header{Number: big.NewInt(int64(number)), Extra: []byte("valid")}
  452. cht = &params.TrustedCheckpoint{
  453. SectionIndex: index,
  454. SectionHead: response.Hash(),
  455. }
  456. }
  457. // Create a checkpoint aware protocol manager
  458. blockchain, err := core.NewBlockChain(db, nil, config, ethash.NewFaker(), vm.Config{}, nil)
  459. if err != nil {
  460. t.Fatalf("failed to create new blockchain: %v", err)
  461. }
  462. pm, err := NewProtocolManager(config, cht, syncmode, DefaultConfig.NetworkId, new(event.TypeMux), new(testTxPool), ethash.NewFaker(), blockchain, db, 1, nil)
  463. if err != nil {
  464. t.Fatalf("failed to start test protocol manager: %v", err)
  465. }
  466. pm.Start(1000)
  467. defer pm.Stop()
  468. // Connect a new peer and check that we receive the checkpoint challenge
  469. peer, _ := newTestPeer("peer", eth63, pm, true)
  470. defer peer.close()
  471. if checkpoint {
  472. challenge := &getBlockHeadersData{
  473. Origin: hashOrNumber{Number: response.Number.Uint64()},
  474. Amount: 1,
  475. Skip: 0,
  476. Reverse: false,
  477. }
  478. if err := p2p.ExpectMsg(peer.app, GetBlockHeadersMsg, challenge); err != nil {
  479. t.Fatalf("challenge mismatch: %v", err)
  480. }
  481. // Create a block to reply to the challenge if no timeout is simulated
  482. if !timeout {
  483. if empty {
  484. if err := p2p.Send(peer.app, BlockHeadersMsg, []*types.Header{}); err != nil {
  485. t.Fatalf("failed to answer challenge: %v", err)
  486. }
  487. } else if match {
  488. if err := p2p.Send(peer.app, BlockHeadersMsg, []*types.Header{response}); err != nil {
  489. t.Fatalf("failed to answer challenge: %v", err)
  490. }
  491. } else {
  492. if err := p2p.Send(peer.app, BlockHeadersMsg, []*types.Header{{Number: response.Number}}); err != nil {
  493. t.Fatalf("failed to answer challenge: %v", err)
  494. }
  495. }
  496. }
  497. }
  498. // Wait until the test timeout passes to ensure proper cleanup
  499. time.Sleep(syncChallengeTimeout + 100*time.Millisecond)
  500. // Verify that the remote peer is maintained or dropped
  501. if drop {
  502. if peers := pm.peers.Len(); peers != 0 {
  503. t.Fatalf("peer count mismatch: have %d, want %d", peers, 0)
  504. }
  505. } else {
  506. if peers := pm.peers.Len(); peers != 1 {
  507. t.Fatalf("peer count mismatch: have %d, want %d", peers, 1)
  508. }
  509. }
  510. }
  511. func TestBroadcastBlock(t *testing.T) {
  512. var tests = []struct {
  513. totalPeers int
  514. broadcastExpected int
  515. }{
  516. {1, 1},
  517. {2, 2},
  518. {3, 3},
  519. {4, 4},
  520. {5, 4},
  521. {9, 4},
  522. {12, 4},
  523. {16, 4},
  524. {26, 5},
  525. {100, 10},
  526. }
  527. for _, test := range tests {
  528. testBroadcastBlock(t, test.totalPeers, test.broadcastExpected)
  529. }
  530. }
  531. func testBroadcastBlock(t *testing.T, totalPeers, broadcastExpected int) {
  532. var (
  533. evmux = new(event.TypeMux)
  534. pow = ethash.NewFaker()
  535. db = rawdb.NewMemoryDatabase()
  536. config = &params.ChainConfig{}
  537. gspec = &core.Genesis{Config: config}
  538. genesis = gspec.MustCommit(db)
  539. )
  540. blockchain, err := core.NewBlockChain(db, nil, config, pow, vm.Config{}, nil)
  541. if err != nil {
  542. t.Fatalf("failed to create new blockchain: %v", err)
  543. }
  544. pm, err := NewProtocolManager(config, nil, downloader.FullSync, DefaultConfig.NetworkId, evmux, new(testTxPool), pow, blockchain, db, 1, nil)
  545. if err != nil {
  546. t.Fatalf("failed to start test protocol manager: %v", err)
  547. }
  548. pm.Start(1000)
  549. defer pm.Stop()
  550. var peers []*testPeer
  551. for i := 0; i < totalPeers; i++ {
  552. peer, _ := newTestPeer(fmt.Sprintf("peer %d", i), eth63, pm, true)
  553. defer peer.close()
  554. peers = append(peers, peer)
  555. }
  556. chain, _ := core.GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, 1, func(i int, gen *core.BlockGen) {})
  557. pm.BroadcastBlock(chain[0], true /*propagate*/)
  558. errCh := make(chan error, totalPeers)
  559. doneCh := make(chan struct{}, totalPeers)
  560. for _, peer := range peers {
  561. go func(p *testPeer) {
  562. if err := p2p.ExpectMsg(p.app, NewBlockMsg, &newBlockData{Block: chain[0], TD: big.NewInt(131136)}); err != nil {
  563. errCh <- err
  564. } else {
  565. doneCh <- struct{}{}
  566. }
  567. }(peer)
  568. }
  569. timeout := time.After(300 * time.Millisecond)
  570. var receivedCount int
  571. outer:
  572. for {
  573. select {
  574. case err = <-errCh:
  575. break outer
  576. case <-doneCh:
  577. receivedCount++
  578. if receivedCount == totalPeers {
  579. break outer
  580. }
  581. case <-timeout:
  582. break outer
  583. }
  584. }
  585. for _, peer := range peers {
  586. peer.app.Close()
  587. }
  588. if err != nil {
  589. t.Errorf("error matching block by peer: %v", err)
  590. }
  591. if receivedCount != broadcastExpected {
  592. t.Errorf("block broadcast to %d peers, expected %d", receivedCount, broadcastExpected)
  593. }
  594. }