github.com/klaytn/klaytn@v1.12.1/networks/p2p/simulations/http_test.go (about)

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