node_test.go 18 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// 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"
	"io/ioutil"
	"os"
23
	"reflect"
24
	"testing"
25
	"time"
26 27 28

	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/p2p"
29
	"github.com/ethereum/go-ethereum/rpc"
30 31 32 33
)

var (
	testNodeKey, _ = crypto.GenerateKey()
34
)
35

36 37
func testNodeConfig() *Config {
	return &Config{
38 39
		Name: "test node",
		P2P:  p2p.Config{PrivateKey: testNodeKey},
40
	}
41
}
42 43 44

// Tests that an empty protocol stack can be started, restarted and stopped.
func TestNodeLifeCycle(t *testing.T) {
45
	stack, err := New(testNodeConfig())
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
	if err != nil {
		t.Fatalf("failed to create protocol stack: %v", err)
	}
	// Ensure that a stopped node can be stopped again
	for i := 0; i < 3; i++ {
		if err := stack.Stop(); err != ErrNodeStopped {
			t.Fatalf("iter %d: stop failure mismatch: have %v, want %v", i, err, ErrNodeStopped)
		}
	}
	// 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 restarted arbitrarily many times
	for i := 0; i < 3; i++ {
		if err := stack.Restart(); err != nil {
			t.Fatalf("iter %d: failed to restart node: %v", i, err)
		}
	}
	// Ensure that a node can be stopped, but only once
	if err := stack.Stop(); err != nil {
		t.Fatalf("failed to stop node: %v", err)
	}
	if err := stack.Stop(); err != ErrNodeStopped {
		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)
	}
	if err := original.Start(); err != nil {
		t.Fatalf("failed to start original protocol stack: %v", err)
	}
	defer original.Stop()

	// Create a second node based on the same data directory and ensure failure
	duplicate, err := New(&Config{DataDir: dir})
	if err != nil {
		t.Fatalf("failed to create duplicate protocol stack: %v", err)
	}
	if err := duplicate.Start(); err != ErrDatadirUsed {
		t.Fatalf("duplicate datadir failure mismatch: have %v, want %v", err, ErrDatadirUsed)
	}
}

106
// Tests whether services can be registered and duplicates caught.
107
func TestServiceRegistry(t *testing.T) {
108
	stack, err := New(testNodeConfig())
109 110 111
	if err != nil {
		t.Fatalf("failed to create protocol stack: %v", err)
	}
112 113 114 115 116
	// Register a batch of unique services and ensure they start successfully
	services := []ServiceConstructor{NewNoopServiceA, NewNoopServiceB, NewNoopServiceC}
	for i, constructor := range services {
		if err := stack.Register(constructor); err != nil {
			t.Fatalf("service #%d: registration failed: %v", i, err)
117 118
		}
	}
119 120
	if err := stack.Start(); err != nil {
		t.Fatalf("failed to start original service stack: %v", err)
121
	}
122 123
	if err := stack.Stop(); err != nil {
		t.Fatalf("failed to stop original service stack: %v", err)
124
	}
125 126 127
	// Duplicate one of the services and retry starting the node
	if err := stack.Register(NewNoopServiceB); err != nil {
		t.Fatalf("duplicate registration failed: %v", err)
128
	}
129 130 131 132 133 134
	if err := stack.Start(); err == nil {
		t.Fatalf("duplicate service started")
	} else {
		if _, ok := err.(*DuplicateServiceError); !ok {
			t.Fatalf("duplicate error mismatch: have %v, want %v", err, DuplicateServiceError{})
		}
135 136 137 138 139
	}
}

// Tests that registered services get started and stopped correctly.
func TestServiceLifeCycle(t *testing.T) {
140
	stack, err := New(testNodeConfig())
141 142 143 144
	if err != nil {
		t.Fatalf("failed to create protocol stack: %v", err)
	}
	// Register a batch of life-cycle instrumented services
145 146 147 148 149
	services := map[string]InstrumentingWrapper{
		"A": InstrumentedServiceMakerA,
		"B": InstrumentedServiceMakerB,
		"C": InstrumentedServiceMakerC,
	}
150 151 152
	started := make(map[string]bool)
	stopped := make(map[string]bool)

153
	for id, maker := range services {
154 155 156
		id := id // Closure for the constructor
		constructor := func(*ServiceContext) (Service, error) {
			return &InstrumentedService{
157
				startHook: func(*p2p.Server) { started[id] = true },
158 159 160
				stopHook:  func() { stopped[id] = true },
			}, nil
		}
161 162
		if err := stack.Register(maker(constructor)); err != nil {
			t.Fatalf("service %s: registration failed: %v", id, err)
163 164 165 166 167 168
		}
	}
	// 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)
	}
