handler_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. "math/rand"
  19. "testing"
  20. "github.com/ethereum/go-ethereum/common"
  21. "github.com/ethereum/go-ethereum/core"
  22. "github.com/ethereum/go-ethereum/core/types"
  23. "github.com/ethereum/go-ethereum/crypto"
  24. "github.com/ethereum/go-ethereum/eth/downloader"
  25. "github.com/ethereum/go-ethereum/ethdb"
  26. "github.com/ethereum/go-ethereum/p2p"
  27. "github.com/ethereum/go-ethereum/rlp"
  28. "github.com/ethereum/go-ethereum/trie"
  29. )
  30. func expectResponse(r p2p.MsgReader, msgcode, reqID, bv uint64, data interface{}) error {
  31. type resp struct {
  32. ReqID, BV uint64
  33. Data interface{}
  34. }
  35. return p2p.ExpectMsg(r, msgcode, resp{reqID, bv, data})
  36. }
  37. // Tests that block headers can be retrieved from a remote chain based on user queries.
  38. func TestGetBlockHeadersLes1(t *testing.T) { testGetBlockHeaders(t, 1) }
  39. func testGetBlockHeaders(t *testing.T, protocol int) {
  40. db, _ := ethdb.NewMemDatabase()
  41. pm := newTestProtocolManagerMust(t, false, downloader.MaxHashFetch+15, nil, nil, nil, db)
  42. bc := pm.blockchain.(*core.BlockChain)
  43. peer, _ := newTestPeer(t, "peer", protocol, pm, true)
  44. defer peer.close()
  45. // Create a "random" unknown hash for testing
  46. var unknown common.Hash
  47. for i := range unknown {
  48. unknown[i] = byte(i)
  49. }
  50. // Create a batch of tests for various scenarios
  51. limit := uint64(MaxHeaderFetch)
  52. tests := []struct {
  53. query *getBlockHeadersData // The query to execute for header retrieval
  54. expect []common.Hash // The hashes of the block whose headers are expected
  55. }{
  56. // A single random block should be retrievable by hash and number too
  57. {
  58. &getBlockHeadersData{Origin: hashOrNumber{Hash: bc.GetBlockByNumber(limit / 2).Hash()}, Amount: 1},
  59. []common.Hash{bc.GetBlockByNumber(limit / 2).Hash()},
  60. }, {
  61. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 1},
  62. []common.Hash{bc.GetBlockByNumber(limit / 2).Hash()},
  63. },
  64. // Multiple headers should be retrievable in both directions
  65. {
  66. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 3},
  67. []common.Hash{
  68. bc.GetBlockByNumber(limit / 2).Hash(),
  69. bc.GetBlockByNumber(limit/2 + 1).Hash(),
  70. bc.GetBlockByNumber(limit/2 + 2).Hash(),
  71. },
  72. }, {
  73. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Amount: 3, Reverse: true},
  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. // Multiple headers with skip lists should be retrievable
  81. {
  82. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Skip: 3, Amount: 3},
  83. []common.Hash{
  84. bc.GetBlockByNumber(limit / 2).Hash(),
  85. bc.GetBlockByNumber(limit/2 + 4).Hash(),
  86. bc.GetBlockByNumber(limit/2 + 8).Hash(),
  87. },
  88. }, {
  89. &getBlockHeadersData{Origin: hashOrNumber{Number: limit / 2}, Skip: 3, Amount: 3, Reverse: true},
  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. // The chain endpoints should be retrievable
  97. {
  98. &getBlockHeadersData{Origin: hashOrNumber{Number: 0}, Amount: 1},
  99. []common.Hash{bc.GetBlockByNumber(0).Hash()},
  100. }, {
  101. &getBlockHeadersData{Origin: hashOrNumber{Number: bc.CurrentBlock().NumberU64()}, Amount: 1},
  102. []common.Hash{bc.CurrentBlock().Hash()},
  103. },
  104. // Ensure protocol limits are honored
  105. /*{
  106. &getBlockHeadersData{Origin: hashOrNumber{Number: bc.CurrentBlock().NumberU64() - 1}, Amount: limit + 10, Reverse: true},
  107. bc.GetBlockHashesFromHash(bc.CurrentBlock().Hash(), limit),
  108. },*/
  109. // Check that requesting more than available is handled gracefully
  110. {
  111. &getBlockHeadersData{Origin: hashOrNumber{Number: bc.CurrentBlock().NumberU64() - 4}, Skip: 3, Amount: 3},
  112. []common.Hash{
  113. bc.GetBlockByNumber(bc.CurrentBlock().NumberU64() - 4).Hash(),
  114. bc.GetBlockByNumber(bc.CurrentBlock().NumberU64()).Hash(),
  115. },
  116. }, {
  117. &getBlockHeadersData{Origin: hashOrNumber{Number: 4}, Skip: 3, Amount: 3, Reverse: true},
  118. []common.Hash{
  119. bc.GetBlockByNumber(4).Hash(),
  120. bc.GetBlockByNumber(0).Hash(),
  121. },
  122. },
  123. // Check that requesting more than available is handled gracefully, even if mid skip
  124. {
  125. &getBlockHeadersData{Origin: hashOrNumber{Number: bc.CurrentBlock().NumberU64() - 4}, Skip: 2, Amount: 3},
  126. []common.Hash{
  127. bc.GetBlockByNumber(bc.CurrentBlock().NumberU64() - 4).Hash(),
  128. bc.GetBlockByNumber(bc.CurrentBlock().NumberU64() - 1).Hash(),
  129. },
  130. }, {
  131. &getBlockHeadersData{Origin: hashOrNumber{Number: 4}, Skip: 2, Amount: 3, Reverse: true},
  132. []common.Hash{
  133. bc.GetBlockByNumber(4).Hash(),
  134. bc.GetBlockByNumber(1).Hash(),
  135. },
  136. },
  137. // Check that non existing headers aren't returned
  138. {
  139. &getBlockHeadersData{Origin: hashOrNumber{Hash: unknown}, Amount: 1},
  140. []common.Hash{},
  141. }, {
  142. &getBlockHeadersData{Origin: hashOrNumber{Number: bc.CurrentBlock().NumberU64() + 1}, Amount: 1},
  143. []common.Hash{},
  144. },
  145. }
  146. // Run each of the tests and verify the results against the chain
  147. var reqID uint64
  148. for i, tt := range tests {
  149. // Collect the headers to expect in the response
  150. headers := []*types.Header{}
  151. for _, hash := range tt.expect {
  152. headers = append(headers, bc.GetHeaderByHash(hash))
  153. }
  154. // Send the hash request and verify the response
  155. reqID++
  156. cost := peer.GetRequestCost(GetBlockHeadersMsg, int(tt.query.Amount))
  157. sendRequest(peer.app, GetBlockHeadersMsg, reqID, cost, tt.query)
  158. if err := expectResponse(peer.app, BlockHeadersMsg, reqID, testBufLimit, headers); err != nil {
  159. t.Errorf("test %d: headers mismatch: %v", i, err)
  160. }
  161. }
  162. }
  163. // Tests that block contents can be retrieved from a remote chain based on their hashes.
  164. func TestGetBlockBodiesLes1(t *testing.T) { testGetBlockBodies(t, 1) }
  165. func testGetBlockBodies(t *testing.T, protocol int) {
  166. db, _ := ethdb.NewMemDatabase()
  167. pm := newTestProtocolManagerMust(t, false, downloader.MaxBlockFetch+15, nil, nil, nil, db)
  168. bc := pm.blockchain.(*core.BlockChain)
  169. peer, _ := newTestPeer(t, "peer", protocol, pm, true)
  170. defer peer.close()
  171. // Create a batch of tests for various scenarios
  172. limit := MaxBodyFetch
  173. tests := []struct {
  174. random int // Number of blocks to fetch randomly from the chain
  175. explicit []common.Hash // Explicitly requested blocks
  176. available []bool // Availability of explicitly requested blocks
  177. expected int // Total number of existing blocks to expect
  178. }{
  179. {1, nil, nil, 1}, // A single random block should be retrievable
  180. {10, nil, nil, 10}, // Multiple random blocks should be retrievable
  181. {limit, nil, nil, limit}, // The maximum possible blocks should be retrievable
  182. //{limit + 1, nil, nil, limit}, // No more than the possible block count should be returned
  183. {0, []common.Hash{bc.Genesis().Hash()}, []bool{true}, 1}, // The genesis block should be retrievable
  184. {0, []common.Hash{bc.CurrentBlock().Hash()}, []bool{true}, 1}, // The chains head block should be retrievable
  185. {0, []common.Hash{{}}, []bool{false}, 0}, // A non existent block should not be returned
  186. // Existing and non-existing blocks interleaved should not cause problems
  187. {0, []common.Hash{
  188. {},
  189. bc.GetBlockByNumber(1).Hash(),
  190. {},
  191. bc.GetBlockByNumber(10).Hash(),
  192. {},
  193. bc.GetBlockByNumber(100).Hash(),
  194. {},
  195. }, []bool{false, true, false, true, false, true, false}, 3},
  196. }
  197. // Run each of the tests and verify the results against the chain
  198. var reqID uint64
  199. for i, tt := range tests {
  200. // Collect the hashes to request, and the response to expect
  201. hashes, seen := []common.Hash{}, make(map[int64]bool)
  202. bodies := []*types.Body{}
  203. for j := 0; j < tt.random; j++ {
  204. for {
  205. num := rand.Int63n(int64(bc.CurrentBlock().NumberU64()))
  206. if !seen[num] {
  207. seen[num] = true
  208. block := bc.GetBlockByNumber(uint64(num))
  209. hashes = append(hashes, block.Hash())
  210. if len(bodies) < tt.expected {
  211. bodies = append(bodies, &types.Body{Transactions: block.Transactions(), Uncles: block.Uncles()})
  212. }
  213. break
  214. }
  215. }
  216. }
  217. for j, hash := range tt.explicit {
  218. hashes = append(hashes, hash)
  219. if tt.available[j] && len(bodies) < tt.expected {
  220. block := bc.GetBlockByHash(hash)
  221. bodies = append(bodies, &types.Body{Transactions: block.Transactions(), Uncles: block.Uncles()})
  222. }
  223. }
  224. reqID++
  225. // Send the hash request and verify the response
  226. cost := peer.GetRequestCost(GetBlockBodiesMsg, len(hashes))
  227. sendRequest(peer.app, GetBlockBodiesMsg, reqID, cost, hashes)
  228. if err := expectResponse(peer.app, BlockBodiesMsg, reqID, testBufLimit, bodies); err != nil {
  229. t.Errorf("test %d: bodies mismatch: %v", i, err)
  230. }
  231. }
  232. }
  233. // Tests that the contract codes can be retrieved based on account addresses.
  234. func TestGetCodeLes1(t *testing.T) { testGetCode(t, 1) }
  235. func testGetCode(t *testing.T, protocol int) {
  236. // Assemble the test environment
  237. db, _ := ethdb.NewMemDatabase()
  238. pm := newTestProtocolManagerMust(t, false, 4, testChainGen, nil, nil, db)
  239. bc := pm.blockchain.(*core.BlockChain)
  240. peer, _ := newTestPeer(t, "peer", protocol, pm, true)
  241. defer peer.close()
  242. var codereqs []*CodeReq
  243. var codes [][]byte
  244. for i := uint64(0); i <= bc.CurrentBlock().NumberU64(); i++ {
  245. header := bc.GetHeaderByNumber(i)
  246. req := &CodeReq{
  247. BHash: header.Hash(),
  248. AccKey: crypto.Keccak256(testContractAddr[:]),
  249. }
  250. codereqs = append(codereqs, req)
  251. if i >= testContractDeployed {
  252. codes = append(codes, testContractCodeDeployed)
  253. }
  254. }
  255. cost := peer.GetRequestCost(GetCodeMsg, len(codereqs))
  256. sendRequest(peer.app, GetCodeMsg, 42, cost, codereqs)
  257. if err := expectResponse(peer.app, CodeMsg, 42, testBufLimit, codes); err != nil {
  258. t.Errorf("codes mismatch: %v", err)
  259. }
  260. }
  261. // Tests that the transaction receipts can be retrieved based on hashes.
  262. func TestGetReceiptLes1(t *testing.T) { testGetReceipt(t, 1) }
  263. func testGetReceipt(t *testing.T, protocol int) {
  264. // Assemble the test environment
  265. db, _ := ethdb.NewMemDatabase()
  266. pm := newTestProtocolManagerMust(t, false, 4, testChainGen, nil, nil, db)
  267. bc := pm.blockchain.(*core.BlockChain)
  268. peer, _ := newTestPeer(t, "peer", protocol, pm, true)
  269. defer peer.close()
  270. // Collect the hashes to request, and the response to expect
  271. hashes, receipts := []common.Hash{}, []types.Receipts{}
  272. for i := uint64(0); i <= bc.CurrentBlock().NumberU64(); i++ {
  273. block := bc.GetBlockByNumber(i)
  274. hashes = append(hashes, block.Hash())
  275. receipts = append(receipts, core.GetBlockReceipts(db, block.Hash(), block.NumberU64()))
  276. }
  277. // Send the hash request and verify the response
  278. cost := peer.GetRequestCost(GetReceiptsMsg, len(hashes))
  279. sendRequest(peer.app, GetReceiptsMsg, 42, cost, hashes)
  280. if err := expectResponse(peer.app, ReceiptsMsg, 42, testBufLimit, receipts); err != nil {
  281. t.Errorf("receipts mismatch: %v", err)
  282. }
  283. }
  284. // Tests that trie merkle proofs can be retrieved
  285. func TestGetProofsLes1(t *testing.T) { testGetReceipt(t, 1) }
  286. func testGetProofs(t *testing.T, protocol int) {
  287. // Assemble the test environment
  288. db, _ := ethdb.NewMemDatabase()
  289. pm := newTestProtocolManagerMust(t, false, 4, testChainGen, nil, nil, db)
  290. bc := pm.blockchain.(*core.BlockChain)
  291. peer, _ := newTestPeer(t, "peer", protocol, pm, true)
  292. defer peer.close()
  293. var proofreqs []ProofReq
  294. var proofs [][]rlp.RawValue
  295. accounts := []common.Address{testBankAddress, acc1Addr, acc2Addr, {}}
  296. for i := uint64(0); i <= bc.CurrentBlock().NumberU64(); i++ {
  297. header := bc.GetHeaderByNumber(i)
  298. root := header.Root
  299. trie, _ := trie.New(root, db)
  300. for _, acc := range accounts {
  301. req := ProofReq{
  302. BHash: header.Hash(),
  303. Key: acc[:],
  304. }
  305. proofreqs = append(proofreqs, req)
  306. proof := trie.Prove(crypto.Keccak256(acc[:]))
  307. proofs = append(proofs, proof)
  308. }
  309. }
  310. // Send the proof request and verify the response
  311. cost := peer.GetRequestCost(GetProofsMsg, len(proofreqs))
  312. sendRequest(peer.app, GetProofsMsg, 42, cost, proofreqs)
  313. if err := expectResponse(peer.app, ProofsMsg, 42, testBufLimit, proofs); err != nil {
  314. t.Errorf("proofs mismatch: %v", err)
  315. }
  316. }