github.com/clem109/go-ethereum@v1.8.3-0.20180316121352-fe6cf00f480a/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 28 "github.com/ethereum/go-ethereum/common" 29 "github.com/ethereum/go-ethereum/consensus/ethash" 30 "github.com/ethereum/go-ethereum/core" 31 "github.com/ethereum/go-ethereum/core/types" 32 "github.com/ethereum/go-ethereum/core/vm" 33 "github.com/ethereum/go-ethereum/crypto" 34 "github.com/ethereum/go-ethereum/eth" 35 "github.com/ethereum/go-ethereum/ethdb" 36 "github.com/ethereum/go-ethereum/event" 37 "github.com/ethereum/go-ethereum/les/flowcontrol" 38 "github.com/ethereum/go-ethereum/light" 39 "github.com/ethereum/go-ethereum/p2p" 40 "github.com/ethereum/go-ethereum/p2p/discover" 41 "github.com/ethereum/go-ethereum/params" 42 ) 43 44 var ( 45 testBankKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 46 testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey) 47 testBankFunds = big.NewInt(1000000000000000000) 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 testEventEmitterCode = common.Hex2Bytes("60606040523415600e57600080fd5b7f57050ab73f6b9ebdd9f76b8d4997793f48cf956e965ee070551b9ca0bb71584e60405160405180910390a160358060476000396000f3006060604052600080fd00a165627a7a723058203f727efcad8b5811f8cb1fc2620ce5e8c63570d697aef968172de296ea3994140029") 60 testEventEmitterAddr common.Address 61 62 testBufLimit = uint64(100) 63 ) 64 65 /* 66 contract test { 67 68 uint256[100] data; 69 70 function Put(uint256 addr, uint256 value) { 71 data[addr] = value; 72 } 73 74 function Get(uint256 addr) constant returns (uint256 value) { 75 return data[addr]; 76 } 77 } 78 */ 79 80 func testChainGen(i int, block *core.BlockGen) { 81 signer := types.HomesteadSigner{} 82 83 switch i { 84 case 0: 85 // In block 1, the test bank sends account #1 some ether. 86 tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, testBankKey) 87 block.AddTx(tx) 88 case 1: 89 // In block 2, the test bank sends some more ether to account #1. 90 // acc1Addr passes it on to account #2. 91 // acc1Addr creates a test contract. 92 // acc1Addr creates a test event. 93 nonce := block.TxNonce(acc1Addr) 94 95 tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, testBankKey) 96 tx2, _ := types.SignTx(types.NewTransaction(nonce, acc2Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, acc1Key) 97 tx3, _ := types.SignTx(types.NewContractCreation(nonce+1, big.NewInt(0), 200000, big.NewInt(0), testContractCode), signer, acc1Key) 98 testContractAddr = crypto.CreateAddress(acc1Addr, nonce+1) 99 tx4, _ := types.SignTx(types.NewContractCreation(nonce+2, big.NewInt(0), 200000, big.NewInt(0), testEventEmitterCode), signer, acc1Key) 100 testEventEmitterAddr = crypto.CreateAddress(acc1Addr, nonce+2) 101 block.AddTx(tx1) 102 block.AddTx(tx2) 103 block.AddTx(tx3) 104 block.AddTx(tx4) 105 case 2: 106 // Block 3 is empty but was mined by account #2. 107 block.SetCoinbase(acc2Addr) 108 block.SetExtra([]byte("yeehaw")) 109 data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001") 110 tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, nil, data), signer, testBankKey) 111 block.AddTx(tx) 112 case 3: 113 // Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data). 114 b2 := block.PrevBlock(1).Header() 115 b2.Extra = []byte("foo") 116 block.AddUncle(b2) 117 b3 := block.PrevBlock(2).Header() 118 b3.Extra = []byte("foo") 119 block.AddUncle(b3) 120 data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002") 121 tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, nil, data), signer, testBankKey) 122 block.AddTx(tx) 123 } 124 } 125 126 func testRCL() RequestCostList { 127 cl := make(RequestCostList, len(reqList)) 128 for i, code := range reqList { 129 cl[i].MsgCode = code 130 cl[i].BaseCost = 0 131 cl[i].ReqCost = 0 132 } 133 return cl 134 } 135 136 // newTestProtocolManager creates a new protocol manager for testing purposes, 137 // with the given number of blocks already known, and potential notification 138 // channels for different events. 139 func newTestProtocolManager(lightSync bool, blocks int, generator func(int, *core.BlockGen), peers *peerSet, odr *LesOdr, db ethdb.Database) (*ProtocolManager, error) { 140 var ( 141 evmux = new(event.TypeMux) 142 engine = ethash.NewFaker() 143 gspec = core.Genesis{ 144 Config: params.TestChainConfig, 145 Alloc: core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}}, 146 } 147 genesis = gspec.MustCommit(db) 148 chain BlockChain 149 ) 150 if peers == nil { 151 peers = newPeerSet() 152 } 153 154 if lightSync { 155 chain, _ = light.NewLightChain(odr, gspec.Config, engine) 156 } else { 157 blockchain, _ := core.NewBlockChain(db, nil, gspec.Config, engine, vm.Config{}) 158 159 chtIndexer := light.NewChtIndexer(db, false) 160 chtIndexer.Start(blockchain) 161 162 bbtIndexer := light.NewBloomTrieIndexer(db, false) 163 164 bloomIndexer := eth.NewBloomIndexer(db, params.BloomBitsBlocks) 165 bloomIndexer.AddChildIndexer(bbtIndexer) 166 bloomIndexer.Start(blockchain) 167 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 var protocolVersions []uint 176 if lightSync { 177 protocolVersions = ClientProtocolVersions 178 } else { 179 protocolVersions = ServerProtocolVersions 180 } 181 pm, err := NewProtocolManager(gspec.Config, lightSync, protocolVersions, NetworkId, evmux, engine, peers, chain, nil, db, odr, nil, make(chan struct{}), new(sync.WaitGroup)) 182 if err != nil { 183 return nil, err 184 } 185 if !lightSync { 186 srv := &LesServer{protocolManager: pm} 187 pm.server = srv 188 189 srv.defParams = &flowcontrol.ServerParams{ 190 BufLimit: testBufLimit, 191 MinRecharge: 1, 192 } 193 194 srv.fcManager = flowcontrol.NewClientManager(50, 10, 1000000000) 195 srv.fcCostStats = newCostStats(nil) 196 } 197 pm.Start(1000) 198 return pm, nil 199 } 200 201 // newTestProtocolManagerMust creates a new protocol manager for testing purposes, 202 // with the given number of blocks already known, and potential notification 203 // channels for different events. In case of an error, the constructor force- 204 // fails the test. 205 func newTestProtocolManagerMust(t *testing.T, lightSync bool, blocks int, generator func(int, *core.BlockGen), peers *peerSet, odr *LesOdr, db ethdb.Database) *ProtocolManager { 206 pm, err := newTestProtocolManager(lightSync, blocks, generator, peers, odr, db) 207 if err != nil { 208 t.Fatalf("Failed to create protocol manager: %v", err) 209 } 210 return pm 211 } 212 213 // testPeer is a simulated peer to allow testing direct network calls. 214 type testPeer struct { 215 net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging 216 app *p2p.MsgPipeRW // Application layer reader/writer to simulate the local side 217 *peer 218 } 219 220 // newTestPeer creates a new peer registered at the given protocol manager. 221 func newTestPeer(t *testing.T, name string, version int, pm *ProtocolManager, shake bool) (*testPeer, <-chan error) { 222 // Create a message pipe to communicate through 223 app, net := p2p.MsgPipe() 224 225 // Generate a random id and create the peer 226 var id discover.NodeID 227 rand.Read(id[:]) 228 229 peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net) 230 231 // Start the peer on a new thread 232 errc := make(chan error, 1) 233 go func() { 234 select { 235 case pm.newPeerCh <- peer: 236 errc <- pm.handle(peer) 237 case <-pm.quitSync: 238 errc <- p2p.DiscQuitting 239 } 240 }() 241 tp := &testPeer{ 242 app: app, 243 net: net, 244 peer: peer, 245 } 246 // Execute any implicitly requested handshakes and return 247 if shake { 248 var ( 249 genesis = pm.blockchain.Genesis() 250 head = pm.blockchain.CurrentHeader() 251 td = pm.blockchain.GetTd(head.Hash(), head.Number.Uint64()) 252 ) 253 tp.handshake(t, td, head.Hash(), head.Number.Uint64(), genesis.Hash()) 254 } 255 return tp, errc 256 } 257 258 func newTestPeerPair(name string, version int, pm, pm2 *ProtocolManager) (*peer, <-chan error, *peer, <-chan error) { 259 // Create a message pipe to communicate through 260 app, net := p2p.MsgPipe() 261 262 // Generate a random id and create the peer 263 var id discover.NodeID 264 rand.Read(id[:]) 265 266 peer := pm.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), net) 267 peer2 := pm2.newPeer(version, NetworkId, p2p.NewPeer(id, name, nil), app) 268 269 // Start the peer on a new thread 270 errc := make(chan error, 1) 271 errc2 := make(chan error, 1) 272 go func() { 273 select { 274 case pm.newPeerCh <- peer: 275 errc <- pm.handle(peer) 276 case <-pm.quitSync: 277 errc <- p2p.DiscQuitting 278 } 279 }() 280 go func() { 281 select { 282 case pm2.newPeerCh <- peer2: 283 errc2 <- pm2.handle(peer2) 284 case <-pm2.quitSync: 285 errc2 <- p2p.DiscQuitting 286 } 287 }() 288 return peer, errc, peer2, errc2 289 } 290 291 // handshake simulates a trivial handshake that expects the same state from the 292 // remote side as we are simulating locally. 293 func (p *testPeer) handshake(t *testing.T, td *big.Int, head common.Hash, headNum uint64, genesis common.Hash) { 294 var expList keyValueList 295 expList = expList.add("protocolVersion", uint64(p.version)) 296 expList = expList.add("networkId", uint64(NetworkId)) 297 expList = expList.add("headTd", td) 298 expList = expList.add("headHash", head) 299 expList = expList.add("headNum", headNum) 300 expList = expList.add("genesisHash", genesis) 301 sendList := make(keyValueList, len(expList)) 302 copy(sendList, expList) 303 expList = expList.add("serveHeaders", nil) 304 expList = expList.add("serveChainSince", uint64(0)) 305 expList = expList.add("serveStateSince", uint64(0)) 306 expList = expList.add("txRelay", nil) 307 expList = expList.add("flowControl/BL", testBufLimit) 308 expList = expList.add("flowControl/MRR", uint64(1)) 309 expList = expList.add("flowControl/MRC", testRCL()) 310 311 if err := p2p.ExpectMsg(p.app, StatusMsg, expList); err != nil { 312 t.Fatalf("status recv: %v", err) 313 } 314 if err := p2p.Send(p.app, StatusMsg, sendList); err != nil { 315 t.Fatalf("status send: %v", err) 316 } 317 318 p.fcServerParams = &flowcontrol.ServerParams{ 319 BufLimit: testBufLimit, 320 MinRecharge: 1, 321 } 322 } 323 324 // close terminates the local side of the peer, notifying the remote protocol 325 // manager of termination. 326 func (p *testPeer) close() { 327 p.app.Close() 328 }