Felix Lange's avatar
Felix Lange committed
169
	for id := range services {
170
		if !started[id] {
171
			t.Fatalf("service %s: freshly started service not running", id)
172 173
		}
		if stopped[id] {
174
			t.Fatalf("service %s: freshly started service already stopped", id)
175 176 177 178 179 180
		}
	}
	// Stop the node and check that all services have been stopped
	if err := stack.Stop(); err != nil {
		t.Fatalf("failed to stop protocol stack: %v", err)
	}
Felix Lange's avatar
Felix Lange committed
181
	for id := range services {
182
		if !stopped[id] {
183
			t.Fatalf("service %s: freshly terminated service still running", id)
184 185 186 187 188 189
		}
	}
}

// Tests that services are restarted cleanly as new instances.
func TestServiceRestarts(t *testing.T) {
190
	stack, err := New(testNodeConfig())
191 192 193 194 195 196 197 198 199 200 201 202
	if err != nil {
		t.Fatalf("failed to create protocol stack: %v", err)
	}
	// Define a service that does not support restarts
	var (
		running bool
		started int
	)
	constructor := func(*ServiceContext) (Service, error) {
		running = false

		return &InstrumentedService{
203
			startHook: func(*p2p.Server) {
204 205 206 207 208 209 210 211 212
				if running {
					panic("already running")
				}
				running = true
				started++
			},
		}, nil
	}
	// Register the service and start the protocol stack
213
	if err := stack.Register(constructor); err != nil {
214 215 216 217 218 219 220
		t.Fatalf("failed to register the service: %v", err)
	}
	if err := stack.Start(); err != nil {
		t.Fatalf("failed to start protocol stack: %v", err)
	}
	defer stack.Stop()

221
	if !running || started != 1 {
222 223 224 225 226 227 228 229
		t.Fatalf("running/started mismatch: have %v/%d, want true/1", running, started)
	}
	// Restart the stack a few times and check successful service restarts
	for i := 0; i < 3; i++ {
		if err := stack.Restart(); err != nil {
			t.Fatalf("iter %d: failed to restart stack: %v", i, err)
		}
	}
230
	if !running || started != 4 {
231 232 233 234 235 236 237
		t.Fatalf("running/started mismatch: have %v/%d, want true/4", running, started)
	}
}

// Tests that if a service fails to initialize itself, none of the other services
// will be allowed to even start.
func TestServiceConstructionAbortion(t *testing.T) {
238
	stack, err := New(testNodeConfig())
239 240 241 242
	if err != nil {
		t.Fatalf("failed to create protocol stack: %v", err)
	}
	// Define a batch of good services
243 244 245 246 247
	services := map[string]InstrumentingWrapper{
		"A": InstrumentedServiceMakerA,
		"B": InstrumentedServiceMakerB,
		"C": InstrumentedServiceMakerC,
	}
248
	started := make(map[string]bool)
249
	for id, maker := range services {
250 251 252
		id := id // Closure for the constructor
		constructor := func(*ServiceContext) (Service, error) {
			return &InstrumentedService{
253
				startHook: func(*p2p.Server) { started[id] = true },
254 255
			}, nil
		}
256 257
		if err := stack.Register(maker(constructor)); err != nil {
			t.Fatalf("service %s: registration failed: %v", id, err)
258 259 260 261 262 263 264
		}
	}
	// Register a service that fails to construct itself
	failure := errors.New("fail")
	failer := func(*ServiceContext) (Service, error) {
		return nil, failure
	}
265
	if err := stack.Register(failer); err != nil {
266 267 268 269 270 271 272
		t.Fatalf("failer registration failed: %v", err)
	}
	// Start the protocol stack and ensure none of the services get started
	for i := 0; i < 100; i++ {
		if err := stack.Start(); err != failure {
			t.Fatalf("iter %d: stack startup failure mismatch: have %v, want %v", i, err, failure)
		}
Felix Lange's avatar
Felix Lange committed
273
		for id := range services {
274
			if started[id] {
275
				t.Fatalf("service %s: started should not have", id)
276 277 278 279 280 281 282 283 284
			}
			delete(started, id)
		}
	}
}

