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