handler_test.go 24 KB

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