node_test.go 17.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package node

import (
	"errors"
21 22
	"fmt"
	"io"
23
	"io/ioutil"
24
	"net"
25
	"net/http"
26
	"os"
27
	"reflect"
28
	"strings"
29 30 31
	"testing"

	"github.com/ethereum/go-ethereum/crypto"
32
	"github.com/ethereum/go-ethereum/ethdb"
33
	"github.com/ethereum/go-ethereum/p2p"
34
	"github.com/ethereum/go-ethereum/rpc"
35 36

	"github.com/stretchr/testify/assert"
37 38 39 40
)

var (
	testNodeKey, _ = crypto.GenerateKey()
41
)
42

43 44
func testNodeConfig() *Config {
	return &Config{
45 46
		Name: "test node",
		P2P:  p2p.Config{PrivateKey: testNodeKey},
47
	}
48
}
49

50 51
// Tests that an empty protocol stack can be closed more than once.
func TestNodeCloseMultipleTimes(t *testing.T) {
52
	stack, err := New(testNodeConfig())
53 54 55
	if err != nil {
		t.Fatalf("failed to create protocol stack: %v", err)
	}
56
	stack.Close()
57

58 59
	// Ensure that a stopped node can be stopped again
	for i := 0; i < 3; i++ {
60
		if err := stack.Close(); err != ErrNodeStopped {
61 62 63
			t.Fatalf("iter %d: stop failure mismatch: have %v, want %v", i, err, ErrNodeStopped)
		}
	}
64 65 66 67 68 69 70 71
}

func TestNodeStartMultipleTimes(t *testing.T) {
	stack, err := New(testNodeConfig())
	if err != nil {
		t.Fatalf("failed to create protocol stack: %v", err)
	}

72 73 74 75 76 77 78 79
	// Ensure that a node can be successfully started, but only once
	if err := stack.Start(); err != nil {
		t.Fatalf("failed to start node: %v", err)
	}
	if err := stack.Start(); err != ErrNodeRunning {
		t.Fatalf("start failure mismatch: have %v, want %v ", err, ErrNodeRunning)
	}
	// Ensure that a node can be stopped, but only once
80
	if err := stack.Close(); err != nil {
81 82
		t.Fatalf("failed to stop node: %v", err)
	}
83
	if err := stack.Close(); err != ErrNodeStopped {
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
		t.Fatalf("stop failure mismatch: have %v, want %v ", err, ErrNodeStopped)
	}
}

// Tests that if the data dir is already in use, an appropriate error is returned.
func TestNodeUsedDataDir(t *testing.T) {
	// Create a temporary folder to use as the data directory
	dir, err := ioutil.TempDir("", "")
	if err != nil {
		t.Fatalf("failed to create temporary data directory: %v", err)
	}
	defer os.RemoveAll(dir)

	// Create a new node based on the data directory
	original, err := New(&Config{DataDir: dir})
	if err != nil {
		t.Fatalf("failed to create original protocol stack: %v", err)
	}
102
	defer original.Close()
103 104 105 106 107
	if err := original.Start(); err != nil {
		t.Fatalf("failed to start original protocol stack: %v", err)
	}

	// Create a second node based on the same data directory and ensure failure
108 109
	_, err = New(&Config{DataDir: dir})
	if err != ErrDatadirUsed {
110 111 112 113
		t.Fatalf("duplicate datadir failure mismatch: have %v, want %v", err, ErrDatadirUsed)
	}
}

114 115
// Tests whether a Lifecycle can be registered.
func TestLifecycleRegistry_Successful(t *testing.T) {
116
	stack, err := New(testNodeConfig())
117 118 119
	if err != nil {
		t.Fatalf("failed to create protocol stack: %v", err)
	}
120 121
	defer stack.Close()

122 123 124 125 126
	noop := NewNoop()
	stack.RegisterLifecycle(noop)

	if !containsLifecycle(stack.lifecycles, noop) {
		t.Fatalf("lifecycle was not properly registered on the node, %v", err)
127 128 129
	}
}

