suite.go 11 KB

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