github.com/zhiqiangxu/go-ethereum@v1.9.16-0.20210824055606-be91cfdebc48/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/zhiqiangxu/go-ethereum/common" 27 "github.com/zhiqiangxu/go-ethereum/common/math" 28 "github.com/zhiqiangxu/go-ethereum/core" 29 "github.com/zhiqiangxu/go-ethereum/core/rawdb" 30 "github.com/zhiqiangxu/go-ethereum/core/state" 31 "github.com/zhiqiangxu/go-ethereum/core/types" 32 "github.com/zhiqiangxu/go-ethereum/core/vm" 33 "github.com/zhiqiangxu/go-ethereum/ethdb" 34 "github.com/zhiqiangxu/go-ethereum/light" 35 "github.com/zhiqiangxu/go-ethereum/params" 36 "github.com/zhiqiangxu/go-ethereum/rlp" 37 ) 38 39 type odrTestFn func(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte 40 41 func TestOdrGetBlockLes2(t *testing.T) { testOdr(t, 2, 1, true, odrGetBlock) } 42 func TestOdrGetBlockLes3(t *testing.T) { testOdr(t, 3, 1, true, odrGetBlock) } 43 44 func odrGetBlock(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte { 45 var block *types.Block 46 if bc != nil { 47 block = bc.GetBlockByHash(bhash) 48 } else { 49 block, _ = lc.GetBlockByHash(ctx, bhash) 50 } 51 if block == nil { 52 return nil 53 } 54 rlp, _ := rlp.EncodeToBytes(block) 55 return rlp 56 } 57 58 func TestOdrGetReceiptsLes2(t *testing.T) { testOdr(t, 2, 1, true, odrGetReceipts) } 59 func TestOdrGetReceiptsLes3(t *testing.T) { testOdr(t, 3, 1, true, odrGetReceipts) } 60 61 func odrGetReceipts(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte { 62 var receipts types.Receipts 63 if bc != nil { 64 if number := rawdb.ReadHeaderNumber(db, bhash); number != nil { 65 receipts = rawdb.ReadReceipts(db, bhash, *number, config) 66 } 67 } else { 68 if number := rawdb.ReadHeaderNumber(db, bhash); number != nil { 69 receipts, _ = light.GetBlockReceipts(ctx, lc.Odr(), bhash, *number) 70 } 71 } 72 if receipts == nil { 73 return nil 74 } 75 rlp, _ := rlp.EncodeToBytes(receipts) 76 return rlp 77 } 78 79 func TestOdrAccountsLes2(t *testing.T) { testOdr(t, 2, 1, true, odrAccounts) } 80 func TestOdrAccountsLes3(t *testing.T) { testOdr(t, 3, 1, true, odrAccounts) } 81 82 func odrAccounts(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte { 83 dummyAddr := common.HexToAddress("1234567812345678123456781234567812345678") 84 acc := []common.Address{bankAddr, userAddr1, userAddr2, dummyAddr} 85 86 var ( 87 res []byte 88 st *state.StateDB 89 err error 90 ) 91 for _, addr := range acc { 92 if bc != nil { 93 header := bc.GetHeaderByHash(bhash) 94 st, err = state.New(header.Root, state.NewDatabase(db), nil) 95 } else { 96 header := lc.GetHeaderByHash(bhash) 97 st = light.NewState(ctx, header, lc.Odr()) 98 } 99 if err == nil { 100 bal := st.GetBalance(addr) 101 rlp, _ := rlp.EncodeToBytes(bal) 102 res = append(res, rlp...) 103 } 104 } 105 return res 106 } 107 108 func TestOdrContractCallLes2(t *testing.T) { testOdr(t, 2, 2, true, odrContractCall) } 109 func TestOdrContractCallLes3(t *testing.T) { testOdr(t, 3, 2, true, odrContractCall) } 110 111 type callmsg struct { 112 types.Message 113 } 114 115 func (callmsg) CheckNonce() bool { return false } 116 117 func odrContractCall(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte { 118 data := common.Hex2Bytes("60CD26850000000000000000000000000000000000000000000000000000000000000000") 119 120 var res []byte 121 for i := 0; i < 3; i++ { 122 data[35] = byte(i) 123 if bc != nil { 124 header := bc.GetHeaderByHash(bhash) 125 statedb, err := state.New(header.Root, state.NewDatabase(db), nil) 126 127 if err == nil { 128 from := statedb.GetOrNewStateObject(bankAddr) 129 from.SetBalance(math.MaxBig256) 130 131 msg := callmsg{types.NewMessage(from.Address(), &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false)} 132 133 context := core.NewEVMContext(msg, header, bc, nil) 134 vmenv := vm.NewEVM(context, statedb, config, vm.Config{}) 135 136 //vmenv := core.NewEnv(statedb, config, bc, msg, header, vm.Config{}) 137 gp := new(core.GasPool).AddGas(math.MaxUint64) 138 result, _ := core.ApplyMessage(vmenv, msg, gp) 139 res = append(res, result.Return()...) 140 } 141 } else { 142 header := lc.GetHeaderByHash(bhash) 143 state := light.NewState(ctx, header, lc.Odr()) 144 state.SetBalance(bankAddr, math.MaxBig256) 145 msg := callmsg{types.NewMessage(bankAddr, &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false)} 146 context := core.NewEVMContext(msg, header, lc, nil) 147 vmenv := vm.NewEVM(context, state, config, vm.Config{}) 148 gp := new(core.GasPool).AddGas(math.MaxUint64) 149 result, _ := core.ApplyMessage(vmenv, msg, gp) 150 if state.Error() == nil { 151 res = append(res, result.Return()...) 152 } 153 } 154 } 155 return res 156 } 157 158 func TestOdrTxStatusLes2(t *testing.T) { testOdr(t, 2, 1, false, odrTxStatus) } 159 func TestOdrTxStatusLes3(t *testing.T) { testOdr(t, 3, 1, false, odrTxStatus) } 160 161 func odrTxStatus(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte { 162 var txs types.Transactions 163 if bc != nil { 164 block := bc.GetBlockByHash(bhash) 165 txs = block.Transactions() 166 } else { 167 if block, _ := lc.GetBlockByHash(ctx, bhash); block != nil { 168 btxs := block.Transactions() 169 txs = make(types.Transactions, len(btxs)) 170 for i, tx := range btxs { 171 var err error 172 txs[i], _, _, _, err = light.GetTransaction(ctx, lc.Odr(), tx.Hash()) 173 if err != nil { 174 return nil 175 } 176 } 177 } 178 } 179 rlp, _ := rlp.EncodeToBytes(txs) 180 return rlp 181 } 182 183 // testOdr tests odr requests whose validation guaranteed by block headers. 184 func testOdr(t *testing.T, protocol int, expFail uint64, checkCached bool, fn odrTestFn) { 185 // Assemble the test environment 186 server, client, tearDown := newClientServerEnv(t, 4, protocol, nil, nil, 0, false, true) 187 defer tearDown() 188 189 // Ensure the client has synced all necessary data. 190 clientHead := client.handler.backend.blockchain.CurrentHeader() 191 if clientHead.Number.Uint64() != 4 { 192 t.Fatalf("Failed to sync the chain with server, head: %v", clientHead.Number.Uint64()) 193 } 194 // Disable the mechanism that we will wait a few time for request 195 // even there is no suitable peer to send right now. 196 waitForPeers = 0 197 198 test := func(expFail uint64) { 199 // Mark this as a helper to put the failures at the correct lines 200 t.Helper() 201 202 for i := uint64(0); i <= server.handler.blockchain.CurrentHeader().Number.Uint64(); i++ { 203 bhash := rawdb.ReadCanonicalHash(server.db, i) 204 b1 := fn(light.NoOdr, server.db, server.handler.server.chainConfig, server.handler.blockchain, nil, bhash) 205 206 // Set the timeout as 1 second here, ensure there is enough time 207 // for travis to make the action. 208 ctx, cancel := context.WithTimeout(context.Background(), time.Second) 209 b2 := fn(ctx, client.db, client.handler.backend.chainConfig, nil, client.handler.backend.blockchain, bhash) 210 cancel() 211 212 eq := bytes.Equal(b1, b2) 213 exp := i < expFail 214 if exp && !eq { 215 t.Fatalf("odr mismatch: have %x, want %x", b2, b1) 216 } 217 if !exp && eq { 218 t.Fatalf("unexpected odr match") 219 } 220 } 221 } 222 223 // expect retrievals to fail (except genesis block) without a les peer 224 client.handler.backend.peers.lock.Lock() 225 client.peer.speer.hasBlock = func(common.Hash, uint64, bool) bool { return false } 226 client.handler.backend.peers.lock.Unlock() 227 test(expFail) 228 229 // expect all retrievals to pass 230 client.handler.backend.peers.lock.Lock() 231 client.peer.speer.hasBlock = func(common.Hash, uint64, bool) bool { return true } 232 client.handler.backend.peers.lock.Unlock() 233 test(5) 234 235 // still expect all retrievals to pass, now data should be cached locally 236 if checkCached { 237 client.handler.backend.peers.unregister(client.peer.speer.id) 238 time.Sleep(time.Millisecond * 10) // ensure that all peerSetNotify callbacks are executed 239 test(5) 240 } 241 }