odr_test.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. "bytes"
  19. "context"
  20. "math/big"
  21. "testing"
  22. "time"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/common/math"
  25. "github.com/ethereum/go-ethereum/core"
  26. "github.com/ethereum/go-ethereum/core/rawdb"
  27. "github.com/ethereum/go-ethereum/core/state"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/core/vm"
  30. "github.com/ethereum/go-ethereum/ethdb"
  31. "github.com/ethereum/go-ethereum/light"
  32. "github.com/ethereum/go-ethereum/params"
  33. "github.com/ethereum/go-ethereum/rlp"
  34. )
  35. type odrTestFn func(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte
  36. func TestOdrGetBlockLes2(t *testing.T) { testOdr(t, 2, 1, true, odrGetBlock) }
  37. func TestOdrGetBlockLes3(t *testing.T) { testOdr(t, 3, 1, true, odrGetBlock) }
  38. func odrGetBlock(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
  39. var block *types.Block
  40. if bc != nil {
  41. block = bc.GetBlockByHash(bhash)
  42. } else {
  43. block, _ = lc.GetBlockByHash(ctx, bhash)
  44. }
  45. if block == nil {
  46. return nil
  47. }
  48. rlp, _ := rlp.EncodeToBytes(block)
  49. return rlp
  50. }
  51. func TestOdrGetReceiptsLes2(t *testing.T) { testOdr(t, 2, 1, true, odrGetReceipts) }
  52. func TestOdrGetReceiptsLes3(t *testing.T) { testOdr(t, 3, 1, true, odrGetReceipts) }
  53. func odrGetReceipts(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
  54. var receipts types.Receipts
  55. if bc != nil {
  56. if number := rawdb.ReadHeaderNumber(db, bhash); number != nil {
  57. receipts = rawdb.ReadReceipts(db, bhash, *number, config)
  58. }
  59. } else {
  60. if number := rawdb.ReadHeaderNumber(db, bhash); number != nil {
  61. receipts, _ = light.GetBlockReceipts(ctx, lc.Odr(), bhash, *number)
  62. }
  63. }
  64. if receipts == nil {
  65. return nil
  66. }
  67. rlp, _ := rlp.EncodeToBytes(receipts)
  68. return rlp
  69. }
  70. func TestOdrAccountsLes2(t *testing.T) { testOdr(t, 2, 1, true, odrAccounts) }
  71. func TestOdrAccountsLes3(t *testing.T) { testOdr(t, 3, 1, true, odrAccounts) }
  72. func odrAccounts(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
  73. dummyAddr := common.HexToAddress("1234567812345678123456781234567812345678")
  74. acc := []common.Address{bankAddr, userAddr1, userAddr2, dummyAddr}
  75. var (
  76. res []byte
  77. st *state.StateDB
  78. err error
  79. )
  80. for _, addr := range acc {
  81. if bc != nil {
  82. header := bc.GetHeaderByHash(bhash)
  83. st, err = state.New(header.Root, state.NewDatabase(db), nil)
  84. } else {
  85. header := lc.GetHeaderByHash(bhash)
  86. st = light.NewState(ctx, header, lc.Odr())
  87. }
  88. if err == nil {
  89. bal := st.GetBalance(addr)
  90. rlp, _ := rlp.EncodeToBytes(bal)
  91. res = append(res, rlp...)
  92. }
  93. }
  94. return res
  95. }
  96. func TestOdrContractCallLes2(t *testing.T) { testOdr(t, 2, 2, true, odrContractCall) }
  97. func TestOdrContractCallLes3(t *testing.T) { testOdr(t, 3, 2, true, odrContractCall) }
  98. type callmsg struct {
  99. types.Message
  100. }
  101. func (callmsg) CheckNonce() bool { return false }
  102. func odrContractCall(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
  103. data := common.Hex2Bytes("60CD26850000000000000000000000000000000000000000000000000000000000000000")
  104. var res []byte
  105. for i := 0; i < 3; i++ {
  106. data[35] = byte(i)
  107. if bc != nil {
  108. header := bc.GetHeaderByHash(bhash)
  109. statedb, err := state.New(header.Root, state.NewDatabase(db), nil)
  110. if err == nil {
  111. from := statedb.GetOrNewStateObject(bankAddr)
  112. from.SetBalance(math.MaxBig256)
  113. msg := callmsg{types.NewMessage(from.Address(), &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false)}
  114. context := core.NewEVMBlockContext(header, bc, nil)
  115. txContext := core.NewEVMTxContext(msg)
  116. vmenv := vm.NewEVM(context, txContext, statedb, config, vm.Config{})
  117. //vmenv := core.NewEnv(statedb, config, bc, msg, header, vm.Config{})
  118. gp := new(core.GasPool).AddGas(math.MaxUint64)
  119. result, _ := core.ApplyMessage(vmenv, msg, gp)
  120. res = append(res, result.Return()...)
  121. }
  122. } else {
  123. header := lc.GetHeaderByHash(bhash)
  124. state := light.NewState(ctx, header, lc.Odr())
  125. state.SetBalance(bankAddr, math.MaxBig256)
  126. msg := callmsg{types.NewMessage(bankAddr, &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false)}
  127. context := core.NewEVMBlockContext(header, lc, nil)
  128. txContext := core.NewEVMTxContext(msg)
  129. vmenv := vm.NewEVM(context, txContext, state, config, vm.Config{})
  130. gp := new(core.GasPool).AddGas(math.MaxUint64)
  131. result, _ := core.ApplyMessage(vmenv, msg, gp)
  132. if state.Error() == nil {
  133. res = append(res, result.Return()...)
  134. }
  135. }
  136. }
  137. return res
  138. }
  139. func TestOdrTxStatusLes2(t *testing.T) { testOdr(t, 2, 1, false, odrTxStatus) }
  140. func TestOdrTxStatusLes3(t *testing.T) { testOdr(t, 3, 1, false, odrTxStatus) }
  141. func odrTxStatus(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
  142. var txs types.Transactions
  143. if bc != nil {
  144. block := bc.GetBlockByHash(bhash)
  145. txs = block.Transactions()
  146. } else {
  147. if block, _ := lc.GetBlockByHash(ctx, bhash); block != nil {
  148. btxs := block.Transactions()
  149. txs = make(types.Transactions, len(btxs))
  150. for i, tx := range btxs {
  151. var err error
  152. txs[i], _, _, _, err = light.GetTransaction(ctx, lc.Odr(), tx.Hash())
  153. if err != nil {
  154. return nil
  155. }
  156. }
  157. }
  158. }
  159. rlp, _ := rlp.EncodeToBytes(txs)
  160. return rlp
  161. }
  162. // testOdr tests odr requests whose validation guaranteed by block headers.
  163. func testOdr(t *testing.T, protocol int, expFail uint64, checkCached bool, fn odrTestFn) {
  164. // Assemble the test environment
  165. server, client, tearDown := newClientServerEnv(t, 4, protocol, nil, nil, 0, false, true, true)
  166. defer tearDown()
  167. // Ensure the client has synced all necessary data.
  168. clientHead := client.handler.backend.blockchain.CurrentHeader()
  169. if clientHead.Number.Uint64() != 4 {
  170. t.Fatalf("Failed to sync the chain with server, head: %v", clientHead.Number.Uint64())
  171. }
  172. // Disable the mechanism that we will wait a few time for request
  173. // even there is no suitable peer to send right now.
  174. waitForPeers = 0
  175. test := func(expFail uint64) {
  176. // Mark this as a helper to put the failures at the correct lines
  177. t.Helper()
  178. for i := uint64(0); i <= server.handler.blockchain.CurrentHeader().Number.Uint64(); i++ {
  179. bhash := rawdb.ReadCanonicalHash(server.db, i)
  180. b1 := fn(light.NoOdr, server.db, server.handler.server.chainConfig, server.handler.blockchain, nil, bhash)
  181. // Set the timeout as 1 second here, ensure there is enough time
  182. // for travis to make the action.
  183. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  184. b2 := fn(ctx, client.db, client.handler.backend.chainConfig, nil, client.handler.backend.blockchain, bhash)
  185. cancel()
  186. eq := bytes.Equal(b1, b2)
  187. exp := i < expFail
  188. if exp && !eq {
  189. t.Fatalf("odr mismatch: have %x, want %x", b2, b1)
  190. }
  191. if !exp && eq {
  192. t.Fatalf("unexpected odr match")
  193. }
  194. }
  195. }
  196. // expect retrievals to fail (except genesis block) without a les peer
  197. client.handler.backend.peers.lock.Lock()
  198. client.peer.speer.hasBlockHook = func(common.Hash, uint64, bool) bool { return false }
  199. client.handler.backend.peers.lock.Unlock()
  200. test(expFail)
  201. // expect all retrievals to pass
  202. client.handler.backend.peers.lock.Lock()
  203. client.peer.speer.hasBlockHook = func(common.Hash, uint64, bool) bool { return true }
  204. client.handler.backend.peers.lock.Unlock()
  205. test(5)
  206. // still expect all retrievals to pass, now data should be cached locally
  207. if checkCached {
  208. client.handler.backend.peers.unregister(client.peer.speer.id)
  209. time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed
  210. test(5)
  211. }
  212. }