github.com/daeglee/go-ethereum@v0.0.0-20190504220456-cad3e8d18e9b/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/rawdb" 34 "github.com/ethereum/go-ethereum/core/types" 35 "github.com/ethereum/go-ethereum/core/vm" 36 "github.com/ethereum/go-ethereum/crypto" 37 "github.com/ethereum/go-ethereum/eth/downloader" 38 "github.com/ethereum/go-ethereum/ethdb" 39 "github.com/ethereum/go-ethereum/event" 40 "github.com/ethereum/go-ethereum/p2p" 41 "github.com/ethereum/go-ethereum/p2p/enode" 42 "github.com/ethereum/go-ethereum/params" 43 ) 44 45 var ( 46 testBankKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 47 testBank = crypto.PubkeyToAddress(testBankKey.PublicKey) 48 ) 49 50 // newTestProtocolManager creates a new protocol manager for testing purposes, 51 // with the given number of blocks already known, and potential notification 52 // channels for different events. 53 func newTestProtocolManager(mode downloader.SyncMode, blocks int, generator func(int, *core.BlockGen), newtx chan<- []*types.Transaction) (*ProtocolManager, ethdb.Database, error) { 54 var ( 55 evmux = new(event.TypeMux) 56 engine = ethash.NewFaker() 57 db = rawdb.NewMemoryDatabase() 58 gspec = &core.Genesis{ 59 Config: params.TestChainConfig, 60 Alloc: core.GenesisAlloc{testBank: {Balance: big.NewInt(1000000)}}, 61 } 62 genesis = gspec.MustCommit(db) 63 blockchain, _ = core.NewBlockChain(db, nil, gspec.Config, engine, vm.Config{}, nil) 64 ) 65 chain, _ := core.GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, blocks, generator) 66 if _, err := blockchain.InsertChain(chain); err != nil { 67 panic(err) 68 } 69 70 pm, err := NewProtocolManager(gspec.Config, mode, DefaultConfig.NetworkId, evmux, &testTxPool{added: newtx}, engine, blockchain, db, nil) 71 if err != nil { 72 return nil, nil, err 73 } 74 pm.Start(1000) 75 return pm, db, nil 76 } 77 78 // newTestProtocolManagerMust creates a new protocol manager for testing purposes, 79 // with the given number of blocks already known, and potential notification 80 // channels for different events. In case of an error, the constructor force- 81 // fails the test. 82 func newTestProtocolManagerMust(t *testing.T, mode downloader.SyncMode, blocks int, generator func(int, *core.BlockGen), newtx chan<- []*types.Transaction) (*ProtocolManager, ethdb.Database) { 83 pm, db, err := newTestProtocolManager(mode, blocks, generator, newtx) 84 if err != nil { 85 t.Fatalf("Failed to create protocol manager: %v", err) 86 } 87 return pm, db 88 } 89 90 // testTxPool is a fake, helper transaction pool for testing purposes 91 type testTxPool struct { 92 txFeed event.Feed 93 pool []*types.Transaction // Collection of all transactions 94 added chan<- []*types.Transaction // Notification channel for new transactions 95 96 lock sync.RWMutex // Protects the transaction pool 97 } 98 99 // AddRemotes appends a batch of transactions to the pool, and notifies any 100 // listeners if the addition channel is non nil 101 func (p *testTxPool) AddRemotes(txs []*types.Transaction) []error { 102 p.lock.Lock() 103 defer p.lock.Unlock() 104 105 p.pool = append(p.pool, txs...) 106 if p.added != nil { 107 p.added <- txs 108 } 109 return make([]error, len(txs)) 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) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) 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), 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 enode.ID 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 var ( 171 genesis = pm.blockchain.Genesis() 172 head = pm.blockchain.CurrentHeader() 173 td = pm.blockchain.GetTd(head.Hash(), head.Number.Uint64()) 174 ) 175 tp.handshake(nil, td, head.Hash(), genesis.Hash()) 176 } 177 return tp, errc 178 } 179 180 // handshake simulates a trivial handshake that expects the same state from the 181 // remote side as we are simulating locally. 182 func (p *testPeer) handshake(t *testing.T, td *big.Int, head common.Hash, genesis common.Hash) { 183 msg := &statusData{ 184 ProtocolVersion: uint32(p.version), 185 NetworkId: DefaultConfig.NetworkId, 186 TD: td, 187 CurrentBlock: head, 188 GenesisBlock: genesis, 189 } 190 if err := p2p.ExpectMsg(p.app, StatusMsg, msg); err != nil { 191 t.Fatalf("status recv: %v", err) 192 } 193 if err := p2p.Send(p.app, StatusMsg, msg); err != nil { 194 t.Fatalf("status send: %v", err) 195 } 196 } 197 198 // close terminates the local side of the peer, notifying the remote protocol 199 // manager of termination. 200 func (p *testPeer) close() { 201 p.app.Close() 202 }