handler_test.go 21 KB

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