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