handler_test.go 21 KB

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