handler_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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.ReadReceipts(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. frequency := config.ChtSize
  317. if protocol == 2 { //qqq
  318. frequency = config.PairChtSize
  319. }
  320. waitIndexers := func(cIndexer, bIndexer, btIndexer *core.ChainIndexer) {
  321. expectSections := frequency / config.ChtSize
  322. for {
  323. cs, _, _ := cIndexer.Sections()
  324. bs, _, _ := bIndexer.Sections()
  325. if cs >= expectSections && bs >= expectSections {
  326. break
  327. }
  328. time.Sleep(10 * time.Millisecond)
  329. }
  330. }
  331. server, tearDown := newServerEnv(t, int(frequency+config.ChtConfirms), protocol, waitIndexers)
  332. defer tearDown()
  333. bc := server.pm.blockchain.(*core.BlockChain)
  334. // Assemble the proofs from the different protocols
  335. header := bc.GetHeaderByNumber(frequency - 1)
  336. rlp, _ := rlp.EncodeToBytes(header)
  337. key := make([]byte, 8)
  338. binary.BigEndian.PutUint64(key, frequency-1)
  339. proofsV2 := HelperTrieResps{
  340. AuxData: [][]byte{rlp},
  341. }
  342. root := light.GetChtRoot(server.db, (frequency/config.ChtSize)-1, bc.GetHeaderByNumber(frequency-1).Hash())
  343. trie, _ := trie.New(root, trie.NewDatabase(rawdb.NewTable(server.db, light.ChtTablePrefix)))
  344. trie.Prove(key, 0, &proofsV2.Proofs)
  345. // Assemble the requests for the different protocols
  346. requestsV2 := []HelperTrieReq{{
  347. Type: htCanonical,
  348. TrieIdx: frequency/config.PairChtSize - 1,
  349. Key: key,
  350. AuxReq: auxHeader,
  351. }}
  352. // Send the proof request and verify the response
  353. cost := server.tPeer.GetRequestCost(GetHelperTrieProofsMsg, len(requestsV2))
  354. sendRequest(server.tPeer.app, GetHelperTrieProofsMsg, 42, cost, requestsV2)
  355. if err := expectResponse(server.tPeer.app, HelperTrieProofsMsg, 42, testBufLimit, proofsV2); err != nil {
  356. t.Errorf("proofs mismatch: %v", err)
  357. }
  358. }
  359. // Tests that bloombits proofs can be correctly retrieved.
  360. func TestGetBloombitsProofs(t *testing.T) {
  361. config := light.TestServerIndexerConfig
  362. waitIndexers := func(cIndexer, bIndexer, btIndexer *core.ChainIndexer) {
  363. for {
  364. cs, _, _ := cIndexer.Sections()
  365. bs, _, _ := bIndexer.Sections()
  366. bts, _, _ := btIndexer.Sections()
  367. if cs >= 8 && bs >= 8 && bts >= 1 {
  368. break
  369. }
  370. time.Sleep(10 * time.Millisecond)
  371. }
  372. }
  373. server, tearDown := newServerEnv(t, int(config.BloomTrieSize+config.BloomTrieConfirms), 2, waitIndexers)
  374. defer tearDown()
  375. bc := server.pm.blockchain.(*core.BlockChain)
  376. // Request and verify each bit of the bloom bits proofs
  377. for bit := 0; bit < 2048; bit++ {
  378. // Assemble the request and proofs for the bloombits
  379. key := make([]byte, 10)
  380. binary.BigEndian.PutUint16(key[:2], uint16(bit))
  381. // Only the first bloom section has data.
  382. binary.BigEndian.PutUint64(key[2:], 0)
  383. requests := []HelperTrieReq{{
  384. Type: htBloomBits,
  385. TrieIdx: 0,
  386. Key: key,
  387. }}
  388. var proofs HelperTrieResps
  389. root := light.GetBloomTrieRoot(server.db, 0, bc.GetHeaderByNumber(config.BloomTrieSize-1).Hash())
  390. trie, _ := trie.New(root, trie.NewDatabase(rawdb.NewTable(server.db, light.BloomTrieTablePrefix)))
  391. trie.Prove(key, 0, &proofs.Proofs)
  392. // Send the proof request and verify the response
  393. cost := server.tPeer.GetRequestCost(GetHelperTrieProofsMsg, len(requests))
  394. sendRequest(server.tPeer.app, GetHelperTrieProofsMsg, 42, cost, requests)
  395. if err := expectResponse(server.tPeer.app, HelperTrieProofsMsg, 42, testBufLimit, proofs); err != nil {
  396. t.Errorf("bit %d: proofs mismatch: %v", bit, err)
  397. }
  398. }
  399. }
  400. func TestTransactionStatusLes2(t *testing.T) {
  401. db := rawdb.NewMemoryDatabase()
  402. pm := newTestProtocolManagerMust(t, false, 0, nil, nil, nil, db, nil)
  403. chain := pm.blockchain.(*core.BlockChain)
  404. config := core.DefaultTxPoolConfig
  405. config.Journal = ""
  406. txpool := core.NewTxPool(config, params.TestChainConfig, chain)
  407. pm.txpool = txpool
  408. peer, _ := newTestPeer(t, "peer", 2, pm, true)
  409. defer peer.close()
  410. var reqID uint64
  411. test := func(tx *types.Transaction, send bool, expStatus txStatus) {
  412. reqID++
  413. if send {
  414. cost := peer.GetRequestCost(SendTxV2Msg, 1)
  415. sendRequest(peer.app, SendTxV2Msg, reqID, cost, types.Transactions{tx})
  416. } else {
  417. cost := peer.GetRequestCost(GetTxStatusMsg, 1)
  418. sendRequest(peer.app, GetTxStatusMsg, reqID, cost, []common.Hash{tx.Hash()})
  419. }
  420. if err := expectResponse(peer.app, TxStatusMsg, reqID, testBufLimit, []txStatus{expStatus}); err != nil {
  421. t.Errorf("transaction status mismatch")
  422. }
  423. }
  424. signer := types.HomesteadSigner{}
  425. // test error status by sending an underpriced transaction
  426. tx0, _ := types.SignTx(types.NewTransaction(0, acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, testBankKey)
  427. test(tx0, true, txStatus{Status: core.TxStatusUnknown, Error: core.ErrUnderpriced.Error()})
  428. tx1, _ := types.SignTx(types.NewTransaction(0, acc1Addr, big.NewInt(10000), params.TxGas, big.NewInt(100000000000), nil), signer, testBankKey)
  429. test(tx1, false, txStatus{Status: core.TxStatusUnknown}) // query before sending, should be unknown
  430. test(tx1, true, txStatus{Status: core.TxStatusPending}) // send valid processable tx, should return pending
  431. test(tx1, true, txStatus{Status: core.TxStatusPending}) // adding it again should not return an error
  432. tx2, _ := types.SignTx(types.NewTransaction(1, acc1Addr, big.NewInt(10000), params.TxGas, big.NewInt(100000000000), nil), signer, testBankKey)
  433. tx3, _ := types.SignTx(types.NewTransaction(2, acc1Addr, big.NewInt(10000), params.TxGas, big.NewInt(100000000000), nil), signer, testBankKey)
  434. // send transactions in the wrong order, tx3 should be queued
  435. test(tx3, true, txStatus{Status: core.TxStatusQueued})
  436. test(tx2, true, txStatus{Status: core.TxStatusPending})
  437. // query again, now tx3 should be pending too
  438. test(tx3, false, txStatus{Status: core.TxStatusPending})
  439. // generate and add a block with tx1 and tx2 included
  440. gchain, _ := core.GenerateChain(params.TestChainConfig, chain.GetBlockByNumber(0), ethash.NewFaker(), db, 1, func(i int, block *core.BlockGen) {
  441. block.AddTx(tx1)
  442. block.AddTx(tx2)
  443. })
  444. if _, err := chain.InsertChain(gchain); err != nil {
  445. panic(err)
  446. }
  447. // wait until TxPool processes the inserted block
  448. for i := 0; i < 10; i++ {
  449. if pending, _ := txpool.Stats(); pending == 1 {
  450. break
  451. }
  452. time.Sleep(100 * time.Millisecond)
  453. }
  454. if pending, _ := txpool.Stats(); pending != 1 {
  455. t.Fatalf("pending count mismatch: have %d, want 1", pending)
  456. }
  457. // check if their status is included now
  458. block1hash := rawdb.ReadCanonicalHash(db, 1)
  459. test(tx1, false, txStatus{Status: core.TxStatusIncluded, Lookup: &rawdb.LegacyTxLookupEntry{BlockHash: block1hash, BlockIndex: 1, Index: 0}})
  460. test(tx2, false, txStatus{Status: core.TxStatusIncluded, Lookup: &rawdb.LegacyTxLookupEntry{BlockHash: block1hash, BlockIndex: 1, Index: 1}})
  461. // create a reorg that rolls them back
  462. gchain, _ = core.GenerateChain(params.TestChainConfig, chain.GetBlockByNumber(0), ethash.NewFaker(), db, 2, func(i int, block *core.BlockGen) {})
  463. if _, err := chain.InsertChain(gchain); err != nil {
  464. panic(err)
  465. }
  466. // wait until TxPool processes the reorg
  467. for i := 0; i < 10; i++ {
  468. if pending, _ := txpool.Stats(); pending == 3 {
  469. break
  470. }
  471. time.Sleep(100 * time.Millisecond)
  472. }
  473. if pending, _ := txpool.Stats(); pending != 3 {
  474. t.Fatalf("pending count mismatch: have %d, want 3", pending)
  475. }
  476. // check if their status is pending again
  477. test(tx1, false, txStatus{Status: core.TxStatusPending})
  478. test(tx2, false, txStatus{Status: core.TxStatusPending})
  479. }