handler_test.go 24 KB

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