github.com/EgonCoin/EgonChain@v1.10.16/p2p/simulations/http_test.go (about)

     1  // Copyright 2017 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  
    17  package simulations
    18  
    19  import (
    20  	"context"
    21  	"flag"
    22  	"fmt"
    23  	"math/rand"
    24  	"net/http/httptest"
    25  	"os"
    26  	"reflect"
    27  	"sync"
    28  	"sync/atomic"
    29  	"testing"
    30  	"time"
    31  
    32  	"github.com/EgonCoin/EgonChain/event"
    33  	"github.com/EgonCoin/EgonChain/log"
    34  	"github.com/EgonCoin/EgonChain/node"
    35  	"github.com/EgonCoin/EgonChain/p2p"
    36  	"github.com/EgonCoin/EgonChain/p2p/enode"
    37  	"github.com/EgonCoin/EgonChain/p2p/simulations/adapters"
    38  	"github.com/EgonCoin/EgonChain/rpc"
    39  	"github.com/mattn/go-colorable"
    40  )
    41  
    42  func TestMain(m *testing.M) {
    43  	loglevel := flag.Int("loglevel", 2, "verbosity of logs")
    44  
    45  	flag.Parse()
    46  	log.PrintOrigins(true)
    47  	log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*loglevel), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(true))))
    48  	os.Exit(m.Run())
    49  }
    50  
    51  // testService implements the node.Service interface and provides protocols
    52  // and APIs which are useful for testing nodes in a simulation network
    53  type testService struct {
    54  	id enode.ID
    55  
    56  	// peerCount is incremented once a peer handshake has been performed
    57  	peerCount int64
    58  
    59  	peers    map[enode.ID]*testPeer
    60  	peersMtx sync.Mutex
    61  
    62  	// state stores []byte which is used to test creating and loading
    63  	// snapshots
    64  	state atomic.Value
    65  }
    66  
    67  func newTestService(ctx *adapters.ServiceContext, stack *node.Node) (node.Lifecycle, error) {
    68  	svc := &testService{
    69  		id:    ctx.Config.ID,
    70  		peers: make(map[enode.ID]*testPeer),
    71  	}
    72  	svc.state.Store(ctx.Snapshot)
    73  
    74  	stack.RegisterProtocols(svc.Protocols())
    75  	stack.RegisterAPIs(svc.APIs())
    76  	return svc, nil
    77  }
    78  
    79  type testPeer struct {
    80  	testReady chan struct{}
    81  	dumReady  chan struct{}
    82  }
    83  
    84  func (t *testService) peer(id enode.ID) *testPeer {
    85  	t.peersMtx.Lock()
    86  	defer t.peersMtx.Unlock()
    87  	if peer, ok := t.peers[id]; ok {
    88  		return peer
    89  	}
    90  	peer := &testPeer{
    91  		testReady: make(chan struct{}),
    92  		dumReady:  make(chan struct{}),
    93  	}
    94  	t.peers[id] = peer
    95  	return peer
    96  }
    97  
    98  func (t *testService) Protocols() []p2p.Protocol {
    99  	return []p2p.Protocol{
   100  		{
   101  			Name:    "test",
   102  			Version: 1,
   103  			Length:  3,
   104  			Run:     t.RunTest,
   105  		},
   106  		{
   107  			Name:    "dum",
   108  			Version: 1,
   109  			Length:  1,
   110  			Run:     t.RunDum,
   111  		},
   112  		{
   113  			Name:    "prb",
   114  			Version: 1,
   115  			Length:  1,
   116  			Run:     t.RunPrb,
   117  		},
   118  	}
   119  }
   120  
   121  func (t *testService) APIs() []rpc.API {
   122  	return []rpc.API{{
   123  		Namespace: "test",
   124  		Version:   "1.0",
   125  		Service: &TestAPI{
   126  			state:     &t.state,
   127  			peerCount: &t.peerCount,
   128  		},
   129  	}}
   130  }
   131  
   132  func (t *testService) Start() error {
   133  	return nil
   134  }
   135  
   136  func (t *testService) Stop() error {
   137  	return nil
   138  }
   139  
   140  // handshake performs a peer handshake by sending and expecting an empty
   141  // message with the given code
   142  func (t *testService) handshake(rw p2p.MsgReadWriter, code uint64) error {
   143  	errc := make(chan error, 2)
   144  	go func() { errc <- p2p.Send(rw, code, struct{}{}) }()
   145  	go func() { errc <- p2p.ExpectMsg(rw, code, struct{}{}) }()
   146  	for i := 0; i < 2; i++ {
   147  		if err := <-errc; err != nil {
   148  			return err
   149  		}
   150  	}
   151  	return nil
   152  }
   153  
   154  func (t *testService) RunTest(p *p2p.Peer, rw p2p.MsgReadWriter) error {
   155  	peer := t.peer(p.ID())
   156  
   157  	// perform three handshakes with three different message codes,
   158  	// used to test message sending and filtering
   159  	if err := t.handshake(rw, 2); err != nil {
   160  		return err
   161  	}
   162  	if err := t.handshake(rw, 1); err != nil {
   163  		return err
   164  	}
   165  	if err := t.handshake(rw, 0); err != nil {
   166  		return err
   167  	}
   168  
   169  	// close the testReady channel so that other protocols can run
   170  	close(peer.testReady)
   171  
   172  	// track the peer
   173  	atomic.AddInt64(&t.peerCount, 1)
   174  	defer atomic.AddInt64(&t.peerCount, -1)
   175  
   176  	// block until the peer is dropped
   177  	for {
   178  		_, err := rw.ReadMsg()
   179  		if err != nil {
   180  			return err
   181  		}
   182  	}
   183  }
   184  
   185  func (t *testService) RunDum(p *p2p.Peer, rw p2p.MsgReadWriter) error {
   186  	peer := t.peer(p.ID())
   187  
   188  	// wait for the test protocol to perform its handshake
   189  	<-peer.testReady
   190  
   191  	// perform a handshake
   192  	if err := t.handshake(rw, 0); err != nil {
   193  		return err
   194  	}
   195  
   196  	// close the dumReady channel so that other protocols can run
   197  	close(peer.dumReady)
   198  
   199  	// block until the peer is dropped
   200  	for {
   201  		_, err := rw.ReadMsg()
   202  		if err != nil {
   203  			return err
   204  		}
   205  	}
   206  }
   207  func (t *testService) RunPrb(p *p2p.Peer, rw p2p.MsgReadWriter) error {
   208  	peer := t.peer(p.ID())
   209  
   210  	// wait for the dum protocol to perform its handshake
   211  	<-peer.dumReady
   212  
   213  	// perform a handshake
   214  	if err := t.handshake(rw, 0); err != nil {
   215  		return err
   216  	}
   217  
   218  	// block until the peer is dropped
   219  	for {
   220  		_, err := rw.ReadMsg()
   221  		if err != nil {
   222  			return err
   223  		}
   224  	}
   225  }
   226  
   227  func (t *testService) Snapshot() ([]byte, error) {
   228  	return t.state.Load().([]byte), nil
   229  }
   230  
   231  // TestAPI provides a test API to:
   232  // * get the peer count
   233  // * get and set an arbitrary state byte slice
   234  // * get and increment a counter
   235  // * subscribe to counter increment events
   236  type TestAPI struct {
   237  	state     *atomic.Value
   238  	peerCount *int64
   239  	counter   int64
   240  	feed      event.Feed
   241  }
   242  
   243  func (t *TestAPI) PeerCount() int64 {
   244  	return atomic.LoadInt64(t.peerCount)
   245  }
   246  
   247  func (t *TestAPI) Get() int64 {
   248  	return atomic.LoadInt64(&t.counter)
   249  }
   250  
   251  func (t *TestAPI) Add(delta int64) {
   252  	atomic.AddInt64(&t.counter, delta)
   253  	t.feed.Send(delta)
   254  }
   255  
   256  func (t *TestAPI) GetState() []byte {
   257  	return t.state.Load().([]byte)
   258  }
   259  
   260  func (t *TestAPI) SetState(state []byte) {
   261  	t.state.Store(state)
   262  }
   263  
   264  func (t *TestAPI) Events(ctx context.Context) (*rpc.Subscription, error) {
   265  	notifier, supported := rpc.NotifierFromContext(ctx)
   266  	if !supported {
   267  		return nil, rpc.ErrNotificationsUnsupported
   268  	}
   269  
   270  	rpcSub := notifier.CreateSubscription()
   271  
   272  	go func() {
   273  		events := make(chan int64)
   274  		sub := t.feed.Subscribe(events)
   275  		defer sub.Unsubscribe()
   276  
   277  		for {
   278  			select {
   279  			case event := <-events:
   280  				notifier.Notify(rpcSub.ID, event)
   281  			case <-sub.Err():
   282  				return
   283  			case <-rpcSub.Err():
   284  				return
   285  			case <-notifier.Closed():
   286  				return
   287  			}
   288  		}
   289  	}()
   290  
   291  	return rpcSub, nil
   292  }
   293  
   294  var testServices = adapters.LifecycleConstructors{
   295  	"test": newTestService,
   296  }
   297  
   298  func testHTTPServer(t *testing.T) (*Network, *httptest.Server) {
   299  	t.Helper()
   300  	adapter := adapters.NewSimAdapter(testServices)
   301  	network := NewNetwork(adapter, &NetworkConfig{
   302  		DefaultService: "test",
   303  	})
   304  	return network, httptest.NewServer(NewServer(network))
   305  }
   306  
   307  // TestHTTPNetwork tests interacting with a simulation network using the HTTP
   308  // API
   309  func TestHTTPNetwork(t *testing.T) {
   310  	// start the server
   311  	network, s := testHTTPServer(t)
   312  	defer s.Close()
   313  
   314  	// subscribe to events so we can check them later
   315  	client := NewClient(s.URL)
   316  	events := make(chan *Event, 100)
   317  	var opts SubscribeOpts
   318  	sub, err := client.SubscribeNetwork(events, opts)
   319  	if err != nil {
   320  		t.Fatalf("error subscribing to network events: %s", err)
   321  	}
   322  	defer sub.Unsubscribe()
   323  
   324  	// check we can retrieve details about the network
   325  	gotNetwork, err := client.GetNetwork()
   326  	if err != nil {
   327  		t.Fatalf("error getting network: %s", err)
   328  	}
   329  	if gotNetwork.ID != network.ID {
   330  		t.Fatalf("expected network to have ID %q, got %q", network.ID, gotNetwork.ID)
   331  	}
   332  
   333  	// start a simulation network
   334  	nodeIDs := startTestNetwork(t, client)
   335  
   336  	// check we got all the events
   337  	x := &expectEvents{t, events, sub}
   338  	x.expect(
   339  		x.nodeEvent(nodeIDs[0], false),
   340  		x.nodeEvent(nodeIDs[1], false),
   341  		x.nodeEvent(nodeIDs[0], true),
   342  		x.nodeEvent(nodeIDs[1], true),
   343  		x.connEvent(nodeIDs[0], nodeIDs[1], false),
   344  		x.connEvent(nodeIDs[0], nodeIDs[1], true),
   345  	)
   346  
   347  	// reconnect the stream and check we get the current nodes and conns
   348  	events = make(chan *Event, 100)
   349  	opts.Current = true
   350  	sub, err = client.SubscribeNetwork(events, opts)
   351  	if err != nil {
   352  		t.Fatalf("error subscribing to network events: %s", err)
   353  	}
   354  	defer sub.Unsubscribe()
   355  	x = &expectEvents{t, events, sub}
   356  	x.expect(
   357  		x.nodeEvent(nodeIDs[0], true),
   358  		x.nodeEvent(nodeIDs[1], true),
   359  		x.connEvent(nodeIDs[0], nodeIDs[1], true),
   360  	)
   361  }
   362  
   363  func startTestNetwork(t *testing.T, client *Client) []string {
   364  	// create two nodes
   365  	nodeCount := 2
   366  	nodeIDs := make([]string, nodeCount)
   367  	for i := 0; i < nodeCount; i++ {
   368  		config := adapters.RandomNodeConfig()
   369  		node, err := client.CreateNode(config)
   370  		if err != nil {
   371  			t.Fatalf("error creating node: %s", err)
   372  		}
   373  		nodeIDs[i] = node.ID
   374  	}
   375  
   376  	// check both nodes exist
   377  	nodes, err := client.GetNodes()
   378  	if err != nil {
   379  		t.Fatalf("error getting nodes: %s", err)
   380  	}
   381  	if len(nodes) != nodeCount {
   382  		t.Fatalf("expected %d nodes, got %d", nodeCount, len(nodes))
   383  	}
   384  	for i, nodeID := range nodeIDs {
   385  		if nodes[i].ID != nodeID {
   386  			t.Fatalf("expected node %d to have ID %q, got %q", i, nodeID, nodes[i].ID)
   387  		}
   388  		node, err := client.GetNode(nodeID)
   389  		if err != nil {
   390  			t.Fatalf("error getting node %d: %s", i, err)
   391  		}
   392  		if node.ID != nodeID {
   393  			t.Fatalf("expected node %d to have ID %q, got %q", i, nodeID, node.ID)
   394  		}
   395  	}
   396  
   397  	// start both nodes
   398  	for _, nodeID := range nodeIDs {
   399  		if err := client.StartNode(nodeID); err != nil {
   400  			t.Fatalf("error starting node %q: %s", nodeID, err)
   401  		}
   402  	}
   403  
   404  	// connect the nodes
   405  	for i := 0; i < nodeCount-1; i++ {
   406  		peerId := i + 1
   407  		if i == nodeCount-1 {
   408  			peerId = 0
   409  		}
   410  		if err := client.ConnectNode(nodeIDs[i], nodeIDs[peerId]); err != nil {
   411  			t.Fatalf("error connecting nodes: %s", err)
   412  		}
   413  	}
   414  
   415  	return nodeIDs
   416  }
   417  
   418  type expectEvents struct {
   419  	*testing.T
   420  
   421  	events chan *Event
   422  	sub    event.Subscription
   423  }
   424  
   425  func (t *expectEvents) nodeEvent(id string, up bool) *Event {
   426  	config := &adapters.NodeConfig{ID: enode.HexID(id)}
   427  	return &Event{Type: EventTypeNode, Node: newNode(nil, config, up)}
   428  }
   429  
   430  func (t *expectEvents) connEvent(one, other string, up bool) *Event {
   431  	return &Event{
   432  		Type: EventTypeConn,
   433  		Conn: &Conn{
   434  			One:   enode.HexID(one),
   435  			Other: enode.HexID(other),
   436  			Up:    up,
   437  		},
   438  	}
   439  }
   440  
   441  func (t *expectEvents) expectMsgs(expected map[MsgFilter]int) {
   442  	actual := make(map[MsgFilter]int)
   443  	timeout := time.After(10 * time.Second)
   444  loop:
   445  	for {
   446  		select {
   447  		case event := <-t.events:
   448  			t.Logf("received %s event: %v", event.Type, event)
   449  
   450  			if event.Type != EventTypeMsg || event.Msg.Received {
   451  				continue loop
   452  			}
   453  			if event.Msg == nil {
   454  				t.Fatal("expected event.Msg to be set")
   455  			}
   456  			filter := MsgFilter{
   457  				Proto: event.Msg.Protocol,
   458  				Code:  int64(event.Msg.Code),
   459  			}
   460  			actual[filter]++
   461  			if actual[filter] > expected[filter] {
   462  				t.Fatalf("received too many msgs for filter: %v", filter)
   463  			}
   464  			if reflect.DeepEqual(actual, expected) {
   465  				return
   466  			}
   467  
   468  		case err := <-t.sub.Err():
   469  			t.Fatalf("network stream closed unexpectedly: %s", err)
   470  
   471  		case <-timeout:
   472  			t.Fatal("timed out waiting for expected events")
   473  		}
   474  	}
   475  }
   476  
   477  func (t *expectEvents) expect(events ...*Event) {
   478  	t.Helper()
   479  	timeout := time.After(10 * time.Second)
   480  	i := 0
   481  	for {
   482  		select {
   483  		case event := <-t.events:
   484  			t.Logf("received %s event: %v", event.Type, event)
   485  
   486  			expected := events[i]
   487  			if event.Type != expected.Type {
   488  				t.Fatalf("expected event %d to have type %q, got %q", i, expected.Type, event.Type)
   489  			}
   490  
   491  			switch expected.Type {
   492  
   493  			case EventTypeNode:
   494  				if event.Node == nil {
   495  					t.Fatal("expected event.Node to be set")
   496  				}
   497  				if event.Node.ID() != expected.Node.ID() {
   498  					t.Fatalf("expected node event %d to have id %q, got %q", i, expected.Node.ID().TerminalString(), event.Node.ID().TerminalString())
   499  				}
   500  				if event.Node.Up() != expected.Node.Up() {
   501  					t.Fatalf("expected node event %d to have up=%t, got up=%t", i, expected.Node.Up(), event.Node.Up())
   502  				}
   503  
   504  			case EventTypeConn:
   505  				if event.Conn == nil {
   506  					t.Fatal("expected event.Conn to be set")
   507  				}
   508  				if event.Conn.One != expected.Conn.One {
   509  					t.Fatalf("expected conn event %d to have one=%q, got one=%q", i, expected.Conn.One.TerminalString(), event.Conn.One.TerminalString())
   510  				}
   511  				if event.Conn.Other != expected.Conn.Other {
   512  					t.Fatalf("expected conn event %d to have other=%q, got other=%q", i, expected.Conn.Other.TerminalString(), event.Conn.Other.TerminalString())
   513  				}
   514  				if event.Conn.Up != expected.Conn.Up {
   515  					t.Fatalf("expected conn event %d to have up=%t, got up=%t", i, expected.Conn.Up, event.Conn.Up)
   516  				}
   517  
   518  			}
   519  
   520  			i++
   521  			if i == len(events) {
   522  				return
   523  			}
   524  
   525  		case err := <-t.sub.Err():
   526  			t.Fatalf("network stream closed unexpectedly: %s", err)
   527  
   528  		case <-timeout:
   529  			t.Fatal("timed out waiting for expected events")
   530  		}
   531  	}
   532  }
   533  
   534  // TestHTTPNodeRPC tests calling RPC methods on nodes via the HTTP API
   535  func TestHTTPNodeRPC(t *testing.T) {
   536  	// start the server
   537  	_, s := testHTTPServer(t)
   538  	defer s.Close()
   539  
   540  	// start a node in the network
   541  	client := NewClient(s.URL)
   542  
   543  	config := adapters.RandomNodeConfig()
   544  	node, err := client.CreateNode(config)
   545  	if err != nil {
   546  		t.Fatalf("error creating node: %s", err)
   547  	}
   548  	if err := client.StartNode(node.ID); err != nil {
   549  		t.Fatalf("error starting node: %s", err)
   550  	}
   551  
   552  	// create two RPC clients
   553  	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
   554  	defer cancel()
   555  	rpcClient1, err := client.RPCClient(ctx, node.ID)
   556  	if err != nil {
   557  		t.Fatalf("error getting node RPC client: %s", err)
   558  	}
   559  	rpcClient2, err := client.RPCClient(ctx, node.ID)
   560  	if err != nil {
   561  		t.Fatalf("error getting node RPC client: %s", err)
   562  	}
   563  
   564  	// subscribe to events using client 1
   565  	events := make(chan int64, 1)
   566  	sub, err := rpcClient1.Subscribe(ctx, "test", events, "events")
   567  	if err != nil {
   568  		t.Fatalf("error subscribing to events: %s", err)
   569  	}
   570  	defer sub.Unsubscribe()
   571  
   572  	// call some RPC methods using client 2
   573  	if err := rpcClient2.CallContext(ctx, nil, "test_add", 10); err != nil {
   574  		t.Fatalf("error calling RPC method: %s", err)
   575  	}
   576  	var result int64
   577  	if err := rpcClient2.CallContext(ctx, &result, "test_get"); err != nil {
   578  		t.Fatalf("error calling RPC method: %s", err)
   579  	}
   580  	if result != 10 {
   581  		t.Fatalf("expected result to be 10, got %d", result)
   582  	}
   583  
   584  	// check we got an event from client 1
   585  	select {
   586  	case event := <-events:
   587  		if event != 10 {
   588  			t.Fatalf("expected event to be 10, got %d", event)
   589  		}
   590  	case <-ctx.Done():
   591  		t.Fatal(ctx.Err())
   592  	}
   593  }
   594  
   595  // TestHTTPSnapshot tests creating and loading network snapshots
   596  func TestHTTPSnapshot(t *testing.T) {
   597  	// start the server
   598  	network, s := testHTTPServer(t)
   599  	defer s.Close()
   600  
   601  	var eventsDone = make(chan struct{})
   602  	count := 1
   603  	eventsDoneChan := make(chan *Event)
   604  	eventSub := network.Events().Subscribe(eventsDoneChan)
   605  	go func() {
   606  		defer eventSub.Unsubscribe()
   607  		for event := range eventsDoneChan {
   608  			if event.Type == EventTypeConn && !event.Control {
   609  				count--
   610  				if count == 0 {
   611  					eventsDone <- struct{}{}
   612  					return
   613  				}
   614  			}
   615  		}
   616  	}()
   617  
   618  	// create a two-node network
   619  	client := NewClient(s.URL)
   620  	nodeCount := 2
   621  	nodes := make([]*p2p.NodeInfo, nodeCount)
   622  	for i := 0; i < nodeCount; i++ {
   623  		config := adapters.RandomNodeConfig()
   624  		node, err := client.CreateNode(config)
   625  		if err != nil {
   626  			t.Fatalf("error creating node: %s", err)
   627  		}
   628  		if err := client.StartNode(node.ID); err != nil {
   629  			t.Fatalf("error starting node: %s", err)
   630  		}
   631  		nodes[i] = node
   632  	}
   633  	if err := client.ConnectNode(nodes[0].ID, nodes[1].ID); err != nil {
   634  		t.Fatalf("error connecting nodes: %s", err)
   635  	}
   636  
   637  	// store some state in the test services
   638  	states := make([]string, nodeCount)
   639  	for i, node := range nodes {
   640  		rpc, err := client.RPCClient(context.Background(), node.ID)
   641  		if err != nil {
   642  			t.Fatalf("error getting RPC client: %s", err)
   643  		}
   644  		defer rpc.Close()
   645  		state := fmt.Sprintf("%x", rand.Int())
   646  		if err := rpc.Call(nil, "test_setState", []byte(state)); err != nil {
   647  			t.Fatalf("error setting service state: %s", err)
   648  		}
   649  		states[i] = state
   650  	}
   651  	<-eventsDone
   652  	// create a snapshot
   653  	snap, err := client.CreateSnapshot()
   654  	if err != nil {
   655  		t.Fatalf("error creating snapshot: %s", err)
   656  	}
   657  	for i, state := range states {
   658  		gotState := snap.Nodes[i].Snapshots["test"]
   659  		if string(gotState) != state {
   660  			t.Fatalf("expected snapshot state %q, got %q", state, gotState)
   661  		}
   662  	}
   663  
   664  	// create another network
   665  	network2, s := testHTTPServer(t)
   666  	defer s.Close()
   667  	client = NewClient(s.URL)
   668  	count = 1
   669  	eventSub = network2.Events().Subscribe(eventsDoneChan)
   670  	go func() {
   671  		defer eventSub.Unsubscribe()
   672  		for event := range eventsDoneChan {
   673  			if event.Type == EventTypeConn && !event.Control {
   674  				count--
   675  				if count == 0 {
   676  					eventsDone <- struct{}{}
   677  					return
   678  				}
   679  			}
   680  		}
   681  	}()
   682  
   683  	// subscribe to events so we can check them later
   684  	events := make(chan *Event, 100)
   685  	var opts SubscribeOpts
   686  	sub, err := client.SubscribeNetwork(events, opts)
   687  	if err != nil {
   688  		t.Fatalf("error subscribing to network events: %s", err)
   689  	}
   690  	defer sub.Unsubscribe()
   691  
   692  	// load the snapshot
   693  	if err := client.LoadSnapshot(snap); err != nil {
   694  		t.Fatalf("error loading snapshot: %s", err)
   695  	}
   696  	<-eventsDone
   697  
   698  	// check the nodes and connection exists
   699  	net, err := client.GetNetwork()
   700  	if err != nil {
   701  		t.Fatalf("error getting network: %s", err)
   702  	}
   703  	if len(net.Nodes) != nodeCount {
   704  		t.Fatalf("expected network to have %d nodes, got %d", nodeCount, len(net.Nodes))
   705  	}
   706  	for i, node := range nodes {
   707  		id := net.Nodes[i].ID().String()
   708  		if id != node.ID {
   709  			t.Fatalf("expected node %d to have ID %s, got %s", i, node.ID, id)
   710  		}
   711  	}
   712  	if len(net.Conns) != 1 {
   713  		t.Fatalf("expected network to have 1 connection, got %d", len(net.Conns))
   714  	}
   715  	conn := net.Conns[0]
   716  	if conn.One.String() != nodes[0].ID {
   717  		t.Fatalf("expected connection to have one=%q, got one=%q", nodes[0].ID, conn.One)
   718  	}
   719  	if conn.Other.String() != nodes[1].ID {
   720  		t.Fatalf("expected connection to have other=%q, got other=%q", nodes[1].ID, conn.Other)
   721  	}
   722  	if !conn.Up {
   723  		t.Fatal("should be up")
   724  	}
   725  
   726  	// check the node states were restored
   727  	for i, node := range nodes {
   728  		rpc, err := client.RPCClient(context.Background(), node.ID)
   729  		if err != nil {
   730  			t.Fatalf("error getting RPC client: %s", err)
   731  		}
   732  		defer rpc.Close()
   733  		var state []byte
   734  		if err := rpc.Call(&state, "test_getState"); err != nil {
   735  			t.Fatalf("error getting service state: %s", err)
   736  		}
   737  		if string(state) != states[i] {
   738  			t.Fatalf("expected snapshot state %q, got %q", states[i], state)
   739  		}
   740  	}
   741  
   742  	// check we got all the events
   743  	x := &expectEvents{t, events, sub}
   744  	x.expect(
   745  		x.nodeEvent(nodes[0].ID, false),
   746  		x.nodeEvent(nodes[0].ID, true),
   747  		x.nodeEvent(nodes[1].ID, false),
   748  		x.nodeEvent(nodes[1].ID, true),
   749  		x.connEvent(nodes[0].ID, nodes[1].ID, false),
   750  		x.connEvent(nodes[0].ID, nodes[1].ID, true),
   751  	)
   752  }
   753  
   754  // TestMsgFilterPassMultiple tests streaming message events using a filter
   755  // with multiple protocols
   756  func TestMsgFilterPassMultiple(t *testing.T) {
   757  	// start the server
   758  	_, s := testHTTPServer(t)
   759  	defer s.Close()
   760  
   761  	// subscribe to events with a message filter
   762  	client := NewClient(s.URL)
   763  	events := make(chan *Event, 10)
   764  	opts := SubscribeOpts{
   765  		Filter: "prb:0-test:0",
   766  	}
   767  	sub, err := client.SubscribeNetwork(events, opts)
   768  	if err != nil {
   769  		t.Fatalf("error subscribing to network events: %s", err)
   770  	}
   771  	defer sub.Unsubscribe()
   772  
   773  	// start a simulation network
   774  	startTestNetwork(t, client)
   775  
   776  	// check we got the expected events
   777  	x := &expectEvents{t, events, sub}
   778  	x.expectMsgs(map[MsgFilter]int{
   779  		{"test", 0}: 2,
   780  		{"prb", 0}:  2,
   781  	})
   782  }
   783  
   784  // TestMsgFilterPassWildcard tests streaming message events using a filter
   785  // with a code wildcard
   786  func TestMsgFilterPassWildcard(t *testing.T) {
   787  	// start the server
   788  	_, s := testHTTPServer(t)
   789  	defer s.Close()
   790  
   791  	// subscribe to events with a message filter
   792  	client := NewClient(s.URL)
   793  	events := make(chan *Event, 10)
   794  	opts := SubscribeOpts{
   795  		Filter: "prb:0,2-test:*",
   796  	}
   797  	sub, err := client.SubscribeNetwork(events, opts)
   798  	if err != nil {
   799  		t.Fatalf("error subscribing to network events: %s", err)
   800  	}
   801  	defer sub.Unsubscribe()
   802  
   803  	// start a simulation network
   804  	startTestNetwork(t, client)
   805  
   806  	// check we got the expected events
   807  	x := &expectEvents{t, events, sub}
   808  	x.expectMsgs(map[MsgFilter]int{
   809  		{"test", 2}: 2,
   810  		{"test", 1}: 2,
   811  		{"test", 0}: 2,
   812  		{"prb", 0}:  2,
   813  	})
   814  }
   815  
   816  // TestMsgFilterPassSingle tests streaming message events using a filter
   817  // with a single protocol and code
   818  func TestMsgFilterPassSingle(t *testing.T) {
   819  	// start the server
   820  	_, s := testHTTPServer(t)
   821  	defer s.Close()
   822  
   823  	// subscribe to events with a message filter
   824  	client := NewClient(s.URL)
   825  	events := make(chan *Event, 10)
   826  	opts := SubscribeOpts{
   827  		Filter: "dum:0",
   828  	}
   829  	sub, err := client.SubscribeNetwork(events, opts)
   830  	if err != nil {
   831  		t.Fatalf("error subscribing to network events: %s", err)
   832  	}
   833  	defer sub.Unsubscribe()
   834  
   835  	// start a simulation network
   836  	startTestNetwork(t, client)
   837  
   838  	// check we got the expected events
   839  	x := &expectEvents{t, events, sub}
   840  	x.expectMsgs(map[MsgFilter]int{
   841  		{"dum", 0}: 2,
   842  	})
   843  }
   844  
   845  // TestMsgFilterPassSingle tests streaming message events using an invalid
   846  // filter
   847  func TestMsgFilterFailBadParams(t *testing.T) {
   848  	// start the server
   849  	_, s := testHTTPServer(t)
   850  	defer s.Close()
   851  
   852  	client := NewClient(s.URL)
   853  	events := make(chan *Event, 10)
   854  	opts := SubscribeOpts{
   855  		Filter: "foo:",
   856  	}
   857  	_, err := client.SubscribeNetwork(events, opts)
   858  	if err == nil {
   859  		t.Fatalf("expected event subscription to fail but succeeded!")
   860  	}
   861  
   862  	opts.Filter = "bzz:aa"
   863  	_, err = client.SubscribeNetwork(events, opts)
   864  	if err == nil {
   865  		t.Fatalf("expected event subscription to fail but succeeded!")
   866  	}
   867  
   868  	opts.Filter = "invalid"
   869  	_, err = client.SubscribeNetwork(events, opts)
   870  	if err == nil {
   871  		t.Fatalf("expected event subscription to fail but succeeded!")
   872  	}
   873  }