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