handler_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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/common/mclock"
  25. "github.com/ethereum/go-ethereum/consensus/ethash"
  26. "github.com/ethereum/go-ethereum/core"
  27. "github.com/ethereum/go-ethereum/core/rawdb"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/crypto"
  30. "github.com/ethereum/go-ethereum/eth/downloader"
  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 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. var 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 TestGetBlockBodiesLes2(t *testing.T) { testGetBlockBodies(t, 2) }
  170. func testGetBlockBodies(t *testing.T, protocol int) {
  171. server, tearDown := newServerEnv(t, downloader.MaxBlockFetch+15, protocol, nil)
  172. defer tearDown()
  173. bc := server.pm.blockchain.(*core.BlockChain)
  174. // Create a batch of tests for various scenarios
  175. limit := MaxBodyFetch
  176. tests := []struct {
  177. random int // Number of blocks to fetch randomly from the chain
  178. explicit []common.Hash // Explicitly requested blocks
  179. available []bool // Availability of explicitly requested blocks
  180. expected int // Total number of existing blocks to expect
  181. }{
  182. {1, nil, nil, 1}, // A single random block should be retrievable
  183. {10, nil, nil, 10}, // Multiple random blocks should be retrievable
  184. {limit, nil, nil, limit}, // The maximum possible blocks should be retrievable
  185. //{limit + 1, nil, nil, limit}, // No more than the possible block count should be returned
  186. {0, []common.Hash{bc.Genesis().Hash()}, []bool{true}, 1}, // The genesis block should be retrievable
  187. {0, []common.Hash{bc.CurrentBlock().Hash()}, []bool{true}, 1}, // The chains head block should be retrievable
  188. {0, []common.Hash{{}}, []bool{false}, 0}, // A non existent block should not be returned
  189. // Existing and non-existing blocks interleaved should not cause problems
  190. {0, []common.Hash{
  191. {},
  192. bc.GetBlockByNumber(1).Hash(),
  193. {},
  194. bc.GetBlockByNumber(10).Hash(),
  195. {},
  196. bc.GetBlockByNumber(100).Hash(),
  197. {},
  198. }, []bool{false, true, false, true, false, true, false}, 3},
  199. }
  200. // Run each of the tests and verify the results against the chain
  201. var reqID uint64
  202. for i, tt := range tests {
  203. // Collect the hashes to request, and the response to expect
  204. var hashes []common.Hash
  205. seen := make(map[int64]bool)
  206. var 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 TestGetCodeLes2(t *testing.T) { testGetCode(t, 2) }
  239. func testGetCode(t *testing.T, protocol int) {
  240. // Assemble the test environment
  241. server, tearDown := newServerEnv(t, 4, protocol, nil)
  242. defer tearDown()
  243. bc := server.pm.blockchain.(*core.BlockChain)
  244. var codereqs []*CodeReq
  245. var codes [][]byte
  246. for i := uint64(0); i <= bc.CurrentBlock().NumberU64(); i++ {
  247. header := bc.GetHeaderByNumber(i)
  248. req := &CodeReq{
  249. BHash: header.Hash(),
  250. AccKey: crypto.Keccak256(testContractAddr[:]),
  251. }
  252. codereqs = append(codereqs, req)
  253. if i >= testContractDeployed {
  254. codes = append(codes, testContractCodeDeployed)
  255. }
  256. }
  257. cost := server.tPeer.GetRequestCost(GetCodeMsg, len(codereqs))
  258. sendRequest(server.tPeer.app, GetCodeMsg, 42, cost, codereqs)
  259. if err := expectResponse(server.tPeer.app, CodeMsg, 42, testBufLimit, codes); err != nil {
  260. t.Errorf("codes mismatch: %v", err)
  261. }
  262. }
  263. // Tests that the stale contract codes can't be retrieved based on account addresses.
  264. func TestGetStaleCodeLes2(t *testing.T) { testGetStaleCode(t, 2) }
  265. func TestGetStaleCodeLes3(t *testing.T) { testGetStaleCode(t, 3) }
  266. func testGetStaleCode(t *testing.T, protocol int) {
  267. server, tearDown := newServerEnv(t, core.TriesInMemory+4, protocol, nil)
  268. defer tearDown()
  269. bc := server.pm.blockchain.(*core.BlockChain)
  270. check := func(number uint64, expected [][]byte) {
  271. req := &CodeReq{
  272. BHash: bc.GetHeaderByNumber(number).Hash(),
  273. AccKey: crypto.Keccak256(testContractAddr[:]),
  274. }
  275. cost := server.tPeer.GetRequestCost(GetCodeMsg, 1)
  276. sendRequest(server.tPeer.app, GetCodeMsg, 42, cost, []*CodeReq{req})
  277. if err := expectResponse(server.tPeer.app, CodeMsg, 42, testBufLimit, expected); err != nil {
  278. t.Errorf("codes mismatch: %v", err)
  279. }
  280. }
  281. check(0, [][]byte{}) // Non-exist contract
  282. check(testContractDeployed, [][]byte{}) // Stale contract
  283. check(bc.CurrentHeader().Number.Uint64(), [][]byte{testContractCodeDeployed}) // Fresh contract
  284. }
  285. // Tests that the transaction receipts can be retrieved based on hashes.
  286. func TestGetReceiptLes2(t *testing.T) { testGetReceipt(t, 2) }
  287. func testGetReceipt(t *testing.T, protocol int) {
  288. // Assemble the test environment
  289. server, tearDown := newServerEnv(t, 4, protocol, nil)
  290. defer tearDown()
  291. bc := server.pm.blockchain.(*core.BlockChain)
  292. // Collect the hashes to request, and the response to expect
  293. var receipts []types.Receipts
  294. var hashes []common.Hash
  295. for i := uint64(0); i <= bc.CurrentBlock().NumberU64(); i++ {
  296. block := bc.GetBlockByNumber(i)
  297. hashes = append(hashes, block.Hash())
  298. receipts = append(receipts, rawdb.ReadRawReceipts(server.db, block.Hash(), block.NumberU64()))
  299. }
  300. // Send the hash request and verify the response
  301. cost := server.tPeer.GetRequestCost(GetReceiptsMsg, len(hashes))
  302. sendRequest(server.tPeer.app, GetReceiptsMsg, 42, cost, hashes)
  303. if err := expectResponse(server.tPeer.app, ReceiptsMsg, 42, testBufLimit, receipts); err != nil {
  304. t.Errorf("receipts mismatch: %v", err)
  305. }
  306. }
  307. // Tests that trie merkle proofs can be retrieved
  308. func TestGetProofsLes2(t *testing.T) { testGetProofs(t, 2) }
  309. func testGetProofs(t *testing.T, protocol int) {
  310. // Assemble the test environment
  311. server, tearDown := newServerEnv(t, 4, protocol, nil)
  312. defer tearDown()
  313. bc := server.pm.blockchain.(*core.BlockChain)
  314. var proofreqs []ProofReq
  315. proofsV2 := light.NewNodeSet()
  316. accounts := []common.Address{bankAddr, userAddr1, userAddr2, {}}
  317. for i := uint64(0); i <= bc.CurrentBlock().NumberU64(); i++ {
  318. header := bc.GetHeaderByNumber(i)
  319. trie, _ := trie.New(header.Root, trie.NewDatabase(server.db))
  320. for _, acc := range accounts {
  321. req := ProofReq{
  322. BHash: header.Hash(),
  323. Key: crypto.Keccak256(acc[:]),
  324. }
  325. proofreqs = append(proofreqs, req)
  326. trie.Prove(crypto.Keccak256(acc[:]), 0, proofsV2)
  327. }
  328. }
  329. // Send the proof request and verify the response
  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. // Tests that the stale contract codes can't be retrieved based on account addresses.
  337. func TestGetStaleProofLes2(t *testing.T) { testGetStaleProof(t, 2) }
  338. func TestGetStaleProofLes3(t *testing.T) { testGetStaleProof(t, 3) }
  339. func testGetStaleProof(t *testing.T, protocol int) {
  340. server, tearDown := newServerEnv(t, core.TriesInMemory+4, protocol, nil)
  341. defer tearDown()
  342. bc := server.pm.blockchain.(*core.BlockChain)
  343. check := func(number uint64, wantOK bool) {
  344. var (
  345. header = bc.GetHeaderByNumber(number)
  346. account = crypto.Keccak256(userAddr1.Bytes())
  347. )
  348. req := &ProofReq{
  349. BHash: header.Hash(),
  350. Key: account,
  351. }
  352. cost := server.tPeer.GetRequestCost(GetProofsV2Msg, 1)
  353. sendRequest(server.tPeer.app, GetProofsV2Msg, 42, cost, []*ProofReq{req})
  354. var expected []rlp.RawValue
  355. if wantOK {
  356. proofsV2 := light.NewNodeSet()
  357. t, _ := trie.New(header.Root, trie.NewDatabase(server.db))
  358. t.Prove(account, 0, proofsV2)
  359. expected = proofsV2.NodeList()
  360. }
  361. if err := expectResponse(server.tPeer.app, ProofsV2Msg, 42, testBufLimit, expected); err != nil {
  362. t.Errorf("codes mismatch: %v", err)
  363. }
  364. }
  365. check(0, false) // Non-exist proof
  366. check(2, false) // Stale proof
  367. check(bc.CurrentHeader().Number.Uint64(), true) // Fresh proof
  368. }
  369. // Tests that CHT proofs can be correctly retrieved.
  370. func TestGetCHTProofsLes2(t *testing.T) { testGetCHTProofs(t, 2) }
  371. func testGetCHTProofs(t *testing.T, protocol int) {
  372. config := light.TestServerIndexerConfig
  373. waitIndexers := func(cIndexer, bIndexer, btIndexer *core.ChainIndexer) {
  374. for {
  375. cs, _, _ := cIndexer.Sections()
  376. if cs >= 1 {
  377. break
  378. }
  379. time.Sleep(10 * time.Millisecond)
  380. }
  381. }
  382. server, tearDown := newServerEnv(t, int(config.ChtSize+config.ChtConfirms), protocol, waitIndexers)
  383. defer tearDown()
  384. bc := server.pm.blockchain.(*core.BlockChain)
  385. // Assemble the proofs from the different protocols
  386. header := bc.GetHeaderByNumber(config.ChtSize - 1)
  387. rlp, _ := rlp.EncodeToBytes(header)
  388. key := make([]byte, 8)
  389. binary.BigEndian.PutUint64(key, config.ChtSize-1)
  390. proofsV2 := HelperTrieResps{
  391. AuxData: [][]byte{rlp},
  392. }
  393. root := light.GetChtRoot(server.db, 0, bc.GetHeaderByNumber(config.ChtSize-1).Hash())
  394. trie, _ := trie.New(root, trie.NewDatabase(rawdb.NewTable(server.db, light.ChtTablePrefix)))
  395. trie.Prove(key, 0, &proofsV2.Proofs)
  396. // Assemble the requests for the different protocols
  397. requestsV2 := []HelperTrieReq{{
  398. Type: htCanonical,
  399. TrieIdx: 0,
  400. Key: key,
  401. AuxReq: auxHeader,
  402. }}
  403. // Send the proof request and verify the response
  404. cost := server.tPeer.GetRequestCost(GetHelperTrieProofsMsg, len(requestsV2))
  405. sendRequest(server.tPeer.app, GetHelperTrieProofsMsg, 42, cost, requestsV2)
  406. if err := expectResponse(server.tPeer.app, HelperTrieProofsMsg, 42, testBufLimit, proofsV2); err != nil {
  407. t.Errorf("proofs mismatch: %v", err)
  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. bts, _, _ := btIndexer.Sections()
  416. if bts >= 1 {
  417. break
  418. }
  419. time.Sleep(10 * time.Millisecond)
  420. }
  421. }
  422. server, tearDown := newServerEnv(t, int(config.BloomTrieSize+config.BloomTrieConfirms), 2, waitIndexers)
  423. defer tearDown()
  424. bc := server.pm.blockchain.(*core.BlockChain)
  425. // Request and verify each bit of the bloom bits proofs
  426. for bit := 0; bit < 2048; bit++ {
  427. // Assemble the request and proofs for the bloombits
  428. key := make([]byte, 10)
  429. binary.BigEndian.PutUint16(key[:2], uint16(bit))
  430. // Only the first bloom section has data.
  431. binary.BigEndian.PutUint64(key[2:], 0)
  432. requests := []HelperTrieReq{{
  433. Type: htBloomBits,
  434. TrieIdx: 0,
  435. Key: key,
  436. }}
  437. var proofs HelperTrieResps
  438. root := light.GetBloomTrieRoot(server.db, 0, bc.GetHeaderByNumber(config.BloomTrieSize-1).Hash())
  439. trie, _ := trie.New(root, trie.NewDatabase(rawdb.NewTable(server.db, light.BloomTrieTablePrefix)))
  440. trie.Prove(key, 0, &proofs.Proofs)
  441. // Send the proof request and verify the response
  442. cost := server.tPeer.GetRequestCost(GetHelperTrieProofsMsg, len(requests))
  443. sendRequest(server.tPeer.app, GetHelperTrieProofsMsg, 42, cost, requests)
  444. if err := expectResponse(server.tPeer.app, HelperTrieProofsMsg, 42, testBufLimit, proofs); err != nil {
  445. t.Errorf("bit %d: proofs mismatch: %v", bit, err)
  446. }
  447. }
  448. }
  449. func TestTransactionStatusLes2(t *testing.T) {
  450. server, tearDown := newServerEnv(t, 0, 2, nil)
  451. defer tearDown()
  452. chain := server.pm.blockchain.(*core.BlockChain)
  453. config := core.DefaultTxPoolConfig
  454. config.Journal = ""
  455. txpool := core.NewTxPool(config, params.TestChainConfig, chain)
  456. server.pm.txpool = txpool
  457. peer, _ := newTestPeer(t, "peer", 2, server.pm, true, 0)
  458. defer peer.close()
  459. var reqID uint64
  460. test := func(tx *types.Transaction, send bool, expStatus light.TxStatus) {
  461. reqID++
  462. if send {
  463. cost := server.tPeer.GetRequestCost(SendTxV2Msg, 1)
  464. sendRequest(server.tPeer.app, SendTxV2Msg, reqID, cost, types.Transactions{tx})
  465. } else {
  466. cost := server.tPeer.GetRequestCost(GetTxStatusMsg, 1)
  467. sendRequest(server.tPeer.app, GetTxStatusMsg, reqID, cost, []common.Hash{tx.Hash()})
  468. }
  469. if err := expectResponse(server.tPeer.app, TxStatusMsg, reqID, testBufLimit, []light.TxStatus{expStatus}); err != nil {
  470. t.Errorf("transaction status mismatch")
  471. }
  472. }
  473. signer := types.HomesteadSigner{}
  474. // test error status by sending an underpriced transaction
  475. tx0, _ := types.SignTx(types.NewTransaction(0, userAddr1, big.NewInt(10000), params.TxGas, nil, nil), signer, bankKey)
  476. test(tx0, true, light.TxStatus{Status: core.TxStatusUnknown, Error: core.ErrUnderpriced.Error()})
  477. tx1, _ := types.SignTx(types.NewTransaction(0, userAddr1, big.NewInt(10000), params.TxGas, big.NewInt(100000000000), nil), signer, bankKey)
  478. test(tx1, false, light.TxStatus{Status: core.TxStatusUnknown}) // query before sending, should be unknown
  479. test(tx1, true, light.TxStatus{Status: core.TxStatusPending}) // send valid processable tx, should return pending
  480. test(tx1, true, light.TxStatus{Status: core.TxStatusPending}) // adding it again should not return an error
  481. tx2, _ := types.SignTx(types.NewTransaction(1, userAddr1, big.NewInt(10000), params.TxGas, big.NewInt(100000000000), nil), signer, bankKey)
  482. tx3, _ := types.SignTx(types.NewTransaction(2, userAddr1, big.NewInt(10000), params.TxGas, big.NewInt(100000000000), nil), signer, bankKey)
  483. // send transactions in the wrong order, tx3 should be queued
  484. test(tx3, true, light.TxStatus{Status: core.TxStatusQueued})
  485. test(tx2, true, light.TxStatus{Status: core.TxStatusPending})
  486. // query again, now tx3 should be pending too
  487. test(tx3, false, light.TxStatus{Status: core.TxStatusPending})
  488. // generate and add a block with tx1 and tx2 included
  489. gchain, _ := core.GenerateChain(params.TestChainConfig, chain.GetBlockByNumber(0), ethash.NewFaker(), server.db, 1, func(i int, block *core.BlockGen) {
  490. block.AddTx(tx1)
  491. block.AddTx(tx2)
  492. })
  493. if _, err := chain.InsertChain(gchain); err != nil {
  494. panic(err)
  495. }
  496. // wait until TxPool processes the inserted block
  497. for i := 0; i < 10; i++ {
  498. if pending, _ := txpool.Stats(); pending == 1 {
  499. break
  500. }
  501. time.Sleep(100 * time.Millisecond)
  502. }
  503. if pending, _ := txpool.Stats(); pending != 1 {
  504. t.Fatalf("pending count mismatch: have %d, want 1", pending)
  505. }
  506. // check if their status is included now
  507. block1hash := rawdb.ReadCanonicalHash(server.db, 1)
  508. test(tx1, false, light.TxStatus{Status: core.TxStatusIncluded, Lookup: &rawdb.LegacyTxLookupEntry{BlockHash: block1hash, BlockIndex: 1, Index: 0}})
  509. test(tx2, false, light.TxStatus{Status: core.TxStatusIncluded, Lookup: &rawdb.LegacyTxLookupEntry{BlockHash: block1hash, BlockIndex: 1, Index: 1}})
  510. // create a reorg that rolls them back
  511. gchain, _ = core.GenerateChain(params.TestChainConfig, chain.GetBlockByNumber(0), ethash.NewFaker(), server.db, 2, func(i int, block *core.BlockGen) {})
  512. if _, err := chain.InsertChain(gchain); err != nil {
  513. panic(err)
  514. }
  515. // wait until TxPool processes the reorg
  516. for i := 0; i < 10; i++ {
  517. if pending, _ := txpool.Stats(); pending == 3 {
  518. break
  519. }
  520. time.Sleep(100 * time.Millisecond)
  521. }
  522. if pending, _ := txpool.Stats(); pending != 3 {
  523. t.Fatalf("pending count mismatch: have %d, want 3", pending)
  524. }
  525. // check if their status is pending again
  526. test(tx1, false, light.TxStatus{Status: core.TxStatusPending})
  527. test(tx2, false, light.TxStatus{Status: core.TxStatusPending})
  528. }
  529. func TestStopResumeLes3(t *testing.T) {
  530. db := rawdb.NewMemoryDatabase()
  531. clock := &mclock.Simulated{}
  532. testCost := testBufLimit / 10
  533. pm, _, err := newTestProtocolManager(false, 0, nil, nil, nil, db, nil, 0, testCost, clock)
  534. if err != nil {
  535. t.Fatalf("Failed to create protocol manager: %v", err)
  536. }
  537. peer, _ := newTestPeer(t, "peer", 3, pm, true, testCost)
  538. defer peer.close()
  539. expBuf := testBufLimit
  540. var reqID uint64
  541. header := pm.blockchain.CurrentHeader()
  542. req := func() {
  543. reqID++
  544. sendRequest(peer.app, GetBlockHeadersMsg, reqID, testCost, &getBlockHeadersData{Origin: hashOrNumber{Hash: header.Hash()}, Amount: 1})
  545. }
  546. for i := 1; i <= 5; i++ {
  547. // send requests while we still have enough buffer and expect a response
  548. for expBuf >= testCost {
  549. req()
  550. expBuf -= testCost
  551. if err := expectResponse(peer.app, BlockHeadersMsg, reqID, expBuf, []*types.Header{header}); err != nil {
  552. t.Fatalf("expected response and failed: %v", err)
  553. }
  554. }
  555. // send some more requests in excess and expect a single StopMsg
  556. c := i
  557. for c > 0 {
  558. req()
  559. c--
  560. }
  561. if err := p2p.ExpectMsg(peer.app, StopMsg, nil); err != nil {
  562. t.Errorf("expected StopMsg and failed: %v", err)
  563. }
  564. // wait until the buffer is recharged by half of the limit
  565. wait := testBufLimit / testBufRecharge / 2
  566. clock.Run(time.Millisecond * time.Duration(wait))
  567. // expect a ResumeMsg with the partially recharged buffer value
  568. expBuf += testBufRecharge * wait
  569. if err := p2p.ExpectMsg(peer.app, ResumeMsg, expBuf); err != nil {
  570. t.Errorf("expected ResumeMsg and failed: %v", err)
  571. }
  572. }
  573. }