eth66_suiteHelpers.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. // Copyright 2021 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 ethtest
  17. import (
  18. "fmt"
  19. "time"
  20. "github.com/ethereum/go-ethereum/core/types"
  21. "github.com/ethereum/go-ethereum/eth/protocols/eth"
  22. "github.com/ethereum/go-ethereum/internal/utesting"
  23. "github.com/ethereum/go-ethereum/p2p"
  24. "github.com/ethereum/go-ethereum/rlp"
  25. "github.com/stretchr/testify/assert"
  26. )
  27. func (c *Conn) statusExchange66(t *utesting.T, chain *Chain) Message {
  28. status := &Status{
  29. ProtocolVersion: uint32(66),
  30. NetworkID: chain.chainConfig.ChainID.Uint64(),
  31. TD: chain.TD(chain.Len()),
  32. Head: chain.blocks[chain.Len()-1].Hash(),
  33. Genesis: chain.blocks[0].Hash(),
  34. ForkID: chain.ForkID(),
  35. }
  36. return c.statusExchange(t, chain, status)
  37. }
  38. func (s *Suite) dial66(t *utesting.T) *Conn {
  39. conn, err := s.dial()
  40. if err != nil {
  41. t.Fatalf("could not dial: %v", err)
  42. }
  43. conn.caps = append(conn.caps, p2p.Cap{Name: "eth", Version: 66})
  44. conn.ourHighestProtoVersion = 66
  45. return conn
  46. }
  47. func (c *Conn) write66(req eth.Packet, code int) error {
  48. payload, err := rlp.EncodeToBytes(req)
  49. if err != nil {
  50. return err
  51. }
  52. _, err = c.Conn.Write(uint64(code), payload)
  53. return err
  54. }
  55. func (c *Conn) read66() (uint64, Message) {
  56. code, rawData, _, err := c.Conn.Read()
  57. if err != nil {
  58. return 0, errorf("could not read from connection: %v", err)
  59. }
  60. var msg Message
  61. switch int(code) {
  62. case (Hello{}).Code():
  63. msg = new(Hello)
  64. case (Ping{}).Code():
  65. msg = new(Ping)
  66. case (Pong{}).Code():
  67. msg = new(Pong)
  68. case (Disconnect{}).Code():
  69. msg = new(Disconnect)
  70. case (Status{}).Code():
  71. msg = new(Status)
  72. case (GetBlockHeaders{}).Code():
  73. ethMsg := new(eth.GetBlockHeadersPacket66)
  74. if err := rlp.DecodeBytes(rawData, ethMsg); err != nil {
  75. return 0, errorf("could not rlp decode message: %v", err)
  76. }
  77. return ethMsg.RequestId, GetBlockHeaders(*ethMsg.GetBlockHeadersPacket)
  78. case (BlockHeaders{}).Code():
  79. ethMsg := new(eth.BlockHeadersPacket66)
  80. if err := rlp.DecodeBytes(rawData, ethMsg); err != nil {
  81. return 0, errorf("could not rlp decode message: %v", err)
  82. }
  83. return ethMsg.RequestId, BlockHeaders(ethMsg.BlockHeadersPacket)
  84. case (GetBlockBodies{}).Code():
  85. ethMsg := new(eth.GetBlockBodiesPacket66)
  86. if err := rlp.DecodeBytes(rawData, ethMsg); err != nil {
  87. return 0, errorf("could not rlp decode message: %v", err)
  88. }
  89. return ethMsg.RequestId, GetBlockBodies(ethMsg.GetBlockBodiesPacket)
  90. case (BlockBodies{}).Code():
  91. ethMsg := new(eth.BlockBodiesPacket66)
  92. if err := rlp.DecodeBytes(rawData, ethMsg); err != nil {
  93. return 0, errorf("could not rlp decode message: %v", err)
  94. }
  95. return ethMsg.RequestId, BlockBodies(ethMsg.BlockBodiesPacket)
  96. case (NewBlock{}).Code():
  97. msg = new(NewBlock)
  98. case (NewBlockHashes{}).Code():
  99. msg = new(NewBlockHashes)
  100. case (Transactions{}).Code():
  101. msg = new(Transactions)
  102. case (NewPooledTransactionHashes{}).Code():
  103. msg = new(NewPooledTransactionHashes)
  104. default:
  105. msg = errorf("invalid message code: %d", code)
  106. }
  107. if msg != nil {
  108. if err := rlp.DecodeBytes(rawData, msg); err != nil {
  109. return 0, errorf("could not rlp decode message: %v", err)
  110. }
  111. return 0, msg
  112. }
  113. return 0, errorf("invalid message: %s", string(rawData))
  114. }
  115. // ReadAndServe serves GetBlockHeaders requests while waiting
  116. // on another message from the node.
  117. func (c *Conn) readAndServe66(chain *Chain, timeout time.Duration) (uint64, Message) {
  118. start := time.Now()
  119. for time.Since(start) < timeout {
  120. timeout := time.Now().Add(10 * time.Second)
  121. c.SetReadDeadline(timeout)
  122. reqID, msg := c.read66()
  123. switch msg := msg.(type) {
  124. case *Ping:
  125. c.Write(&Pong{})
  126. case *GetBlockHeaders:
  127. headers, err := chain.GetHeaders(*msg)
  128. if err != nil {
  129. return 0, errorf("could not get headers for inbound header request: %v", err)
  130. }
  131. resp := &eth.BlockHeadersPacket66{
  132. RequestId: reqID,
  133. BlockHeadersPacket: eth.BlockHeadersPacket(headers),
  134. }
  135. if err := c.write66(resp, BlockHeaders{}.Code()); err != nil {
  136. return 0, errorf("could not write to connection: %v", err)
  137. }
  138. default:
  139. return reqID, msg
  140. }
  141. }
  142. return 0, errorf("no message received within %v", timeout)
  143. }
  144. func (s *Suite) setupConnection66(t *utesting.T) *Conn {
  145. // create conn
  146. sendConn := s.dial66(t)
  147. sendConn.handshake(t)
  148. sendConn.statusExchange66(t, s.chain)
  149. return sendConn
  150. }
  151. func (s *Suite) testAnnounce66(t *utesting.T, sendConn, receiveConn *Conn, blockAnnouncement *NewBlock) {
  152. // Announce the block.
  153. if err := sendConn.Write(blockAnnouncement); err != nil {
  154. t.Fatalf("could not write to connection: %v", err)
  155. }
  156. s.waitAnnounce66(t, receiveConn, blockAnnouncement)
  157. }
  158. func (s *Suite) waitAnnounce66(t *utesting.T, conn *Conn, blockAnnouncement *NewBlock) {
  159. timeout := 20 * time.Second
  160. _, msg := conn.readAndServe66(s.chain, timeout)
  161. switch msg := msg.(type) {
  162. case *NewBlock:
  163. t.Logf("received NewBlock message: %s", pretty.Sdump(msg.Block))
  164. assert.Equal(t,
  165. blockAnnouncement.Block.Header(), msg.Block.Header(),
  166. "wrong block header in announcement",
  167. )
  168. assert.Equal(t,
  169. blockAnnouncement.TD, msg.TD,
  170. "wrong TD in announcement",
  171. )
  172. case *NewBlockHashes:
  173. blockHashes := *msg
  174. t.Logf("received NewBlockHashes message: %s", pretty.Sdump(blockHashes))
  175. assert.Equal(t, blockAnnouncement.Block.Hash(), blockHashes[0].Hash,
  176. "wrong block hash in announcement",
  177. )
  178. default:
  179. t.Fatalf("unexpected: %s", pretty.Sdump(msg))
  180. }
  181. }
  182. // waitForBlock66 waits for confirmation from the client that it has
  183. // imported the given block.
  184. func (c *Conn) waitForBlock66(block *types.Block) error {
  185. defer c.SetReadDeadline(time.Time{})
  186. timeout := time.Now().Add(20 * time.Second)
  187. c.SetReadDeadline(timeout)
  188. for {
  189. req := eth.GetBlockHeadersPacket66{
  190. RequestId: 54,
  191. GetBlockHeadersPacket: &eth.GetBlockHeadersPacket{
  192. Origin: eth.HashOrNumber{
  193. Hash: block.Hash(),
  194. },
  195. Amount: 1,
  196. },
  197. }
  198. if err := c.write66(req, GetBlockHeaders{}.Code()); err != nil {
  199. return err
  200. }
  201. reqID, msg := c.read66()
  202. // check message
  203. switch msg := msg.(type) {
  204. case BlockHeaders:
  205. // check request ID
  206. if reqID != req.RequestId {
  207. return fmt.Errorf("request ID mismatch: wanted %d, got %d", req.RequestId, reqID)
  208. }
  209. if len(msg) > 0 {
  210. return nil
  211. }
  212. time.Sleep(100 * time.Millisecond)
  213. default:
  214. return fmt.Errorf("invalid message: %s", pretty.Sdump(msg))
  215. }
  216. }
  217. }
  218. func sendSuccessfulTx66(t *utesting.T, s *Suite, tx *types.Transaction) {
  219. sendConn := s.setupConnection66(t)
  220. sendSuccessfulTxWithConn(t, s, tx, sendConn)
  221. }
  222. func sendFailingTx66(t *utesting.T, s *Suite, tx *types.Transaction) {
  223. sendConn, recvConn := s.setupConnection66(t), s.setupConnection66(t)
  224. sendFailingTxWithConns(t, s, tx, sendConn, recvConn)
  225. }
  226. func (s *Suite) getBlockHeaders66(t *utesting.T, conn *Conn, req eth.Packet, expectedID uint64) BlockHeaders {
  227. if err := conn.write66(req, GetBlockHeaders{}.Code()); err != nil {
  228. t.Fatalf("could not write to connection: %v", err)
  229. }
  230. // check block headers response
  231. reqID, msg := conn.readAndServe66(s.chain, timeout)
  232. switch msg := msg.(type) {
  233. case BlockHeaders:
  234. if reqID != expectedID {
  235. t.Fatalf("request ID mismatch: wanted %d, got %d", expectedID, reqID)
  236. }
  237. return msg
  238. default:
  239. t.Fatalf("unexpected: %s", pretty.Sdump(msg))
  240. return nil
  241. }
  242. }
  243. func headersMatch(t *utesting.T, chain *Chain, headers BlockHeaders) {
  244. for _, header := range headers {
  245. num := header.Number.Uint64()
  246. t.Logf("received header (%d): %s", num, pretty.Sdump(header.Hash()))
  247. assert.Equal(t, chain.blocks[int(num)].Header(), header)
  248. }
  249. }