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