protocol_test.go 7.4 KB

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