github.com/sonm-io/go-ethereum@v1.8.18/les/helper_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 // This file contains some shares testing functionality, common to multiple 18 // different files and modules being tested. 19 20 package les 21 22 import ( 23 "crypto/rand" 24 "math/big" 25 "sync" 26 "testing" 27 "time" 28 29 "github.com/ethereum/go-ethereum/common" 30 "github.com/ethereum/go-ethereum/consensus/ethash" 31 "github.com/ethereum/go-ethereum/core" 32 "github.com/ethereum/go-ethereum/core/types" 33 "github.com/ethereum/go-ethereum/core/vm" 34 "github.com/ethereum/go-ethereum/crypto" 35 "github.com/ethereum/go-ethereum/eth" 36 "github.com/ethereum/go-ethereum/ethdb" 37 "github.com/ethereum/go-ethereum/event" 38 "github.com/ethereum/go-ethereum/les/flowcontrol" 39 "github.com/ethereum/go-ethereum/light" 40 "github.com/ethereum/go-ethereum/p2p" 41 "github.com/ethereum/go-ethereum/p2p/enode" 42 "github.com/ethereum/go-ethereum/params" 43 ) 44 45 var ( 46 testBankKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 47 testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey) 48 testBankFunds = big.NewInt(1000000000000000000) 49 50 acc1Key, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a") 51 acc2Key, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee") 52 acc1Addr = crypto.PubkeyToAddress(acc1Key.PublicKey) 53 acc2Addr = crypto.PubkeyToAddress(acc2Key.PublicKey) 54 55 testContractCode = common.Hex2Bytes("606060405260cc8060106000396000f360606040526000357c01000000000000000000000000000000000000000000000000000000009004806360cd2685146041578063c16431b914606b57603f565b005b6055600480803590602001909190505060a9565b6040518082815260200191505060405180910390f35b60886004808035906020019091908035906020019091905050608a565b005b80600060005083606481101560025790900160005b50819055505b5050565b6000600060005082606481101560025790900160005b5054905060c7565b91905056") 56 testContractAddr common.Address 57 testContractCodeDeployed = testContractCode[16:] 58 testContractDeployed = uint64(2) 59 60 testEventEmitterCode = common.Hex2Bytes("60606040523415600e57600080fd5b7f57050ab73f6b9ebdd9f76b8d4997793f48cf956e965ee070551b9ca0bb71584e60405160405180910390a160358060476000396000f3006060604052600080fd00a165627a7a723058203f727efcad8b5811f8cb1fc2620ce5e8c63570d697aef968172de296ea3994140029") 61 testEventEmitterAddr common.Address 62 63 testBufLimit = uint64(100) 64 ) 65 66 /* 67 contract test { 68 69 uint256[100] data; 70 71 function Put(uint256 addr, uint256 value) { 72 data[addr] = value; 73 } 74 75 function Get(uint256 addr) constant returns (uint256 value) { 76 return data[addr]; 77 } 78 } 79 */ 80 81 func testChainGen(i int, block *core.BlockGen) { 82 signer := types.HomesteadSigner{} 83 84 switch i { 85 case 0: 86 // In block 1, the test bank sends account #1 some ether. 87 tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, testBankKey) 88 block.AddTx(tx) 89 case 1: 90 // In block 2, the test bank sends some more ether to account #1. 91 // acc1Addr passes it on to account #2. 92 // acc1Addr creates a test contract. 93 // acc1Addr creates a test event. 94 nonce := block.TxNonce(acc1Addr) 95 96 tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, testBankKey) 97 tx2, _ := types.SignTx(types.NewTransaction(nonce, acc2Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, acc1Key) 98 tx3, _ := types.SignTx(types.NewContractCreation(nonce+1, big.NewInt(0), 200000, big.NewInt(0), testContractCode), signer, acc1Key) 99 testContractAddr = crypto.CreateAddress(acc1Addr, nonce+1) 100 tx4, _ := types.SignTx(types.NewContractCreation(nonce+2, big.NewInt(0), 200000, big.NewInt(0), testEventEmitterCode), signer, acc1Key) 101 testEventEmitterAddr = crypto.CreateAddress(acc1Addr, nonce+2) 102 block.AddTx(tx1) 103 block.AddTx(tx2) 104 block.AddTx(tx3) 105 block.AddTx(tx4) 106 case 2: 107 // Block 3 is empty but was mined by account #2. 108 block.SetCoinbase(acc2Addr) 109 block.SetExtra([]byte("yeehaw")) 110 data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001") 111 tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, nil, data), signer, testBankKey) 112 block.AddTx(tx) 113 case 3: 114 // Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data). 115 b2 := block.PrevBlock(1).Header() 116 b2.Extra = []byte("foo") 117 block.AddUncle(b2) 118 b3 := block.PrevBlock(2).Header() 119 b3.Extra = []byte("foo") 120 block.AddUncle(b3) 121 data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002") 122 tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, nil, data), signer, testBankKey) 123 block.AddTx(tx) 124 } 125 } 126 127 // testIndexers creates a set of indexers with specified params for testing purpose. 128 func testIndexers(db ethdb.Database, odr light.OdrBackend, iConfig *light.IndexerConfig) (*core.ChainIndexer, *core.ChainIndexer, *core.ChainIndexer) { 129 chtIndexer := light.NewChtIndexer(db, odr, iConfig.ChtSize, iConfig.ChtConfirms) 130 bloomIndexer := eth.NewBloomIndexer(db, iConfig.BloomSize, iConfig.BloomConfirms) 131 bloomTrieIndexer := light.NewBloomTrieIndexer(db, odr, iConfig.BloomSize, iConfig.BloomTrieSize) 132 bloomIndexer.AddChildIndexer(bloomTrieIndexer) 133 return chtIndexer, bloomIndexer, bloomTrieIndexer 134 } 135 136 func testRCL() RequestCostList { 137 cl := make(RequestCostList, len(reqList)) 138 for i, code := range reqList { 139 cl[i].MsgCode = code 140 cl[i].BaseCost = 0 141 cl[i].ReqCost = 0 142 } 143 return cl 144 } 145 146 // newTestProtocolManager creates a new protocol manager for testing purposes, 147 // with the given number of blocks already known, potential notification 148 // channels for different events and relative chain indexers array. 149 func newTestProtocolManager(lightSync bool, blocks int, generator func(int, *core.BlockGen), odr *LesOdr, peers *peerSet, db ethdb.Database) (*ProtocolManager, error) { 150 var ( 151 evmux = new(event.TypeMux) 152 engine = ethash.NewFaker() 153 gspec = core.Genesis{ 154 Config: params.TestChainConfig, 155 Alloc: core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}}, 156 } 157 genesis = gspec.MustCommit(db) 158 chain BlockChain 159 ) 160 if peers == nil { 161 peers = newPeerSet() 162 } 163 164 if lightSync { 165 chain, _ = light.NewLightChain(odr, gspec.Config, engine) 166 } else { 167 blockchain, _ := core.NewBlockChain(db, nil, gspec.Config, engine, vm.Config{}, nil) 168 gchain, _ := core.GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, blocks, generator) 169 if _, err := blockchain.InsertChain(gchain); err != nil { 170 panic(err) 171 } 172 chain = blockchain 173 } 174 175 indexConfig := light.TestServerIndexerConfig 176 if lightSync { 177 indexConfig = light.TestClientIndexerConfig 178 } 179 pm, err := NewProtocolManager(gspec.Config, indexConfig, lightSync, NetworkId, evmux, engine, peers, chain, nil, db, odr, nil, nil, make(chan struct{}), new(sync.WaitGroup)) 180 if err != nil { 181 return nil, err 182 } 183 if !lightSync { 184 srv := &LesServer{lesCommons: lesCommons{protocolManager: pm}} 185 pm.server = srv 186 187 srv.defParams = &flowcontrol.ServerParams{ 188 BufLimit: testBufLimit, 189 MinRecharge: 1, 190 } 191 192 srv.fcManager = flowcontrol.NewClientManager(50, 10, 1000000000) 193 srv.fcCostStats = newCostStats(nil) 194 } 195 pm.Start(1000) 196 return pm, nil 197 } 198 199 // newTestProtocolManagerMust creates a new protocol manager for testing purposes, 200 // with the given number of blocks already known, potential notification 201 // channels for different events and relative chain indexers array. In case of an error, the constructor force- 202 // fails the test. 203 func newTestProtocolManagerMust(t *testing.T, lightSync bool, blocks int, generator func(int, *core.BlockGen), odr *LesOdr, peers *peerSet, db ethdb.Database) *ProtocolManager { 204 pm, err := newTestProtocolManager(lightSync, blocks, generator, odr, peers, db) 205 if err != nil { 206 t.Fatalf("Failed to create protocol manager: %v", err) 207 } 208 return pm 209 } 210 211 // testPeer is a simulated peer to allow testing direct network calls. 212 type testPeer struct { 213 net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging 214 app *p2p.MsgPipeRW // Application layer reader/writer to simulate the local side 215 *peer 216 } 217 218 // newTestPeer creates a new peer registered at the given protocol manager. 219 func newTestPeer(t *testing.T, name string, version int, pm *ProtocolManager, shake bool) (*testPeer, <-chan error) { 220 // Create a message pipe to communicate through 221 app, net := p2p.MsgPipe() 222 223 // Generate a random id and create the peer 224 var id enode.ID 225 rand.Read(id[:]) 226 227 peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net) 228 229 // Start the peer on a new thread 230 errc := make(chan error, 1) 231 go func() { 232 select { 233 case pm.newPeerCh <- peer: 234 errc <- pm.handle(peer) 235 case <-pm.quitSync: 236 errc <- p2p.DiscQuitting 237 } 238 }() 239 tp := &testPeer{ 240 app: app, 241 net: net, 242 peer: peer, 243 } 244 // Execute any implicitly requested handshakes and return 245 if shake { 246 var ( 247 genesis = pm.blockchain.Genesis() 248 head = pm.blockchain.CurrentHeader() 249 td = pm.blockchain.GetTd(head.Hash(), head.Number.Uint64()) 250 ) 251 tp.handshake(t, td, head.Hash(), head.Number.Uint64(), genesis.Hash()) 252 } 253 return tp, errc 254 } 255 256 func newTestPeerPair(name string, version int, pm, pm2 *ProtocolManager) (*peer, <-chan error, *peer, <-chan error) { 257 // Create a message pipe to communicate through 258 app, net := p2p.MsgPipe() 259 260 // Generate a random id and create the peer 261 var id enode.ID 262 rand.Read(id[:]) 263 264 peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net) 265 peer2 := pm2.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), app) 266 267 // Start the peer on a new thread 268 errc := make(chan error, 1) 269 errc2 := make(chan error, 1) 270 go func() { 271 select { 272 case pm.newPeerCh <- peer: 273 errc <- pm.handle(peer) 274 case <-pm.quitSync: 275 errc <- p2p.DiscQuitting 276 } 277 }() 278 go func() { 279 select { 280 case pm2.newPeerCh <- peer2: 281 errc2 <- pm2.handle(peer2) 282 case <-pm2.quitSync: 283 errc2 <- p2p.DiscQuitting 284 } 285 }() 286 return peer, errc, peer2, errc2 287 } 288 289 // handshake simulates a trivial handshake that expects the same state from the 290 // remote side as we are simulating locally. 291 func (p *testPeer) handshake(t *testing.T, td *big.Int, head common.Hash, headNum uint64, genesis common.Hash) { 292 var expList keyValueList 293 expList = expList.add("protocolVersion", uint64(p.version)) 294 expList = expList.add("networkId", uint64(NetworkId)) 295 expList = expList.add("headTd", td) 296 expList = expList.add("headHash", head) 297 expList = expList.add("headNum", headNum) 298 expList = expList.add("genesisHash", genesis) 299 sendList := make(keyValueList, len(expList)) 300 copy(sendList, expList) 301 expList = expList.add("serveHeaders", nil) 302 expList = expList.add("serveChainSince", uint64(0)) 303 expList = expList.add("serveStateSince", uint64(0)) 304 expList = expList.add("txRelay", nil) 305 expList = expList.add("flowControl/BL", testBufLimit) 306 expList = expList.add("flowControl/MRR", uint64(1)) 307 expList = expList.add("flowControl/MRC", testRCL()) 308 309 if err := p2p.ExpectMsg(p.app, StatusMsg, expList); err != nil { 310 t.Fatalf("status recv: %v", err) 311 } 312 if err := p2p.Send(p.app, StatusMsg, sendList); err != nil { 313 t.Fatalf("status send: %v", err) 314 } 315 316 p.fcServerParams = &flowcontrol.ServerParams{ 317 BufLimit: testBufLimit, 318 MinRecharge: 1, 319 } 320 } 321 322 // close terminates the local side of the peer, notifying the remote protocol 323 // manager of termination. 324 func (p *testPeer) close() { 325 p.app.Close() 326 } 327 328 // TestEntity represents a network entity for testing with necessary auxiliary fields. 329 type TestEntity struct { 330 db ethdb.Database 331 rPeer *peer 332 tPeer *testPeer 333 peers *peerSet 334 pm *ProtocolManager 335 // Indexers 336 chtIndexer *core.ChainIndexer 337 bloomIndexer *core.ChainIndexer 338 bloomTrieIndexer *core.ChainIndexer 339 } 340 341 // newServerEnv creates a server testing environment with a connected test peer for testing purpose. 342 func newServerEnv(t *testing.T, blocks int, protocol int, waitIndexers func(*core.ChainIndexer, *core.ChainIndexer, *core.ChainIndexer)) (*TestEntity, func()) { 343 db := ethdb.NewMemDatabase() 344 cIndexer, bIndexer, btIndexer := testIndexers(db, nil, light.TestServerIndexerConfig) 345 346 pm := newTestProtocolManagerMust(t, false, blocks, testChainGen, nil, nil, db) 347 peer, _ := newTestPeer(t, "peer", protocol, pm, true) 348 349 cIndexer.Start(pm.blockchain.(*core.BlockChain)) 350 bIndexer.Start(pm.blockchain.(*core.BlockChain)) 351 352 // Wait until indexers generate enough index data. 353 if waitIndexers != nil { 354 waitIndexers(cIndexer, bIndexer, btIndexer) 355 } 356 357 return &TestEntity{ 358 db: db, 359 tPeer: peer, 360 pm: pm, 361 chtIndexer: cIndexer, 362 bloomIndexer: bIndexer, 363 bloomTrieIndexer: btIndexer, 364 }, func() { 365 peer.close() 366 // Note bloom trie indexer will be closed by it parent recursively. 367 cIndexer.Close() 368 bIndexer.Close() 369 } 370 } 371 372 // newClientServerEnv creates a client/server arch environment with a connected les server and light client pair 373 // for testing purpose. 374 func newClientServerEnv(t *testing.T, blocks int, protocol int, waitIndexers func(*core.ChainIndexer, *core.ChainIndexer, *core.ChainIndexer), newPeer bool) (*TestEntity, *TestEntity, func()) { 375 db, ldb := ethdb.NewMemDatabase(), ethdb.NewMemDatabase() 376 peers, lPeers := newPeerSet(), newPeerSet() 377 378 dist := newRequestDistributor(lPeers, make(chan struct{})) 379 rm := newRetrieveManager(lPeers, dist, nil) 380 odr := NewLesOdr(ldb, light.TestClientIndexerConfig, rm) 381 382 cIndexer, bIndexer, btIndexer := testIndexers(db, nil, light.TestServerIndexerConfig) 383 lcIndexer, lbIndexer, lbtIndexer := testIndexers(ldb, odr, light.TestClientIndexerConfig) 384 odr.SetIndexers(lcIndexer, lbtIndexer, lbIndexer) 385 386 pm := newTestProtocolManagerMust(t, false, blocks, testChainGen, nil, peers, db) 387 lpm := newTestProtocolManagerMust(t, true, 0, nil, odr, lPeers, ldb) 388 389 startIndexers := func(clientMode bool, pm *ProtocolManager) { 390 if clientMode { 391 lcIndexer.Start(pm.blockchain.(*light.LightChain)) 392 lbIndexer.Start(pm.blockchain.(*light.LightChain)) 393 } else { 394 cIndexer.Start(pm.blockchain.(*core.BlockChain)) 395 bIndexer.Start(pm.blockchain.(*core.BlockChain)) 396 } 397 } 398 399 startIndexers(false, pm) 400 startIndexers(true, lpm) 401 402 // Execute wait until function if it is specified. 403 if waitIndexers != nil { 404 waitIndexers(cIndexer, bIndexer, btIndexer) 405 } 406 407 var ( 408 peer, lPeer *peer 409 err1, err2 <-chan error 410 ) 411 if newPeer { 412 peer, err1, lPeer, err2 = newTestPeerPair("peer", protocol, pm, lpm) 413 select { 414 case <-time.After(time.Millisecond * 100): 415 case err := <-err1: 416 t.Fatalf("peer 1 handshake error: %v", err) 417 case err := <-err2: 418 t.Fatalf("peer 2 handshake error: %v", err) 419 } 420 } 421 422 return &TestEntity{ 423 db: db, 424 pm: pm, 425 rPeer: peer, 426 peers: peers, 427 chtIndexer: cIndexer, 428 bloomIndexer: bIndexer, 429 bloomTrieIndexer: btIndexer, 430 }, &TestEntity{ 431 db: ldb, 432 pm: lpm, 433 rPeer: lPeer, 434 peers: lPeers, 435 chtIndexer: lcIndexer, 436 bloomIndexer: lbIndexer, 437 bloomTrieIndexer: lbtIndexer, 438 }, func() { 439 // Note bloom trie indexers will be closed by their parents recursively. 440 cIndexer.Close() 441 bIndexer.Close() 442 lcIndexer.Close() 443 lbIndexer.Close() 444 } 445 }