odr_test.go 8.5 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))
  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))
  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.NewEVMContext(msg, header, bc, nil)
  115. vmenv := vm.NewEVM(context, statedb, config, vm.Config{})
  116. //vmenv := core.NewEnv(statedb, config, bc, msg, header, vm.Config{})
  117. gp := new(core.GasPool).AddGas(math.MaxUint64)
  118. ret, _, _, _ := core.ApplyMessage(vmenv, msg, gp)
  119. res = append(res, ret...)
  120. }
  121. } else {
  122. header := lc.GetHeaderByHash(bhash)
  123. state := light.NewState(ctx, header, lc.Odr())
  124. state.SetBalance(bankAddr, math.MaxBig256)
  125. msg := callmsg{types.NewMessage(bankAddr, &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false)}
  126. context := core.NewEVMContext(msg, header, lc, nil)
  127. vmenv := vm.NewEVM(context, state, config, vm.Config{})
  128. gp := new(core.GasPool).AddGas(math.MaxUint64)
  129. ret, _, _, _ := core.ApplyMessage(vmenv, msg, gp)
  130. if state.Error() == nil {
  131. res = append(res, ret...)
  132. }
  133. }
  134. }
  135. return res
  136. }
  137. func TestOdrTxStatusLes2(t *testing.T) { testOdr(t, 2, 1, false, odrTxStatus) }
  138. func TestOdrTxStatusLes3(t *testing.T) { testOdr(t, 3, 1, false, odrTxStatus) }
  139. func odrTxStatus(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
  140. var txs types.Transactions
  141. if bc != nil {
  142. block := bc.GetBlockByHash(bhash)
  143. txs = block.Transactions()
  144. } else {
  145. if block, _ := lc.GetBlockByHash(ctx, bhash); block != nil {
  146. btxs := block.Transactions()
  147. txs = make(types.Transactions, len(btxs))
  148. for i, tx := range btxs {
  149. var err error
  150. txs[i], _, _, _, err = light.GetTransaction(ctx, lc.Odr(), tx.Hash())
  151. if err != nil {
  152. return nil
  153. }
  154. }
  155. }
  156. }
  157. rlp, _ := rlp.EncodeToBytes(txs)
  158. return rlp
  159. }
  160. // testOdr tests odr requests whose validation guaranteed by block headers.
  161. func testOdr(t *testing.T, protocol int, expFail uint64, checkCached bool, fn odrTestFn) {
  162. // Assemble the test environment
  163. server, client, tearDown := newClientServerEnv(t, 4, protocol, nil, nil, 0, false, true)
  164. defer tearDown()
  165. client.handler.synchronise(client.peer.speer)
  166. // Ensure the client has synced all necessary data.
  167. clientHead := client.handler.backend.blockchain.CurrentHeader()
  168. if clientHead.Number.Uint64() != 4 {
  169. t.Fatalf("Failed to sync the chain with server, head: %v", clientHead.Number.Uint64())
  170. }
  171. // Disable the mechanism that we will wait a few time for request
  172. // even there is no suitable peer to send right now.
  173. waitForPeers = 0
  174. test := func(expFail uint64) {
  175. // Mark this as a helper to put the failures at the correct lines
  176. t.Helper()
  177. for i := uint64(0); i <= server.handler.blockchain.CurrentHeader().Number.Uint64(); i++ {
  178. bhash := rawdb.ReadCanonicalHash(server.db, i)
  179. b1 := fn(light.NoOdr, server.db, server.handler.server.chainConfig, server.handler.blockchain, nil, bhash)
  180. // Set the timeout as 1 second here, ensure there is enough time
  181. // for travis to make the action.
  182. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  183. b2 := fn(ctx, client.db, client.handler.backend.chainConfig, nil, client.handler.backend.blockchain, bhash)
  184. cancel()
  185. eq := bytes.Equal(b1, b2)
  186. exp := i < expFail
  187. if exp && !eq {
  188. t.Fatalf("odr mismatch: have %x, want %x", b2, b1)
  189. }
  190. if !exp && eq {
  191. t.Fatalf("unexpected odr match")
  192. }
  193. }
  194. }
  195. // expect retrievals to fail (except genesis block) without a les peer
  196. client.handler.backend.peers.lock.Lock()
  197. client.peer.speer.hasBlock = func(common.Hash, uint64, bool) bool { return false }
  198. client.handler.backend.peers.lock.Unlock()
  199. test(expFail)
  200. // expect all retrievals to pass
  201. client.handler.backend.peers.lock.Lock()
  202. client.peer.speer.hasBlock = func(common.Hash, uint64, bool) bool { return true }
  203. client.handler.backend.peers.lock.Unlock()
  204. test(5)
  205. // still expect all retrievals to pass, now data should be cached locally
  206. if checkCached {
  207. client.handler.backend.peers.unregister(client.peer.speer.id)
  208. time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed
  209. test(5)
  210. }
  211. }