handler_test.go 21 KB

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