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