handler_test.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. // Copyright 2016 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 les
  17. import (
  18. "encoding/binary"
  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/rawdb"
  27. "github.com/ethereum/go-ethereum/core/types"
  28. "github.com/ethereum/go-ethereum/crypto"
  29. "github.com/ethereum/go-ethereum/eth/downloader"
  30. "github.com/ethereum/go-ethereum/light"
  31. "github.com/ethereum/go-ethereum/p2p"
  32. "github.com/ethereum/go-ethereum/params"
  33. "github.com/ethereum/go-ethereum/rlp"
  34. "github.com/ethereum/go-ethereum/trie"
  35. )
  36. func expectResponse(r p2p.MsgReader, msgcode, reqID, bv uint64, data interface{}) error {
  37. type resp struct {
  38. ReqID, BV uint64
  39. Data interface{}
  40. }
  41. return p2p.ExpectMsg(r, msgcode, resp{reqID, bv, data})
  42. }
  43. // Tests that block headers can be retrieved from a remote chain based on user queries.
  44. func TestGetBlockHeadersLes2(t *testing.T) { testGetBlockHeaders(t, 2) }
  45. func testGetBlockHeaders(t *testing.T, protocol int) {
  46. server, tearDown := newServerEnv(t, downloader.MaxHashFetch+15, protocol, nil)
  47. defer tearDown()
  48. bc := server.pm.blockchain.(*core.BlockChain)
  49. // Create a "random" unknown hash for testing
  50. var unknown common.Hash
  51. for i := range unknown {
  52. unknown[i] = byte(i)
  53. }
  54. // Create a batch of tests for various scenarios
  55. limit := uint64(MaxHeaderFetch)
  56. tests := []struct {
  57. query *getBlockHeadersData // The query to execute for header retrieval
  58. expect []common.Hash // The hashes of the block whose headers are expected
  59. }{
  60. // A single random block should be retrievable by hash and number too
  61. {
  62. &getBlockHeadersData{Origin: hashOrNumber{Hash: bc.GetBlockByNumber(limit / 2).Hash()}, Amount: 1},
  63. []common.Hash{bc.GetBlockByNumber(limit / 2).Hash()},
  64. }, {
  65. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 1},
  66. []common.Hash{bc.GetBlockByNumber(limit / 2).Hash()},
  67. },
  68. // Multiple headers should be retrievable in both directions
  69. {
  70. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 3},
  71. []common.Hash{
  72. bc.GetBlockByNumber(limit / 2).Hash(),
  73. bc.GetBlockByNumber(limit/2 + 1).Hash(),
  74. bc.GetBlockByNumber(limit/2 + 2).Hash(),
  75. },
  76. }, {
  77. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 3, Reverse: true},
  78. []common.Hash{
  79. bc.GetBlockByNumber(limit / 2).Hash(),
  80. bc.GetBlockByNumber(limit/2 - 1).Hash(),
  81. bc.GetBlockByNumber(limit/2 - 2).Hash(),
  82. },
  83. },
  84. // Multiple headers with skip lists should be retrievable
  85. {
  86. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Skip: 3, Amount: 3},
  87. []common.Hash{
  88. bc.GetBlockByNumber(limit / 2).Hash(),
  89. bc.GetBlockByNumber(limit/2 + 4).Hash(),
  90. bc.GetBlockByNumber(limit/2 + 8).Hash(),
  91. },
  92. }, {
  93. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Skip: 3, Amount: 3, Reverse: true},
  94. []common.Hash{
  95. bc.GetBlockByNumber(limit / 2).Hash(),
  96. bc.GetBlockByNumber(limit/2 - 4).Hash(),
  97. bc.GetBlockByNumber(limit/2 - 8).Hash(),
  98. },
  99. },
  100. // The chain endpoints should be retrievable
  101. {
  102. &getBlockHeadersData{Origin: hashOrNumber{Number: 0}, Amount: 1},
  103. []common.Hash{bc.GetBlockByNumber(0).Hash()},
  104. }, {
  105. &getBlockHeadersData{Origin: hashOrNumber{Number: bc.CurrentBlock().NumberU64()}, Amount: 1},
  106. []common.Hash{bc.CurrentBlock().Hash()},
  107. },
  108. // Ensure protocol limits are honored
  109. /*{
  110. &getBlockHeadersData{Origin: hashOrNumber{Number: bc.CurrentBlock().NumberU64() - 1}, Amount: limit + 10, Reverse: true},
  111. bc.GetBlockHashesFromHash(bc.CurrentBlock().Hash(), limit),
  112. },*/
  113. // Check that requesting more than available is handled gracefully
  114. {
  115. &getBlockHeadersData{Origin: hashOrNumber{Number: bc.CurrentBlock().NumberU64() - 4}, Skip: 3, Amount: 3},
  116. []common.Hash{
  117. bc.GetBlockByNumber(bc.CurrentBlock().NumberU64() - 4).Hash(),
  118. bc.GetBlockByNumber(bc.CurrentBlock().NumberU64()).Hash(),
  119. },
  120. }, {
  121. &getBlockHeadersData{Origin: hashOrNumber{Number: 4}, Skip: 3, Amount: 3, Reverse: true},
  122. []common.Hash{
  123. bc.GetBlockByNumber(4).Hash(),
  124. bc.GetBlockByNumber(0).Hash(),
  125. },
  126. },
  127. // Check that requesting more than available is handled gracefully, even if mid skip
  128. {
  129. &getBlockHeadersData{Origin: hashOrNumber{Number: bc.CurrentBlock().NumberU64() - 4}, Skip: 2, Amount: 3},
  130. []common.Hash{
  131. bc.GetBlockByNumber(bc.CurrentBlock().NumberU64() - 4).Hash(),
  132. bc.GetBlockByNumber(bc.CurrentBlock().NumberU64() - 1).Hash(),
  133. },
  134. }, {
  135. &getBlockHeadersData{Origin: hashOrNumber{Number: 4}, Skip: 2, Amount: 3, Reverse: true},
  136. []common.Hash{
  137. bc.GetBlockByNumber(4).Hash(),
  138. bc.GetBlockByNumber(1).Hash(),
  139. },
  140. },
  141. // Check that non existing headers aren't returned
  142. {
  143. &getBlockHeadersData{Origin: hashOrNumber{Hash: unknown}, Amount: 1},
  144. []common.Hash{},
  145. }, {
  146. &getBlockHeadersData{Origin: hashOrNumber{Number: bc.CurrentBlock().NumberU64() + 1}, Amount: 1},
  147. []common.Hash{},
  148. },
  149. }
  150. // Run each of the tests and verify the results against the chain
  151. var reqID uint64
  152. for i, tt := range tests {
  153. // Collect the headers to expect in the response
  154. headers := []*types.Header{}
  155. for _, hash := range tt.expect {
  156. headers = append(headers, bc.GetHeaderByHash(hash))
  157. }
  158. // Send the hash request and verify the response
  159. reqID++
  160. cost := server.tPeer.GetRequestCost(GetBlockHeadersMsg, int(tt.query.Amount))
  161. sendRequest(server.tPeer.app, GetBlockHeadersMsg, reqID, cost, tt.query)
  162. if err := expectResponse(server.tPeer.app, BlockHeadersMsg, reqID, testBufLimit, headers); err != nil {
  163. t.Errorf("test %d: headers mismatch: %v", i, err)
  164. }
  165. }
  166. }
  167. // Tests that block contents can be retrieved from a remote chain based on their hashes.
  168. func TestGetBlockBodiesLes2(t *testing.T) { testGetBlockBodies(t, 2) }
  169. func testGetBlockBodies(t *testing.T, protocol int) {
  170. server, tearDown := newServerEnv(t, downloader.MaxBlockFetch+15, protocol, nil)
  171. defer tearDown()
  172. bc := server.pm.blockchain.(*core.BlockChain)
  173. // Create a batch of tests for various scenarios
  174. limit := MaxBodyFetch
  175. tests := []struct {
  176. random int // Number of blocks to fetch randomly from the chain
  177. explicit []common.Hash // Explicitly requested blocks
  178. available []bool // Availability of explicitly requested blocks
  179. expected int // Total number of existing blocks to expect
  180. }{
  181. {1, nil, nil, 1}, // A single random block should be retrievable
  182. {10, nil, nil, 10}, // Multiple random blocks should be retrievable
  183. {limit, nil, nil, limit}, // The maximum possible blocks should be retrievable
  184. //{limit + 1, nil, nil, limit}, // No more than the possible block count should be returned
  185. {0, []common.Hash{bc.Genesis().Hash()}, []bool{true}, 1}, // The genesis block should be retrievable
  186. {0, []common.Hash{bc.CurrentBlock().Hash()}, []bool{true}, 1}, // The chains head block should be retrievable
  187. {0, []common.Hash{{}}, []bool{false}, 0}, // A non existent block should not be returned
  188. // Existing and non-existing blocks interleaved should not cause problems
  189. {0, []common.Hash{
  190. {},
  191. bc.GetBlockByNumber(1).Hash(),
  192. {},
  193. bc.GetBlockByNumber(10).Hash(),
  194. {},
  195. bc.GetBlockByNumber(100).Hash(),
  196. {},
  197. }, []bool{false, true, false, true, false, true, false}, 3},
  198. }
  199. // Run each of the tests and verify the results against the chain
  200. var reqID uint64
  201. for i, tt := range tests {
  202. // Collect the hashes to request, and the response to expect
  203. hashes, seen := []common.Hash{}, make(map[int64]bool)
  204. bodies := []*types.Body{}
  205. for j := 0; j < tt.random; j++ {
  206. for {
  207. num := rand.Int63n(int64(bc.CurrentBlock().NumberU64()))
  208. if !seen[num] {
  209. seen[num] = true
  210. block := bc.GetBlockByNumber(uint64(num))
  211. hashes = append(hashes, block.Hash())
  212. if len(bodies) < tt.expected {
  213. bodies = append(bodies, &types.Body{Transactions: block.Transactions(), Uncles: block.Uncles()})
  214. }
  215. break
  216. }
  217. }
  218. }
  219. for j, hash := range tt.explicit {
  220. hashes = append(hashes, hash)
  221. if tt.available[j] && len(bodies) < tt.expected {
  222. block := bc.GetBlockByHash(hash)
  223. bodies = append(bodies, &types.Body{Transactions: block.Transactions(), Uncles: block.Uncles()})
  224. }
  225. }
  226. reqID++
  227. // Send the hash request and verify the response
  228. cost := server.tPeer.GetRequestCost(GetBlockBodiesMsg, len(hashes))
  229. sendRequest(server.tPeer.app, GetBlockBodiesMsg, reqID, cost, hashes)
  230. if err := expectResponse(server.tPeer.app, BlockBodiesMsg, reqID, testBufLimit, bodies); err != nil {
  231. t.Errorf("test %d: bodies mismatch: %v", i, err)
  232. }
  233. }
  234. }
  235. // Tests that the contract codes can be retrieved based on account addresses.
  236. func TestGetCodeLes2(t *testing.T) { testGetCode(t, 2) }
  237. func testGetCode(t *testing.T, protocol int) {
  238. // Assemble the test environment
  239. server, tearDown := newServerEnv(t, 4, protocol, nil)
  240. defer tearDown()
  241. bc := server.pm.blockchain.(*core.BlockChain)
  242. var codereqs []*CodeReq
  243. var codes [][]byte
  244. for i := uint64(0); i <= bc.CurrentBlock().NumberU64(); i++ {
  245. header := bc.GetHeaderByNumber(i)
  246. req := &CodeReq{
  247. BHash: header.Hash(),
  248. AccKey: crypto.Keccak256(testContractAddr[:]),
  249. }
  250. codereqs = append(codereqs, req)
  251. if i >= testContractDeployed {
  252. codes = append(codes, testContractCodeDeployed)
  253. }
  254. }
  255. cost := server.tPeer.GetRequestCost(GetCodeMsg, len(codereqs))
  256. sendRequest(server.tPeer.app, GetCodeMsg, 42, cost, codereqs)
  257. if err := expectResponse(server.tPeer.app, CodeMsg, 42, testBufLimit, codes); err != nil {
  258. t.Errorf("codes mismatch: %v", err)
  259. }
  260. }
  261. // Tests that the transaction receipts can be retrieved based on hashes.
  262. func TestGetReceiptLes2(t *testing.T) { testGetReceipt(t, 2) }
  263. func testGetReceipt(t *testing.T, protocol int) {
  264. // Assemble the test environment
  265. server, tearDown := newServerEnv(t, 4, protocol, nil)
  266. defer tearDown()
  267. bc := server.pm.blockchain.(*core.BlockChain)
  268. // Collect the hashes to request, and the response to expect
  269. hashes, receipts := []common.Hash{}, []types.Receipts{}
  270. for i := uint64(0); i <= bc.CurrentBlock().NumberU64(); i++ {
  271. block := bc.GetBlockByNumber(i)
  272. hashes = append(hashes, block.Hash())
  273. receipts = append(receipts, rawdb.ReadRawReceipts(server.db, block.Hash(), block.NumberU64()))
  274. }
  275. // Send the hash request and verify the response
  276. cost := server.tPeer.GetRequestCost(GetReceiptsMsg, len(hashes))
  277. sendRequest(server.tPeer.app, GetReceiptsMsg, 42, cost, hashes)
  278. if err := expectResponse(server.tPeer.app, ReceiptsMsg, 42, testBufLimit, receipts); err != nil {
  279. t.Errorf("receipts mismatch: %v", err)
  280. }
  281. }
  282. // Tests that trie merkle proofs can be retrieved
  283. func TestGetProofsLes2(t *testing.T) { testGetProofs(t, 2) }
  284. func testGetProofs(t *testing.T, protocol int) {
  285. // Assemble the test environment
  286. server, tearDown := newServerEnv(t, 4, protocol, nil)
  287. defer tearDown()
  288. bc := server.pm.blockchain.(*core.BlockChain)
  289. var proofreqs []ProofReq
  290. proofsV2 := light.NewNodeSet()
  291. accounts := []common.Address{testBankAddress, acc1Addr, acc2Addr, {}}
  292. for i := uint64(0); i <= bc.CurrentBlock().NumberU64(); i++ {
  293. header := bc.GetHeaderByNumber(i)
  294. root := header.Root
  295. trie, _ := trie.New(root, trie.NewDatabase(server.db))
  296. for _, acc := range accounts {
  297. req := ProofReq{
  298. BHash: header.Hash(),
  299. Key: crypto.Keccak256(acc[:]),
  300. }
  301. proofreqs = append(proofreqs, req)
  302. trie.Prove(crypto.Keccak256(acc[:]), 0, proofsV2)
  303. }
  304. }
  305. // Send the proof request and verify the response
  306. cost := server.tPeer.GetRequestCost(GetProofsV2Msg, len(proofreqs))
  307. sendRequest(server.tPeer.app, GetProofsV2Msg, 42, cost, proofreqs)
  308. if err := expectResponse(server.tPeer.app, ProofsV2Msg, 42, testBufLimit, proofsV2.NodeList()); err != nil {
  309. t.Errorf("proofs mismatch: %v", err)
  310. }
  311. }
  312. // Tests that CHT proofs can be correctly retrieved.
  313. func TestGetCHTProofsLes2(t *testing.T) { testGetCHTProofs(t, 2) }
  314. func testGetCHTProofs(t *testing.T, protocol int) {
  315. config := light.TestServerIndexerConfig
  316. waitIndexers := func(cIndexer, bIndexer, btIndexer *core.ChainIndexer) {
  317. for {
  318. cs, _, _ := cIndexer.Sections()
  319. if cs >= 1 {
  320. break
  321. }
  322. time.Sleep(10 * time.Millisecond)
  323. }
  324. }
  325. server, tearDown := newServerEnv(t, int(config.ChtSize+config.ChtConfirms), protocol, waitIndexers)
  326. defer tearDown()
  327. bc := server.pm.blockchain.(*core.BlockChain)
  328. // Assemble the proofs from the different protocols
  329. header := bc.GetHeaderByNumber(config.ChtSize - 1)
  330. rlp, _ := rlp.EncodeToBytes(header)
  331. key := make([]byte, 8)
  332. binary.BigEndian.PutUint64(key, config.ChtSize-1)
  333. proofsV2 := HelperTrieResps{
  334. AuxData: [][]byte{rlp},
  335. }
  336. root := light.GetChtRoot(server.db, 0, bc.GetHeaderByNumber(config.ChtSize-1).Hash())
  337. trie, _ := trie.New(root, trie.NewDatabase(rawdb.NewTable(server.db, light.ChtTablePrefix)))
  338. trie.Prove(key, 0, &proofsV2.Proofs)
  339. // Assemble the requests for the different protocols
  340. requestsV2 := []HelperTrieReq{{
  341. Type: htCanonical,
  342. TrieIdx: 0,
  343. Key: key,
  344. AuxReq: auxHeader,
  345. }}
  346. // Send the proof request and verify the response
  347. cost := server.tPeer.GetRequestCost(GetHelperTrieProofsMsg, len(requestsV2))
  348. sendRequest(server.tPeer.app, GetHelperTrieProofsMsg, 42, cost, requestsV2)
  349. if err := expectResponse(server.tPeer.app, HelperTrieProofsMsg, 42, testBufLimit, proofsV2); err != nil {
  350. t.Errorf("proofs mismatch: %v", err)
  351. }
  352. }
  353. // Tests that bloombits proofs can be correctly retrieved.
  354. func TestGetBloombitsProofs(t *testing.T) {
  355. config := light.TestServerIndexerConfig
  356. waitIndexers := func(cIndexer, bIndexer, btIndexer *core.ChainIndexer) {
  357. for {
  358. bts, _, _ := btIndexer.Sections()
  359. if bts >= 1 {
  360. break
  361. }
  362. time.Sleep(10 * time.Millisecond)
  363. }
  364. }
  365. server, tearDown := newServerEnv(t, int(config.BloomTrieSize+config.BloomTrieConfirms), 2, waitIndexers)
  366. defer tearDown()
  367. bc := server.pm.blockchain.(*core.BlockChain)
  368. // Request and verify each bit of the bloom bits proofs
  369. for bit := 0; bit < 2048; bit++ {
  370. // Assemble the request and proofs for the bloombits
  371. key := make([]byte, 10)
  372. binary.BigEndian.PutUint16(key[:2], uint16(bit))
  373. // Only the first bloom section has data.
  374. binary.BigEndian.PutUint64(key[2:], 0)
  375. requests := []HelperTrieReq{{
  376. Type: htBloomBits,
  377. TrieIdx: 0,
  378. Key: key,
  379. }}
  380. var proofs HelperTrieResps
  381. root := light.GetBloomTrieRoot(server.db, 0, bc.GetHeaderByNumber(config.BloomTrieSize-1).Hash())
  382. trie, _ := trie.New(root, trie.NewDatabase(rawdb.NewTable(server.db, light.BloomTrieTablePrefix)))
  383. trie.Prove(key, 0, &proofs.Proofs)
  384. // Send the proof request and verify the response
  385. cost := server.tPeer.GetRequestCost(GetHelperTrieProofsMsg, len(requests))
  386. sendRequest(server.tPeer.app, GetHelperTrieProofsMsg, 42, cost, requests)
  387. if err := expectResponse(server.tPeer.app, HelperTrieProofsMsg, 42, testBufLimit, proofs); err != nil {
  388. t.Errorf("bit %d: proofs mismatch: %v", bit, err)
  389. }
  390. }
  391. }
  392. func TestTransactionStatusLes2(t *testing.T) {
  393. db := rawdb.NewMemoryDatabase()
  394. pm := newTestProtocolManagerMust(t, false, 0, nil, nil, nil, db, nil)
  395. chain := pm.blockchain.(*core.BlockChain)
  396. config := core.DefaultTxPoolConfig
  397. config.Journal = ""
  398. txpool := core.NewTxPool(config, params.TestChainConfig, chain)
  399. pm.txpool = txpool
  400. peer, _ := newTestPeer(t, "peer", 2, pm, true)
  401. defer peer.close()
  402. var reqID uint64
  403. test := func(tx *types.Transaction, send bool, expStatus txStatus) {
  404. reqID++
  405. if send {
  406. cost := peer.GetRequestCost(SendTxV2Msg, 1)
  407. sendRequest(peer.app, SendTxV2Msg, reqID, cost, types.Transactions{tx})
  408. } else {
  409. cost := peer.GetRequestCost(GetTxStatusMsg, 1)
  410. sendRequest(peer.app, GetTxStatusMsg, reqID, cost, []common.Hash{tx.Hash()})
  411. }
  412. if err := expectResponse(peer.app, TxStatusMsg, reqID, testBufLimit, []txStatus{expStatus}); err != nil {
  413. t.Errorf("transaction status mismatch")
  414. }
  415. }
  416. signer := types.HomesteadSigner{}
  417. // test error status by sending an underpriced transaction
  418. tx0, _ := types.SignTx(types.NewTransaction(0, acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, testBankKey)
  419. test(tx0, true, txStatus{Status: core.TxStatusUnknown, Error: core.ErrUnderpriced.Error()})
  420. tx1, _ := types.SignTx(types.NewTransaction(0, acc1Addr, big.NewInt(10000), params.TxGas, big.NewInt(100000000000), nil), signer, testBankKey)
  421. test(tx1, false, txStatus{Status: core.TxStatusUnknown}) // query before sending, should be unknown
  422. test(tx1, true, txStatus{Status: core.TxStatusPending}) // send valid processable tx, should return pending
  423. test(tx1, true, txStatus{Status: core.TxStatusPending}) // adding it again should not return an error
  424. tx2, _ := types.SignTx(types.NewTransaction(1, acc1Addr, big.NewInt(10000), params.TxGas, big.NewInt(100000000000), nil), signer, testBankKey)
  425. tx3, _ := types.SignTx(types.NewTransaction(2, acc1Addr, big.NewInt(10000), params.TxGas, big.NewInt(100000000000), nil), signer, testBankKey)
  426. // send transactions in the wrong order, tx3 should be queued
  427. test(tx3, true, txStatus{Status: core.TxStatusQueued})
  428. test(tx2, true, txStatus{Status: core.TxStatusPending})
  429. // query again, now tx3 should be pending too
  430. test(tx3, false, txStatus{Status: core.TxStatusPending})
  431. // generate and add a block with tx1 and tx2 included
  432. gchain, _ := core.GenerateChain(params.TestChainConfig, chain.GetBlockByNumber(0), ethash.NewFaker(), db, 1, func(i int, block *core.BlockGen) {
  433. block.AddTx(tx1)
  434. block.AddTx(tx2)
  435. })
  436. if _, err := chain.InsertChain(gchain); err != nil {
  437. panic(err)
  438. }
  439. // wait until TxPool processes the inserted block
  440. for i := 0; i < 10; i++ {
  441. if pending, _ := txpool.Stats(); pending == 1 {
  442. break
  443. }
  444. time.Sleep(100 * time.Millisecond)
  445. }
  446. if pending, _ := txpool.Stats(); pending != 1 {
  447. t.Fatalf("pending count mismatch: have %d, want 1", pending)
  448. }
  449. // check if their status is included now
  450. block1hash := rawdb.ReadCanonicalHash(db, 1)
  451. test(tx1, false, txStatus{Status: core.TxStatusIncluded, Lookup: &rawdb.LegacyTxLookupEntry{BlockHash: block1hash, BlockIndex: 1, Index: 0}})
  452. test(tx2, false, txStatus{Status: core.TxStatusIncluded, Lookup: &rawdb.LegacyTxLookupEntry{BlockHash: block1hash, BlockIndex: 1, Index: 1}})
  453. // create a reorg that rolls them back
  454. gchain, _ = core.GenerateChain(params.TestChainConfig, chain.GetBlockByNumber(0), ethash.NewFaker(), db, 2, func(i int, block *core.BlockGen) {})
  455. if _, err := chain.InsertChain(gchain); err != nil {
  456. panic(err)
  457. }
  458. // wait until TxPool processes the reorg
  459. for i := 0; i < 10; i++ {
  460. if pending, _ := txpool.Stats(); pending == 3 {
  461. break
  462. }
  463. time.Sleep(100 * time.Millisecond)
  464. }
  465. if pending, _ := txpool.Stats(); pending != 3 {
  466. t.Fatalf("pending count mismatch: have %d, want 3", pending)
  467. }
  468. // check if their status is pending again
  469. test(tx1, false, txStatus{Status: core.TxStatusPending})
  470. test(tx2, false, txStatus{Status: core.TxStatusPending})
  471. }