github.com/ylsGit/go-ethereum@v1.6.5/eth/helper_test.go (about) 1 // Copyright 2015 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 eth 21 22 import ( 23 "crypto/ecdsa" 24 "crypto/rand" 25 "math/big" 26 "sort" 27 "sync" 28 "testing" 29 30 "github.com/ethereum/go-ethereum/common" 31 "github.com/ethereum/go-ethereum/consensus/ethash" 32 "github.com/ethereum/go-ethereum/core" 33 "github.com/ethereum/go-ethereum/core/types" 34 "github.com/ethereum/go-ethereum/core/vm" 35 "github.com/ethereum/go-ethereum/crypto" 36 "github.com/ethereum/go-ethereum/eth/downloader" 37 "github.com/ethereum/go-ethereum/ethdb" 38 "github.com/ethereum/go-ethereum/event" 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 testBank = crypto.PubkeyToAddress(testBankKey.PublicKey) 47 ) 48 49 // newTestProtocolManager creates a new protocol manager for testing purposes, 50 // with the given number of blocks already known, and potential notification 51 // channels for different events. 52 func newTestProtocolManager(mode downloader.SyncMode, blocks int, generator func(int, *core.BlockGen), newtx chan<- []*types.Transaction) (*ProtocolManager, error) { 53 var ( 54 evmux = new(event.TypeMux) 55 engine = ethash.NewFaker() 56 db, _ = ethdb.NewMemDatabase() 57 gspec = &core.Genesis{ 58 Config: params.TestChainConfig, 59 Alloc: core.GenesisAlloc{testBank: {Balance: big.NewInt(1000000)}}, 60 } 61 genesis = gspec.MustCommit(db) 62 blockchain, _ = core.NewBlockChain(db, gspec.Config, engine, evmux, vm.Config{}) 63 ) 64 chain, _ := core.GenerateChain(gspec.Config, genesis, db, blocks, generator) 65 if _, err := blockchain.InsertChain(chain); err != nil { 66 panic(err) 67 } 68 69 pm, err := NewProtocolManager(gspec.Config, mode, DefaultConfig.NetworkId, 1000, evmux, &testTxPool{added: newtx}, engine, blockchain, db) 70 if err != nil { 71 return nil, err 72 } 73 pm.Start() 74 return pm, nil 75 } 76 77 // newTestProtocolManagerMust creates a new protocol manager for testing purposes, 78 // with the given number of blocks already known, and potential notification 79 // channels for different events. In case of an error, the constructor force- 80 // fails the test. 81 func newTestProtocolManagerMust(t *testing.T, mode downloader.SyncMode, blocks int, generator func(int, *core.BlockGen), newtx chan<- []*types.Transaction) *ProtocolManager { 82 pm, err := newTestProtocolManager(mode, blocks, generator, newtx) 83 if err != nil { 84 t.Fatalf("Failed to create protocol manager: %v", err) 85 } 86 return pm 87 } 88 89 // testTxPool is a fake, helper transaction pool for testing purposes 90 type testTxPool struct { 91 pool []*types.Transaction // Collection of all transactions 92 added chan<- []*types.Transaction // Notification channel for new transactions 93 94 lock sync.RWMutex // Protects the transaction pool 95 } 96 97 // AddBatch appends a batch of transactions to the pool, and notifies any 98 // listeners if the addition channel is non nil 99 func (p *testTxPool) AddBatch(txs []*types.Transaction) error { 100 p.lock.Lock() 101 defer p.lock.Unlock() 102 103 p.pool = append(p.pool, txs...) 104 if p.added != nil { 105 p.added <- txs 106 } 107 108 return nil 109 } 110 111 // Pending returns all the transactions known to the pool 112 func (p *testTxPool) Pending() (map[common.Address]types.Transactions, error) { 113 p.lock.RLock() 114 defer p.lock.RUnlock() 115 116 batches := make(map[common.Address]types.Transactions) 117 for _, tx := range p.pool { 118 from, _ := types.Sender(types.HomesteadSigner{}, tx) 119 batches[from] = append(batches[from], tx) 120 } 121 for _, batch := range batches { 122 sort.Sort(types.TxByNonce(batch)) 123 } 124 return batches, nil 125 } 126 127 // newTestTransaction create a new dummy transaction. 128 func newTestTransaction(from *ecdsa.PrivateKey, nonce uint64, datasize int) *types.Transaction { 129 tx := types.NewTransaction(nonce, common.Address{}, big.NewInt(0), big.NewInt(100000), big.NewInt(0), make([]byte, datasize)) 130 tx, _ = types.SignTx(tx, types.HomesteadSigner{}, from) 131 return tx 132 } 133 134 // testPeer is a simulated peer to allow testing direct network calls. 135 type testPeer struct { 136 net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging 137 app *p2p.MsgPipeRW // Application layer reader/writer to simulate the local side 138 *peer 139 } 140 141 // newTestPeer creates a new peer registered at the given protocol manager. 142 func newTestPeer(name string, version int, pm *ProtocolManager, shake bool) (*testPeer, <-chan error) { 143 // Create a message pipe to communicate through 144 app, net := p2p.MsgPipe() 145 146 // Generate a random id and create the peer 147 var id discover.NodeID 148 rand.Read(id[:]) 149 150 peer := pm.newPeer(version, p2p.NewPeer(id, name, nil), net) 151 152 // Start the peer on a new thread 153 errc := make(chan error, 1) 154 go func() { 155 select { 156 case pm.newPeerCh <- peer: 157 errc <- pm.handle(peer) 158 case <-pm.quitSync: 159 errc <- p2p.DiscQuitting 160 } 161 }() 162 tp := &testPeer{app: app, net: net, peer: peer} 163 // Execute any implicitly requested handshakes and return 164 if shake { 165 td, head, genesis := pm.blockchain.Status() 166 tp.handshake(nil, td, head, genesis) 167 } 168 return tp, errc 169 } 170 171 // handshake simulates a trivial handshake that expects the same state from the 172 // remote side as we are simulating locally. 173 func (p *testPeer) handshake(t *testing.T, td *big.Int, head common.Hash, genesis common.Hash) { 174 msg := &statusData{ 175 ProtocolVersion: uint32(p.version), 176 NetworkId: DefaultConfig.NetworkId, 177 TD: td, 178 CurrentBlock: head, 179 GenesisBlock: genesis, 180 } 181 if err := p2p.ExpectMsg(p.app, StatusMsg, msg); err != nil { 182 t.Fatalf("status recv: %v", err) 183 } 184 if err := p2p.Send(p.app, StatusMsg, msg); err != nil { 185 t.Fatalf("status send: %v", err) 186 } 187 } 188 189 // close terminates the local side of the peer, notifying the remote protocol 190 // manager of termination. 191 func (p *testPeer) close() { 192 p.app.Close() 193 }