github.com/energicryptocurrency/go-energi@v1.1.7/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/energicryptocurrency/go-energi/common" 30 "github.com/energicryptocurrency/go-energi/consensus/ethash" 31 "github.com/energicryptocurrency/go-energi/core" 32 "github.com/energicryptocurrency/go-energi/core/types" 33 "github.com/energicryptocurrency/go-energi/core/vm" 34 "github.com/energicryptocurrency/go-energi/crypto" 35 "github.com/energicryptocurrency/go-energi/eth" 36 "github.com/energicryptocurrency/go-energi/ethdb" 37 "github.com/energicryptocurrency/go-energi/event" 38 "github.com/energicryptocurrency/go-energi/les/flowcontrol" 39 "github.com/energicryptocurrency/go-energi/light" 40 "github.com/energicryptocurrency/go-energi/p2p" 41 "github.com/energicryptocurrency/go-energi/p2p/enode" 42 "github.com/energicryptocurrency/go-energi/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) ( 257 *peer, <-chan error, *peer, <-chan error) { 258 // Create a message pipe to communicate through 259 app, net := p2p.MsgPipe() 260 261 // Generate a random id and create the peer 262 var id enode.ID 263 _, _ = rand.Read(id[:]) 264 265 peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net) 266 peer2 := pm2.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), app) 267 268 // Start the peer on a new thread 269 errc := make(chan error, 1) 270 errc2 := make(chan error, 1) 271 go func() { 272 select { 273 case pm.newPeerCh <- peer: 274 errc <- pm.handle(peer) 275 case <-pm.quitSync: 276 errc <- p2p.DiscQuitting 277 } 278 }() 279 go func() { 280 select { 281 case pm2.newPeerCh <- peer2: 282 errc2 <- pm2.handle(peer2) 283 case <-pm2.quitSync: 284 errc2 <- p2p.DiscQuitting 285 } 286 }() 287 return peer, errc, peer2, errc2 288 } 289 290 // handshake simulates a trivial handshake that expects the same state from the 291 // remote side as we are simulating locally. 292 func (p *testPeer) handshake(t *testing.T, td *big.Int, head common.Hash, headNum uint64, genesis common.Hash) { 293 var expList keyValueList 294 expList = expList.add("protocolVersion", uint64(p.version)) 295 expList = expList.add("networkId", uint64(NetworkId)) 296 expList = expList.add("headTd", td) 297 expList = expList.add("headHash", head) 298 expList = expList.add("headNum", headNum) 299 expList = expList.add("genesisHash", genesis) 300 sendList := make(keyValueList, len(expList)) 301 copy(sendList, expList) 302 expList = expList.add("serveHeaders", nil) 303 expList = expList.add("serveChainSince", uint64(0)) 304 expList = expList.add("serveStateSince", uint64(0)) 305 expList = expList.add("txRelay", nil) 306 expList = expList.add("flowControl/BL", testBufLimit) 307 expList = expList.add("flowControl/MRR", uint64(1)) 308 expList = expList.add("flowControl/MRC", testRCL()) 309 310 if err := p2p.ExpectMsg(p.app, StatusMsg, expList); err != nil { 311 t.Fatalf("status recv: %v", err) 312 } 313 if err := p2p.Send(p.app, StatusMsg, sendList); err != nil { 314 t.Fatalf("status send: %v", err) 315 } 316 317 p.fcServerParams = &flowcontrol.ServerParams{ 318 BufLimit: testBufLimit, 319 MinRecharge: 1, 320 } 321 } 322 323 // close terminates the local side of the peer, notifying the remote protocol 324 // manager of termination. 325 func (p *testPeer) close() { 326 p.app.Close() 327 } 328 329 // TestEntity represents a network entity for testing with necessary auxiliary fields. 330 type TestEntity struct { 331 db ethdb.Database 332 rPeer *peer 333 tPeer *testPeer 334 peers *peerSet 335 pm *ProtocolManager 336 // Indexers 337 chtIndexer *core.ChainIndexer 338 bloomIndexer *core.ChainIndexer 339 bloomTrieIndexer *core.ChainIndexer 340 } 341 342 // newServerEnv creates a server testing environment with a connected test peer for testing purpose. 343 func newServerEnv(t *testing.T, blocks int, protocol int, waitIndexers func(*core.ChainIndexer, *core.ChainIndexer, *core.ChainIndexer)) (*TestEntity, func()) { 344 db := ethdb.NewMemDatabase() 345 cIndexer, bIndexer, btIndexer := testIndexers(db, nil, light.TestServerIndexerConfig) 346 347 pm := newTestProtocolManagerMust(t, false, blocks, testChainGen, nil, nil, db) 348 peer, _ := newTestPeer(t, "peer", protocol, pm, true) 349 350 cIndexer.Start(pm.blockchain.(*core.BlockChain)) 351 bIndexer.Start(pm.blockchain.(*core.BlockChain)) 352 353 // Wait until indexers generate enough index data. 354 if waitIndexers != nil { 355 waitIndexers(cIndexer, bIndexer, btIndexer) 356 } 357 358 return &TestEntity{ 359 db: db, 360 tPeer: peer, 361 pm: pm, 362 chtIndexer: cIndexer, 363 bloomIndexer: bIndexer, 364 bloomTrieIndexer: btIndexer, 365 }, func() { 366 peer.close() 367 // Note bloom trie indexer will be closed by it parent recursively. 368 cIndexer.Close() 369 bIndexer.Close() 370 } 371 } 372 373 // newClientServerEnv creates a client/server arch environment with a connected les server and light client pair 374 // for testing purpose. 375 func newClientServerEnv(t *testing.T, blocks int, protocol int, waitIndexers func(*core.ChainIndexer, *core.ChainIndexer, *core.ChainIndexer), newPeer bool) (*TestEntity, *TestEntity, func()) { 376 db, ldb := ethdb.NewMemDatabase(), ethdb.NewMemDatabase() 377 peers, lPeers := newPeerSet(), newPeerSet() 378 379 dist := newRequestDistributor(lPeers, make(chan struct{})) 380 rm := newRetrieveManager(lPeers, dist, nil) 381 odr := NewLesOdr(ldb, light.TestClientIndexerConfig, rm) 382 383 cIndexer, bIndexer, btIndexer := testIndexers(db, nil, light.TestServerIndexerConfig) 384 lcIndexer, lbIndexer, lbtIndexer := testIndexers(ldb, odr, light.TestClientIndexerConfig) 385 odr.SetIndexers(lcIndexer, lbtIndexer, lbIndexer) 386 387 pm := newTestProtocolManagerMust(t, false, blocks, testChainGen, nil, peers, db) 388 lpm := newTestProtocolManagerMust(t, true, 0, nil, odr, lPeers, ldb) 389 390 startIndexers := func(clientMode bool, pm *ProtocolManager) { 391 if clientMode { 392 lcIndexer.Start(pm.blockchain.(*light.LightChain)) 393 lbIndexer.Start(pm.blockchain.(*light.LightChain)) 394 } else { 395 cIndexer.Start(pm.blockchain.(*core.BlockChain)) 396 bIndexer.Start(pm.blockchain.(*core.BlockChain)) 397 } 398 } 399 400 startIndexers(false, pm) 401 startIndexers(true, lpm) 402 403 // Execute wait until function if it is specified. 404 if waitIndexers != nil { 405 waitIndexers(cIndexer, bIndexer, btIndexer) 406 } 407 408 var ( 409 peer, lPeer *peer 410 err1, err2 <-chan error 411 ) 412 if newPeer { 413 peer, err1, lPeer, err2 = newTestPeerPair("peer", protocol, pm, lpm) 414 select { 415 case <-time.After(time.Millisecond * 100): 416 case err := <-err1: 417 t.Fatalf("peer 1 handshake error: %v", err) 418 case err := <-err2: 419 t.Fatalf("peer 2 handshake error: %v", err) 420 } 421 } 422 423 return &TestEntity{ 424 db: db, 425 pm: pm, 426 rPeer: peer, 427 peers: peers, 428 chtIndexer: cIndexer, 429 bloomIndexer: bIndexer, 430 bloomTrieIndexer: btIndexer, 431 }, &TestEntity{ 432 db: ldb, 433 pm: lpm, 434 rPeer: lPeer, 435 peers: lPeers, 436 chtIndexer: lcIndexer, 437 bloomIndexer: lbIndexer, 438 bloomTrieIndexer: lbtIndexer, 439 }, func() { 440 // Note bloom trie indexers will be closed by their parents recursively. 441 cIndexer.Close() 442 bIndexer.Close() 443 lcIndexer.Close() 444 lbIndexer.Close() 445 } 446 }