suite.go 16 KB

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