odr_test.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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 odrGetBlock(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
  38. var block *types.Block
  39. if bc != nil {
  40. block = bc.GetBlockByHash(bhash)
  41. } else {
  42. block, _ = lc.GetBlockByHash(ctx, bhash)
  43. }
  44. if block == nil {
  45. return nil
  46. }
  47. rlp, _ := rlp.EncodeToBytes(block)
  48. return rlp
  49. }
  50. func TestOdrGetReceiptsLes2(t *testing.T) { testOdr(t, 2, 1, true, odrGetReceipts) }
  51. func odrGetReceipts(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
  52. var receipts types.Receipts
  53. if bc != nil {
  54. if number := rawdb.ReadHeaderNumber(db, bhash); number != nil {
  55. receipts = rawdb.ReadReceipts(db, bhash, *number, config)
  56. }
  57. } else {
  58. if number := rawdb.ReadHeaderNumber(db, bhash); number != nil {
  59. receipts, _ = light.GetBlockReceipts(ctx, lc.Odr(), bhash, *number)
  60. }
  61. }
  62. if receipts == nil {
  63. return nil
  64. }
  65. rlp, _ := rlp.EncodeToBytes(receipts)
  66. return rlp
  67. }
  68. func TestOdrAccountsLes2(t *testing.T) { testOdr(t, 2, 1, true, odrAccounts) }
  69. func odrAccounts(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
  70. dummyAddr := common.HexToAddress("1234567812345678123456781234567812345678")
  71. acc := []common.Address{testBankAddress, acc1Addr, acc2Addr, dummyAddr}
  72. var (
  73. res []byte
  74. st *state.StateDB
  75. err error
  76. )
  77. for _, addr := range acc {
  78. if bc != nil {
  79. header := bc.GetHeaderByHash(bhash)
  80. st, err = state.New(header.Root, state.NewDatabase(db))
  81. } else {
  82. header := lc.GetHeaderByHash(bhash)
  83. st = light.NewState(ctx, header, lc.Odr())
  84. }
  85. if err == nil {
  86. bal := st.GetBalance(addr)
  87. rlp, _ := rlp.EncodeToBytes(bal)
  88. res = append(res, rlp...)
  89. }
  90. }
  91. return res
  92. }
  93. func TestOdrContractCallLes2(t *testing.T) { testOdr(t, 2, 2, true, odrContractCall) }
  94. type callmsg struct {
  95. types.Message
  96. }
  97. func (callmsg) CheckNonce() bool { return false }
  98. func odrContractCall(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
  99. data := common.Hex2Bytes("60CD26850000000000000000000000000000000000000000000000000000000000000000")
  100. var res []byte
  101. for i := 0; i < 3; i++ {
  102. data[35] = byte(i)
  103. if bc != nil {
  104. header := bc.GetHeaderByHash(bhash)
  105. statedb, err := state.New(header.Root, state.NewDatabase(db))
  106. if err == nil {
  107. from := statedb.GetOrNewStateObject(testBankAddress)
  108. from.SetBalance(math.MaxBig256)
  109. msg := callmsg{types.NewMessage(from.Address(), &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false)}
  110. context := core.NewEVMContext(msg, header, bc, nil)
  111. vmenv := vm.NewEVM(context, statedb, config, vm.Config{})
  112. //vmenv := core.NewEnv(statedb, config, bc, msg, header, vm.Config{})
  113. gp := new(core.GasPool).AddGas(math.MaxUint64)
  114. ret, _, _, _ := core.ApplyMessage(vmenv, msg, gp)
  115. res = append(res, ret...)
  116. }
  117. } else {
  118. header := lc.GetHeaderByHash(bhash)
  119. state := light.NewState(ctx, header, lc.Odr())
  120. state.SetBalance(testBankAddress, math.MaxBig256)
  121. msg := callmsg{types.NewMessage(testBankAddress, &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false)}
  122. context := core.NewEVMContext(msg, header, lc, nil)
  123. vmenv := vm.NewEVM(context, state, config, vm.Config{})
  124. gp := new(core.GasPool).AddGas(math.MaxUint64)
  125. ret, _, _, _ := core.ApplyMessage(vmenv, msg, gp)
  126. if state.Error() == nil {
  127. res = append(res, ret...)
  128. }
  129. }
  130. }
  131. return res
  132. }
  133. func TestOdrTxStatusLes2(t *testing.T) { testOdr(t, 2, 1, false, odrTxStatus) }
  134. func odrTxStatus(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
  135. var txs types.Transactions
  136. if bc != nil {
  137. block := bc.GetBlockByHash(bhash)
  138. txs = block.Transactions()
  139. } else {
  140. if block, _ := lc.GetBlockByHash(ctx, bhash); block != nil {
  141. btxs := block.Transactions()
  142. txs = make(types.Transactions, len(btxs))
  143. for i, tx := range btxs {
  144. var err error
  145. txs[i], _, _, _, err = light.GetTransaction(ctx, lc.Odr(), tx.Hash())
  146. if err != nil {
  147. return nil
  148. }
  149. }
  150. }
  151. }
  152. rlp, _ := rlp.EncodeToBytes(txs)
  153. return rlp
  154. }
  155. // testOdr tests odr requests whose validation guaranteed by block headers.
  156. func testOdr(t *testing.T, protocol int, expFail uint64, checkCached bool, fn odrTestFn) {
  157. // Assemble the test environment
  158. server, client, tearDown := newClientServerEnv(t, 4, protocol, nil, true)
  159. defer tearDown()
  160. client.pm.synchronise(client.rPeer)
  161. test := func(expFail uint64) {
  162. // Mark this as a helper to put the failures at the correct lines
  163. t.Helper()
  164. for i := uint64(0); i <= server.pm.blockchain.CurrentHeader().Number.Uint64(); i++ {
  165. bhash := rawdb.ReadCanonicalHash(server.db, i)
  166. b1 := fn(light.NoOdr, server.db, server.pm.chainConfig, server.pm.blockchain.(*core.BlockChain), nil, bhash)
  167. ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
  168. defer cancel()
  169. b2 := fn(ctx, client.db, client.pm.chainConfig, nil, client.pm.blockchain.(*light.LightChain), bhash)
  170. eq := bytes.Equal(b1, b2)
  171. exp := i < expFail
  172. if exp && !eq {
  173. t.Fatalf("odr mismatch: have %x, want %x", b2, b1)
  174. }
  175. if !exp && eq {
  176. t.Fatalf("unexpected odr match")
  177. }
  178. }
  179. }
  180. // temporarily remove peer to test odr fails
  181. // expect retrievals to fail (except genesis block) without a les peer
  182. client.peers.Unregister(client.rPeer.id)
  183. time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed
  184. test(expFail)
  185. // expect all retrievals to pass
  186. client.peers.Register(client.rPeer)
  187. time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed
  188. client.peers.lock.Lock()
  189. client.rPeer.hasBlock = func(common.Hash, uint64, bool) bool { return true }
  190. client.peers.lock.Unlock()
  191. test(5)
  192. if checkCached {
  193. // still expect all retrievals to pass, now data should be cached locally
  194. client.peers.Unregister(client.rPeer.id)
  195. time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed
  196. test(5)
  197. }
  198. }