130 131
// Tests whether a service's protocols can be registered properly on the node's p2p server.
func TestRegisterProtocols(t *testing.T) {
132
	stack, err := New(testNodeConfig())
133 134 135
	if err != nil {
		t.Fatalf("failed to create protocol stack: %v", err)
	}
136 137
	defer stack.Close()

138 139 140
	fs, err := NewFullService(stack)
	if err != nil {
		t.Fatalf("could not create full service: %v", err)
141
	}
142

143 144 145
	for _, protocol := range fs.Protocols() {
		if !containsProtocol(stack.server.Protocols, protocol) {
			t.Fatalf("protocol %v was not successfully registered", protocol)
146 147
		}
	}
148 149 150 151

	for _, api := range fs.APIs() {
		if !containsAPI(stack.rpcAPIs, api) {
			t.Fatalf("api %v was not successfully registered", api)
152 153 154 155
		}
	}
}

156 157 158
// This test checks that open databases are closed with node.
func TestNodeCloseClosesDB(t *testing.T) {
	stack, _ := New(testNodeConfig())
159 160
	defer stack.Close()

161
	db, err := stack.OpenDatabase("mydb", 0, 0, "", false)
162 163
	if err != nil {
		t.Fatal("can't open DB:", err)
164
	}
165 166
	if err = db.Put([]byte{}, []byte{}); err != nil {
		t.Fatal("can't Put on open DB:", err)
167 168
	}

169 170 171
	stack.Close()
	if err = db.Put([]byte{}, []byte{}); err == nil {
		t.Fatal("Put succeeded after node is closed")
172 173 174
	}
}

175 176 177 178 179 180 181 182 183
// This test checks that OpenDatabase can be used from within a Lifecycle Start method.
func TestNodeOpenDatabaseFromLifecycleStart(t *testing.T) {
	stack, _ := New(testNodeConfig())
	defer stack.Close()

	var db ethdb.Database
	var err error
	stack.RegisterLifecycle(&InstrumentedService{
		startHook: func() {
184
			db, err = stack.OpenDatabase("mydb", 0, 0, "", false)
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
			if err != nil {
				t.Fatal("can't open DB:", err)
			}
		},
		stopHook: func() {
			db.Close()
		},
	})

	stack.Start()
	stack.Close()
}

// This test checks that OpenDatabase can be used from within a Lifecycle Stop method.
func TestNodeOpenDatabaseFromLifecycleStop(t *testing.T) {
	stack, _ := New(testNodeConfig())
	defer stack.Close()

	stack.RegisterLifecycle(&InstrumentedService{
		stopHook: func() {
205
			db, err := stack.OpenDatabase("mydb", 0, 0, "", false)
206 207 208 209 210 211 212 213 214 215 216 217 218 219
			if err != nil {
				t.Fatal("can't open DB:", err)
			}
			db.Close()
		},
	})

	stack.Start()
	stack.Close()
}

// Tests that registered Lifecycles get started and stopped correctly.
func TestLifecycleLifeCycle(t *testing.T) {
	stack, _ := New(testNodeConfig())
220 221
	defer stack.Close()

222
	started := make(map[string]bool)
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
	stopped := make(map[string]bool)

	// Create a batch of instrumented services
	lifecycles := map[string]Lifecycle{
		"A": &InstrumentedService{
			startHook: func() { started["A"] = true },
			stopHook:  func() { stopped["A"] = true },
		},
		"B": &InstrumentedService{
			startHook: func() { started["B"] = true },
			stopHook:  func() { stopped["B"] = true },
		},
		"C": &InstrumentedService{
			startHook: func() { started["C"] = true },
			stopHook:  func() { stopped["C"] = true },
		},
	}
	// register lifecycles on node
	for _, lifecycle := range lifecycles {
		stack.RegisterLifecycle(lifecycle)
	}
	// Start the node and check that all services are running
	if err := stack.Start(); err != nil {
		t.Fatalf("failed to start protocol stack: %v", err)
	}
	for id := range lifecycles {
		if !started[id] {
			t.Fatalf("service %s: freshly started service not running", id)
251
		}
252 253
		if stopped[id] {
			t.Fatalf("service %s: freshly started service already stopped", id)
254 255
		}
	}
256 257 258
	// Stop the node and check that all services have been stopped
	if err := stack.Close(); err != nil {
		t.Fatalf("failed to stop protocol stack: %v", err)
259
	}
260 261 262
	for id := range lifecycles {
		if !stopped[id] {
			t.Fatalf("service %s: freshly terminated service still running", id)
263 264 265 266
		}
	}
}

