github.com/puppeth/go-ethereum@v0.8.6-0.20171014130046-e9295163aa25/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, 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, evmux, &testTxPool{added: newtx}, engine, blockchain, db) 70 if err != nil { 71 return nil, err 72 } 73 pm.Start(1000) 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 txFeed event.Feed 92 pool []*types.Transaction // Collection of all transactions 93 added chan<- []*types.Transaction // Notification channel for new transactions 94 95 lock sync.RWMutex // Protects the transaction pool 96 } 97 98 // AddRemotes appends a batch of transactions to the pool, and notifies any 99 // listeners if the addition channel is non nil 100 func (p *testTxPool) AddRemotes(txs []*types.Transaction) error { 101 p.lock.Lock() 102 defer p.lock.Unlock() 103 104 p.pool = append(p.pool, txs...) 105 if p.added != nil { 106 p.added <- txs 107 } 108 109 return nil 110 } 111 112 // Pending returns all the transactions known to the pool 113 func (p *testTxPool) Pending() (map[common.Address]types.Transactions, error) { 114 p.lock.RLock() 115 defer p.lock.RUnlock() 116 117 batches := make(map[common.Address]types.Transactions) 118 for _, tx := range p.pool { 119 from, _ := types.Sender(types.HomesteadSigner{}, tx) 120 batches[from] = append(batches[from], tx) 121 } 122 for _, batch := range batches { 123 sort.Sort(types.TxByNonce(batch)) 124 } 125 return batches, nil 126 } 127 128 func (p *testTxPool) SubscribeTxPreEvent(ch chan<- core.TxPreEvent) event.Subscription { 129 return p.txFeed.Subscribe(ch) 130 } 131 132 // newTestTransaction create a new dummy transaction. 133 func newTestTransaction(from *ecdsa.PrivateKey, nonce uint64, datasize int) *types.Transaction { 134 tx := types.NewTransaction(nonce, common.Address{}, big.NewInt(0), big.NewInt(100000), big.NewInt(0), make([]byte, datasize)) 135 tx, _ = types.SignTx(tx, types.HomesteadSigner{}, from) 136 return tx 137 } 138 139 // testPeer is a simulated peer to allow testing direct network calls. 140 type testPeer struct { 141 net p2p.MsgReadWriter // Network layer reader/writer to simulate remote messaging 142 app *p2p.MsgPipeRW // Application layer reader/writer to simulate the local side 143 *peer 144 } 145 146 // newTestPeer creates a new peer registered at the given protocol manager. 147 func newTestPeer(name string, version int, pm *ProtocolManager, shake bool) (*testPeer, <-chan error) { 148 // Create a message pipe to communicate through 149 app, net := p2p.MsgPipe() 150 151 // Generate a random id and create the peer 152 var id discover.NodeID 153 rand.Read(id[:]) 154 155 peer := pm.newPeer(version, p2p.NewPeer(id, name, nil), net) 156 157 // Start the peer on a new thread 158 errc := make(chan error, 1) 159 go func() { 160 select { 161 case pm.newPeerCh <- peer: 162 errc <- pm.handle(peer) 163 case <-pm.quitSync: 164 errc <- p2p.DiscQuitting 165 } 166 }() 167 tp := &testPeer{app: app, net: net, peer: peer} 168 // Execute any implicitly requested handshakes and return 169 if shake { 170 td, head, genesis := pm.blockchain.Status() 171 tp.handshake(nil, td, head, genesis) 172 } 173 return tp, errc 174 } 175 176 // handshake simulates a trivial handshake that expects the same state from the 177 // remote side as we are simulating locally. 178 func (p *testPeer) handshake(t *testing.T, td *big.Int, head common.Hash, genesis common.Hash) { 179 msg := &statusData{ 180 ProtocolVersion: uint32(p.version), 181 NetworkId: DefaultConfig.NetworkId, 182 TD: td, 183 CurrentBlock: head, 184 GenesisBlock: genesis, 185 } 186 if err := p2p.ExpectMsg(p.app, StatusMsg, msg); err != nil { 187 t.Fatalf("status recv: %v", err) 188 } 189 if err := p2p.Send(p.app, StatusMsg, msg); err != nil { 190 t.Fatalf("status send: %v", err) 191 } 192 } 193 194 // close terminates the local side of the peer, notifying the remote protocol 195 // manager of termination. 196 func (p *testPeer) close() { 197 p.app.Close() 198 }