handler_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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 that non existing headers aren't returned
  285. {
  286. &getBlockHeadersData{Origin: hashOrNumber{Hash: unknown}, Amount: 1},
  287. []common.Hash{},
  288. }, {
  289. &getBlockHeadersData{Origin: hashOrNumber{Number: pm.blockchain.CurrentBlock().NumberU64() + 1}, Amount: 1},
  290. []common.Hash{},
  291. },
  292. }
  293. // Run each of the tests and verify the results against the chain
  294. for i, tt := range tests {
  295. // Collect the headers to expect in the response
  296. headers := []*types.Header{}
  297. for _, hash := range tt.expect {
  298. headers = append(headers, pm.blockchain.GetBlock(hash).Header())
  299. }
  300. // Send the hash request and verify the response
  301. p2p.Send(peer.app, 0x03, tt.query)
  302. if err := p2p.ExpectMsg(peer.app, 0x04, headers); err != nil {
  303. t.Errorf("test %d: headers mismatch: %v", i, err)
  304. }
  305. }
  306. }
  307. // Tests that block contents can be retrieved from a remote chain based on their hashes.
  308. func TestGetBlockBodies62(t *testing.T) { testGetBlockBodies(t, 62) }
  309. func TestGetBlockBodies63(t *testing.T) { testGetBlockBodies(t, 63) }
  310. func testGetBlockBodies(t *testing.T, protocol int) {
  311. pm := newTestProtocolManagerMust(t, false, downloader.MaxBlockFetch+15, nil, nil)
  312. peer, _ := newTestPeer("peer", protocol, pm, true)
  313. defer peer.close()
  314. // Create a batch of tests for various scenarios
  315. limit := downloader.MaxBlockFetch
  316. tests := []struct {
  317. random int // Number of blocks to fetch randomly from the chain
  318. explicit []common.Hash // Explicitly requested blocks
  319. available []bool // Availability of explicitly requested blocks
  320. expected int // Total number of existing blocks to expect
  321. }{
  322. {1, nil, nil, 1}, // A single random block should be retrievable
  323. {10, nil, nil, 10}, // Multiple random blocks should be retrievable
  324. {limit, nil, nil, limit}, // The maximum possible blocks should be retrievable
  325. {limit + 1, nil, nil, limit}, // No more than the possible block count should be returned
  326. {0, []common.Hash{pm.blockchain.Genesis().Hash()}, []bool{true}, 1}, // The genesis block should be retrievable
  327. {0, []common.Hash{pm.blockchain.CurrentBlock().Hash()}, []bool{true}, 1}, // The chains head block should be retrievable
  328. {0, []common.Hash{common.Hash{}}, []bool{false}, 0}, // A non existent block should not be returned
  329. // Existing and non-existing blocks interleaved should not cause problems
  330. {0, []common.Hash{
  331. common.Hash{},
  332. pm.blockchain.GetBlockByNumber(1).Hash(),
  333. common.Hash{},
  334. pm.blockchain.GetBlockByNumber(10).Hash(),
  335. common.Hash{},
  336. pm.blockchain.GetBlockByNumber(100).Hash(),
  337. common.Hash{},
  338. }, []bool{false, true, false, true, false, true, false}, 3},
  339. }
  340. // Run each of the tests and verify the results against the chain
  341. for i, tt := range tests {
  342. // Collect the hashes to request, and the response to expect
  343. hashes, seen := []common.Hash{}, make(map[int64]bool)
  344. bodies := []*blockBody{}
  345. for j := 0; j < tt.random; j++ {
  346. for {
  347. num := rand.Int63n(int64(pm.blockchain.CurrentBlock().NumberU64()))
  348. if !seen[num] {
  349. seen[num] = true
  350. block := pm.blockchain.GetBlockByNumber(uint64(num))
  351. hashes = append(hashes, block.Hash())
  352. if len(bodies) < tt.expected {
  353. bodies = append(bodies, &blockBody{Transactions: block.Transactions(), Uncles: block.Uncles()})
  354. }
  355. break
  356. }
  357. }
  358. }
  359. for j, hash := range tt.explicit {
  360. hashes = append(hashes, hash)
  361. if tt.available[j] && len(bodies) < tt.expected {
  362. block := pm.blockchain.GetBlock(hash)
  363. bodies = append(bodies, &blockBody{Transactions: block.Transactions(), Uncles: block.Uncles()})
  364. }
  365. }
  366. // Send the hash request and verify the response
  367. p2p.Send(peer.app, 0x05, hashes)
  368. if err := p2p.ExpectMsg(peer.app, 0x06, bodies); err != nil {
  369. t.Errorf("test %d: bodies mismatch: %v", i, err)
  370. }
  371. }
  372. }
  373. // Tests that the node state database can be retrieved based on hashes.
  374. func TestGetNodeData63(t *testing.T) { testGetNodeData(t, 63) }
  375. func testGetNodeData(t *testing.T, protocol int) {
  376. // Define three accounts to simulate transactions with
  377. acc1Key, _ := crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
  378. acc2Key, _ := crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
  379. acc1Addr := crypto.PubkeyToAddress(acc1Key.PublicKey)
  380. acc2Addr := crypto.PubkeyToAddress(acc2Key.PublicKey)
  381. // Create a chain generator with some simple transactions (blatantly stolen from @fjl/chain_makerts_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.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil).SignECDSA(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.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(testBankKey)
  392. tx2, _ := types.NewTransaction(block.TxNonce(acc1Addr), acc2Addr, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(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, false, 4, generator, nil)
  411. peer, _ := newTestPeer("peer", protocol, pm, true)
  412. defer peer.close()
  413. // Fetch for now the entire chain db
  414. hashes := []common.Hash{}
  415. for _, key := range pm.chaindb.(*ethdb.MemDatabase).Keys() {
  416. if len(key) == len(common.Hash{}) {
  417. hashes = append(hashes, common.BytesToHash(key))
  418. }
  419. }
  420. p2p.Send(peer.app, 0x0d, hashes)
  421. msg, err := peer.app.ReadMsg()
  422. if err != nil {
  423. t.Fatalf("failed to read node data response: %v", err)
  424. }
  425. if msg.Code != 0x0e {
  426. t.Fatalf("response packet code mismatch: have %x, want %x", msg.Code, 0x0c)
  427. }
  428. var data [][]byte
  429. if err := msg.Decode(&data); err != nil {
  430. t.Fatalf("failed to decode response node data: %v", err)
  431. }
  432. // Verify that all hashes correspond to the requested data, and reconstruct a state tree
  433. for i, want := range hashes {
  434. if hash := crypto.Sha3Hash(data[i]); hash != want {
  435. fmt.Errorf("data hash mismatch: have %x, want %x", hash, want)
  436. }
  437. }
  438. statedb, _ := ethdb.NewMemDatabase()
  439. for i := 0; i < len(data); i++ {
  440. statedb.Put(hashes[i].Bytes(), data[i])
  441. }
  442. accounts := []common.Address{testBankAddress, acc1Addr, acc2Addr}
  443. for i := uint64(0); i <= pm.blockchain.CurrentBlock().NumberU64(); i++ {
  444. trie, _ := state.New(pm.blockchain.GetBlockByNumber(i).Root(), statedb)
  445. for j, acc := range accounts {
  446. state, _ := pm.blockchain.State()
  447. bw := state.GetBalance(acc)
  448. bh := trie.GetBalance(acc)
  449. if (bw != nil && bh == nil) || (bw == nil && bh != nil) {
  450. t.Errorf("test %d, account %d: balance mismatch: have %v, want %v", i, j, bh, bw)
  451. }
  452. if bw != nil && bh != nil && bw.Cmp(bw) != 0 {
  453. t.Errorf("test %d, account %d: balance mismatch: have %v, want %v", i, j, bh, bw)
  454. }
  455. }
  456. }
  457. }
  458. // Tests that the transaction receipts can be retrieved based on hashes.
  459. func TestGetReceipt63(t *testing.T) { testGetReceipt(t, 63) }
  460. func testGetReceipt(t *testing.T, protocol int) {
  461. // Define three accounts to simulate transactions with
  462. acc1Key, _ := crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
  463. acc2Key, _ := crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
  464. acc1Addr := crypto.PubkeyToAddress(acc1Key.PublicKey)
  465. acc2Addr := crypto.PubkeyToAddress(acc2Key.PublicKey)
  466. // Create a chain generator with some simple transactions (blatantly stolen from @fjl/chain_makerts_test)
  467. generator := func(i int, block *core.BlockGen) {
  468. switch i {
  469. case 0:
  470. // In block 1, the test bank sends account #1 some ether.
  471. tx, _ := types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil).SignECDSA(testBankKey)
  472. block.AddTx(tx)
  473. case 1:
  474. // In block 2, the test bank sends some more ether to account #1.
  475. // acc1Addr passes it on to account #2.
  476. tx1, _ := types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(testBankKey)
  477. tx2, _ := types.NewTransaction(block.TxNonce(acc1Addr), acc2Addr, big.NewInt(1000), params.TxGas, nil, nil).SignECDSA(acc1Key)
  478. block.AddTx(tx1)
  479. block.AddTx(tx2)
  480. case 2:
  481. // Block 3 is empty but was mined by account #2.
  482. block.SetCoinbase(acc2Addr)
  483. block.SetExtra([]byte("yeehaw"))
  484. case 3:
  485. // Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
  486. b2 := block.PrevBlock(1).Header()
  487. b2.Extra = []byte("foo")
  488. block.AddUncle(b2)
  489. b3 := block.PrevBlock(2).Header()
  490. b3.Extra = []byte("foo")
  491. block.AddUncle(b3)
  492. }
  493. }
  494. // Assemble the test environment
  495. pm := newTestProtocolManagerMust(t, false, 4, generator, nil)
  496. peer, _ := newTestPeer("peer", protocol, pm, true)
  497. defer peer.close()
  498. // Collect the hashes to request, and the response to expect
  499. hashes, receipts := []common.Hash{}, []types.Receipts{}
  500. for i := uint64(0); i <= pm.blockchain.CurrentBlock().NumberU64(); i++ {
  501. block := pm.blockchain.GetBlockByNumber(i)
  502. hashes = append(hashes, block.Hash())
  503. receipts = append(receipts, core.GetBlockReceipts(pm.chaindb, block.Hash()))
  504. }
  505. // Send the hash request and verify the response
  506. p2p.Send(peer.app, 0x0f, hashes)
  507. if err := p2p.ExpectMsg(peer.app, 0x10, receipts); err != nil {
  508. t.Errorf("receipts mismatch: %v", err)
  509. }
  510. }