handler_test.go 21 KB

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