handler_test.go 24 KB

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