267
// Tests that if a Lifecycle fails to start, all others started before it will be
268
// shut down.
269
func TestLifecycleStartupError(t *testing.T) {
270
	stack, err := New(testNodeConfig())
271 272 273
	if err != nil {
		t.Fatalf("failed to create protocol stack: %v", err)
	}
274 275
	defer stack.Close()

276 277 278
	started := make(map[string]bool)
	stopped := make(map[string]bool)

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
	// Create a batch of instrumented services
	lifecycles := map[string]Lifecycle{
		"A": &InstrumentedService{
			startHook: func() { started["A"] = true },
			stopHook:  func() { stopped["A"] = true },
		},
		"B": &InstrumentedService{
			startHook: func() { started["B"] = true },
			stopHook:  func() { stopped["B"] = true },
		},
		"C": &InstrumentedService{
			startHook: func() { started["C"] = true },
			stopHook:  func() { stopped["C"] = true },
		},
	}
	// register lifecycles on node
	for _, lifecycle := range lifecycles {
		stack.RegisterLifecycle(lifecycle)
297
	}
298 299

	// Register a service that fails to construct itself
300
	failure := errors.New("fail")
301 302 303
	failer := &InstrumentedService{start: failure}
	stack.RegisterLifecycle(failer)

304
	// Start the protocol stack and ensure all started services stop
305 306 307 308 309 310
	if err := stack.Start(); err != failure {
		t.Fatalf("stack startup failure mismatch: have %v, want %v", err, failure)
	}
	for id := range lifecycles {
		if started[id] && !stopped[id] {
			t.Fatalf("service %s: started but not stopped", id)
311
		}
312 313
		delete(started, id)
		delete(stopped, id)
314 315 316
	}
}

317
// Tests that even if a registered Lifecycle fails to shut down cleanly, it does
318
// not influence the rest of the shutdown invocations.
319
func TestLifecycleTerminationGuarantee(t *testing.T) {
320
	stack, err := New(testNodeConfig())
321 322 323
	if err != nil {
		t.Fatalf("failed to create protocol stack: %v", err)
	}
324 325
	defer stack.Close()

326 327 328
	started := make(map[string]bool)
	stopped := make(map[string]bool)

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
	// Create a batch of instrumented services
	lifecycles := map[string]Lifecycle{
		"A": &InstrumentedService{
			startHook: func() { started["A"] = true },
			stopHook:  func() { stopped["A"] = true },
		},
		"B": &InstrumentedService{
			startHook: func() { started["B"] = true },
			stopHook:  func() { stopped["B"] = true },
		},
		"C": &InstrumentedService{
			startHook: func() { started["C"] = true },
			stopHook:  func() { stopped["C"] = true },
		},
	}
	// register lifecycles on node
	for _, lifecycle := range lifecycles {
		stack.RegisterLifecycle(lifecycle)
347
	}
348

349 350
	// Register a service that fails to shot down cleanly
	failure := errors.New("fail")
351 352 353
	failer := &InstrumentedService{stop: failure}
	stack.RegisterLifecycle(failer)

354
	// Start the protocol stack, and ensure that a failing shut down terminates all
355 356 357 358 359 360 361
	// Start the stack and make sure all is online
	if err := stack.Start(); err != nil {
		t.Fatalf("failed to start protocol stack: %v", err)
	}
	for id := range lifecycles {
		if !started[id] {
			t.Fatalf("service %s: service not running", id)
362
		}
363 364
		if stopped[id] {
			t.Fatalf("service %s: service already stopped", id)
365
		}
366 367 368 369 370 371 372 373 374
	}
	// Stop the stack, verify failure and check all terminations
	err = stack.Close()
	if err, ok := err.(*StopError); !ok {
		t.Fatalf("termination failure mismatch: have %v, want StopError", err)
	} else {
		failer := reflect.TypeOf(&InstrumentedService{})
		if err.Services[failer] != failure {
			t.Fatalf("failer termination failure mismatch: have %v, want %v", err.Services[failer], failure)
375
		}
376 377
		if len(err.Services) != 1 {
			t.Fatalf("failure count mismatch: have %d, want %d", len(err.Services), 1)
378 379
		}
	}
380 381 382 383 384 385 386 387 388 389
	for id := range lifecycles {
		if !stopped[id] {
			t.Fatalf("service %s: service not terminated", id)
		}
		delete(started, id)
		delete(stopped, id)
	}

	stack.server = &p2p.Server{}
	stack.server.PrivateKey = testNodeKey
390 391
}

392
// Tests whether a handler can be successfully mounted on the canonical HTTP server
393
// on the given prefix
394 395
func TestRegisterHandler_Successful(t *testing.T) {
	node := createNode(t, 7878, 7979)
396

397 398 399 400 401
	// create and mount handler
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("success"))
	})
	node.RegisterHandler("test", "/test", handler)