// Tests that if a service fails to start, all others started before it will be
// shut down.
func TestServiceStartupAbortion(t *testing.T) {
285
	stack, err := New(testNodeConfig())
286 287 288 289
	if err != nil {
		t.Fatalf("failed to create protocol stack: %v", err)
	}
	// Register a batch of good services
290 291 292 293 294
	services := map[string]InstrumentingWrapper{
		"A": InstrumentedServiceMakerA,
		"B": InstrumentedServiceMakerB,
		"C": InstrumentedServiceMakerC,
	}
295 296 297
	started := make(map[string]bool)
	stopped := make(map[string]bool)

298
	for id, maker := range services {
299 300 301
		id := id // Closure for the constructor
		constructor := func(*ServiceContext) (Service, error) {
			return &InstrumentedService{
302
				startHook: func(*p2p.Server) { started[id] = true },
303 304 305
				stopHook:  func() { stopped[id] = true },
			}, nil
		}
306 307
		if err := stack.Register(maker(constructor)); err != nil {
			t.Fatalf("service %s: registration failed: %v", id, err)
308 309 310 311 312 313 314 315 316
		}
	}
	// Register a service that fails to start
	failure := errors.New("fail")
	failer := func(*ServiceContext) (Service, error) {
		return &InstrumentedService{
			start: failure,
		}, nil
	}
317
	if err := stack.Register(failer); err != nil {
318 319 320 321 322 323 324
		t.Fatalf("failer registration failed: %v", err)
	}
	// Start the protocol stack and ensure all started services stop
	for i := 0; i < 100; i++ {
		if err := stack.Start(); err != failure {
			t.Fatalf("iter %d: stack startup failure mismatch: have %v, want %v", i, err, failure)
		}
Felix Lange's avatar
Felix Lange committed
325
		for id := range services {
326
			if started[id] && !stopped[id] {
327
				t.Fatalf("service %s: started but not stopped", id)
328 329 330 331 332 333 334 335 336 337
			}
			delete(started, id)
			delete(stopped, id)
		}
	}
}

// Tests that even if a registered service fails to shut down cleanly, it does
// not influece the rest of the shutdown invocations.
func TestServiceTerminationGuarantee(t *testing.T) {
338
	stack, err := New(testNodeConfig())
339 340 341 342
	if err != nil {
		t.Fatalf("failed to create protocol stack: %v", err)
	}
	// Register a batch of good services
343 344 345 346 347
	services := map[string]InstrumentingWrapper{
		"A": InstrumentedServiceMakerA,
		"B": InstrumentedServiceMakerB,
		"C": InstrumentedServiceMakerC,
	}
348 349 350
	started := make(map[string]bool)
	stopped := make(map[string]bool)

351
	for id, maker := range services {
352 353 354
		id := id // Closure for the constructor
		constructor := func(*ServiceContext) (Service, error) {
			return &InstrumentedService{
355
				startHook: func(*p2p.Server) { started[id] = true },
356 357 358
				stopHook:  func() { stopped[id] = true },
			}, nil
		}
359 360
		if err := stack.Register(maker(constructor)); err != nil {
			t.Fatalf("service %s: registration failed: %v", id, err)
361 362 363 364 365 366 367 368 369
		}
	}
	// Register a service that fails to shot down cleanly
	failure := errors.New("fail")
	failer := func(*ServiceContext) (Service, error) {
		return &InstrumentedService{
			stop: failure,
		}, nil
	}
370
	if err := stack.Register(failer); err != nil {
371 372 373 374 375 376 377 378
		t.Fatalf("failer registration failed: %v", err)
	}
	// Start the protocol stack, and ensure that a failing shut down terminates all
	for i := 0; i < 100; i++ {
		// Start the stack and make sure all is online
		if err := stack.Start(); err != nil {
			t.Fatalf("iter %d: failed to start protocol stack: %v", i, err)
		}
Felix Lange's avatar
Felix Lange committed
379
		for id := range services {
380
			if !started[id] {
381
				t.Fatalf("iter %d, service %s: service not running", i, id)
382 383
			}
			if stopped[id] {
384
				t.Fatalf("iter %d, service %s: service already stopped", i, id)
385 386 387 388 389 390 391
			}
		}
		// Stop the stack, verify failure and check all terminations
		err := stack.Stop()
		if err, ok := err.(*StopError); !ok {
			t.Fatalf("iter %d: termination failure mismatch: have %v, want StopError", i, err)
		} else {
392 393 394
			failer := reflect.TypeOf(&InstrumentedService{})
			if err.Services[failer] != failure {
				t.Fatalf("iter %d: failer termination failure mismatch: have %v, want %v", i, err.Services[failer], failure)
395 396 397 398 399
			}
			if len(err.Services) != 1 {
				t.Fatalf("iter %d: failure count mismatch: have %d, want %d", i, len(err.Services), 1)
			}
		}
Felix Lange's avatar
Felix Lange committed
400
		for id := range services {
401
			if !stopped[id] {
402
				t.Fatalf("iter %d, service %s: service not terminated", i, id)
403 404 405 406 407 408 409
			}
			delete(started, id)
			delete(stopped, id)
		}
	}
}

