protocol_test.go 7.7 KB

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