protocol_test.go 7.5 KB

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