suite.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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. s.sendNextBlock(t)
  242. }
  243. func (s *Suite) sendNextBlock(t *utesting.T) {
  244. sendConn, receiveConn := s.setupConnection(t), s.setupConnection(t)
  245. defer sendConn.Close()
  246. defer receiveConn.Close()
  247. // create new block announcement
  248. nextBlock := len(s.chain.blocks)
  249. blockAnnouncement := &NewBlock{
  250. Block: s.fullChain.blocks[nextBlock],
  251. TD: s.fullChain.TD(nextBlock + 1),
  252. }
  253. // send announcement and wait for node to request the header
  254. s.testAnnounce(t, sendConn, receiveConn, blockAnnouncement)
  255. // wait for client to update its chain
  256. if err := receiveConn.waitForBlock(s.fullChain.blocks[nextBlock]); err != nil {
  257. t.Fatal(err)
  258. }
  259. // update test suite chain
  260. s.chain.blocks = append(s.chain.blocks, s.fullChain.blocks[nextBlock])
  261. }
  262. // TestMaliciousHandshake tries to send malicious data during the handshake.
  263. func (s *Suite) TestMaliciousHandshake(t *utesting.T) {
  264. conn, err := s.dial()
  265. if err != nil {
  266. t.Fatalf("could not dial: %v", err)
  267. }
  268. defer conn.Close()
  269. // write hello to client
  270. pub0 := crypto.FromECDSAPub(&conn.ourKey.PublicKey)[1:]
  271. handshakes := []*Hello{
  272. {
  273. Version: 5,
  274. Caps: []p2p.Cap{
  275. {Name: largeString(2), Version: 64},
  276. },
  277. ID: pub0,
  278. },
  279. {
  280. Version: 5,
  281. Caps: []p2p.Cap{
  282. {Name: "eth", Version: 64},
  283. {Name: "eth", Version: 65},
  284. },
  285. ID: append(pub0, byte(0)),
  286. },
  287. {
  288. Version: 5,
  289. Caps: []p2p.Cap{
  290. {Name: "eth", Version: 64},
  291. {Name: "eth", Version: 65},
  292. },
  293. ID: append(pub0, pub0...),
  294. },
  295. {
  296. Version: 5,
  297. Caps: []p2p.Cap{
  298. {Name: "eth", Version: 64},
  299. {Name: "eth", Version: 65},
  300. },
  301. ID: largeBuffer(2),
  302. },
  303. {
  304. Version: 5,
  305. Caps: []p2p.Cap{
  306. {Name: largeString(2), Version: 64},
  307. },
  308. ID: largeBuffer(2),
  309. },
  310. }
  311. for i, handshake := range handshakes {
  312. t.Logf("Testing malicious handshake %v\n", i)
  313. // Init the handshake
  314. if err := conn.Write(handshake); err != nil {
  315. t.Fatalf("could not write to connection: %v", err)
  316. }
  317. // check that the peer disconnected
  318. timeout := 20 * time.Second
  319. // Discard one hello
  320. for i := 0; i < 2; i++ {
  321. switch msg := conn.ReadAndServe(s.chain, timeout).(type) {
  322. case *Disconnect:
  323. case *Error:
  324. case *Hello:
  325. // Hello's are send concurrently, so ignore them
  326. continue
  327. default:
  328. t.Fatalf("unexpected: %s", pretty.Sdump(msg))
  329. }
  330. }
  331. // Dial for the next round
  332. conn, err = s.dial()
  333. if err != nil {
  334. t.Fatalf("could not dial: %v", err)
  335. }
  336. }
  337. }
  338. // TestLargeAnnounce tests the announcement mechanism with a large block.
  339. func (s *Suite) TestLargeAnnounce(t *utesting.T) {
  340. nextBlock := len(s.chain.blocks)
  341. blocks := []*NewBlock{
  342. {
  343. Block: largeBlock(),
  344. TD: s.fullChain.TD(nextBlock + 1),
  345. },
  346. {
  347. Block: s.fullChain.blocks[nextBlock],
  348. TD: largeNumber(2),
  349. },
  350. {
  351. Block: largeBlock(),
  352. TD: largeNumber(2),
  353. },
  354. {
  355. Block: s.fullChain.blocks[nextBlock],
  356. TD: s.fullChain.TD(nextBlock + 1),
  357. },
  358. }
  359. for i, blockAnnouncement := range blocks[0:3] {
  360. t.Logf("Testing malicious announcement: %v\n", i)
  361. sendConn := s.setupConnection(t)
  362. if err := sendConn.Write(blockAnnouncement); err != nil {
  363. t.Fatalf("could not write to connection: %v", err)
  364. }
  365. // Invalid announcement, check that peer disconnected
  366. switch msg := sendConn.ReadAndServe(s.chain, time.Second*8).(type) {
  367. case *Disconnect:
  368. case *Error:
  369. break
  370. default:
  371. t.Fatalf("unexpected: %s wanted disconnect", pretty.Sdump(msg))
  372. }
  373. sendConn.Close()
  374. }
  375. // Test the last block as a valid block
  376. s.sendNextBlock(t)
  377. }
  378. func (s *Suite) TestOldAnnounce(t *utesting.T) {
  379. sendConn, recvConn := s.setupConnection(t), s.setupConnection(t)
  380. defer sendConn.Close()
  381. defer recvConn.Close()
  382. s.oldAnnounce(t, sendConn, recvConn)
  383. }
  384. func (s *Suite) oldAnnounce(t *utesting.T, sendConn, receiveConn *Conn) {
  385. oldBlockAnnounce := &NewBlock{
  386. Block: s.chain.blocks[len(s.chain.blocks)/2],
  387. TD: s.chain.blocks[len(s.chain.blocks)/2].Difficulty(),
  388. }
  389. if err := sendConn.Write(oldBlockAnnounce); err != nil {
  390. t.Fatalf("could not write to connection: %v", err)
  391. }
  392. switch msg := receiveConn.ReadAndServe(s.chain, time.Second*8).(type) {
  393. case *NewBlock:
  394. block := *msg
  395. if block.Block.Hash() == oldBlockAnnounce.Block.Hash() {
  396. t.Fatalf("unexpected: block propagated: %s", pretty.Sdump(msg))
  397. }
  398. case *NewBlockHashes:
  399. hashes := *msg
  400. for _, hash := range hashes {
  401. if hash.Hash == oldBlockAnnounce.Block.Hash() {
  402. t.Fatalf("unexpected: block announced: %s", pretty.Sdump(msg))
  403. }
  404. }
  405. case *Error:
  406. errMsg := *msg
  407. // check to make sure error is timeout (propagation didn't come through == test successful)
  408. if !strings.Contains(errMsg.String(), "timeout") {
  409. t.Fatalf("unexpected error: %v", pretty.Sdump(msg))
  410. }
  411. default:
  412. t.Fatalf("unexpected: %s", pretty.Sdump(msg))
  413. }
  414. }
  415. func (s *Suite) testAnnounce(t *utesting.T, sendConn, receiveConn *Conn, blockAnnouncement *NewBlock) {
  416. // Announce the block.
  417. if err := sendConn.Write(blockAnnouncement); err != nil {
  418. t.Fatalf("could not write to connection: %v", err)
  419. }
  420. s.waitAnnounce(t, receiveConn, blockAnnouncement)
  421. }
  422. func (s *Suite) waitAnnounce(t *utesting.T, conn *Conn, blockAnnouncement *NewBlock) {
  423. switch msg := conn.ReadAndServe(s.chain, timeout).(type) {
  424. case *NewBlock:
  425. t.Logf("received NewBlock message: %s", pretty.Sdump(msg.Block))
  426. assert.Equal(t,
  427. blockAnnouncement.Block.Header(), msg.Block.Header(),
  428. "wrong block header in announcement",
  429. )
  430. assert.Equal(t,
  431. blockAnnouncement.TD, msg.TD,
  432. "wrong TD in announcement",
  433. )
  434. case *NewBlockHashes:
  435. message := *msg
  436. t.Logf("received NewBlockHashes message: %s", pretty.Sdump(message))
  437. assert.Equal(t, blockAnnouncement.Block.Hash(), message[0].Hash,
  438. "wrong block hash in announcement",
  439. )
  440. default:
  441. t.Fatalf("unexpected: %s", pretty.Sdump(msg))
  442. }
  443. }
  444. func (s *Suite) setupConnection(t *utesting.T) *Conn {
  445. // create conn
  446. sendConn, err := s.dial()
  447. if err != nil {
  448. t.Fatalf("could not dial: %v", err)
  449. }
  450. sendConn.handshake(t)
  451. sendConn.statusExchange(t, s.chain, nil)
  452. return sendConn
  453. }
  454. // dial attempts to dial the given node and perform a handshake,
  455. // returning the created Conn if successful.
  456. func (s *Suite) dial() (*Conn, error) {
  457. var conn Conn
  458. // dial
  459. fd, err := net.Dial("tcp", fmt.Sprintf("%v:%d", s.Dest.IP(), s.Dest.TCP()))
  460. if err != nil {
  461. return nil, err
  462. }
  463. conn.Conn = rlpx.NewConn(fd, s.Dest.Pubkey())
  464. // do encHandshake
  465. conn.ourKey, _ = crypto.GenerateKey()
  466. _, err = conn.Handshake(conn.ourKey)
  467. if err != nil {
  468. return nil, err
  469. }
  470. // set default p2p capabilities
  471. conn.caps = []p2p.Cap{
  472. {Name: "eth", Version: 64},
  473. {Name: "eth", Version: 65},
  474. }
  475. conn.ourHighestProtoVersion = 65
  476. return &conn, nil
  477. }
  478. func (s *Suite) TestTransaction(t *utesting.T) {
  479. tests := []*types.Transaction{
  480. getNextTxFromChain(t, s),
  481. unknownTx(t, s),
  482. }
  483. for i, tx := range tests {
  484. t.Logf("Testing tx propagation: %v\n", i)
  485. sendSuccessfulTx(t, s, tx)
  486. }
  487. }
  488. func (s *Suite) TestMaliciousTx(t *utesting.T) {
  489. badTxs := []*types.Transaction{
  490. getOldTxFromChain(t, s),
  491. invalidNonceTx(t, s),
  492. hugeAmount(t, s),
  493. hugeGasPrice(t, s),
  494. hugeData(t, s),
  495. }
  496. sendConn := s.setupConnection(t)
  497. defer sendConn.Close()
  498. // set up receiving connection before sending txs to make sure
  499. // no announcements are missed
  500. recvConn := s.setupConnection(t)
  501. defer recvConn.Close()
  502. for i, tx := range badTxs {
  503. t.Logf("Testing malicious tx propagation: %v\n", i)
  504. if err := sendConn.Write(&Transactions{tx}); err != nil {
  505. t.Fatalf("could not write to connection: %v", err)
  506. }
  507. }
  508. // check to make sure bad txs aren't propagated
  509. waitForTxPropagation(t, s, badTxs, recvConn)
  510. }