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