handler_test.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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 TestGetBlockHeadersLes3(t *testing.T) { testGetBlockHeaders(t, 3) }
  47. func testGetBlockHeaders(t *testing.T, protocol int) {
  48. server, tearDown := newServerEnv(t, downloader.MaxHeaderFetch+15, protocol, nil, false, true, 0)
  49. defer tearDown()
  50. bc := server.handler.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. // []common.Hash{},
  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. var 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. sendRequest(server.peer.app, GetBlockHeadersMsg, reqID, tt.query)
  163. if err := expectResponse(server.peer.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 TestGetBlockBodiesLes3(t *testing.T) { testGetBlockBodies(t, 3) }
  171. func testGetBlockBodies(t *testing.T, protocol int) {
  172. server, tearDown := newServerEnv(t, downloader.MaxBlockFetch+15, protocol, nil, false, true, 0)
  173. defer tearDown()
  174. bc := server.handler.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. var hashes []common.Hash
  206. seen := make(map[int64]bool)
  207. var 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. sendRequest(server.peer.app, GetBlockBodiesMsg, reqID, hashes)
  232. if err := expectResponse(server.peer.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 TestGetCodeLes3(t *testing.T) { testGetCode(t, 3) }
  240. func testGetCode(t *testing.T, protocol int) {
  241. // Assemble the test environment
  242. server, tearDown := newServerEnv(t, 4, protocol, nil, false, true, 0)
  243. defer tearDown()
  244. bc := server.handler.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. sendRequest(server.peer.app, GetCodeMsg, 42, codereqs)
  259. if err := expectResponse(server.peer.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, false, true, 0)
  268. defer tearDown()
  269. bc := server.handler.blockchain
  270. check := func(number uint64, expected [][]byte) {
  271. req := &CodeReq{
  272. BHash: bc.GetHeaderByNumber(number).Hash(),
  273. AccKey: crypto.Keccak256(testContractAddr[:]),
  274. }
  275. sendRequest(server.peer.app, GetCodeMsg, 42, []*CodeReq{req})
  276. if err := expectResponse(server.peer.app, CodeMsg, 42, testBufLimit, expected); err != nil {
  277. t.Errorf("codes mismatch: %v", err)
  278. }
  279. }
  280. check(0, [][]byte{}) // Non-exist contract
  281. check(testContractDeployed, [][]byte{}) // Stale contract
  282. check(bc.CurrentHeader().Number.Uint64(), [][]byte{testContractCodeDeployed}) // Fresh contract
  283. }
  284. // Tests that the transaction receipts can be retrieved based on hashes.
  285. func TestGetReceiptLes2(t *testing.T) { testGetReceipt(t, 2) }
  286. func TestGetReceiptLes3(t *testing.T) { testGetReceipt(t, 3) }
  287. func testGetReceipt(t *testing.T, protocol int) {
  288. // Assemble the test environment
  289. server, tearDown := newServerEnv(t, 4, protocol, nil, false, true, 0)
  290. defer tearDown()
  291. bc := server.handler.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. sendRequest(server.peer.app, GetReceiptsMsg, 42, hashes)
  302. if err := expectResponse(server.peer.app, ReceiptsMsg, 42, testBufLimit, receipts); err != nil {
  303. t.Errorf("receipts mismatch: %v", err)
  304. }
  305. }
  306. // Tests that trie merkle proofs can be retrieved
  307. func TestGetProofsLes2(t *testing.T) { testGetProofs(t, 2) }
  308. func TestGetProofsLes3(t *testing.T) { testGetProofs(t, 3) }
  309. func testGetProofs(t *testing.T, protocol int) {
  310. // Assemble the test environment
  311. server, tearDown := newServerEnv(t, 4, protocol, nil, false, true, 0)
  312. defer tearDown()
  313. bc := server.handler.blockchain
  314. var proofreqs []ProofReq
  315. proofsV2 := light.NewNodeSet()
  316. accounts := []common.Address{bankAddr, userAddr1, userAddr2, signerAddr, {}}
  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. sendRequest(server.peer.app, GetProofsV2Msg, 42, proofreqs)
  331. if err := expectResponse(server.peer.app, ProofsV2Msg, 42, testBufLimit, proofsV2.NodeList()); err != nil {
  332. t.Errorf("proofs mismatch: %v", err)
  333. }
  334. }
  335. // Tests that the stale contract codes can't be retrieved based on account addresses.
  336. func TestGetStaleProofLes2(t *testing.T) { testGetStaleProof(t, 2) }
  337. func TestGetStaleProofLes3(t *testing.T) { testGetStaleProof(t, 3) }
  338. func testGetStaleProof(t *testing.T, protocol int) {
  339. server, tearDown := newServerEnv(t, core.TriesInMemory+4, protocol, nil, false, true, 0)
  340. defer tearDown()
  341. bc := server.handler.blockchain
  342. check := func(number uint64, wantOK bool) {
  343. var (
  344. header = bc.GetHeaderByNumber(number)
  345. account = crypto.Keccak256(userAddr1.Bytes())
  346. )
  347. req := &ProofReq{
  348. BHash: header.Hash(),
  349. Key: account,
  350. }
  351. sendRequest(server.peer.app, GetProofsV2Msg, 42, []*ProofReq{req})
  352. var expected []rlp.RawValue
  353. if wantOK {
  354. proofsV2 := light.NewNodeSet()
  355. t, _ := trie.New(header.Root, trie.NewDatabase(server.db))
  356. t.Prove(account, 0, proofsV2)
  357. expected = proofsV2.NodeList()
  358. }
  359. if err := expectResponse(server.peer.app, ProofsV2Msg, 42, testBufLimit, expected); err != nil {
  360. t.Errorf("codes mismatch: %v", err)
  361. }
  362. }
  363. check(0, false) // Non-exist proof
  364. check(2, false) // Stale proof
  365. check(bc.CurrentHeader().Number.Uint64(), true) // Fresh proof
  366. }
  367. // Tests that CHT proofs can be correctly retrieved.
  368. func TestGetCHTProofsLes2(t *testing.T) { testGetCHTProofs(t, 2) }
  369. func TestGetCHTProofsLes3(t *testing.T) { testGetCHTProofs(t, 3) }
  370. func testGetCHTProofs(t *testing.T, protocol int) {
  371. config := light.TestServerIndexerConfig
  372. waitIndexers := func(cIndexer, bIndexer, btIndexer *core.ChainIndexer) {
  373. for {
  374. cs, _, _ := cIndexer.Sections()
  375. if cs >= 1 {
  376. break
  377. }
  378. time.Sleep(10 * time.Millisecond)
  379. }
  380. }
  381. server, tearDown := newServerEnv(t, int(config.ChtSize+config.ChtConfirms), protocol, waitIndexers, false, true, 0)
  382. defer tearDown()
  383. bc := server.handler.blockchain
  384. // Assemble the proofs from the different protocols
  385. header := bc.GetHeaderByNumber(config.ChtSize - 1)
  386. rlp, _ := rlp.EncodeToBytes(header)
  387. key := make([]byte, 8)
  388. binary.BigEndian.PutUint64(key, config.ChtSize-1)
  389. proofsV2 := HelperTrieResps{
  390. AuxData: [][]byte{rlp},
  391. }
  392. root := light.GetChtRoot(server.db, 0, bc.GetHeaderByNumber(config.ChtSize-1).Hash())
  393. trie, _ := trie.New(root, trie.NewDatabase(rawdb.NewTable(server.db, light.ChtTablePrefix)))
  394. trie.Prove(key, 0, &proofsV2.Proofs)
  395. // Assemble the requests for the different protocols
  396. requestsV2 := []HelperTrieReq{{
  397. Type: htCanonical,
  398. TrieIdx: 0,
  399. Key: key,
  400. AuxReq: htAuxHeader,
  401. }}
  402. // Send the proof request and verify the response
  403. sendRequest(server.peer.app, GetHelperTrieProofsMsg, 42, requestsV2)
  404. if err := expectResponse(server.peer.app, HelperTrieProofsMsg, 42, testBufLimit, proofsV2); err != nil {
  405. t.Errorf("proofs mismatch: %v", err)
  406. }
  407. }
  408. func TestGetBloombitsProofsLes2(t *testing.T) { testGetBloombitsProofs(t, 2) }
  409. func TestGetBloombitsProofsLes3(t *testing.T) { testGetBloombitsProofs(t, 3) }
  410. // Tests that bloombits proofs can be correctly retrieved.
  411. func testGetBloombitsProofs(t *testing.T, protocol int) {
  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), protocol, waitIndexers, false, true, 0)
  423. defer tearDown()
  424. bc := server.handler.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. sendRequest(server.peer.app, GetHelperTrieProofsMsg, 42, requests)
  443. if err := expectResponse(server.peer.app, HelperTrieProofsMsg, 42, testBufLimit, proofs); err != nil {
  444. t.Errorf("bit %d: proofs mismatch: %v", bit, err)
  445. }
  446. }
  447. }
  448. func TestTransactionStatusLes2(t *testing.T) { testTransactionStatus(t, 2) }
  449. func TestTransactionStatusLes3(t *testing.T) { testTransactionStatus(t, 3) }
  450. func testTransactionStatus(t *testing.T, protocol int) {
  451. server, tearDown := newServerEnv(t, 0, protocol, nil, false, true, 0)
  452. defer tearDown()
  453. server.handler.addTxsSync = true
  454. chain := server.handler.blockchain
  455. var reqID uint64
  456. test := func(tx *types.Transaction, send bool, expStatus light.TxStatus) {
  457. reqID++
  458. if send {
  459. sendRequest(server.peer.app, SendTxV2Msg, reqID, types.Transactions{tx})
  460. } else {
  461. sendRequest(server.peer.app, GetTxStatusMsg, reqID, []common.Hash{tx.Hash()})
  462. }
  463. if err := expectResponse(server.peer.app, TxStatusMsg, reqID, testBufLimit, []light.TxStatus{expStatus}); err != nil {
  464. t.Errorf("transaction status mismatch")
  465. }
  466. }
  467. signer := types.HomesteadSigner{}
  468. // test error status by sending an underpriced transaction
  469. tx0, _ := types.SignTx(types.NewTransaction(0, userAddr1, big.NewInt(10000), params.TxGas, nil, nil), signer, bankKey)
  470. test(tx0, true, light.TxStatus{Status: core.TxStatusUnknown, Error: core.ErrUnderpriced.Error()})
  471. tx1, _ := types.SignTx(types.NewTransaction(0, userAddr1, big.NewInt(10000), params.TxGas, big.NewInt(100000000000), nil), signer, bankKey)
  472. test(tx1, false, light.TxStatus{Status: core.TxStatusUnknown}) // query before sending, should be unknown
  473. test(tx1, true, light.TxStatus{Status: core.TxStatusPending}) // send valid processable tx, should return pending
  474. test(tx1, true, light.TxStatus{Status: core.TxStatusPending}) // adding it again should not return an error
  475. tx2, _ := types.SignTx(types.NewTransaction(1, userAddr1, big.NewInt(10000), params.TxGas, big.NewInt(100000000000), nil), signer, bankKey)
  476. tx3, _ := types.SignTx(types.NewTransaction(2, userAddr1, big.NewInt(10000), params.TxGas, big.NewInt(100000000000), nil), signer, bankKey)
  477. // send transactions in the wrong order, tx3 should be queued
  478. test(tx3, true, light.TxStatus{Status: core.TxStatusQueued})
  479. test(tx2, true, light.TxStatus{Status: core.TxStatusPending})
  480. // query again, now tx3 should be pending too
  481. test(tx3, false, light.TxStatus{Status: core.TxStatusPending})
  482. // generate and add a block with tx1 and tx2 included
  483. gchain, _ := core.GenerateChain(params.TestChainConfig, chain.GetBlockByNumber(0), ethash.NewFaker(), server.db, 1, func(i int, block *core.BlockGen) {
  484. block.AddTx(tx1)
  485. block.AddTx(tx2)
  486. })
  487. if _, err := chain.InsertChain(gchain); err != nil {
  488. panic(err)
  489. }
  490. // wait until TxPool processes the inserted block
  491. for i := 0; i < 10; i++ {
  492. if pending, _ := server.handler.txpool.Stats(); pending == 1 {
  493. break
  494. }
  495. time.Sleep(100 * time.Millisecond)
  496. }
  497. if pending, _ := server.handler.txpool.Stats(); pending != 1 {
  498. t.Fatalf("pending count mismatch: have %d, want 1", pending)
  499. }
  500. // Discard new block announcement
  501. msg, _ := server.peer.app.ReadMsg()
  502. msg.Discard()
  503. // check if their status is included now
  504. block1hash := rawdb.ReadCanonicalHash(server.db, 1)
  505. test(tx1, false, light.TxStatus{Status: core.TxStatusIncluded, Lookup: &rawdb.LegacyTxLookupEntry{BlockHash: block1hash, BlockIndex: 1, Index: 0}})
  506. test(tx2, false, light.TxStatus{Status: core.TxStatusIncluded, Lookup: &rawdb.LegacyTxLookupEntry{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(), server.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, _ := server.handler.txpool.Stats(); pending == 3 {
  515. break
  516. }
  517. time.Sleep(100 * time.Millisecond)
  518. }
  519. if pending, _ := server.handler.txpool.Stats(); pending != 3 {
  520. t.Fatalf("pending count mismatch: have %d, want 3", pending)
  521. }
  522. // Discard new block announcement
  523. msg, _ = server.peer.app.ReadMsg()
  524. msg.Discard()
  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. server, tearDown := newServerEnv(t, 0, 3, nil, true, true, testBufLimit/10)
  531. defer tearDown()
  532. server.handler.server.costTracker.testing = true
  533. var (
  534. reqID uint64
  535. expBuf = testBufLimit
  536. testCost = testBufLimit / 10
  537. )
  538. header := server.handler.blockchain.CurrentHeader()
  539. req := func() {
  540. reqID++
  541. sendRequest(server.peer.app, GetBlockHeadersMsg, reqID, &getBlockHeadersData{Origin: hashOrNumber{Hash: header.Hash()}, Amount: 1})
  542. }
  543. for i := 1; i <= 5; i++ {
  544. // send requests while we still have enough buffer and expect a response
  545. for expBuf >= testCost {
  546. req()
  547. expBuf -= testCost
  548. if err := expectResponse(server.peer.app, BlockHeadersMsg, reqID, expBuf, []*types.Header{header}); err != nil {
  549. t.Errorf("expected response and failed: %v", err)
  550. }
  551. }
  552. // send some more requests in excess and expect a single StopMsg
  553. c := i
  554. for c > 0 {
  555. req()
  556. c--
  557. }
  558. if err := p2p.ExpectMsg(server.peer.app, StopMsg, nil); err != nil {
  559. t.Errorf("expected StopMsg and failed: %v", err)
  560. }
  561. // wait until the buffer is recharged by half of the limit
  562. wait := testBufLimit / testBufRecharge / 2
  563. server.clock.(*mclock.Simulated).Run(time.Millisecond * time.Duration(wait))
  564. // expect a ResumeMsg with the partially recharged buffer value
  565. expBuf += testBufRecharge * wait
  566. if err := p2p.ExpectMsg(server.peer.app, ResumeMsg, expBuf); err != nil {
  567. t.Errorf("expected ResumeMsg and failed: %v", err)
  568. }
  569. }
  570. }