odr_test.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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/state"
  27. "github.com/ethereum/go-ethereum/core/types"
  28. "github.com/ethereum/go-ethereum/core/vm"
  29. "github.com/ethereum/go-ethereum/eth"
  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 TestOdrGetBlockLes1(t *testing.T) { testOdr(t, 1, 1, odrGetBlock) }
  37. func TestOdrGetBlockLes2(t *testing.T) { testOdr(t, 2, 1, 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 TestOdrGetReceiptsLes1(t *testing.T) { testOdr(t, 1, 1, odrGetReceipts) }
  52. func TestOdrGetReceiptsLes2(t *testing.T) { testOdr(t, 2, 1, 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. receipts = core.GetBlockReceipts(db, bhash, core.GetBlockNumber(db, bhash))
  57. } else {
  58. receipts, _ = light.GetBlockReceipts(ctx, lc.Odr(), bhash, core.GetBlockNumber(db, bhash))
  59. }
  60. if receipts == nil {
  61. return nil
  62. }
  63. rlp, _ := rlp.EncodeToBytes(receipts)
  64. return rlp
  65. }
  66. func TestOdrAccountsLes1(t *testing.T) { testOdr(t, 1, 1, odrAccounts) }
  67. func TestOdrAccountsLes2(t *testing.T) { testOdr(t, 2, 1, odrAccounts) }
  68. func odrAccounts(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte {
  69. dummyAddr := common.HexToAddress("1234567812345678123456781234567812345678")
  70. acc := []common.Address{testBankAddress, acc1Addr, acc2Addr, dummyAddr}
  71. var (
  72. res []byte
  73. st *state.StateDB
  74. err error
  75. )
  76. for _, addr := range acc {
  77. if bc != nil {
  78. header := bc.GetHeaderByHash(bhash)
  79. st, err = state.New(header.Root, state.NewDatabase(db))
  80. } else {
  81. header := lc.GetHeaderByHash(bhash)
  82. st = light.NewState(ctx, header, lc.Odr())
  83. }
  84. if err == nil {
  85. bal := st.GetBalance(addr)
  86. rlp, _ := rlp.EncodeToBytes(bal)
  87. res = append(res, rlp...)
  88. }
  89. }
  90. return res
  91. }
  92. func TestOdrContractCallLes1(t *testing.T) { testOdr(t, 1, 2, odrContractCall) }
  93. func TestOdrContractCallLes2(t *testing.T) { testOdr(t, 2, 2, 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 testOdr(t *testing.T, protocol int, expFail uint64, fn odrTestFn) {
  134. // Assemble the test environment
  135. peers := newPeerSet()
  136. dist := newRequestDistributor(peers, make(chan struct{}))
  137. rm := newRetrieveManager(peers, dist, nil)
  138. db, _ := ethdb.NewMemDatabase()
  139. ldb, _ := ethdb.NewMemDatabase()
  140. odr := NewLesOdr(ldb, light.NewChtIndexer(db, true), light.NewBloomTrieIndexer(db, true), eth.NewBloomIndexer(db, light.BloomTrieFrequency), rm)
  141. pm := newTestProtocolManagerMust(t, false, 4, testChainGen, nil, nil, db)
  142. lpm := newTestProtocolManagerMust(t, true, 0, nil, peers, odr, ldb)
  143. _, err1, lpeer, err2 := newTestPeerPair("peer", protocol, pm, lpm)
  144. select {
  145. case <-time.After(time.Millisecond * 100):
  146. case err := <-err1:
  147. t.Fatalf("peer 1 handshake error: %v", err)
  148. case err := <-err2:
  149. t.Fatalf("peer 1 handshake error: %v", err)
  150. }
  151. lpm.synchronise(lpeer)
  152. test := func(expFail uint64) {
  153. for i := uint64(0); i <= pm.blockchain.CurrentHeader().Number.Uint64(); i++ {
  154. bhash := core.GetCanonicalHash(db, i)
  155. b1 := fn(light.NoOdr, db, pm.chainConfig, pm.blockchain.(*core.BlockChain), nil, bhash)
  156. ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
  157. defer cancel()
  158. b2 := fn(ctx, ldb, lpm.chainConfig, nil, lpm.blockchain.(*light.LightChain), bhash)
  159. eq := bytes.Equal(b1, b2)
  160. exp := i < expFail
  161. if exp && !eq {
  162. t.Errorf("odr mismatch")
  163. }
  164. if !exp && eq {
  165. t.Errorf("unexpected odr match")
  166. }
  167. }
  168. }
  169. // temporarily remove peer to test odr fails
  170. // expect retrievals to fail (except genesis block) without a les peer
  171. peers.Unregister(lpeer.id)
  172. time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed
  173. test(expFail)
  174. // expect all retrievals to pass
  175. peers.Register(lpeer)
  176. time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed
  177. lpeer.lock.Lock()
  178. lpeer.hasBlock = func(common.Hash, uint64) bool { return true }
  179. lpeer.lock.Unlock()
  180. test(5)
  181. // still expect all retrievals to pass, now data should be cached locally
  182. peers.Unregister(lpeer.id)
  183. time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed
  184. test(5)
  185. }