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