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