handler_test.go 21 KB

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