402

403 404 405
	// start node
	if err := node.Start(); err != nil {
		t.Fatalf("could not start node: %v", err)
406 407
	}

408 409
	// create HTTP request
	httpReq, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:7878/test", nil)
410
	if err != nil {
411
		t.Error("could not issue new http request ", err)
412 413
	}

414 415 416 417 418 419
	// check response
	resp := doHTTPRequest(t, httpReq)
	buf := make([]byte, 7)
	_, err = io.ReadFull(resp.Body, buf)
	if err != nil {
		t.Fatalf("could not read response: %v", err)
420
	}
421
	assert.Equal(t, "success", string(buf))
422
}
423

424 425 426 427
// Tests that the given handler will not be successfully mounted since no HTTP server
// is enabled for RPC
func TestRegisterHandler_Unsuccessful(t *testing.T) {
	node, err := New(&DefaultConfig)
428
	if err != nil {
429
		t.Fatalf("could not create new node: %v", err)
430
	}
431

432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
	// create and mount handler
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("success"))
	})
	node.RegisterHandler("test", "/test", handler)
}

// Tests whether websocket requests can be handled on the same port as a regular http server.
func TestWebsocketHTTPOnSamePort_WebsocketRequest(t *testing.T) {
	node := startHTTP(t, 0, 0)
	defer node.Close()

	ws := strings.Replace(node.HTTPEndpoint(), "http://", "ws://", 1)

	if node.WSEndpoint() != ws {
		t.Fatalf("endpoints should be the same")
448
	}
449 450
	if !checkRPC(ws) {
		t.Fatalf("ws request failed")
451
	}
452 453
	if !checkRPC(node.HTTPEndpoint()) {
		t.Fatalf("http request failed")
454 455
	}
}
456

457 458 459
func TestWebsocketHTTPOnSeparatePort_WSRequest(t *testing.T) {
	// try and get a free port
	listener, err := net.Listen("tcp", "127.0.0.1:0")
460
	if err != nil {
461
		t.Fatal("can't listen:", err)
462
	}
463 464
	port := listener.Addr().(*net.TCPAddr).Port
	listener.Close()
465

466 467
	node := startHTTP(t, 0, port)
	defer node.Close()
468

469 470
	wsOnHTTP := strings.Replace(node.HTTPEndpoint(), "http://", "ws://", 1)
	ws := fmt.Sprintf("ws://127.0.0.1:%d", port)
471

472 473 474 475 476 477 478 479 480 481 482 483 484
	if node.WSEndpoint() == wsOnHTTP {
		t.Fatalf("endpoints should not be the same")
	}
	// ensure ws endpoint matches the expected endpoint
	if node.WSEndpoint() != ws {
		t.Fatalf("ws endpoint is incorrect: expected %s, got %s", ws, node.WSEndpoint())
	}

	if !checkRPC(ws) {
		t.Fatalf("ws request failed")
	}
	if !checkRPC(node.HTTPEndpoint()) {
		t.Fatalf("http request failed")
485
	}
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
}

type rpcPrefixTest struct {
	httpPrefix, wsPrefix string
	// These lists paths on which JSON-RPC should be served / not served.
	wantHTTP   []string
	wantNoHTTP []string
	wantWS     []string
	wantNoWS   []string
}

