suite.go 16 KB

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