suite.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. // Copyright 2020 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. "net"
  20. "time"
  21. "github.com/davecgh/go-spew/spew"
  22. "github.com/ethereum/go-ethereum/core/types"
  23. "github.com/ethereum/go-ethereum/crypto"
  24. "github.com/ethereum/go-ethereum/eth/protocols/eth"
  25. "github.com/ethereum/go-ethereum/internal/utesting"
  26. "github.com/ethereum/go-ethereum/p2p"
  27. "github.com/ethereum/go-ethereum/p2p/enode"
  28. "github.com/ethereum/go-ethereum/p2p/rlpx"
  29. "github.com/stretchr/testify/assert"
  30. )
  31. var pretty = spew.ConfigState{
  32. Indent: " ",
  33. DisableCapacities: true,
  34. DisablePointerAddresses: true,
  35. SortKeys: true,
  36. }
  37. var timeout = 20 * time.Second
  38. // Suite represents a structure used to test the eth
  39. // protocol of a node(s).
  40. type Suite struct {
  41. Dest *enode.Node
  42. chain *Chain
  43. fullChain *Chain
  44. }
  45. // NewSuite creates and returns a new eth-test suite that can
  46. // be used to test the given node against the given blockchain
  47. // data.
  48. func NewSuite(dest *enode.Node, chainfile string, genesisfile string) (*Suite, error) {
  49. chain, err := loadChain(chainfile, genesisfile)
  50. if err != nil {
  51. return nil, err
  52. }
  53. return &Suite{
  54. Dest: dest,
  55. chain: chain.Shorten(1000),
  56. fullChain: chain,
  57. }, nil
  58. }
  59. func (s *Suite) EthTests() []utesting.Test {
  60. return []utesting.Test{
  61. // status
  62. {Name: "Status", Fn: s.TestStatus},
  63. {Name: "Status_66", Fn: s.TestStatus_66},
  64. // get block headers
  65. {Name: "GetBlockHeaders", Fn: s.TestGetBlockHeaders},
  66. {Name: "GetBlockHeaders_66", Fn: s.TestGetBlockHeaders_66},
  67. {Name: "TestSimultaneousRequests_66", Fn: s.TestSimultaneousRequests_66},
  68. {Name: "TestSameRequestID_66", Fn: s.TestSameRequestID_66},
  69. {Name: "TestZeroRequestID_66", Fn: s.TestZeroRequestID_66},
  70. // get block bodies
  71. {Name: "GetBlockBodies", Fn: s.TestGetBlockBodies},
  72. {Name: "GetBlockBodies_66", Fn: s.TestGetBlockBodies_66},
  73. // broadcast
  74. {Name: "Broadcast", Fn: s.TestBroadcast},
  75. {Name: "Broadcast_66", Fn: s.TestBroadcast_66},
  76. {Name: "TestLargeAnnounce", Fn: s.TestLargeAnnounce},
  77. {Name: "TestLargeAnnounce_66", Fn: s.TestLargeAnnounce_66},
  78. // malicious handshakes + status
  79. {Name: "TestMaliciousHandshake", Fn: s.TestMaliciousHandshake},
  80. {Name: "TestMaliciousStatus", Fn: s.TestMaliciousStatus},
  81. {Name: "TestMaliciousHandshake_66", Fn: s.TestMaliciousHandshake_66},
  82. {Name: "TestMaliciousStatus_66", Fn: s.TestMaliciousStatus},
  83. // test transactions
  84. {Name: "TestTransactions", Fn: s.TestTransaction},
  85. {Name: "TestTransactions_66", Fn: s.TestTransaction_66},
  86. {Name: "TestMaliciousTransactions", Fn: s.TestMaliciousTx},
  87. {Name: "TestMaliciousTransactions_66", Fn: s.TestMaliciousTx_66},
  88. }
  89. }
  90. // TestStatus attempts to connect to the given node and exchange
  91. // a status message with it, and then check to make sure
  92. // the chain head is correct.
  93. func (s *Suite) TestStatus(t *utesting.T) {
  94. conn, err := s.dial()
  95. if err != nil {
  96. t.Fatalf("could not dial: %v", err)
  97. }
  98. // get protoHandshake
  99. conn.handshake(t)
  100. // get status
  101. switch msg := conn.statusExchange(t, s.chain, nil).(type) {
  102. case *Status:
  103. t.Logf("got status message: %s", pretty.Sdump(msg))
  104. default:
  105. t.Fatalf("unexpected: %s", pretty.Sdump(msg))
  106. }
  107. }
  108. // TestMaliciousStatus sends a status package with a large total difficulty.
  109. func (s *Suite) TestMaliciousStatus(t *utesting.T) {
  110. conn, err := s.dial()
  111. if err != nil {
  112. t.Fatalf("could not dial: %v", err)
  113. }
  114. // get protoHandshake
  115. conn.handshake(t)
  116. status := &Status{
  117. ProtocolVersion: uint32(conn.ethProtocolVersion),
  118. NetworkID: s.chain.chainConfig.ChainID.Uint64(),
  119. TD: largeNumber(2),
  120. Head: s.chain.blocks[s.chain.Len()-1].Hash(),
  121. Genesis: s.chain.blocks[0].Hash(),
  122. ForkID: s.chain.ForkID(),
  123. }
  124. // get status
  125. switch msg := conn.statusExchange(t, s.chain, status).(type) {
  126. case *Status:
  127. t.Logf("%+v\n", msg)
  128. default:
  129. t.Fatalf("expected status, got: %#v ", msg)
  130. }
  131. // wait for disconnect
  132. switch msg := conn.ReadAndServe(s.chain, timeout).(type) {
  133. case *Disconnect:
  134. case *Error:
  135. return
  136. default:
  137. t.Fatalf("expected disconnect, got: %s", pretty.Sdump(msg))
  138. }
  139. }
  140. // TestGetBlockHeaders tests whether the given node can respond to
  141. // a `GetBlockHeaders` request and that the response is accurate.
  142. func (s *Suite) TestGetBlockHeaders(t *utesting.T) {
  143. conn, err := s.dial()
  144. if err != nil {
  145. t.Fatalf("could not dial: %v", err)
  146. }
  147. conn.handshake(t)
  148. conn.statusExchange(t, s.chain, nil)
  149. // get block headers
  150. req := &GetBlockHeaders{
  151. Origin: eth.HashOrNumber{
  152. Hash: s.chain.blocks[1].Hash(),
  153. },
  154. Amount: 2,
  155. Skip: 1,
  156. Reverse: false,
  157. }
  158. if err := conn.Write(req); err != nil {
  159. t.Fatalf("could not write to connection: %v", err)
  160. }
  161. switch msg := conn.ReadAndServe(s.chain, timeout).(type) {
  162. case *BlockHeaders:
  163. headers := *msg
  164. for _, header := range headers {
  165. num := header.Number.Uint64()
  166. t.Logf("received header (%d): %s", num, pretty.Sdump(header.Hash()))
  167. assert.Equal(t, s.chain.blocks[int(num)].Header(), header)
  168. }
  169. default:
  170. t.Fatalf("unexpected: %s", pretty.Sdump(msg))
  171. }
  172. }
  173. // TestGetBlockBodies tests whether the given node can respond to
  174. // a `GetBlockBodies` request and that the response is accurate.
  175. func (s *Suite) TestGetBlockBodies(t *utesting.T) {
  176. conn, err := s.dial()
  177. if err != nil {
  178. t.Fatalf("could not dial: %v", err)
  179. }
  180. conn.handshake(t)
  181. conn.statusExchange(t, s.chain, nil)
  182. // create block bodies request
  183. req := &GetBlockBodies{
  184. s.chain.blocks[54].Hash(),
  185. s.chain.blocks[75].Hash(),
  186. }
  187. if err := conn.Write(req); err != nil {
  188. t.Fatalf("could not write to connection: %v", err)
  189. }
  190. switch msg := conn.ReadAndServe(s.chain, timeout).(type) {
  191. case *BlockBodies:
  192. t.Logf("received %d block bodies", len(*msg))
  193. default:
  194. t.Fatalf("unexpected: %s", pretty.Sdump(msg))
  195. }
  196. }
  197. // TestBroadcast tests whether a block announcement is correctly
  198. // propagated to the given node's peer(s).
  199. func (s *Suite) TestBroadcast(t *utesting.T) {
  200. sendConn, receiveConn := s.setupConnection(t), s.setupConnection(t)
  201. nextBlock := len(s.chain.blocks)
  202. blockAnnouncement := &NewBlock{
  203. Block: s.fullChain.blocks[nextBlock],
  204. TD: s.fullChain.TD(nextBlock + 1),
  205. }
  206. s.testAnnounce(t, sendConn, receiveConn, blockAnnouncement)
  207. // update test suite chain
  208. s.chain.blocks = append(s.chain.blocks, s.fullChain.blocks[nextBlock])
  209. // wait for client to update its chain
  210. if err := receiveConn.waitForBlock(s.chain.Head()); err != nil {
  211. t.Fatal(err)
  212. }
  213. }
  214. // TestMaliciousHandshake tries to send malicious data during the handshake.
  215. func (s *Suite) TestMaliciousHandshake(t *utesting.T) {
  216. conn, err := s.dial()
  217. if err != nil {
  218. t.Fatalf("could not dial: %v", err)
  219. }
  220. // write hello to client
  221. pub0 := crypto.FromECDSAPub(&conn.ourKey.PublicKey)[1:]
  222. handshakes := []*Hello{
  223. {
  224. Version: 5,
  225. Caps: []p2p.Cap{
  226. {Name: largeString(2), Version: 64},
  227. },
  228. ID: pub0,
  229. },
  230. {
  231. Version: 5,
  232. Caps: []p2p.Cap{
  233. {Name: "eth", Version: 64},
  234. {Name: "eth", Version: 65},
  235. },
  236. ID: append(pub0, byte(0)),
  237. },
  238. {
  239. Version: 5,
  240. Caps: []p2p.Cap{
  241. {Name: "eth", Version: 64},
  242. {Name: "eth", Version: 65},
  243. },
  244. ID: append(pub0, pub0...),
  245. },
  246. {
  247. Version: 5,
  248. Caps: []p2p.Cap{
  249. {Name: "eth", Version: 64},
  250. {Name: "eth", Version: 65},
  251. },
  252. ID: largeBuffer(2),
  253. },
  254. {
  255. Version: 5,
  256. Caps: []p2p.Cap{
  257. {Name: largeString(2), Version: 64},
  258. },
  259. ID: largeBuffer(2),
  260. },
  261. }
  262. for i, handshake := range handshakes {
  263. t.Logf("Testing malicious handshake %v\n", i)
  264. // Init the handshake
  265. if err := conn.Write(handshake); err != nil {
  266. t.Fatalf("could not write to connection: %v", err)
  267. }
  268. // check that the peer disconnected
  269. timeout := 20 * time.Second
  270. // Discard one hello
  271. for i := 0; i < 2; i++ {
  272. switch msg := conn.ReadAndServe(s.chain, timeout).(type) {
  273. case *Disconnect:
  274. case *Error:
  275. case *Hello:
  276. // Hello's are send concurrently, so ignore them
  277. continue
  278. default:
  279. t.Fatalf("unexpected: %s", pretty.Sdump(msg))
  280. }
  281. }
  282. // Dial for the next round
  283. conn, err = s.dial()
  284. if err != nil {
  285. t.Fatalf("could not dial: %v", err)
  286. }
  287. }
  288. }
  289. // TestLargeAnnounce tests the announcement mechanism with a large block.
  290. func (s *Suite) TestLargeAnnounce(t *utesting.T) {
  291. nextBlock := len(s.chain.blocks)
  292. blocks := []*NewBlock{
  293. {
  294. Block: largeBlock(),
  295. TD: s.fullChain.TD(nextBlock + 1),
  296. },
  297. {
  298. Block: s.fullChain.blocks[nextBlock],
  299. TD: largeNumber(2),
  300. },
  301. {
  302. Block: largeBlock(),
  303. TD: largeNumber(2),
  304. },
  305. {
  306. Block: s.fullChain.blocks[nextBlock],
  307. TD: s.fullChain.TD(nextBlock + 1),
  308. },
  309. }
  310. for i, blockAnnouncement := range blocks[0:3] {
  311. t.Logf("Testing malicious announcement: %v\n", i)
  312. sendConn := s.setupConnection(t)
  313. if err := sendConn.Write(blockAnnouncement); err != nil {
  314. t.Fatalf("could not write to connection: %v", err)
  315. }
  316. // Invalid announcement, check that peer disconnected
  317. switch msg := sendConn.ReadAndServe(s.chain, timeout).(type) {
  318. case *Disconnect:
  319. case *Error:
  320. break
  321. default:
  322. t.Fatalf("unexpected: %s wanted disconnect", pretty.Sdump(msg))
  323. }
  324. }
  325. // Test the last block as a valid block
  326. sendConn := s.setupConnection(t)
  327. receiveConn := s.setupConnection(t)
  328. s.testAnnounce(t, sendConn, receiveConn, blocks[3])
  329. // update test suite chain
  330. s.chain.blocks = append(s.chain.blocks, s.fullChain.blocks[nextBlock])
  331. // wait for client to update its chain
  332. if err := receiveConn.waitForBlock(s.fullChain.blocks[nextBlock]); err != nil {
  333. t.Fatal(err)
  334. }
  335. }
  336. func (s *Suite) testAnnounce(t *utesting.T, sendConn, receiveConn *Conn, blockAnnouncement *NewBlock) {
  337. // Announce the block.
  338. if err := sendConn.Write(blockAnnouncement); err != nil {
  339. t.Fatalf("could not write to connection: %v", err)
  340. }
  341. s.waitAnnounce(t, receiveConn, blockAnnouncement)
  342. }
  343. func (s *Suite) waitAnnounce(t *utesting.T, conn *Conn, blockAnnouncement *NewBlock) {
  344. timeout := 20 * time.Second
  345. switch msg := conn.ReadAndServe(s.chain, timeout).(type) {
  346. case *NewBlock:
  347. t.Logf("received NewBlock message: %s", pretty.Sdump(msg.Block))
  348. assert.Equal(t,
  349. blockAnnouncement.Block.Header(), msg.Block.Header(),
  350. "wrong block header in announcement",
  351. )
  352. assert.Equal(t,
  353. blockAnnouncement.TD, msg.TD,
  354. "wrong TD in announcement",
  355. )
  356. case *NewBlockHashes:
  357. message := *msg
  358. t.Logf("received NewBlockHashes message: %s", pretty.Sdump(message))
  359. assert.Equal(t, blockAnnouncement.Block.Hash(), message[0].Hash,
  360. "wrong block hash in announcement",
  361. )
  362. default:
  363. t.Fatalf("unexpected: %s", pretty.Sdump(msg))
  364. }
  365. }
  366. func (s *Suite) setupConnection(t *utesting.T) *Conn {
  367. // create conn
  368. sendConn, err := s.dial()
  369. if err != nil {
  370. t.Fatalf("could not dial: %v", err)
  371. }
  372. sendConn.handshake(t)
  373. sendConn.statusExchange(t, s.chain, nil)
  374. return sendConn
  375. }
  376. // dial attempts to dial the given node and perform a handshake,
  377. // returning the created Conn if successful.
  378. func (s *Suite) dial() (*Conn, error) {
  379. var conn Conn
  380. // dial
  381. fd, err := net.Dial("tcp", fmt.Sprintf("%v:%d", s.Dest.IP(), s.Dest.TCP()))
  382. if err != nil {
  383. return nil, err
  384. }
  385. conn.Conn = rlpx.NewConn(fd, s.Dest.Pubkey())
  386. // do encHandshake
  387. conn.ourKey, _ = crypto.GenerateKey()
  388. _, err = conn.Handshake(conn.ourKey)
  389. if err != nil {
  390. return nil, err
  391. }
  392. // set default p2p capabilities
  393. conn.caps = []p2p.Cap{
  394. {Name: "eth", Version: 64},
  395. {Name: "eth", Version: 65},
  396. }
  397. return &conn, nil
  398. }
  399. func (s *Suite) TestTransaction(t *utesting.T) {
  400. tests := []*types.Transaction{
  401. getNextTxFromChain(t, s),
  402. unknownTx(t, s),
  403. }
  404. for i, tx := range tests {
  405. t.Logf("Testing tx propagation: %v\n", i)
  406. sendSuccessfulTx(t, s, tx)
  407. }
  408. }
  409. func (s *Suite) TestMaliciousTx(t *utesting.T) {
  410. tests := []*types.Transaction{
  411. getOldTxFromChain(t, s),
  412. invalidNonceTx(t, s),
  413. hugeAmount(t, s),
  414. hugeGasPrice(t, s),
  415. hugeData(t, s),
  416. }
  417. for i, tx := range tests {
  418. t.Logf("Testing malicious tx propagation: %v\n", i)
  419. sendFailingTx(t, s, tx)
  420. }
  421. }