func TestNodeRPCPrefix(t *testing.T) {
	t.Parallel()

	tests := []rpcPrefixTest{
		// both off
		{
			httpPrefix: "", wsPrefix: "",
			wantHTTP:   []string{"/", "/?p=1"},
			wantNoHTTP: []string{"/test", "/test?p=1"},
			wantWS:     []string{"/", "/?p=1"},
			wantNoWS:   []string{"/test", "/test?p=1"},
		},
		// only http prefix
		{
			httpPrefix: "/testprefix", wsPrefix: "",
			wantHTTP:   []string{"/testprefix", "/testprefix?p=1", "/testprefix/x", "/testprefix/x?p=1"},
			wantNoHTTP: []string{"/", "/?p=1", "/test", "/test?p=1"},
			wantWS:     []string{"/", "/?p=1"},
			wantNoWS:   []string{"/testprefix", "/testprefix?p=1", "/test", "/test?p=1"},
		},
		// only ws prefix
		{
			httpPrefix: "", wsPrefix: "/testprefix",
			wantHTTP:   []string{"/", "/?p=1"},
			wantNoHTTP: []string{"/testprefix", "/testprefix?p=1", "/test", "/test?p=1"},
			wantWS:     []string{"/testprefix", "/testprefix?p=1", "/testprefix/x", "/testprefix/x?p=1"},
			wantNoWS:   []string{"/", "/?p=1", "/test", "/test?p=1"},
		},
		// both set
		{
			httpPrefix: "/testprefix", wsPrefix: "/testprefix",
			wantHTTP:   []string{"/testprefix", "/testprefix?p=1", "/testprefix/x", "/testprefix/x?p=1"},
			wantNoHTTP: []string{"/", "/?p=1", "/test", "/test?p=1"},
			wantWS:     []string{"/testprefix", "/testprefix?p=1", "/testprefix/x", "/testprefix/x?p=1"},
			wantNoWS:   []string{"/", "/?p=1", "/test", "/test?p=1"},
		},
	}

	for _, test := range tests {
		test := test
		name := fmt.Sprintf("http=%s ws=%s", test.httpPrefix, test.wsPrefix)
		t.Run(name, func(t *testing.T) {
			cfg := &Config{
				HTTPHost:       "127.0.0.1",
				HTTPPathPrefix: test.httpPrefix,
				WSHost:         "127.0.0.1",
				WSPathPrefix:   test.wsPrefix,
			}
			node, err := New(cfg)
			if err != nil {
				t.Fatal("can't create node:", err)
			}
			defer node.Close()
			if err := node.Start(); err != nil {
				t.Fatal("can't start node:", err)
			}
			test.check(t, node)
		})
	}
}

func (test rpcPrefixTest) check(t *testing.T, node *Node) {
	t.Helper()
	httpBase := "http://" + node.http.listenAddr()
	wsBase := "ws://" + node.http.listenAddr()

	if node.WSEndpoint() != wsBase+test.wsPrefix {
		t.Errorf("Error: node has wrong WSEndpoint %q", node.WSEndpoint())
	}

	for _, path := range test.wantHTTP {
		resp := rpcRequest(t, httpBase+path)
		if resp.StatusCode != 200 {
			t.Errorf("Error: %s: bad status code %d, want 200", path, resp.StatusCode)
		}
	}
	for _, path := range test.wantNoHTTP {
		resp := rpcRequest(t, httpBase+path)
		if resp.StatusCode != 404 {
			t.Errorf("Error: %s: bad status code %d, want 404", path, resp.StatusCode)
		}
	}
	for _, path := range test.wantWS {
		err := wsRequest(t, wsBase+path, "")
		if err != nil {
			t.Errorf("Error: %s: WebSocket connection failed: %v", path, err)
		}
	}
	for _, path := range test.wantNoWS {
		err := wsRequest(t, wsBase+path, "")
		if err == nil {
			t.Errorf("Error: %s: WebSocket connection succeeded for path in wantNoWS", path)
		}
590

591
	}
592 593
}

594 595 596 597 598 599 600
func createNode(t *testing.T, httpPort, wsPort int) *Node {
	conf := &Config{
		HTTPHost: "127.0.0.1",
		HTTPPort: httpPort,
		WSHost:   "127.0.0.1",
		WSPort:   wsPort,
	}
601 602
	node, err := New(conf)
	if err != nil {
603
		t.Fatalf("could not create a new node: %v", err)
604
	}
605 606
	return node
}
607

608 609 610
func startHTTP(t *testing.T, httpPort, wsPort int) *Node {
	node := createNode(t, httpPort, wsPort)
	err := node.Start()
611
	if err != nil {
612
		t.Fatalf("could not start http service on node: %v", err)
613 614 615 616 617 618
	}

	return node
}

func doHTTPRequest(t *testing.T, req *http.Request) *http.Response {
619
	client := http.DefaultClient
620 621
	resp, err := client.Do(req)
	if err != nil {
622 623
		t.Fatalf("could not issue a GET request to the given endpoint: %v", err)

624 625 626
	}
	return resp
}
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644

func containsProtocol(stackProtocols []p2p.Protocol, protocol p2p.Protocol) bool {
	for _, a := range stackProtocols {
		if reflect.DeepEqual(a, protocol) {
			return true
		}
	}
	return false
}

func containsAPI(stackAPIs []rpc.API, api rpc.API) bool {
	for _, a := range stackAPIs {
		if reflect.DeepEqual(a, api) {
			return true
		}
	}
	return false
}