protocol_test.go 7.4 KB

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