github.com/digdeepmining/go-atheios@v1.5.13-0.20180902133602-d5687a2e6f43/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/ecdsa" 24 "crypto/rand" 25 "math/big" 26 "sync" 27 "testing" 28 "time" 29 30 "github.com/atheioschain/go-atheios/common" 31 "github.com/atheioschain/go-atheios/core" 32 "github.com/atheioschain/go-atheios/core/types" 33 "github.com/atheioschain/go-atheios/core/vm" 34 "github.com/atheioschain/go-atheios/crypto" 35 "github.com/atheioschain/go-atheios/ethdb" 36 "github.com/atheioschain/go-atheios/event" 37 "github.com/atheioschain/go-atheios/les/flowcontrol" 38 "github.com/atheioschain/go-atheios/light" 39 "github.com/atheioschain/go-atheios/p2p" 40 "github.com/atheioschain/go-atheios/p2p/discover" 41 "github.com/atheioschain/go-atheios/params" 42 ) 43 44 var ( 45 testBankKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 46 testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey) 47 testBankFunds = big.NewInt(1000000) 48 49 acc1Key, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a") 50 acc2Key, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee") 51 acc1Addr = crypto.PubkeyToAddress(acc1Key.PublicKey) 52 acc2Addr = crypto.PubkeyToAddress(acc2Key.PublicKey) 53 54 testContractCode = common.Hex2Bytes("606060405260cc8060106000396000f360606040526000357c01000000000000000000000000000000000000000000000000000000009004806360cd2685146041578063c16431b914606b57603f565b005b6055600480803590602001909190505060a9565b6040518082815260200191505060405180910390f35b60886004808035906020019091908035906020019091905050608a565b005b80600060005083606481101560025790900160005b50819055505b5050565b6000600060005082606481101560025790900160005b5054905060c7565b91905056") 55 testContractAddr common.Address 56 testContractCodeDeployed = testContractCode[16:] 57 testContractDeployed = uint64(2) 58 59 testBufLimit = uint64(100) 60 ) 61 62 /* 63 contract test { 64 65 uint256[100] data; 66 67 function Put(uint256 addr, uint256 value) { 68 data[addr] = value; 69 } 70 71 function Get(uint256 addr) constant returns (uint256 value) { 72 return data[addr]; 73 } 74 } 75 */ 76 77 func testChainGen(i int, block *core.BlockGen) { 78 signer := types.HomesteadSigner{} 79 80 switch i { 81 case 0: 82 // In block 1, the test bank sends account #1 some ether. 83 tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, testBankKey) 84 block.AddTx(tx) 85 case 1: 86 // In block 2, the test bank sends some more ether to account #1. 87 // acc1Addr passes it on to account #2. 88 // acc1Addr creates a test contract. 89 tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, testBankKey) 90 nonce := block.TxNonce(acc1Addr) 91 tx2, _ := types.SignTx(types.NewTransaction(nonce, acc2Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, acc1Key) 92 nonce++ 93 tx3, _ := types.SignTx(types.NewContractCreation(nonce, big.NewInt(0), big.NewInt(200000), big.NewInt(0), testContractCode), signer, acc1Key) 94 testContractAddr = crypto.CreateAddress(acc1Addr, nonce) 95 block.AddTx(tx1) 96 block.AddTx(tx2) 97 block.AddTx(tx3) 98 case 2: 99 // Block 3 is empty but was mined by account #2. 100 block.SetCoinbase(acc2Addr) 101 block.SetExtra([]byte("yeehaw")) 102 data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001") 103 tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), big.NewInt(100000), nil, data), signer, testBankKey) 104 block.AddTx(tx) 105 case 3: 106 // Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data). 107 b2 := block.PrevBlock(1).Header() 108 b2.Extra = []byte("foo") 109 block.AddUncle(b2) 110 b3 := block.PrevBlock(2).Header() 111 b3.Extra = []byte("foo") 112 block.AddUncle(b3) 113 data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002") 114 tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), big.NewInt(100000), nil, data), signer, testBankKey) 115 block.AddTx(tx) 116 } 117 } 118 119 func testRCL() RequestCostList { 120 cl := make(RequestCostList, len(reqList)) 121 for i, code := range reqList { 122 cl[i].MsgCode = code 123 cl[i].BaseCost = 0 124 cl[i].ReqCost = 0 125 } 126 return cl 127 } 128 129 // newTestProtocolManager creates a new protocol manager for testing purposes, 130 // with the given number of blocks already known, and potential notification 131 // channels for different events. 132 func newTestProtocolManager(lightSync bool, blocks int, generator func(int, *core.BlockGen)) (*ProtocolManager, ethdb.Database, *LesOdr, error) { 133 var ( 134 evmux = new(event.TypeMux) 135 pow = new(core.FakePow) 136 db, _ = ethdb.NewMemDatabase() 137 genesis = core.WriteGenesisBlockForTesting(db, core.GenesisAccount{Address: testBankAddress, Balance: testBankFunds}) 138 chainConfig = ¶ms.ChainConfig{HomesteadBlock: big.NewInt(0)} // homestead set to 0 because of chain maker 139 odr *LesOdr 140 chain BlockChain 141 ) 142 143 if lightSync { 144 odr = NewLesOdr(db) 145 chain, _ = light.NewLightChain(odr, chainConfig, pow, evmux) 146 } else { 147 blockchain, _ := core.NewBlockChain(db, chainConfig, pow, evmux, vm.Config{}) 148 gchain, _ := core.GenerateChain(chainConfig, genesis, db, blocks, generator) 149 if _, err := blockchain.InsertChain(gchain); err != nil { 150 panic(err) 151 } 152 chain = blockchain 153 } 154 155 pm, err := NewProtocolManager(chainConfig, lightSync, NetworkId, evmux, pow, chain, nil, db, odr, nil) 156 if err != nil { 157 return nil, nil, nil, err 158 } 159 if !lightSync { 160 srv := &LesServer{protocolManager: pm} 161 pm.server = srv 162 163 srv.defParams = &flowcontrol.ServerParams{ 164 BufLimit: testBufLimit, 165 MinRecharge: 1, 166 } 167 168 srv.fcManager = flowcontrol.NewClientManager(50, 10, 1000000000) 169 srv.fcCostStats = newCostStats(nil) 170 } 171 pm.Start(nil) 172 return pm, db, odr, nil 173 } 174 175 // newTestProtocolManagerMust creates a new protocol manager for testing purposes, 176 // with the given number of blocks already known, and potential notification 177 // channels for different events. In case of an error, the constructor force- 178 // fails the test. 179 func newTestProtocolManagerMust(t *testing.T, lightSync bool, blocks int, generator func(int, *core.BlockGen)) (*ProtocolManager, ethdb.Database, *LesOdr) { 180 pm, db, odr, err := newTestProtocolManager(lightSync, blocks, generator) 181 if err != nil { 182 t.Fatalf("Failed to create protocol manager: %v", err) 183 } 184 return pm, db, odr 185 } 186 187 // testTxPool is a fake, helper transaction pool for testing purposes 188 type testTxPool struct { 189 pool []*types.Transaction // Collection of all transactions 190 added chan<- []*types.Transaction // Notification channel for new transactions 191 192 lock sync.RWMutex // Protects the transaction pool 193 } 194 195 // AddTransactions appends a batch of transactions to the pool, and notifies any 196 // listeners if the addition channel is non nil 197 func (p *testTxPool) AddBatch(txs []*types.Transaction) { 198 p.lock.Lock() 199 defer p.lock.Unlock() 200 201 p.pool = append(p.pool, txs...) 202 if p.added != nil { 203 p.added <- txs 204 } 205 } 206 207 // GetTransactions returns all the transactions known to the pool 208 func (p *testTxPool) GetTransactions() types.Transactions { 209 p.lock.RLock() 210 defer p.lock.RUnlock() 211 212 txs := make([]*types.Transaction, len(p.pool)) 213 copy(txs, p.pool) 214 215 return txs 216 } 217 218 // newTestTransaction create a new dummy transaction. 219 func newTestTransaction(from *ecdsa.PrivateKey, nonce uint64, datasize int) *types.Transaction { 220 tx := types.NewTransaction(nonce, common.Address{}, big.NewInt(0), big.NewInt(100000), big.NewInt(0), make([]byte, datasize)) 221 tx, _ = types.SignTx(tx, types.HomesteadSigner{}, from) 222 223 return tx 224 } 225 226 // testPeer is a simulated peer to allow testing direct network calls. 227 type testPeer struct { 228 net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging 229 app *p2p.MsgPipeRW // Application layer reader/writer to simulate the local side 230 *peer 231 } 232 233 // newTestPeer creates a new peer registered at the given protocol manager. 234 func newTestPeer(t *testing.T, name string, version int, pm *ProtocolManager, shake bool) (*testPeer, <-chan error) { 235 // Create a message pipe to communicate through 236 app, net := p2p.MsgPipe() 237 238 // Generate a random id and create the peer 239 var id discover.NodeID 240 rand.Read(id[:]) 241 242 peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net) 243 244 // Start the peer on a new thread 245 errc := make(chan error, 1) 246 go func() { 247 select { 248 case pm.newPeerCh <- peer: 249 errc <- pm.handle(peer) 250 case <-pm.quitSync: 251 errc <- p2p.DiscQuitting 252 } 253 }() 254 tp := &testPeer{ 255 app: app, 256 net: net, 257 peer: peer, 258 } 259 // Execute any implicitly requested handshakes and return 260 if shake { 261 td, head, genesis := pm.blockchain.Status() 262 headNum := pm.blockchain.CurrentHeader().Number.Uint64() 263 tp.handshake(t, td, head, headNum, genesis) 264 } 265 return tp, errc 266 } 267 268 func newTestPeerPair(name string, version int, pm, pm2 *ProtocolManager) (*peer, <-chan error, *peer, <-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 discover.NodeID 274 rand.Read(id[:]) 275 276 peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net) 277 peer2 := pm2.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), app) 278 279 // Start the peer on a new thread 280 errc := make(chan error, 1) 281 errc2 := make(chan error, 1) 282 go func() { 283 select { 284 case pm.newPeerCh <- peer: 285 errc <- pm.handle(peer) 286 case <-pm.quitSync: 287 errc <- p2p.DiscQuitting 288 } 289 }() 290 go func() { 291 select { 292 case pm2.newPeerCh <- peer2: 293 errc2 <- pm2.handle(peer2) 294 case <-pm2.quitSync: 295 errc2 <- p2p.DiscQuitting 296 } 297 }() 298 return peer, errc, peer2, errc2 299 } 300 301 // handshake simulates a trivial handshake that expects the same state from the 302 // remote side as we are simulating locally. 303 func (p *testPeer) handshake(t *testing.T, td *big.Int, head common.Hash, headNum uint64, genesis common.Hash) { 304 var expList keyValueList 305 expList = expList.add("protocolVersion", uint64(p.version)) 306 expList = expList.add("networkId", uint64(NetworkId)) 307 expList = expList.add("headTd", td) 308 expList = expList.add("headHash", head) 309 expList = expList.add("headNum", headNum) 310 expList = expList.add("genesisHash", genesis) 311 sendList := make(keyValueList, len(expList)) 312 copy(sendList, expList) 313 expList = expList.add("serveHeaders", nil) 314 expList = expList.add("serveChainSince", uint64(0)) 315 expList = expList.add("serveStateSince", uint64(0)) 316 expList = expList.add("txRelay", nil) 317 expList = expList.add("flowControl/BL", testBufLimit) 318 expList = expList.add("flowControl/MRR", uint64(1)) 319 expList = expList.add("flowControl/MRC", testRCL()) 320 321 if err := p2p.ExpectMsg(p.app, StatusMsg, expList); err != nil { 322 t.Fatalf("status recv: %v", err) 323 } 324 if err := p2p.Send(p.app, StatusMsg, sendList); err != nil { 325 t.Fatalf("status send: %v", err) 326 } 327 328 p.fcServerParams = &flowcontrol.ServerParams{ 329 BufLimit: testBufLimit, 330 MinRecharge: 1, 331 } 332 } 333 334 // close terminates the local side of the peer, notifying the remote protocol 335 // manager of termination. 336 func (p *testPeer) close() { 337 p.app.Close() 338 } 339 340 type testServerPool struct { 341 peer *peer 342 lock sync.RWMutex 343 } 344 345 func (p *testServerPool) setPeer(peer *peer) { 346 p.lock.Lock() 347 defer p.lock.Unlock() 348 349 p.peer = peer 350 } 351 352 func (p *testServerPool) selectPeerWait(uint64, func(*peer) (bool, time.Duration), <-chan struct{}) *peer { 353 p.lock.RLock() 354 defer p.lock.RUnlock() 355 356 return p.peer 357 } 358 359 func (p *testServerPool) adjustResponseTime(*poolEntry, time.Duration, bool) { 360 361 }