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