node_test.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. // Copyright 2015 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 node
  17. import (
  18. "errors"
  19. "fmt"
  20. "io"
  21. "net"
  22. "net/http"
  23. "reflect"
  24. "strings"
  25. "testing"
  26. "github.com/ethereum/go-ethereum/crypto"
  27. "github.com/ethereum/go-ethereum/ethdb"
  28. "github.com/ethereum/go-ethereum/p2p"
  29. "github.com/ethereum/go-ethereum/rpc"
  30. "github.com/stretchr/testify/assert"
  31. )
  32. var (
  33. testNodeKey, _ = crypto.GenerateKey()
  34. )
  35. func testNodeConfig() *Config {
  36. return &Config{
  37. Name: "test node",
  38. P2P: p2p.Config{PrivateKey: testNodeKey},
  39. }
  40. }
  41. // Tests that an empty protocol stack can be closed more than once.
  42. func TestNodeCloseMultipleTimes(t *testing.T) {
  43. stack, err := New(testNodeConfig())
  44. if err != nil {
  45. t.Fatalf("failed to create protocol stack: %v", err)
  46. }
  47. stack.Close()
  48. // Ensure that a stopped node can be stopped again
  49. for i := 0; i < 3; i++ {
  50. if err := stack.Close(); err != ErrNodeStopped {
  51. t.Fatalf("iter %d: stop failure mismatch: have %v, want %v", i, err, ErrNodeStopped)
  52. }
  53. }
  54. }
  55. func TestNodeStartMultipleTimes(t *testing.T) {
  56. stack, err := New(testNodeConfig())
  57. if err != nil {
  58. t.Fatalf("failed to create protocol stack: %v", err)
  59. }
  60. // Ensure that a node can be successfully started, but only once
  61. if err := stack.Start(); err != nil {
  62. t.Fatalf("failed to start node: %v", err)
  63. }
  64. if err := stack.Start(); err != ErrNodeRunning {
  65. t.Fatalf("start failure mismatch: have %v, want %v ", err, ErrNodeRunning)
  66. }
  67. // Ensure that a node can be stopped, but only once
  68. if err := stack.Close(); err != nil {
  69. t.Fatalf("failed to stop node: %v", err)
  70. }
  71. if err := stack.Close(); err != ErrNodeStopped {
  72. t.Fatalf("stop failure mismatch: have %v, want %v ", err, ErrNodeStopped)
  73. }
  74. }
  75. // Tests that if the data dir is already in use, an appropriate error is returned.
  76. func TestNodeUsedDataDir(t *testing.T) {
  77. // Create a temporary folder to use as the data directory
  78. dir := t.TempDir()
  79. // Create a new node based on the data directory
  80. original, err := New(&Config{DataDir: dir})
  81. if err != nil {
  82. t.Fatalf("failed to create original protocol stack: %v", err)
  83. }
  84. defer original.Close()
  85. if err := original.Start(); err != nil {
  86. t.Fatalf("failed to start original protocol stack: %v", err)
  87. }
  88. // Create a second node based on the same data directory and ensure failure
  89. _, err = New(&Config{DataDir: dir})
  90. if err != ErrDatadirUsed {
  91. t.Fatalf("duplicate datadir failure mismatch: have %v, want %v", err, ErrDatadirUsed)
  92. }
  93. }
  94. // Tests whether a Lifecycle can be registered.
  95. func TestLifecycleRegistry_Successful(t *testing.T) {
  96. stack, err := New(testNodeConfig())
  97. if err != nil {
  98. t.Fatalf("failed to create protocol stack: %v", err)
  99. }
  100. defer stack.Close()
  101. noop := NewNoop()
  102. stack.RegisterLifecycle(noop)
  103. if !containsLifecycle(stack.lifecycles, noop) {
  104. t.Fatalf("lifecycle was not properly registered on the node, %v", err)
  105. }
  106. }
  107. // Tests whether a service's protocols can be registered properly on the node's p2p server.
  108. func TestRegisterProtocols(t *testing.T) {
  109. stack, err := New(testNodeConfig())
  110. if err != nil {
  111. t.Fatalf("failed to create protocol stack: %v", err)
  112. }
  113. defer stack.Close()
  114. fs, err := NewFullService(stack)
  115. if err != nil {
  116. t.Fatalf("could not create full service: %v", err)
  117. }
  118. for _, protocol := range fs.Protocols() {
  119. if !containsProtocol(stack.server.Protocols, protocol) {
  120. t.Fatalf("protocol %v was not successfully registered", protocol)
  121. }
  122. }
  123. for _, api := range fs.APIs() {
  124. if !containsAPI(stack.rpcAPIs, api) {
  125. t.Fatalf("api %v was not successfully registered", api)
  126. }
  127. }
  128. }
  129. // This test checks that open databases are closed with node.
  130. func TestNodeCloseClosesDB(t *testing.T) {
  131. stack, _ := New(testNodeConfig())
  132. defer stack.Close()
  133. db, err := stack.OpenDatabase("mydb", 0, 0, "", false)
  134. if err != nil {
  135. t.Fatal("can't open DB:", err)
  136. }
  137. if err = db.Put([]byte{}, []byte{}); err != nil {
  138. t.Fatal("can't Put on open DB:", err)
  139. }
  140. stack.Close()
  141. if err = db.Put([]byte{}, []byte{}); err == nil {
  142. t.Fatal("Put succeeded after node is closed")
  143. }
  144. }
  145. // This test checks that OpenDatabase can be used from within a Lifecycle Start method.
  146. func TestNodeOpenDatabaseFromLifecycleStart(t *testing.T) {
  147. stack, _ := New(testNodeConfig())
  148. defer stack.Close()
  149. var db ethdb.Database
  150. var err error
  151. stack.RegisterLifecycle(&InstrumentedService{
  152. startHook: func() {
  153. db, err = stack.OpenDatabase("mydb", 0, 0, "", false)
  154. if err != nil {
  155. t.Fatal("can't open DB:", err)
  156. }
  157. },
  158. stopHook: func() {
  159. db.Close()
  160. },
  161. })
  162. stack.Start()
  163. stack.Close()
  164. }
  165. // This test checks that OpenDatabase can be used from within a Lifecycle Stop method.
  166. func TestNodeOpenDatabaseFromLifecycleStop(t *testing.T) {
  167. stack, _ := New(testNodeConfig())
  168. defer stack.Close()
  169. stack.RegisterLifecycle(&InstrumentedService{
  170. stopHook: func() {
  171. db, err := stack.OpenDatabase("mydb", 0, 0, "", false)
  172. if err != nil {
  173. t.Fatal("can't open DB:", err)
  174. }
  175. db.Close()
  176. },
  177. })
  178. stack.Start()
  179. stack.Close()
  180. }
  181. // Tests that registered Lifecycles get started and stopped correctly.
  182. func TestLifecycleLifeCycle(t *testing.T) {
  183. stack, _ := New(testNodeConfig())
  184. defer stack.Close()
  185. started := make(map[string]bool)
  186. stopped := make(map[string]bool)
  187. // Create a batch of instrumented services
  188. lifecycles := map[string]Lifecycle{
  189. "A": &InstrumentedService{
  190. startHook: func() { started["A"] = true },
  191. stopHook: func() { stopped["A"] = true },
  192. },
  193. "B": &InstrumentedService{
  194. startHook: func() { started["B"] = true },
  195. stopHook: func() { stopped["B"] = true },
  196. },
  197. "C": &InstrumentedService{
  198. startHook: func() { started["C"] = true },
  199. stopHook: func() { stopped["C"] = true },
  200. },
  201. }
  202. // register lifecycles on node
  203. for _, lifecycle := range lifecycles {
  204. stack.RegisterLifecycle(lifecycle)
  205. }
  206. // Start the node and check that all services are running
  207. if err := stack.Start(); err != nil {
  208. t.Fatalf("failed to start protocol stack: %v", err)
  209. }
  210. for id := range lifecycles {
  211. if !started[id] {
  212. t.Fatalf("service %s: freshly started service not running", id)
  213. }
  214. if stopped[id] {
  215. t.Fatalf("service %s: freshly started service already stopped", id)
  216. }
  217. }
  218. // Stop the node and check that all services have been stopped
  219. if err := stack.Close(); err != nil {
  220. t.Fatalf("failed to stop protocol stack: %v", err)
  221. }
  222. for id := range lifecycles {
  223. if !stopped[id] {
  224. t.Fatalf("service %s: freshly terminated service still running", id)
  225. }
  226. }
  227. }
  228. // Tests that if a Lifecycle fails to start, all others started before it will be
  229. // shut down.
  230. func TestLifecycleStartupError(t *testing.T) {
  231. stack, err := New(testNodeConfig())
  232. if err != nil {
  233. t.Fatalf("failed to create protocol stack: %v", err)
  234. }
  235. defer stack.Close()
  236. started := make(map[string]bool)
  237. stopped := make(map[string]bool)
  238. // Create a batch of instrumented services
  239. lifecycles := map[string]Lifecycle{
  240. "A": &InstrumentedService{
  241. startHook: func() { started["A"] = true },
  242. stopHook: func() { stopped["A"] = true },
  243. },
  244. "B": &InstrumentedService{
  245. startHook: func() { started["B"] = true },
  246. stopHook: func() { stopped["B"] = true },
  247. },
  248. "C": &InstrumentedService{
  249. startHook: func() { started["C"] = true },
  250. stopHook: func() { stopped["C"] = true },
  251. },
  252. }
  253. // register lifecycles on node
  254. for _, lifecycle := range lifecycles {
  255. stack.RegisterLifecycle(lifecycle)
  256. }
  257. // Register a service that fails to construct itself
  258. failure := errors.New("fail")
  259. failer := &InstrumentedService{start: failure}
  260. stack.RegisterLifecycle(failer)
  261. // Start the protocol stack and ensure all started services stop
  262. if err := stack.Start(); err != failure {
  263. t.Fatalf("stack startup failure mismatch: have %v, want %v", err, failure)
  264. }
  265. for id := range lifecycles {
  266. if started[id] && !stopped[id] {
  267. t.Fatalf("service %s: started but not stopped", id)
  268. }
  269. delete(started, id)
  270. delete(stopped, id)
  271. }
  272. }
  273. // Tests that even if a registered Lifecycle fails to shut down cleanly, it does
  274. // not influence the rest of the shutdown invocations.
  275. func TestLifecycleTerminationGuarantee(t *testing.T) {
  276. stack, err := New(testNodeConfig())
  277. if err != nil {
  278. t.Fatalf("failed to create protocol stack: %v", err)
  279. }
  280. defer stack.Close()
  281. started := make(map[string]bool)
  282. stopped := make(map[string]bool)
  283. // Create a batch of instrumented services
  284. lifecycles := map[string]Lifecycle{
  285. "A": &InstrumentedService{
  286. startHook: func() { started["A"] = true },
  287. stopHook: func() { stopped["A"] = true },
  288. },
  289. "B": &InstrumentedService{
  290. startHook: func() { started["B"] = true },
  291. stopHook: func() { stopped["B"] = true },
  292. },
  293. "C": &InstrumentedService{
  294. startHook: func() { started["C"] = true },
  295. stopHook: func() { stopped["C"] = true },
  296. },
  297. }
  298. // register lifecycles on node
  299. for _, lifecycle := range lifecycles {
  300. stack.RegisterLifecycle(lifecycle)
  301. }
  302. // Register a service that fails to shot down cleanly
  303. failure := errors.New("fail")
  304. failer := &InstrumentedService{stop: failure}
  305. stack.RegisterLifecycle(failer)
  306. // Start the protocol stack, and ensure that a failing shut down terminates all
  307. // Start the stack and make sure all is online
  308. if err := stack.Start(); err != nil {
  309. t.Fatalf("failed to start protocol stack: %v", err)
  310. }
  311. for id := range lifecycles {
  312. if !started[id] {
  313. t.Fatalf("service %s: service not running", id)
  314. }
  315. if stopped[id] {
  316. t.Fatalf("service %s: service already stopped", id)
  317. }
  318. }
  319. // Stop the stack, verify failure and check all terminations
  320. err = stack.Close()
  321. if err, ok := err.(*StopError); !ok {
  322. t.Fatalf("termination failure mismatch: have %v, want StopError", err)
  323. } else {
  324. failer := reflect.TypeOf(&InstrumentedService{})
  325. if err.Services[failer] != failure {
  326. t.Fatalf("failer termination failure mismatch: have %v, want %v", err.Services[failer], failure)
  327. }
  328. if len(err.Services) != 1 {
  329. t.Fatalf("failure count mismatch: have %d, want %d", len(err.Services), 1)
  330. }
  331. }
  332. for id := range lifecycles {
  333. if !stopped[id] {
  334. t.Fatalf("service %s: service not terminated", id)
  335. }
  336. delete(started, id)
  337. delete(stopped, id)
  338. }
  339. stack.server = &p2p.Server{}
  340. stack.server.PrivateKey = testNodeKey
  341. }
  342. // Tests whether a handler can be successfully mounted on the canonical HTTP server
  343. // on the given prefix
  344. func TestRegisterHandler_Successful(t *testing.T) {
  345. node := createNode(t, 7878, 7979)
  346. defer node.Close()
  347. // create and mount handler
  348. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  349. w.Write([]byte("success"))
  350. })
  351. node.RegisterHandler("test", "/test", handler)
  352. // start node
  353. if err := node.Start(); err != nil {
  354. t.Fatalf("could not start node: %v", err)
  355. }
  356. // create HTTP request
  357. httpReq, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:7878/test", nil)
  358. if err != nil {
  359. t.Error("could not issue new http request ", err)
  360. }
  361. // check response
  362. resp := doHTTPRequest(t, httpReq)
  363. buf := make([]byte, 7)
  364. _, err = io.ReadFull(resp.Body, buf)
  365. if err != nil {
  366. t.Fatalf("could not read response: %v", err)
  367. }
  368. assert.Equal(t, "success", string(buf))
  369. }
  370. // Tests that the given handler will not be successfully mounted since no HTTP server
  371. // is enabled for RPC
  372. func TestRegisterHandler_Unsuccessful(t *testing.T) {
  373. node, err := New(&DefaultConfig)
  374. if err != nil {
  375. t.Fatalf("could not create new node: %v", err)
  376. }
  377. // create and mount handler
  378. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  379. w.Write([]byte("success"))
  380. })
  381. node.RegisterHandler("test", "/test", handler)
  382. }
  383. // Tests whether websocket requests can be handled on the same port as a regular http server.
  384. func TestWebsocketHTTPOnSamePort_WebsocketRequest(t *testing.T) {
  385. node := startHTTP(t, 0, 0)
  386. defer node.Close()
  387. ws := strings.Replace(node.HTTPEndpoint(), "http://", "ws://", 1)
  388. if node.WSEndpoint() != ws {
  389. t.Fatalf("endpoints should be the same")
  390. }
  391. if !checkRPC(ws) {
  392. t.Fatalf("ws request failed")
  393. }
  394. if !checkRPC(node.HTTPEndpoint()) {
  395. t.Fatalf("http request failed")
  396. }
  397. }
  398. func TestWebsocketHTTPOnSeparatePort_WSRequest(t *testing.T) {
  399. // try and get a free port
  400. listener, err := net.Listen("tcp", "127.0.0.1:0")
  401. if err != nil {
  402. t.Fatal("can't listen:", err)
  403. }
  404. port := listener.Addr().(*net.TCPAddr).Port
  405. listener.Close()
  406. node := startHTTP(t, 0, port)
  407. defer node.Close()
  408. wsOnHTTP := strings.Replace(node.HTTPEndpoint(), "http://", "ws://", 1)
  409. ws := fmt.Sprintf("ws://127.0.0.1:%d", port)
  410. if node.WSEndpoint() == wsOnHTTP {
  411. t.Fatalf("endpoints should not be the same")
  412. }
  413. // ensure ws endpoint matches the expected endpoint
  414. if node.WSEndpoint() != ws {
  415. t.Fatalf("ws endpoint is incorrect: expected %s, got %s", ws, node.WSEndpoint())
  416. }
  417. if !checkRPC(ws) {
  418. t.Fatalf("ws request failed")
  419. }
  420. if !checkRPC(node.HTTPEndpoint()) {
  421. t.Fatalf("http request failed")
  422. }
  423. }
  424. type rpcPrefixTest struct {
  425. httpPrefix, wsPrefix string
  426. // These lists paths on which JSON-RPC should be served / not served.
  427. wantHTTP []string
  428. wantNoHTTP []string
  429. wantWS []string
  430. wantNoWS []string
  431. }
  432. func TestNodeRPCPrefix(t *testing.T) {
  433. t.Parallel()
  434. tests := []rpcPrefixTest{
  435. // both off
  436. {
  437. httpPrefix: "", wsPrefix: "",
  438. wantHTTP: []string{"/", "/?p=1"},
  439. wantNoHTTP: []string{"/test", "/test?p=1"},
  440. wantWS: []string{"/", "/?p=1"},
  441. wantNoWS: []string{"/test", "/test?p=1"},
  442. },
  443. // only http prefix
  444. {
  445. httpPrefix: "/testprefix", wsPrefix: "",
  446. wantHTTP: []string{"/testprefix", "/testprefix?p=1", "/testprefix/x", "/testprefix/x?p=1"},
  447. wantNoHTTP: []string{"/", "/?p=1", "/test", "/test?p=1"},
  448. wantWS: []string{"/", "/?p=1"},
  449. wantNoWS: []string{"/testprefix", "/testprefix?p=1", "/test", "/test?p=1"},
  450. },
  451. // only ws prefix
  452. {
  453. httpPrefix: "", wsPrefix: "/testprefix",
  454. wantHTTP: []string{"/", "/?p=1"},
  455. wantNoHTTP: []string{"/testprefix", "/testprefix?p=1", "/test", "/test?p=1"},
  456. wantWS: []string{"/testprefix", "/testprefix?p=1", "/testprefix/x", "/testprefix/x?p=1"},
  457. wantNoWS: []string{"/", "/?p=1", "/test", "/test?p=1"},
  458. },
  459. // both set
  460. {
  461. httpPrefix: "/testprefix", wsPrefix: "/testprefix",
  462. wantHTTP: []string{"/testprefix", "/testprefix?p=1", "/testprefix/x", "/testprefix/x?p=1"},
  463. wantNoHTTP: []string{"/", "/?p=1", "/test", "/test?p=1"},
  464. wantWS: []string{"/testprefix", "/testprefix?p=1", "/testprefix/x", "/testprefix/x?p=1"},
  465. wantNoWS: []string{"/", "/?p=1", "/test", "/test?p=1"},
  466. },
  467. }
  468. for _, test := range tests {
  469. test := test
  470. name := fmt.Sprintf("http=%s ws=%s", test.httpPrefix, test.wsPrefix)
  471. t.Run(name, func(t *testing.T) {
  472. cfg := &Config{
  473. HTTPHost: "127.0.0.1",
  474. HTTPPathPrefix: test.httpPrefix,
  475. WSHost: "127.0.0.1",
  476. WSPathPrefix: test.wsPrefix,
  477. }
  478. node, err := New(cfg)
  479. if err != nil {
  480. t.Fatal("can't create node:", err)
  481. }
  482. defer node.Close()
  483. if err := node.Start(); err != nil {
  484. t.Fatal("can't start node:", err)
  485. }
  486. test.check(t, node)
  487. })
  488. }
  489. }
  490. func (test rpcPrefixTest) check(t *testing.T, node *Node) {
  491. t.Helper()
  492. httpBase := "http://" + node.http.listenAddr()
  493. wsBase := "ws://" + node.http.listenAddr()
  494. if node.WSEndpoint() != wsBase+test.wsPrefix {
  495. t.Errorf("Error: node has wrong WSEndpoint %q", node.WSEndpoint())
  496. }
  497. for _, path := range test.wantHTTP {
  498. resp := rpcRequest(t, httpBase+path)
  499. if resp.StatusCode != 200 {
  500. t.Errorf("Error: %s: bad status code %d, want 200", path, resp.StatusCode)
  501. }
  502. }
  503. for _, path := range test.wantNoHTTP {
  504. resp := rpcRequest(t, httpBase+path)
  505. if resp.StatusCode != 404 {
  506. t.Errorf("Error: %s: bad status code %d, want 404", path, resp.StatusCode)
  507. }
  508. }
  509. for _, path := range test.wantWS {
  510. err := wsRequest(t, wsBase+path)
  511. if err != nil {
  512. t.Errorf("Error: %s: WebSocket connection failed: %v", path, err)
  513. }
  514. }
  515. for _, path := range test.wantNoWS {
  516. err := wsRequest(t, wsBase+path)
  517. if err == nil {
  518. t.Errorf("Error: %s: WebSocket connection succeeded for path in wantNoWS", path)
  519. }
  520. }
  521. }
  522. func createNode(t *testing.T, httpPort, wsPort int) *Node {
  523. conf := &Config{
  524. HTTPHost: "127.0.0.1",
  525. HTTPPort: httpPort,
  526. WSHost: "127.0.0.1",
  527. WSPort: wsPort,
  528. }
  529. node, err := New(conf)
  530. if err != nil {
  531. t.Fatalf("could not create a new node: %v", err)
  532. }
  533. return node
  534. }
  535. func startHTTP(t *testing.T, httpPort, wsPort int) *Node {
  536. node := createNode(t, httpPort, wsPort)
  537. err := node.Start()
  538. if err != nil {
  539. t.Fatalf("could not start http service on node: %v", err)
  540. }
  541. return node
  542. }
  543. func doHTTPRequest(t *testing.T, req *http.Request) *http.Response {
  544. client := http.DefaultClient
  545. resp, err := client.Do(req)
  546. if err != nil {
  547. t.Fatalf("could not issue a GET request to the given endpoint: %v", err)
  548. }
  549. return resp
  550. }
  551. func containsProtocol(stackProtocols []p2p.Protocol, protocol p2p.Protocol) bool {
  552. for _, a := range stackProtocols {
  553. if reflect.DeepEqual(a, protocol) {
  554. return true
  555. }
  556. }
  557. return false
  558. }
  559. func containsAPI(stackAPIs []rpc.API, api rpc.API) bool {
  560. for _, a := range stackAPIs {
  561. if reflect.DeepEqual(a, api) {
  562. return true
  563. }
  564. }
  565. return false
  566. }