410 411
// TestServiceRetrieval tests that individual services can be retrieved.
func TestServiceRetrieval(t *testing.T) {
412
	// Create a simple stack and register two service types
413
	stack, err := New(testNodeConfig())
414 415 416
	if err != nil {
		t.Fatalf("failed to create protocol stack: %v", err)
	}
417
	if err := stack.Register(NewNoopService); err != nil {
418 419
		t.Fatalf("noop service registration failed: %v", err)
	}
420
	if err := stack.Register(NewInstrumentedService); err != nil {
421 422 423 424
		t.Fatalf("instrumented service registration failed: %v", err)
	}
	// Make sure none of the services can be retrieved until started
	var noopServ *NoopService
425 426
	if err := stack.Service(&noopServ); err != ErrNodeStopped {
		t.Fatalf("noop service retrieval mismatch: have %v, want %v", err, ErrNodeStopped)
427 428
	}
	var instServ *InstrumentedService
429 430
	if err := stack.Service(&instServ); err != ErrNodeStopped {
		t.Fatalf("instrumented service retrieval mismatch: have %v, want %v", err, ErrNodeStopped)
431 432 433 434 435 436 437
	}
	// Start the stack and ensure everything is retrievable now
	if err := stack.Start(); err != nil {
		t.Fatalf("failed to start stack: %v", err)
	}
	defer stack.Stop()

438 439
	if err := stack.Service(&noopServ); err != nil {
		t.Fatalf("noop service retrieval mismatch: have %v, want %v", err, nil)
440
	}
441 442
	if err := stack.Service(&instServ); err != nil {
		t.Fatalf("instrumented service retrieval mismatch: have %v, want %v", err, nil)
443 444 445
	}
}

