suite.go 15 KB

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