github.com/jartcoin/go-jartdiuma@v0.0.0-20210708013502-b71bfe42bfc3/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 "context" 24 "crypto/rand" 25 "math/big" 26 "sync" 27 "testing" 28 "time" 29 30 "github.com/jartcoin/go-jartdiuma/accounts/abi/bind" 31 "github.com/jartcoin/go-jartdiuma/accounts/abi/bind/backends" 32 "github.com/jartcoin/go-jartdiuma/common" 33 "github.com/jartcoin/go-jartdiuma/common/mclock" 34 "github.com/jartcoin/go-jartdiuma/consensus/ethash" 35 "github.com/jartcoin/go-jartdiuma/contracts/checkpointoracle/contract" 36 "github.com/jartcoin/go-jartdiuma/core" 37 "github.com/jartcoin/go-jartdiuma/core/rawdb" 38 "github.com/jartcoin/go-jartdiuma/core/types" 39 "github.com/jartcoin/go-jartdiuma/crypto" 40 "github.com/jartcoin/go-jartdiuma/eth" 41 "github.com/jartcoin/go-jartdiuma/ethdb" 42 "github.com/jartcoin/go-jartdiuma/event" 43 "github.com/jartcoin/go-jartdiuma/les/flowcontrol" 44 "github.com/jartcoin/go-jartdiuma/light" 45 "github.com/jartcoin/go-jartdiuma/p2p" 46 "github.com/jartcoin/go-jartdiuma/p2p/enode" 47 "github.com/jartcoin/go-jartdiuma/params" 48 ) 49 50 var ( 51 bankKey, _ = crypto.GenerateKey() 52 bankAddr = crypto.PubkeyToAddress(bankKey.PublicKey) 53 bankFunds = big.NewInt(1000000000000000000) 54 55 userKey1, _ = crypto.GenerateKey() 56 userKey2, _ = crypto.GenerateKey() 57 userAddr1 = crypto.PubkeyToAddress(userKey1.PublicKey) 58 userAddr2 = crypto.PubkeyToAddress(userKey2.PublicKey) 59 60 testContractCode = common.Hex2Bytes("606060405260cc8060106000396000f360606040526000357c01000000000000000000000000000000000000000000000000000000009004806360cd2685146041578063c16431b914606b57603f565b005b6055600480803590602001909190505060a9565b6040518082815260200191505060405180910390f35b60886004808035906020019091908035906020019091905050608a565b005b80600060005083606481101560025790900160005b50819055505b5050565b6000600060005082606481101560025790900160005b5054905060c7565b91905056") 61 testContractAddr common.Address 62 testContractCodeDeployed = testContractCode[16:] 63 testContractDeployed = uint64(2) 64 65 testEventEmitterCode = common.Hex2Bytes("60606040523415600e57600080fd5b7f57050ab73f6b9ebdd9f76b8d4997793f48cf956e965ee070551b9ca0bb71584e60405160405180910390a160358060476000396000f3006060604052600080fd00a165627a7a723058203f727efcad8b5811f8cb1fc2620ce5e8c63570d697aef968172de296ea3994140029") 66 67 // Checkpoint registrar relative 68 registrarAddr common.Address 69 signerKey, _ = crypto.GenerateKey() 70 signerAddr = crypto.PubkeyToAddress(signerKey.PublicKey) 71 ) 72 73 var ( 74 // The block frequency for creating checkpoint(only used in test) 75 sectionSize = big.NewInt(512) 76 77 // The number of confirmations needed to generate a checkpoint(only used in test). 78 processConfirms = big.NewInt(4) 79 80 // 81 testBufLimit = uint64(1000000) 82 testBufRecharge = uint64(1000) 83 ) 84 85 /* 86 contract test { 87 88 uint256[100] data; 89 90 function Put(uint256 addr, uint256 value) { 91 data[addr] = value; 92 } 93 94 function Get(uint256 addr) constant returns (uint256 value) { 95 return data[addr]; 96 } 97 } 98 */ 99 100 // prepareTestchain pre-commits specified number customized blocks into chain. 101 func prepareTestchain(n int, backend *backends.SimulatedBackend) { 102 var ( 103 ctx = context.Background() 104 signer = types.HomesteadSigner{} 105 ) 106 for i := 0; i < n; i++ { 107 switch i { 108 case 0: 109 // deploy checkpoint contract 110 registrarAddr, _, _, _ = contract.DeployCheckpointOracle(bind.NewKeyedTransactor(bankKey), backend, []common.Address{signerAddr}, sectionSize, processConfirms, big.NewInt(1)) 111 // bankUser transfers some ether to user1 112 nonce, _ := backend.PendingNonceAt(ctx, bankAddr) 113 tx, _ := types.SignTx(types.NewTransaction(nonce, userAddr1, big.NewInt(10000), params.TxGas, nil, nil), signer, bankKey) 114 backend.SendTransaction(ctx, tx) 115 case 1: 116 bankNonce, _ := backend.PendingNonceAt(ctx, bankAddr) 117 userNonce1, _ := backend.PendingNonceAt(ctx, userAddr1) 118 119 // bankUser transfers more ether to user1 120 tx1, _ := types.SignTx(types.NewTransaction(bankNonce, userAddr1, big.NewInt(1000), params.TxGas, nil, nil), signer, bankKey) 121 backend.SendTransaction(ctx, tx1) 122 123 // user1 relays ether to user2 124 tx2, _ := types.SignTx(types.NewTransaction(userNonce1, userAddr2, big.NewInt(1000), params.TxGas, nil, nil), signer, userKey1) 125 backend.SendTransaction(ctx, tx2) 126 127 // user1 deploys a test contract 128 tx3, _ := types.SignTx(types.NewContractCreation(userNonce1+1, big.NewInt(0), 200000, big.NewInt(0), testContractCode), signer, userKey1) 129 backend.SendTransaction(ctx, tx3) 130 testContractAddr = crypto.CreateAddress(userAddr1, userNonce1+1) 131 132 // user1 deploys a event contract 133 tx4, _ := types.SignTx(types.NewContractCreation(userNonce1+2, big.NewInt(0), 200000, big.NewInt(0), testEventEmitterCode), signer, userKey1) 134 backend.SendTransaction(ctx, tx4) 135 case 2: 136 // bankUser transfer some ether to signer 137 bankNonce, _ := backend.PendingNonceAt(ctx, bankAddr) 138 tx1, _ := types.SignTx(types.NewTransaction(bankNonce, signerAddr, big.NewInt(1000000000), params.TxGas, nil, nil), signer, bankKey) 139 backend.SendTransaction(ctx, tx1) 140 141 // invoke test contract 142 data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001") 143 tx2, _ := types.SignTx(types.NewTransaction(bankNonce+1, testContractAddr, big.NewInt(0), 100000, nil, data), signer, bankKey) 144 backend.SendTransaction(ctx, tx2) 145 case 3: 146 // invoke test contract 147 bankNonce, _ := backend.PendingNonceAt(ctx, bankAddr) 148 data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002") 149 tx, _ := types.SignTx(types.NewTransaction(bankNonce, testContractAddr, big.NewInt(0), 100000, nil, data), signer, bankKey) 150 backend.SendTransaction(ctx, tx) 151 } 152 backend.Commit() 153 } 154 } 155 156 // testIndexers creates a set of indexers with specified params for testing purpose. 157 func testIndexers(db ethdb.Database, odr light.OdrBackend, config *light.IndexerConfig) []*core.ChainIndexer { 158 var indexers [3]*core.ChainIndexer 159 indexers[0] = light.NewChtIndexer(db, odr, config.ChtSize, config.ChtConfirms) 160 indexers[1] = eth.NewBloomIndexer(db, config.BloomSize, config.BloomConfirms) 161 indexers[2] = light.NewBloomTrieIndexer(db, odr, config.BloomSize, config.BloomTrieSize) 162 // make bloomTrieIndexer as a child indexer of bloom indexer. 163 indexers[1].AddChildIndexer(indexers[2]) 164 return indexers[:] 165 } 166 167 // newTestProtocolManager creates a new protocol manager for testing purposes, 168 // with the given number of blocks already known, potential notification 169 // channels for different events and relative chain indexers array. 170 func newTestProtocolManager(lightSync bool, blocks int, odr *LesOdr, indexers []*core.ChainIndexer, peers *peerSet, db ethdb.Database, ulcServers []string, ulcFraction int, testCost uint64, clock mclock.Clock) (*ProtocolManager, *backends.SimulatedBackend, error) { 171 var ( 172 evmux = new(event.TypeMux) 173 engine = ethash.NewFaker() 174 gspec = core.Genesis{ 175 Config: params.AllEthashProtocolChanges, 176 Alloc: core.GenesisAlloc{bankAddr: {Balance: bankFunds}}, 177 } 178 pool txPool 179 chain BlockChain 180 exitCh = make(chan struct{}) 181 ) 182 gspec.MustCommit(db) 183 if peers == nil { 184 peers = newPeerSet() 185 } 186 // create a simulation backend and pre-commit several customized block to the database. 187 simulation := backends.NewSimulatedBackendWithDatabase(db, gspec.Alloc, 100000000) 188 prepareTestchain(blocks, simulation) 189 190 // initialize empty chain for light client or pre-committed chain for server. 191 if lightSync { 192 chain, _ = light.NewLightChain(odr, gspec.Config, engine, nil) 193 } else { 194 chain = simulation.Blockchain() 195 pool = core.NewTxPool(core.DefaultTxPoolConfig, gspec.Config, simulation.Blockchain()) 196 } 197 198 // Create contract registrar 199 indexConfig := light.TestServerIndexerConfig 200 if lightSync { 201 indexConfig = light.TestClientIndexerConfig 202 } 203 config := ¶ms.CheckpointOracleConfig{ 204 Address: crypto.CreateAddress(bankAddr, 0), 205 Signers: []common.Address{signerAddr}, 206 Threshold: 1, 207 } 208 var reg *checkpointOracle 209 if indexers != nil { 210 getLocal := func(index uint64) params.TrustedCheckpoint { 211 chtIndexer := indexers[0] 212 sectionHead := chtIndexer.SectionHead(index) 213 return params.TrustedCheckpoint{ 214 SectionIndex: index, 215 SectionHead: sectionHead, 216 CHTRoot: light.GetChtRoot(db, index, sectionHead), 217 BloomRoot: light.GetBloomTrieRoot(db, index, sectionHead), 218 } 219 } 220 reg = newCheckpointOracle(config, getLocal) 221 } 222 pm, err := NewProtocolManager(gspec.Config, nil, indexConfig, ulcServers, ulcFraction, lightSync, NetworkId, evmux, peers, chain, pool, db, odr, nil, reg, exitCh, new(sync.WaitGroup), func() bool { return true }) 223 if err != nil { 224 return nil, nil, err 225 } 226 // Registrar initialization could failed if checkpoint contract is not specified. 227 if pm.reg != nil { 228 pm.reg.start(simulation) 229 } 230 // Set up les server stuff. 231 if !lightSync { 232 srv := &LesServer{lesCommons: lesCommons{protocolManager: pm, chainDb: db}} 233 pm.server = srv 234 pm.servingQueue = newServingQueue(int64(time.Millisecond*10), 1) 235 pm.servingQueue.setThreads(4) 236 237 srv.defParams = flowcontrol.ServerParams{ 238 BufLimit: testBufLimit, 239 MinRecharge: testBufRecharge, 240 } 241 srv.testCost = testCost 242 srv.fcManager = flowcontrol.NewClientManager(nil, clock) 243 } 244 pm.Start(1000) 245 return pm, simulation, nil 246 } 247 248 // newTestProtocolManagerMust creates a new protocol manager for testing purposes, 249 // with the given number of blocks already known, potential notification channels 250 // for different events and relative chain indexers array. In case of an error, the 251 // constructor force-fails the test. 252 func newTestProtocolManagerMust(t *testing.T, lightSync bool, blocks int, odr *LesOdr, indexers []*core.ChainIndexer, peers *peerSet, db ethdb.Database, ulcServers []string, ulcFraction int) (*ProtocolManager, *backends.SimulatedBackend) { 253 pm, backend, err := newTestProtocolManager(lightSync, blocks, odr, indexers, peers, db, ulcServers, ulcFraction, 0, &mclock.System{}) 254 if err != nil { 255 t.Fatalf("Failed to create protocol manager: %v", err) 256 } 257 return pm, backend 258 } 259 260 // testPeer is a simulated peer to allow testing direct network calls. 261 type testPeer struct { 262 net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging 263 app *p2p.MsgPipeRW // Application layer reader/writer to simulate the local side 264 *peer 265 } 266 267 // newTestPeer creates a new peer registered at the given protocol manager. 268 func newTestPeer(t *testing.T, name string, version int, pm *ProtocolManager, shake bool, testCost uint64) (*testPeer, <-chan error) { 269 // Create a message pipe to communicate through 270 app, net := p2p.MsgPipe() 271 272 // Generate a random id and create the peer 273 var id enode.ID 274 rand.Read(id[:]) 275 276 peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net) 277 278 // Start the peer on a new thread 279 errc := make(chan error, 1) 280 go func() { 281 select { 282 case pm.newPeerCh <- peer: 283 errc <- pm.handle(peer) 284 case <-pm.quitSync: 285 errc <- p2p.DiscQuitting 286 } 287 }() 288 tp := &testPeer{ 289 app: app, 290 net: net, 291 peer: peer, 292 } 293 // Execute any implicitly requested handshakes and return 294 if shake { 295 var ( 296 genesis = pm.blockchain.Genesis() 297 head = pm.blockchain.CurrentHeader() 298 td = pm.blockchain.GetTd(head.Hash(), head.Number.Uint64()) 299 ) 300 tp.handshake(t, td, head.Hash(), head.Number.Uint64(), genesis.Hash(), testCost) 301 } 302 return tp, errc 303 } 304 305 func newTestPeerPair(name string, version int, pm, pm2 *ProtocolManager) (*peer, <-chan error, *peer, <-chan error) { 306 // Create a message pipe to communicate through 307 app, net := p2p.MsgPipe() 308 309 // Generate a random id and create the peer 310 var id enode.ID 311 rand.Read(id[:]) 312 313 peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net) 314 peer2 := pm2.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), app) 315 316 // Start the peer on a new thread 317 errc := make(chan error, 1) 318 errc2 := make(chan error, 1) 319 go func() { 320 select { 321 case pm.newPeerCh <- peer: 322 errc <- pm.handle(peer) 323 case <-pm.quitSync: 324 errc <- p2p.DiscQuitting 325 } 326 }() 327 go func() { 328 select { 329 case pm2.newPeerCh <- peer2: 330 errc2 <- pm2.handle(peer2) 331 case <-pm2.quitSync: 332 errc2 <- p2p.DiscQuitting 333 } 334 }() 335 return peer, errc, peer2, errc2 336 } 337 338 // handshake simulates a trivial handshake that expects the same state from the 339 // remote side as we are simulating locally. 340 func (p *testPeer) handshake(t *testing.T, td *big.Int, head common.Hash, headNum uint64, genesis common.Hash, testCost uint64) { 341 var expList keyValueList 342 expList = expList.add("protocolVersion", uint64(p.version)) 343 expList = expList.add("networkId", uint64(NetworkId)) 344 expList = expList.add("headTd", td) 345 expList = expList.add("headHash", head) 346 expList = expList.add("headNum", headNum) 347 expList = expList.add("genesisHash", genesis) 348 sendList := make(keyValueList, len(expList)) 349 copy(sendList, expList) 350 expList = expList.add("serveHeaders", nil) 351 expList = expList.add("serveChainSince", uint64(0)) 352 expList = expList.add("serveStateSince", uint64(0)) 353 expList = expList.add("serveRecentState", uint64(core.TriesInMemory-4)) 354 expList = expList.add("txRelay", nil) 355 expList = expList.add("flowControl/BL", testBufLimit) 356 expList = expList.add("flowControl/MRR", testBufRecharge) 357 expList = expList.add("flowControl/MRC", testCostList(testCost)) 358 359 if err := p2p.ExpectMsg(p.app, StatusMsg, expList); err != nil { 360 t.Fatalf("status recv: %v", err) 361 } 362 if err := p2p.Send(p.app, StatusMsg, sendList); err != nil { 363 t.Fatalf("status send: %v", err) 364 } 365 366 p.fcParams = flowcontrol.ServerParams{ 367 BufLimit: testBufLimit, 368 MinRecharge: testBufRecharge, 369 } 370 } 371 372 // close terminates the local side of the peer, notifying the remote protocol 373 // manager of termination. 374 func (p *testPeer) close() { 375 p.app.Close() 376 } 377 378 // TestEntity represents a network entity for testing with necessary auxiliary fields. 379 type TestEntity struct { 380 db ethdb.Database 381 rPeer *peer 382 tPeer *testPeer 383 peers *peerSet 384 pm *ProtocolManager 385 backend *backends.SimulatedBackend 386 387 // Indexers 388 chtIndexer *core.ChainIndexer 389 bloomIndexer *core.ChainIndexer 390 bloomTrieIndexer *core.ChainIndexer 391 } 392 393 // newServerEnv creates a server testing environment with a connected test peer for testing purpose. 394 func newServerEnv(t *testing.T, blocks int, protocol int, waitIndexers func(*core.ChainIndexer, *core.ChainIndexer, *core.ChainIndexer)) (*TestEntity, func()) { 395 db := rawdb.NewMemoryDatabase() 396 indexers := testIndexers(db, nil, light.TestServerIndexerConfig) 397 398 pm, b := newTestProtocolManagerMust(t, false, blocks, nil, indexers, nil, db, nil, 0) 399 peer, _ := newTestPeer(t, "peer", protocol, pm, true, 0) 400 401 cIndexer, bIndexer, btIndexer := indexers[0], indexers[1], indexers[2] 402 cIndexer.Start(pm.blockchain.(*core.BlockChain)) 403 bIndexer.Start(pm.blockchain.(*core.BlockChain)) 404 405 // Wait until indexers generate enough index data. 406 if waitIndexers != nil { 407 waitIndexers(cIndexer, bIndexer, btIndexer) 408 } 409 410 return &TestEntity{ 411 db: db, 412 tPeer: peer, 413 pm: pm, 414 backend: b, 415 chtIndexer: cIndexer, 416 bloomIndexer: bIndexer, 417 bloomTrieIndexer: btIndexer, 418 }, func() { 419 peer.close() 420 // Note bloom trie indexer will be closed by it parent recursively. 421 cIndexer.Close() 422 bIndexer.Close() 423 } 424 } 425 426 // newClientServerEnv creates a client/server arch environment with a connected les server and light client pair 427 // for testing purpose. 428 func newClientServerEnv(t *testing.T, blocks int, protocol int, waitIndexers func(*core.ChainIndexer, *core.ChainIndexer, *core.ChainIndexer), newPeer bool) (*TestEntity, *TestEntity, func()) { 429 db, ldb := rawdb.NewMemoryDatabase(), rawdb.NewMemoryDatabase() 430 peers, lPeers := newPeerSet(), newPeerSet() 431 432 dist := newRequestDistributor(lPeers, make(chan struct{}), &mclock.System{}) 433 rm := newRetrieveManager(lPeers, dist, nil) 434 odr := NewLesOdr(ldb, light.TestClientIndexerConfig, rm) 435 436 indexers := testIndexers(db, nil, light.TestServerIndexerConfig) 437 lIndexers := testIndexers(ldb, odr, light.TestClientIndexerConfig) 438 439 cIndexer, bIndexer, btIndexer := indexers[0], indexers[1], indexers[2] 440 lcIndexer, lbIndexer, lbtIndexer := lIndexers[0], lIndexers[1], lIndexers[2] 441 442 odr.SetIndexers(lcIndexer, lbtIndexer, lbIndexer) 443 444 pm, b := newTestProtocolManagerMust(t, false, blocks, nil, indexers, peers, db, nil, 0) 445 lpm, lb := newTestProtocolManagerMust(t, true, 0, odr, lIndexers, lPeers, ldb, nil, 0) 446 447 startIndexers := func(clientMode bool, pm *ProtocolManager) { 448 if clientMode { 449 lcIndexer.Start(pm.blockchain.(*light.LightChain)) 450 lbIndexer.Start(pm.blockchain.(*light.LightChain)) 451 } else { 452 cIndexer.Start(pm.blockchain.(*core.BlockChain)) 453 bIndexer.Start(pm.blockchain.(*core.BlockChain)) 454 } 455 } 456 457 startIndexers(false, pm) 458 startIndexers(true, lpm) 459 460 // Execute wait until function if it is specified. 461 if waitIndexers != nil { 462 waitIndexers(cIndexer, bIndexer, btIndexer) 463 } 464 465 var ( 466 peer, lPeer *peer 467 err1, err2 <-chan error 468 ) 469 if newPeer { 470 peer, err1, lPeer, err2 = newTestPeerPair("peer", protocol, pm, lpm) 471 select { 472 case <-time.After(time.Millisecond * 100): 473 case err := <-err1: 474 t.Fatalf("peer 1 handshake error: %v", err) 475 case err := <-err2: 476 t.Fatalf("peer 2 handshake error: %v", err) 477 } 478 } 479 480 return &TestEntity{ 481 db: db, 482 pm: pm, 483 rPeer: peer, 484 peers: peers, 485 backend: b, 486 chtIndexer: cIndexer, 487 bloomIndexer: bIndexer, 488 bloomTrieIndexer: btIndexer, 489 }, &TestEntity{ 490 db: ldb, 491 pm: lpm, 492 rPeer: lPeer, 493 peers: lPeers, 494 backend: lb, 495 chtIndexer: lcIndexer, 496 bloomIndexer: lbIndexer, 497 bloomTrieIndexer: lbtIndexer, 498 }, func() { 499 // Note bloom trie indexers will be closed by their parents recursively. 500 cIndexer.Close() 501 bIndexer.Close() 502 lcIndexer.Close() 503 lbIndexer.Close() 504 } 505 }