odr_test.go 7.0 KB

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