handler_test.go 23 KB

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