handler_test.go 21 KB

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