handler_test.go 20 KB

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