446 447
// Tests that all protocols defined by individual services get launched.
func TestProtocolGather(t *testing.T) {
448
	stack, err := New(testNodeConfig())
449 450 451 452
	if err != nil {
		t.Fatalf("failed to create protocol stack: %v", err)
	}
	// Register a batch of services with some configured number of protocols
453 454 455 456 457 458 459 460 461 462
	services := map[string]struct {
		Count int
		Maker InstrumentingWrapper
	}{
		"Zero Protocols":  {0, InstrumentedServiceMakerA},
		"Single Protocol": {1, InstrumentedServiceMakerB},
		"Many Protocols":  {25, InstrumentedServiceMakerC},
	}
	for id, config := range services {
		protocols := make([]p2p.Protocol, config.Count)
463 464 465 466 467 468 469 470 471
		for i := 0; i < len(protocols); i++ {
			protocols[i].Name = id
			protocols[i].Version = uint(i)
		}
		constructor := func(*ServiceContext) (Service, error) {
			return &InstrumentedService{
				protocols: protocols,
			}, nil
		}
472
		if err := stack.Register(config.Maker(constructor)); err != nil {
473 474 475 476 477 478 479 480 481 482 483 484 485
			t.Fatalf("service %s: registration failed: %v", id, err)
		}
	}
	// Start the services and ensure all protocols start successfully
	if err := stack.Start(); err != nil {
		t.Fatalf("failed to start protocol stack: %v", err)
	}
	defer stack.Stop()

	protocols := stack.Server().Protocols
	if len(protocols) != 26 {
		t.Fatalf("mismatching number of protocols launched: have %d, want %d", len(protocols), 26)
	}
486 487
	for id, config := range services {
		for ver := 0; ver < config.Count; ver++ {
488 489 490 491 492 493 494 495 496 497 498 499 500
			launched := false
			for i := 0; i < len(protocols); i++ {
				if protocols[i].Name == id && protocols[i].Version == uint(ver) {
					launched = true
					break
				}
			}
			if !launched {
				t.Errorf("configured protocol not launched: %s v%d", id, ver)
			}
		}
	}
}
501 502 503 504 505 506 507 508 509

// Tests that all APIs defined by individual services get exposed.
func TestAPIGather(t *testing.T) {
	stack, err := New(testNodeConfig())
	if err != nil {
		t.Fatalf("failed to create protocol stack: %v", err)
	}
	// Register a batch of services with some configured APIs
	calls := make(chan string, 1)
510 511 512
	makeAPI := func(result string) *OneMethodApi {
		return &OneMethodApi{fun: func() { calls <- result }}
	}
513 514 515 516
	services := map[string]struct {
		APIs  []rpc.API
		Maker InstrumentingWrapper
	}{
517 518 519 520 521 522 523 524 525 526 527 528
		"Zero APIs": {
			[]rpc.API{}, InstrumentedServiceMakerA},
		"Single API": {
			[]rpc.API{
				{Namespace: "single", Version: "1", Service: makeAPI("single.v1"), Public: true},
			}, InstrumentedServiceMakerB},
		"Many APIs": {
			[]rpc.API{
				{Namespace: "multi", Version: "1", Service: makeAPI("multi.v1"), Public: true},
				{Namespace: "multi.v2", Version: "2", Service: makeAPI("multi.v2"), Public: true},
				{Namespace: "multi.v2.nested", Version: "2", Service: makeAPI("multi.v2.nested"), Public: true},
			}, InstrumentedServiceMakerC},
529
	}
530

531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
	for id, config := range services {
		config := config
		constructor := func(*ServiceContext) (Service, error) {
			return &InstrumentedService{apis: config.APIs}, nil
		}
		if err := stack.Register(config.Maker(constructor)); err != nil {
			t.Fatalf("service %s: registration failed: %v", id, err)
		}
	}
	// Start the services and ensure all API start successfully
	if err := stack.Start(); err != nil {
		t.Fatalf("failed to start protocol stack: %v", err)
	}
	defer stack.Stop()

	// Connect to the RPC server and verify the various registered endpoints
547
	client, err := stack.Attach()
548
	if err != nil {
549
		t.Fatalf("failed to connect to the inproc API server: %v", err)
550
	}
551
	defer client.Close()
552 553 554 555 556 557 558 559 560 561 562

	tests := []struct {
		Method string
		Result string
	}{
		{"single_theOneMethod", "single.v1"},
		{"multi_theOneMethod", "multi.v1"},
		{"multi.v2_theOneMethod", "multi.v2"},
		{"multi.v2.nested_theOneMethod", "multi.v2.nested"},
	}
	for i, test := range tests {
563 564
		if err := client.Call(nil, test.Method); err != nil {
			t.Errorf("test %d: API request failed: %v", i, err)
565 566 567 568 569 570 571 572 573 574 575
		}
		select {
		case result := <-calls:
			if result != test.Result {
				t.Errorf("test %d: result mismatch: have %s, want %s", i, result, test.Result)
			}
		case <-time.After(time.Second):
			t.Fatalf("test %d: rpc execution timeout", i)
		}
	}
}