github.com/codingfuture/orig-energi3@v0.8.4/eth/protocol_test.go (about) 1 // Copyright 2018 The Energi Core Authors 2 // Copyright 2014 The go-ethereum Authors 3 // This file is part of the Energi Core library. 4 // 5 // The Energi Core library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The Energi Core library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the Energi Core library. If not, see <http://www.gnu.org/licenses/>. 17 18 package eth 19 20 import ( 21 "fmt" 22 "sync" 23 "testing" 24 "time" 25 26 "github.com/ethereum/go-ethereum/common" 27 "github.com/ethereum/go-ethereum/core/types" 28 "github.com/ethereum/go-ethereum/crypto" 29 "github.com/ethereum/go-ethereum/eth/downloader" 30 "github.com/ethereum/go-ethereum/p2p" 31 "github.com/ethereum/go-ethereum/rlp" 32 ) 33 34 func init() { 35 // log.Root().SetHandler(log.LvlFilterHandler(log.LvlTrace, log.StreamHandler(os.Stderr, log.TerminalFormat(false)))) 36 } 37 38 var testAccount, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 39 40 // Tests that handshake failures are detected and reported correctly. 41 func TestStatusMsgErrors62(t *testing.T) { testStatusMsgErrors(t, 62) } 42 func TestStatusMsgErrors63(t *testing.T) { testStatusMsgErrors(t, 63) } 43 44 func testStatusMsgErrors(t *testing.T, protocol int) { 45 pm, _ := newTestProtocolManagerMust(t, downloader.FullSync, 0, nil, nil) 46 var ( 47 genesis = pm.blockchain.Genesis() 48 head = pm.blockchain.CurrentHeader() 49 td = pm.blockchain.GetTd(head.Hash(), head.Number.Uint64()) 50 ) 51 defer pm.Stop() 52 53 tests := []struct { 54 code uint64 55 data interface{} 56 wantError error 57 }{ 58 { 59 code: TxMsg, data: []interface{}{}, 60 wantError: errResp(ErrNoStatusMsg, "first msg has code 2 (!= 0)"), 61 }, 62 { 63 code: StatusMsg, data: statusData{10, DefaultConfig.NetworkId, td, head.Hash(), genesis.Hash()}, 64 wantError: errResp(ErrProtocolVersionMismatch, "10 (!= %d)", protocol), 65 }, 66 { 67 code: StatusMsg, data: statusData{uint32(protocol), 999, td, head.Hash(), genesis.Hash()}, 68 wantError: errResp(ErrNetworkIdMismatch, "999 (!= 39797)"), 69 }, 70 { 71 code: StatusMsg, data: statusData{uint32(protocol), DefaultConfig.NetworkId, td, head.Hash(), common.Hash{3}}, 72 wantError: errResp(ErrGenesisBlockMismatch, "0300000000000000 (!= %x)", genesis.Hash().Bytes()[:8]), 73 }, 74 } 75 76 for i, test := range tests { 77 p, errc := newTestPeer("peer", protocol, pm, false) 78 // The send call might hang until reset because 79 // the protocol might not read the payload. 80 go p2p.Send(p.app, test.code, test.data) 81 82 select { 83 case err := <-errc: 84 if err == nil { 85 t.Errorf("test %d: protocol returned nil error, want %q", i, test.wantError) 86 } else if err.Error() != test.wantError.Error() { 87 t.Errorf("test %d: wrong error: got %q, want %q", i, err, test.wantError) 88 } 89 case <-time.After(2 * time.Second): 90 t.Errorf("protocol did not shut down within 2 seconds") 91 } 92 p.close() 93 } 94 } 95 96 // This test checks that received transactions are added to the local pool. 97 func TestRecvTransactions62(t *testing.T) { testRecvTransactions(t, 62) } 98 func TestRecvTransactions63(t *testing.T) { testRecvTransactions(t, 63) } 99 100 func testRecvTransactions(t *testing.T, protocol int) { 101 txAdded := make(chan []*types.Transaction) 102 pm, _ := newTestProtocolManagerMust(t, downloader.FullSync, 0, nil, txAdded) 103 pm.acceptTxs = 1 // mark synced to accept transactions 104 p, _ := newTestPeer("peer", protocol, pm, true) 105 defer pm.Stop() 106 defer p.close() 107 108 tx := newTestTransaction(testAccount, 0, 0) 109 if err := p2p.Send(p.app, TxMsg, []interface{}{tx}); err != nil { 110 t.Fatalf("send error: %v", err) 111 } 112 select { 113 case added := <-txAdded: 114 if len(added) != 1 { 115 t.Errorf("wrong number of added transactions: got %d, want 1", len(added)) 116 } else if added[0].Hash() != tx.Hash() { 117 t.Errorf("added wrong tx hash: got %v, want %v", added[0].Hash(), tx.Hash()) 118 } 119 case <-time.After(2 * time.Second): 120 t.Errorf("no NewTxsEvent received within 2 seconds") 121 } 122 } 123 124 // This test checks that pending transactions are sent. 125 func TestSendTransactions62(t *testing.T) { testSendTransactions(t, 62) } 126 func TestSendTransactions63(t *testing.T) { testSendTransactions(t, 63) } 127 128 func testSendTransactions(t *testing.T, protocol int) { 129 pm, _ := newTestProtocolManagerMust(t, downloader.FullSync, 0, nil, nil) 130 defer pm.Stop() 131 132 // Fill the pool with big transactions. 133 const txsize = txsyncPackSize / 10 134 alltxs := make([]*types.Transaction, 100) 135 for nonce := range alltxs { 136 alltxs[nonce] = newTestTransaction(testAccount, uint64(nonce), txsize) 137 } 138 pm.txpool.AddRemotes(alltxs) 139 140 // Connect several peers. They should all receive the pending transactions. 141 var wg sync.WaitGroup 142 checktxs := func(p *testPeer) { 143 defer wg.Done() 144 defer p.close() 145 seen := make(map[common.Hash]bool) 146 for _, tx := range alltxs { 147 seen[tx.Hash()] = false 148 } 149 for n := 0; n < len(alltxs) && !t.Failed(); { 150 var txs []*types.Transaction 151 msg, err := p.app.ReadMsg() 152 if err != nil { 153 t.Errorf("%v: read error: %v", p.Peer, err) 154 } else if msg.Code != TxMsg { 155 t.Errorf("%v: got code %d, want TxMsg", p.Peer, msg.Code) 156 } 157 if err := msg.Decode(&txs); err != nil { 158 t.Errorf("%v: %v", p.Peer, err) 159 } 160 for _, tx := range txs { 161 hash := tx.Hash() 162 seentx, want := seen[hash] 163 if seentx { 164 t.Errorf("%v: got tx more than once: %x", p.Peer, hash) 165 } 166 if !want { 167 t.Errorf("%v: got unexpected tx: %x", p.Peer, hash) 168 } 169 seen[hash] = true 170 n++ 171 } 172 } 173 } 174 for i := 0; i < 3; i++ { 175 p, _ := newTestPeer(fmt.Sprintf("peer #%d", i), protocol, pm, true) 176 wg.Add(1) 177 go checktxs(p) 178 } 179 wg.Wait() 180 } 181 182 // Tests that the custom union field encoder and decoder works correctly. 183 func TestGetBlockHeadersDataEncodeDecode(t *testing.T) { 184 // Create a "random" hash for testing 185 var hash common.Hash 186 for i := range hash { 187 hash[i] = byte(i) 188 } 189 // Assemble some table driven tests 190 tests := []struct { 191 packet *getBlockHeadersData 192 fail bool 193 }{ 194 // Providing the origin as either a hash or a number should both work 195 {fail: false, packet: &getBlockHeadersData{Origin: hashOrNumber{Number: 314}}}, 196 {fail: false, packet: &getBlockHeadersData{Origin: hashOrNumber{Hash: hash}}}, 197 198 // Providing arbitrary query field should also work 199 {fail: false, packet: &getBlockHeadersData{Origin: hashOrNumber{Number: 314}, Amount: 314, Skip: 1, Reverse: true}}, 200 {fail: false, packet: &getBlockHeadersData{Origin: hashOrNumber{Hash: hash}, Amount: 314, Skip: 1, Reverse: true}}, 201 202 // Providing both the origin hash and origin number must fail 203 {fail: true, packet: &getBlockHeadersData{Origin: hashOrNumber{Hash: hash, Number: 314}}}, 204 } 205 // Iterate over each of the tests and try to encode and then decode 206 for i, tt := range tests { 207 bytes, err := rlp.EncodeToBytes(tt.packet) 208 if err != nil && !tt.fail { 209 t.Fatalf("test %d: failed to encode packet: %v", i, err) 210 } else if err == nil && tt.fail { 211 t.Fatalf("test %d: encode should have failed", i) 212 } 213 if !tt.fail { 214 packet := new(getBlockHeadersData) 215 if err := rlp.DecodeBytes(bytes, packet); err != nil { 216 t.Fatalf("test %d: failed to decode packet: %v", i, err) 217 } 218 if packet.Origin.Hash != tt.packet.Origin.Hash || packet.Origin.Number != tt.packet.Origin.Number || packet.Amount != tt.packet.Amount || 219 packet.Skip != tt.packet.Skip || packet.Reverse != tt.packet.Reverse { 220 t.Fatalf("test %d: encode decode mismatch: have %+v, want %+v", i, packet, tt.packet) 221 } 222 } 223 } 224 }