handler_test.go 27 KB

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