handler_test.go 25 KB

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