odr_test.go 7.6 KB

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