handler_test.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. package eth
  2. import (
  3. "fmt"
  4. "math/big"
  5. "math/rand"
  6. "testing"
  7. "github.com/ethereum/go-ethereum/common"
  8. "github.com/ethereum/go-ethereum/core"
  9. "github.com/ethereum/go-ethereum/core/state"
  10. "github.com/ethereum/go-ethereum/core/types"
  11. "github.com/ethereum/go-ethereum/crypto"
  12. "github.com/ethereum/go-ethereum/eth/downloader"
  13. "github.com/ethereum/go-ethereum/ethdb"
  14. "github.com/ethereum/go-ethereum/p2p"
  15. "github.com/ethereum/go-ethereum/params"
  16. )
  17. // Tests that protocol versions and modes of operations are matched up properly.
  18. func TestProtocolCompatibility(t *testing.T) {
  19. // Define the compatibility chart
  20. tests := []struct {
  21. version uint
  22. mode Mode
  23. compatible bool
  24. }{
  25. {61, ArchiveMode, true}, {62, ArchiveMode, true}, {63, ArchiveMode, true}, {64, ArchiveMode, true},
  26. {61, FullMode, false}, {62, FullMode, false}, {63, FullMode, true}, {64, FullMode, true},
  27. {61, LightMode, false}, {62, LightMode, false}, {63, LightMode, false}, {64, LightMode, true},
  28. }
  29. // Make sure anything we screw up is restored
  30. backup := ProtocolVersions
  31. defer func() { ProtocolVersions = backup }()
  32. // Try all available compatibility configs and check for errors
  33. for i, tt := range tests {
  34. ProtocolVersions = []uint{tt.version}
  35. pm, err := newTestProtocolManager(tt.mode, 0, nil, nil)
  36. if pm != nil {
  37. defer pm.Stop()
  38. }
  39. if (err == nil && !tt.compatible) || (err != nil && tt.compatible) {
  40. t.Errorf("test %d: compatibility mismatch: have error %v, want compatibility %v", i, err, tt.compatible)
  41. }
  42. }
  43. }
  44. // Tests that hashes can be retrieved from a remote chain by hashes in reverse
  45. // order.
  46. func TestGetBlockHashes61(t *testing.T) { testGetBlockHashes(t, 61) }
  47. func testGetBlockHashes(t *testing.T, protocol int) {
  48. pm := newTestProtocolManagerMust(t, ArchiveMode, downloader.MaxHashFetch+15, nil, nil)
  49. peer, _ := newTestPeer("peer", protocol, pm, true)
  50. defer peer.close()
  51. // Create a batch of tests for various scenarios
  52. limit := downloader.MaxHashFetch
  53. tests := []struct {
  54. origin common.Hash
  55. number int
  56. result int
  57. }{
  58. {common.Hash{}, 1, 0}, // Make sure non existent hashes don't return results
  59. {pm.blockchain.Genesis().Hash(), 1, 0}, // There are no hashes to retrieve up from the genesis
  60. {pm.blockchain.GetBlockByNumber(5).Hash(), 5, 5}, // All the hashes including the genesis requested
  61. {pm.blockchain.GetBlockByNumber(5).Hash(), 10, 5}, // More hashes than available till the genesis requested
  62. {pm.blockchain.GetBlockByNumber(100).Hash(), 10, 10}, // All hashes available from the middle of the chain
  63. {pm.blockchain.CurrentBlock().Hash(), 10, 10}, // All hashes available from the head of the chain
  64. {pm.blockchain.CurrentBlock().Hash(), limit, limit}, // Request the maximum allowed hash count
  65. {pm.blockchain.CurrentBlock().Hash(), limit + 1, limit}, // Request more than the maximum allowed hash count
  66. }
  67. // Run each of the tests and verify the results against the chain
  68. for i, tt := range tests {
  69. // Assemble the hash response we would like to receive
  70. resp := make([]common.Hash, tt.result)
  71. if len(resp) > 0 {
  72. from := pm.blockchain.GetBlock(tt.origin).NumberU64() - 1
  73. for j := 0; j < len(resp); j++ {
  74. resp[j] = pm.blockchain.GetBlockByNumber(uint64(int(from) - j)).Hash()
  75. }
  76. }
  77. // Send the hash request and verify the response
  78. p2p.Send(peer.app, 0x03, getBlockHashesData{tt.origin, uint64(tt.number)})
  79. if err := p2p.ExpectMsg(peer.app, 0x04, resp); err != nil {
  80. t.Errorf("test %d: block hashes mismatch: %v", i, err)
  81. }
  82. }
  83. }
  84. // Tests that hashes can be retrieved from a remote chain by numbers in forward
  85. // order.
  86. func TestGetBlockHashesFromNumber61(t *testing.T) { testGetBlockHashesFromNumber(t, 61) }
  87. func testGetBlockHashesFromNumber(t *testing.T, protocol int) {
  88. pm := newTestProtocolManagerMust(t, ArchiveMode, downloader.MaxHashFetch+15, nil, nil)
  89. peer, _ := newTestPeer("peer", protocol, pm, true)
  90. defer peer.close()
  91. // Create a batch of tests for various scenarios
  92. limit := downloader.MaxHashFetch
  93. tests := []struct {
  94. origin uint64
  95. number int
  96. result int
  97. }{
  98. {pm.blockchain.CurrentBlock().NumberU64() + 1, 1, 0}, // Out of bounds requests should return empty
  99. {pm.blockchain.CurrentBlock().NumberU64(), 1, 1}, // Make sure the head hash can be retrieved
  100. {pm.blockchain.CurrentBlock().NumberU64() - 4, 5, 5}, // All hashes, including the head hash requested
  101. {pm.blockchain.CurrentBlock().NumberU64() - 4, 10, 5}, // More hashes requested than available till the head
  102. {pm.blockchain.CurrentBlock().NumberU64() - 100, 10, 10}, // All hashes available from the middle of the chain
  103. {0, 10, 10}, // All hashes available from the root of the chain
  104. {0, limit, limit}, // Request the maximum allowed hash count
  105. {0, limit + 1, limit}, // Request more than the maximum allowed hash count
  106. {0, 1, 1}, // Make sure the genesis hash can be retrieved
  107. }
  108. // Run each of the tests and verify the results against the chain
  109. for i, tt := range tests {
  110. // Assemble the hash response we would like to receive
  111. resp := make([]common.Hash, tt.result)
  112. for j := 0; j < len(resp); j++ {
  113. resp[j] = pm.blockchain.GetBlockByNumber(tt.origin + uint64(j)).Hash()
  114. }
  115. // Send the hash request and verify the response
  116. p2p.Send(peer.app, 0x08, getBlockHashesFromNumberData{tt.origin, uint64(tt.number)})
  117. if err := p2p.ExpectMsg(peer.app, 0x04, resp); err != nil {
  118. t.Errorf("test %d: block hashes mismatch: %v", i, err)
  119. }
  120. }
  121. }
  122. // Tests that blocks can be retrieved from a remote chain based on their hashes.
  123. func TestGetBlocks61(t *testing.T) { testGetBlocks(t, 61) }
  124. func testGetBlocks(t *testing.T, protocol int) {
  125. pm := newTestProtocolManagerMust(t, ArchiveMode, downloader.MaxHashFetch+15, nil, nil)
  126. peer, _ := newTestPeer("peer", protocol, pm, true)
  127. defer peer.close()
  128. // Create a batch of tests for various scenarios
  129. limit := downloader.MaxBlockFetch
  130. tests := []struct {
  131. random int // Number of blocks to fetch randomly from the chain
  132. explicit []common.Hash // Explicitly requested blocks
  133. available []bool // Availability of explicitly requested blocks
  134. expected int // Total number of existing blocks to expect
  135. }{
  136. {1, nil, nil, 1}, // A single random block should be retrievable
  137. {10, nil, nil, 10}, // Multiple random blocks should be retrievable
  138. {limit, nil, nil, limit}, // The maximum possible blocks should be retrievable
  139. {limit + 1, nil, nil, limit}, // No more than the possible block count should be returned
  140. {0, []common.Hash{pm.blockchain.Genesis().Hash()}, []bool{true}, 1}, // The genesis block should be retrievable
  141. {0, []common.Hash{pm.blockchain.CurrentBlock().Hash()}, []bool{true}, 1}, // The chains head block should be retrievable
  142. {0, []common.Hash{common.Hash{}}, []bool{false}, 0}, // A non existent block should not be returned
  143. // Existing and non-existing blocks interleaved should not cause problems
  144. {0, []common.Hash{
  145. common.Hash{},
  146. pm.blockchain.GetBlockByNumber(1).Hash(),
  147. common.Hash{},
  148. pm.blockchain.GetBlockByNumber(10).Hash(),
  149. common.Hash{},
  150. pm.blockchain.GetBlockByNumber(100).Hash(),
  151. common.Hash{},
  152. }, []bool{false, true, false, true, false, true, false}, 3},
  153. }
  154. // Run each of the tests and verify the results against the chain
  155. for i, tt := range tests {
  156. // Collect the hashes to request, and the response to expect
  157. hashes, seen := []common.Hash{}, make(map[int64]bool)
  158. blocks := []*types.Block{}
  159. for j := 0; j < tt.random; j++ {
  160. for {
  161. num := rand.Int63n(int64(pm.blockchain.CurrentBlock().NumberU64()))
  162. if !seen[num] {
  163. seen[num] = true
  164. block := pm.blockchain.GetBlockByNumber(uint64(num))
  165. hashes = append(hashes, block.Hash())
  166. if len(blocks) < tt.expected {
  167. blocks = append(blocks, block)
  168. }
  169. break
  170. }
  171. }
  172. }
  173. for j, hash := range tt.explicit {
  174. hashes = append(hashes, hash)
  175. if tt.available[j] && len(blocks) < tt.expected {
  176. blocks = append(blocks, pm.blockchain.GetBlock(hash))
  177. }
  178. }
  179. // Send the hash request and verify the response
  180. p2p.Send(peer.app, 0x05, hashes)
  181. if err := p2p.ExpectMsg(peer.app, 0x06, blocks); err != nil {
  182. t.Errorf("test %d: blocks mismatch: %v", i, err)
  183. }
  184. }
  185. }
  186. // Tests that block headers can be retrieved from a remote chain based on user queries.
  187. func TestGetBlockHeaders62(t *testing.T) { testGetBlockHeaders(t, 62) }
  188. func TestGetBlockHeaders63(t *testing.T) { testGetBlockHeaders(t, 63) }
  189. func TestGetBlockHeaders64(t *testing.T) { testGetBlockHeaders(t, 64) }
  190. func testGetBlockHeaders(t *testing.T, protocol int) {
  191. pm := newTestProtocolManagerMust(t, ArchiveMode, downloader.MaxHashFetch+15, nil, nil)
  192. peer, _ := newTestPeer("peer", protocol, pm, true)
  193. defer peer.close()
  194. // Create a "random" unknown hash for testing
  195. var unknown common.Hash
  196. for i, _ := range unknown {
  197. unknown[i] = byte(i)
  198. }
  199. // Create a batch of tests for various scenarios
  200. limit := uint64(downloader.MaxHeaderFetch)
  201. tests := []struct {
  202. query *getBlockHeadersData // The query to execute for header retrieval
  203. expect []common.Hash // The hashes of the block whose headers are expected
  204. }{
  205. // A single random block should be retrievable by hash and number too
  206. {
  207. &getBlockHeadersData{Origin: hashOrNumber{Hash: pm.blockchain.GetBlockByNumber(limit / 2).Hash()}, Amount: 1},
  208. []common.Hash{pm.blockchain.GetBlockByNumber(limit / 2).Hash()},
  209. }, {
  210. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 1},
  211. []common.Hash{pm.blockchain.GetBlockByNumber(limit / 2).Hash()},
  212. },
  213. // Multiple headers should be retrievable in both directions
  214. {
  215. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 3},
  216. []common.Hash{
  217. pm.blockchain.GetBlockByNumber(limit / 2).Hash(),
  218. pm.blockchain.GetBlockByNumber(limit/2 + 1).Hash(),
  219. pm.blockchain.GetBlockByNumber(limit/2 + 2).Hash(),
  220. },
  221. }, {
  222. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 3, Reverse: true},
  223. []common.Hash{
  224. pm.blockchain.GetBlockByNumber(limit / 2).Hash(),
  225. pm.blockchain.GetBlockByNumber(limit/2 - 1).Hash(),
  226. pm.blockchain.GetBlockByNumber(limit/2 - 2).Hash(),
  227. },
  228. },
  229. // Multiple headers with skip lists should be retrievable
  230. {
  231. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Skip: 3, Amount: 3},
  232. []common.Hash{
  233. pm.blockchain.GetBlockByNumber(limit / 2).Hash(),
  234. pm.blockchain.GetBlockByNumber(limit/2 + 4).Hash(),
  235. pm.blockchain.GetBlockByNumber(limit/2 + 8).Hash(),
  236. },
  237. }, {
  238. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Skip: 3, Amount: 3, Reverse: true},
  239. []common.Hash{
  240. pm.blockchain.GetBlockByNumber(limit / 2).Hash(),
  241. pm.blockchain.GetBlockByNumber(limit/2 - 4).Hash(),
  242. pm.blockchain.GetBlockByNumber(limit/2 - 8).Hash(),
  243. },
  244. },
  245. // The chain endpoints should be retrievable
  246. {
  247. &getBlockHeadersData{Origin: hashOrNumber{Number: 0}, Amount: 1},
  248. []common.Hash{pm.blockchain.GetBlockByNumber(0).Hash()},
  249. }, {
  250. &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64()}, Amount: 1},
  251. []common.Hash{pm.blockchain.CurrentBlock().Hash()},
  252. },
  253. // Ensure protocol limits are honored
  254. {
  255. &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64() - 1}, Amount: limit + 10, Reverse: true},
  256. pm.blockchain.GetBlockHashesFromHash(pm.blockchain.CurrentBlock().Hash(), limit),
  257. },
  258. // Check that requesting more than available is handled gracefully
  259. {
  260. &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64() - 4}, Skip: 3, Amount: 3},
  261. []common.Hash{
  262. pm.blockchain.GetBlockByNumber(pm.blockchain.CurrentBlock().NumberU64() - 4).Hash(),
  263. pm.blockchain.GetBlockByNumber(pm.blockchain.CurrentBlock().NumberU64()).Hash(),
  264. },
  265. }, {
  266. &getBlockHeadersData{Origin: hashOrNumber{Number: 4}, Skip: 3, Amount: 3, Reverse: true},
  267. []common.Hash{
  268. pm.blockchain.GetBlockByNumber(4).Hash(),
  269. pm.blockchain.GetBlockByNumber(0).Hash(),
  270. },
  271. },
  272. // Check that requesting more than available is handled gracefully, even if mid skip
  273. {
  274. &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64() - 4}, Skip: 2, Amount: 3},
  275. []common.Hash{
  276. pm.blockchain.GetBlockByNumber(pm.blockchain.CurrentBlock().NumberU64() - 4).Hash(),
  277. pm.blockchain.GetBlockByNumber(pm.blockchain.CurrentBlock().NumberU64() - 1).Hash(),
  278. },
  279. }, {
  280. &getBlockHeadersData{Origin: hashOrNumber{Number: 4}, Skip: 2, Amount: 3, Reverse: true},
  281. []common.Hash{
  282. pm.blockchain.GetBlockByNumber(4).Hash(),
  283. pm.blockchain.GetBlockByNumber(1).Hash(),
  284. },
  285. },
  286. // Check that non existing headers aren't returned
  287. {
  288. &getBlockHeadersData{Origin: hashOrNumber{Hash: unknown}, Amount: 1},
  289. []common.Hash{},
  290. }, {
  291. &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64() + 1}, Amount: 1},
  292. []common.Hash{},
  293. },
  294. }
  295. // Run each of the tests and verify the results against the chain
  296. for i, tt := range tests {
  297. // Collect the headers to expect in the response
  298. headers := []*types.Header{}
  299. for _, hash := range tt.expect {
  300. headers = append(headers, pm.blockchain.GetBlock(hash).Header())
  301. }
  302. // Send the hash request and verify the response
  303. p2p.Send(peer.app, 0x03, tt.query)
  304. if err := p2p.ExpectMsg(peer.app, 0x04, headers); err != nil {
  305. t.Errorf("test %d: headers mismatch: %v", i, err)
  306. }
  307. }
  308. }
  309. // Tests that block contents can be retrieved from a remote chain based on their hashes.
  310. func TestGetBlockBodies62(t *testing.T) { testGetBlockBodies(t, 62) }
  311. func TestGetBlockBodies63(t *testing.T) { testGetBlockBodies(t, 63) }
  312. func TestGetBlockBodies64(t *testing.T) { testGetBlockBodies(t, 64) }
  313. func testGetBlockBodies(t *testing.T, protocol int) {
  314. pm := newTestProtocolManagerMust(t, ArchiveMode, downloader.MaxBlockFetch+15, nil, nil)
  315. peer, _ := newTestPeer("peer", protocol, pm, true)
  316. defer peer.close()
  317. // Create a batch of tests for various scenarios
  318. limit := downloader.MaxBlockFetch
  319. tests := []struct {
  320. random int // Number of blocks to fetch randomly from the chain
  321. explicit []common.Hash // Explicitly requested blocks
  322. available []bool // Availability of explicitly requested blocks
  323. expected int // Total number of existing blocks to expect
  324. }{
  325. {1, nil, nil, 1}, // A single random block should be retrievable
  326. {10, nil, nil, 10}, // Multiple random blocks should be retrievable
  327. {limit, nil, nil, limit}, // The maximum possible blocks should be retrievable
  328. {limit + 1, nil, nil, limit}, // No more than the possible block count should be returned
  329. {0, []common.Hash{pm.blockchain.Genesis().Hash()}, []bool{true}, 1}, // The genesis block should be retrievable
  330. {0, []common.Hash{pm.blockchain.CurrentBlock().Hash()}, []bool{true}, 1}, // The chains head block should be retrievable
  331. {0, []common.Hash{common.Hash{}}, []bool{false}, 0}, // A non existent block should not be returned
  332. // Existing and non-existing blocks interleaved should not cause problems
  333. {0, []common.Hash{
  334. common.Hash{},
  335. pm.blockchain.GetBlockByNumber(1).Hash(),
  336. common.Hash{},
  337. pm.blockchain.GetBlockByNumber(10).Hash(),
  338. common.Hash{},
  339. pm.blockchain.GetBlockByNumber(100).Hash(),
  340. common.Hash{},
  341. }, []bool{false, true, false, true, false, true, false}, 3},
  342. }
  343. // Run each of the tests and verify the results against the chain
  344. for i, tt := range tests {
  345. // Collect the hashes to request, and the response to expect
  346. hashes, seen := []common.Hash{}, make(map[int64]bool)
  347. bodies := []*blockBody{}
  348. for j := 0; j < tt.random; j++ {
  349. for {
  350. num := rand.Int63n(int64(pm.blockchain.CurrentBlock().NumberU64()))
  351. if !seen[num] {
  352. seen[num] = true
  353. block := pm.blockchain.GetBlockByNumber(uint64(num))
  354. hashes = append(hashes, block.Hash())
  355. if len(bodies) < tt.expected {
  356. bodies = append(bodies, &blockBody{Transactions: block.Transactions(), Uncles: block.Uncles()})
  357. }
  358. break
  359. }
  360. }
  361. }
  362. for j, hash := range tt.explicit {
  363. hashes = append(hashes, hash)
  364. if tt.available[j] && len(bodies) < tt.expected {
  365. block := pm.blockchain.GetBlock(hash)
  366. bodies = append(bodies, &blockBody{Transactions: block.Transactions(), Uncles: block.Uncles()})
  367. }
  368. }
  369. // Send the hash request and verify the response
  370. p2p.Send(peer.app, 0x05, hashes)
  371. if err := p2p.ExpectMsg(peer.app, 0x06, bodies); err != nil {
  372. t.Errorf("test %d: bodies mismatch: %v", i, err)
  373. }
  374. }
  375. }
  376. // Tests that the node state database can be retrieved based on hashes.
  377. func TestGetNodeData63(t *testing.T) { testGetNodeData(t, 63) }
  378. func TestGetNodeData64(t *testing.T) { testGetNodeData(t, 64) }
  379. func testGetNodeData(t *testing.T, protocol int) {
  380. // Define three accounts to simulate transactions with
  381. acc1Key, _ := crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
  382. acc2Key, _ := crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
  383. acc1Addr := crypto.PubkeyToAddress(acc1Key.PublicKey)
  384. acc2Addr := crypto.PubkeyToAddress(acc2Key.PublicKey)
  385. // Create a chain generator with some simple transactions (blatantly stolen from @fjl/chain_makerts_test)
  386. generator := func(i int, block *core.BlockGen) {
  387. switch i {
  388. case 0:
  389. // In block 1, the test bank sends account #1 some ether.
  390. tx, _ := types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil).SignECDSA(testBankKey)
  391. block.AddTx(tx)
  392. case 1:
  393. // In block 2, the test bank sends some more ether to account #1.
  394. // acc1Addr passes it on to account #2.
  395. tx1, _ := types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(testBankKey)
  396. tx2, _ := types.NewTransaction(block.TxNonce(acc1Addr), acc2Addr, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(acc1Key)
  397. block.AddTx(tx1)
  398. block.AddTx(tx2)
  399. case 2:
  400. // Block 3 is empty but was mined by account #2.
  401. block.SetCoinbase(acc2Addr)
  402. block.SetExtra([]byte("yeehaw"))
  403. case 3:
  404. // Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
  405. b2 := block.PrevBlock(1).Header()
  406. b2.Extra = []byte("foo")
  407. block.AddUncle(b2)
  408. b3 := block.PrevBlock(2).Header()
  409. b3.Extra = []byte("foo")
  410. block.AddUncle(b3)
  411. }
  412. }
  413. // Assemble the test environment
  414. pm := newTestProtocolManagerMust(t, ArchiveMode, 4, generator, nil)
  415. peer, _ := newTestPeer("peer", protocol, pm, true)
  416. defer peer.close()
  417. // Fetch for now the entire chain db
  418. hashes := []common.Hash{}
  419. for _, key := range pm.chaindb.(*ethdb.MemDatabase).Keys() {
  420. hashes = append(hashes, common.BytesToHash(key))
  421. }
  422. p2p.Send(peer.app, 0x0d, hashes)
  423. msg, err := peer.app.ReadMsg()
  424. if err != nil {
  425. t.Fatalf("failed to read node data response: %v", err)
  426. }
  427. if msg.Code != 0x0e {
  428. t.Fatalf("response packet code mismatch: have %x, want %x", msg.Code, 0x0c)
  429. }
  430. var data [][]byte
  431. if err := msg.Decode(&data); err != nil {
  432. t.Fatalf("failed to decode response node data: %v", err)
  433. }
  434. // Verify that all hashes correspond to the requested data, and reconstruct a state tree
  435. for i, want := range hashes {
  436. if hash := crypto.Sha3Hash(data[i]); hash != want {
  437. fmt.Errorf("data hash mismatch: have %x, want %x", hash, want)
  438. }
  439. }
  440. statedb, _ := ethdb.NewMemDatabase()
  441. for i := 0; i < len(data); i++ {
  442. statedb.Put(hashes[i].Bytes(), data[i])
  443. }
  444. accounts := []common.Address{testBankAddress, acc1Addr, acc2Addr}
  445. for i := uint64(0); i <= pm.blockchain.CurrentBlock().NumberU64(); i++ {
  446. trie, _ := state.New(pm.blockchain.GetBlockByNumber(i).Root(), statedb)
  447. for j, acc := range accounts {
  448. state, _ := pm.blockchain.State()
  449. bw := state.GetBalance(acc)
  450. bh := trie.GetBalance(acc)
  451. if (bw != nil && bh == nil) || (bw == nil && bh != nil) {
  452. t.Errorf("test %d, account %d: balance mismatch: have %v, want %v", i, j, bh, bw)
  453. }
  454. if bw != nil && bh != nil && bw.Cmp(bw) != 0 {
  455. t.Errorf("test %d, account %d: balance mismatch: have %v, want %v", i, j, bh, bw)
  456. }
  457. }
  458. }
  459. }
  460. // Tests that the transaction receipts can be retrieved based on hashes.
  461. func TestGetReceipt63(t *testing.T) { testGetReceipt(t, 63) }
  462. func TestGetReceipt64(t *testing.T) { testGetReceipt(t, 64) }
  463. func testGetReceipt(t *testing.T, protocol int) {
  464. // Define three accounts to simulate transactions with
  465. acc1Key, _ := crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
  466. acc2Key, _ := crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
  467. acc1Addr := crypto.PubkeyToAddress(acc1Key.PublicKey)
  468. acc2Addr := crypto.PubkeyToAddress(acc2Key.PublicKey)
  469. // Create a chain generator with some simple transactions (blatantly stolen from @fjl/chain_makerts_test)
  470. generator := func(i int, block *core.BlockGen) {
  471. switch i {
  472. case 0:
  473. // In block 1, the test bank sends account #1 some ether.
  474. tx, _ := types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil).SignECDSA(testBankKey)
  475. block.AddTx(tx)
  476. case 1:
  477. // In block 2, the test bank sends some more ether to account #1.
  478. // acc1Addr passes it on to account #2.
  479. tx1, _ := types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(testBankKey)
  480. tx2, _ := types.NewTransaction(block.TxNonce(acc1Addr), acc2Addr, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(acc1Key)
  481. block.AddTx(tx1)
  482. block.AddTx(tx2)
  483. case 2:
  484. // Block 3 is empty but was mined by account #2.
  485. block.SetCoinbase(acc2Addr)
  486. block.SetExtra([]byte("yeehaw"))
  487. case 3:
  488. // Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
  489. b2 := block.PrevBlock(1).Header()
  490. b2.Extra = []byte("foo")
  491. block.AddUncle(b2)
  492. b3 := block.PrevBlock(2).Header()
  493. b3.Extra = []byte("foo")
  494. block.AddUncle(b3)
  495. }
  496. }
  497. // Assemble the test environment
  498. pm := newTestProtocolManagerMust(t, ArchiveMode, 4, generator, nil)
  499. peer, _ := newTestPeer("peer", protocol, pm, true)
  500. defer peer.close()
  501. // Collect the hashes to request, and the response to expect
  502. hashes, receipts := []common.Hash{}, []types.Receipts{}
  503. for i := uint64(0); i <= pm.blockchain.CurrentBlock().NumberU64(); i++ {
  504. block := pm.blockchain.GetBlockByNumber(i)
  505. hashes = append(hashes, block.Hash())
  506. receipts = append(receipts, core.GetBlockReceipts(pm.chaindb, block.Hash()))
  507. }
  508. // Send the hash request and verify the response
  509. p2p.Send(peer.app, 0x0f, hashes)
  510. if err := p2p.ExpectMsg(peer.app, 0x10, receipts); err != nil {
  511. t.Errorf("receipts mismatch: %v", err)
  512. }
  513. }