protocol_test.go 7.7 KB

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