handler_test.go 22 KB

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