github.com/Unheilbar/quorum@v1.0.0/p2p/simulations/network.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  	"bytes"
    21  	"context"
    22  	"encoding/json"
    23  	"errors"
    24  	"fmt"
    25  	"io"
    26  	"math/rand"
    27  	"sync"
    28  	"time"
    29  
    30  	"github.com/ethereum/go-ethereum/event"
    31  	"github.com/ethereum/go-ethereum/log"
    32  	"github.com/ethereum/go-ethereum/p2p"
    33  	"github.com/ethereum/go-ethereum/p2p/enode"
    34  	"github.com/ethereum/go-ethereum/p2p/simulations/adapters"
    35  )
    36  
    37  var DialBanTimeout = 200 * time.Millisecond
    38  
    39  // NetworkConfig defines configuration options for starting a Network
    40  type NetworkConfig struct {
    41  	ID             string `json:"id"`
    42  	DefaultService string `json:"default_service,omitempty"`
    43  }
    44  
    45  // Network models a p2p simulation network which consists of a collection of
    46  // simulated nodes and the connections which exist between them.
    47  //
    48  // The Network has a single NodeAdapter which is responsible for actually
    49  // starting nodes and connecting them together.
    50  //
    51  // The Network emits events when nodes are started and stopped, when they are
    52  // connected and disconnected, and also when messages are sent between nodes.
    53  type Network struct {
    54  	NetworkConfig
    55  
    56  	Nodes   []*Node `json:"nodes"`
    57  	nodeMap map[enode.ID]int
    58  
    59  	// Maps a node property string to node indexes of all nodes that hold this property
    60  	propertyMap map[string][]int
    61  
    62  	Conns   []*Conn `json:"conns"`
    63  	connMap map[string]int
    64  
    65  	nodeAdapter adapters.NodeAdapter
    66  	events      event.Feed
    67  	lock        sync.RWMutex
    68  	quitc       chan struct{}
    69  }
    70  
    71  // NewNetwork returns a Network which uses the given NodeAdapter and NetworkConfig
    72  func NewNetwork(nodeAdapter adapters.NodeAdapter, conf *NetworkConfig) *Network {
    73  	return &Network{
    74  		NetworkConfig: *conf,
    75  		nodeAdapter:   nodeAdapter,
    76  		nodeMap:       make(map[enode.ID]int),
    77  		propertyMap:   make(map[string][]int),
    78  		connMap:       make(map[string]int),
    79  		quitc:         make(chan struct{}),
    80  	}
    81  }
    82  
    83  // Events returns the output event feed of the Network.
    84  func (net *Network) Events() *event.Feed {
    85  	return &net.events
    86  }
    87  
    88  // NewNodeWithConfig adds a new node to the network with the given config,
    89  // returning an error if a node with the same ID or name already exists
    90  func (net *Network) NewNodeWithConfig(conf *adapters.NodeConfig) (*Node, error) {
    91  	net.lock.Lock()
    92  	defer net.lock.Unlock()
    93  
    94  	if conf.Reachable == nil {
    95  		conf.Reachable = func(otherID enode.ID) bool {
    96  			_, err := net.InitConn(conf.ID, otherID)
    97  			if err != nil && bytes.Compare(conf.ID.Bytes(), otherID.Bytes()) < 0 {
    98  				return false
    99  			}
   100  			return true
   101  		}
   102  	}
   103  
   104  	// check the node doesn't already exist
   105  	if node := net.getNode(conf.ID); node != nil {
   106  		return nil, fmt.Errorf("node with ID %q already exists", conf.ID)
   107  	}
   108  	if node := net.getNodeByName(conf.Name); node != nil {
   109  		return nil, fmt.Errorf("node with name %q already exists", conf.Name)
   110  	}
   111  
   112  	// if no services are configured, use the default service
   113  	if len(conf.Lifecycles) == 0 {
   114  		conf.Lifecycles = []string{net.DefaultService}
   115  	}
   116  
   117  	// use the NodeAdapter to create the node
   118  	adapterNode, err := net.nodeAdapter.NewNode(conf)
   119  	if err != nil {
   120  		return nil, err
   121  	}
   122  	node := newNode(adapterNode, conf, false)
   123  	log.Trace("Node created", "id", conf.ID)
   124  
   125  	nodeIndex := len(net.Nodes)
   126  	net.nodeMap[conf.ID] = nodeIndex
   127  	net.Nodes = append(net.Nodes, node)
   128  
   129  	// Register any node properties with the network-level propertyMap
   130  	for _, property := range conf.Properties {
   131  		net.propertyMap[property] = append(net.propertyMap[property], nodeIndex)
   132  	}
   133  
   134  	// emit a "control" event
   135  	net.events.Send(ControlEvent(node))
   136  
   137  	return node, nil
   138  }
   139  
   140  // Config returns the network configuration
   141  func (net *Network) Config() *NetworkConfig {
   142  	return &net.NetworkConfig
   143  }
   144  
   145  // StartAll starts all nodes in the network
   146  func (net *Network) StartAll() error {
   147  	for _, node := range net.Nodes {
   148  		if node.Up() {
   149  			continue
   150  		}
   151  		if err := net.Start(node.ID()); err != nil {
   152  			return err
   153  		}
   154  	}
   155  	return nil
   156  }
   157  
   158  // StopAll stops all nodes in the network
   159  func (net *Network) StopAll() error {
   160  	for _, node := range net.Nodes {
   161  		if !node.Up() {
   162  			continue
   163  		}
   164  		if err := net.Stop(node.ID()); err != nil {
   165  			return err
   166  		}
   167  	}
   168  	return nil
   169  }
   170  
   171  // Start starts the node with the given ID
   172  func (net *Network) Start(id enode.ID) error {
   173  	return net.startWithSnapshots(id, nil)
   174  }
   175  
   176  // startWithSnapshots starts the node with the given ID using the give
   177  // snapshots
   178  func (net *Network) startWithSnapshots(id enode.ID, snapshots map[string][]byte) error {
   179  	net.lock.Lock()
   180  	defer net.lock.Unlock()
   181  
   182  	node := net.getNode(id)
   183  	if node == nil {
   184  		return fmt.Errorf("node %v does not exist", id)
   185  	}
   186  	if node.Up() {
   187  		return fmt.Errorf("node %v already up", id)
   188  	}
   189  	log.Trace("Starting node", "id", id, "adapter", net.nodeAdapter.Name())
   190  	if err := node.Start(snapshots); err != nil {
   191  		log.Warn("Node startup failed", "id", id, "err", err)
   192  		return err
   193  	}
   194  	node.SetUp(true)
   195  	log.Info("Started node", "id", id)
   196  	ev := NewEvent(node)
   197  	net.events.Send(ev)
   198  
   199  	// subscribe to peer events
   200  	client, err := node.Client()
   201  	if err != nil {
   202  		return fmt.Errorf("error getting rpc client  for node %v: %s", id, err)
   203  	}
   204  	events := make(chan *p2p.PeerEvent)
   205  	sub, err := client.Subscribe(context.Background(), "admin", events, "peerEvents")
   206  	if err != nil {
   207  		return fmt.Errorf("error getting peer events for node %v: %s", id, err)
   208  	}
   209  	go net.watchPeerEvents(id, events, sub)
   210  	return nil
   211  }
   212  
   213  // watchPeerEvents reads peer events from the given channel and emits
   214  // corresponding network events
   215  func (net *Network) watchPeerEvents(id enode.ID, events chan *p2p.PeerEvent, sub event.Subscription) {
   216  	defer func() {
   217  		sub.Unsubscribe()
   218  
   219  		// assume the node is now down
   220  		net.lock.Lock()
   221  		defer net.lock.Unlock()
   222  
   223  		node := net.getNode(id)
   224  		if node == nil {
   225  			return
   226  		}
   227  		node.SetUp(false)
   228  		ev := NewEvent(node)
   229  		net.events.Send(ev)
   230  	}()
   231  	for {
   232  		select {
   233  		case event, ok := <-events:
   234  			if !ok {
   235  				return
   236  			}
   237  			peer := event.Peer
   238  			switch event.Type {
   239  			case p2p.PeerEventTypeAdd:
   240  				net.DidConnect(id, peer)
   241  
   242  			case p2p.PeerEventTypeDrop:
   243  				net.DidDisconnect(id, peer)
   244  
   245  			case p2p.PeerEventTypeMsgSend:
   246  				net.DidSend(id, peer, event.Protocol, *event.MsgCode)
   247  
   248  			case p2p.PeerEventTypeMsgRecv:
   249  				net.DidReceive(peer, id, event.Protocol, *event.MsgCode)
   250  			}
   251  
   252  		case err := <-sub.Err():
   253  			if err != nil {
   254  				log.Error("Error in peer event subscription", "id", id, "err", err)
   255  			}
   256  			return
   257  		}
   258  	}
   259  }
   260  
   261  // Stop stops the node with the given ID
   262  func (net *Network) Stop(id enode.ID) error {
   263  	// IMPORTANT: node.Stop() must NOT be called under net.lock as
   264  	// node.Reachable() closure has a reference to the network and
   265  	// calls net.InitConn() what also locks the network. => DEADLOCK
   266  	// That holds until the following ticket is not resolved:
   267  
   268  	var err error
   269  
   270  	node, err := func() (*Node, error) {
   271  		net.lock.Lock()
   272  		defer net.lock.Unlock()
   273  
   274  		node := net.getNode(id)
   275  		if node == nil {
   276  			return nil, fmt.Errorf("node %v does not exist", id)
   277  		}
   278  		if !node.Up() {
   279  			return nil, fmt.Errorf("node %v already down", id)
   280  		}
   281  		node.SetUp(false)
   282  		return node, nil
   283  	}()
   284  	if err != nil {
   285  		return err
   286  	}
   287  
   288  	err = node.Stop() // must be called without net.lock
   289  
   290  	net.lock.Lock()
   291  	defer net.lock.Unlock()
   292  
   293  	if err != nil {
   294  		node.SetUp(true)
   295  		return err
   296  	}
   297  	log.Info("Stopped node", "id", id, "err", err)
   298  	ev := ControlEvent(node)
   299  	net.events.Send(ev)
   300  	return nil
   301  }
   302  
   303  // Connect connects two nodes together by calling the "admin_addPeer" RPC
   304  // method on the "one" node so that it connects to the "other" node
   305  func (net *Network) Connect(oneID, otherID enode.ID) error {
   306  	net.lock.Lock()
   307  	defer net.lock.Unlock()
   308  	return net.connect(oneID, otherID)
   309  }
   310  
   311  func (net *Network) connect(oneID, otherID enode.ID) error {
   312  	log.Debug("Connecting nodes with addPeer", "id", oneID, "other", otherID)
   313  	conn, err := net.initConn(oneID, otherID)
   314  	if err != nil {
   315  		return err
   316  	}
   317  	client, err := conn.one.Client()
   318  	if err != nil {
   319  		return err
   320  	}
   321  	net.events.Send(ControlEvent(conn))
   322  	return client.Call(nil, "admin_addPeer", string(conn.other.Addr()))
   323  }
   324  
   325  // Disconnect disconnects two nodes by calling the "admin_removePeer" RPC
   326  // method on the "one" node so that it disconnects from the "other" node
   327  func (net *Network) Disconnect(oneID, otherID enode.ID) error {
   328  	conn := net.GetConn(oneID, otherID)
   329  	if conn == nil {
   330  		return fmt.Errorf("connection between %v and %v does not exist", oneID, otherID)
   331  	}
   332  	if !conn.Up {
   333  		return fmt.Errorf("%v and %v already disconnected", oneID, otherID)
   334  	}
   335  	client, err := conn.one.Client()
   336  	if err != nil {
   337  		return err
   338  	}
   339  	net.events.Send(ControlEvent(conn))
   340  	return client.Call(nil, "admin_removePeer", string(conn.other.Addr()))
   341  }
   342  
   343  // DidConnect tracks the fact that the "one" node connected to the "other" node
   344  func (net *Network) DidConnect(one, other enode.ID) error {
   345  	net.lock.Lock()
   346  	defer net.lock.Unlock()
   347  	conn, err := net.getOrCreateConn(one, other)
   348  	if err != nil {
   349  		return fmt.Errorf("connection between %v and %v does not exist", one, other)
   350  	}
   351  	if conn.Up {
   352  		return fmt.Errorf("%v and %v already connected", one, other)
   353  	}
   354  	conn.Up = true
   355  	net.events.Send(NewEvent(conn))
   356  	return nil
   357  }
   358  
   359  // DidDisconnect tracks the fact that the "one" node disconnected from the
   360  // "other" node
   361  func (net *Network) DidDisconnect(one, other enode.ID) error {
   362  	net.lock.Lock()
   363  	defer net.lock.Unlock()
   364  	conn := net.getConn(one, other)
   365  	if conn == nil {
   366  		return fmt.Errorf("connection between %v and %v does not exist", one, other)
   367  	}
   368  	if !conn.Up {
   369  		return fmt.Errorf("%v and %v already disconnected", one, other)
   370  	}
   371  	conn.Up = false
   372  	conn.initiated = time.Now().Add(-DialBanTimeout)
   373  	net.events.Send(NewEvent(conn))
   374  	return nil
   375  }
   376  
   377  // DidSend tracks the fact that "sender" sent a message to "receiver"
   378  func (net *Network) DidSend(sender, receiver enode.ID, proto string, code uint64) error {
   379  	msg := &Msg{
   380  		One:      sender,
   381  		Other:    receiver,
   382  		Protocol: proto,
   383  		Code:     code,
   384  		Received: false,
   385  	}
   386  	net.events.Send(NewEvent(msg))
   387  	return nil
   388  }
   389  
   390  // DidReceive tracks the fact that "receiver" received a message from "sender"
   391  func (net *Network) DidReceive(sender, receiver enode.ID, proto string, code uint64) error {
   392  	msg := &Msg{
   393  		One:      sender,
   394  		Other:    receiver,
   395  		Protocol: proto,
   396  		Code:     code,
   397  		Received: true,
   398  	}
   399  	net.events.Send(NewEvent(msg))
   400  	return nil
   401  }
   402  
   403  // GetNode gets the node with the given ID, returning nil if the node does not
   404  // exist
   405  func (net *Network) GetNode(id enode.ID) *Node {
   406  	net.lock.RLock()
   407  	defer net.lock.RUnlock()
   408  	return net.getNode(id)
   409  }
   410  
   411  func (net *Network) getNode(id enode.ID) *Node {
   412  	i, found := net.nodeMap[id]
   413  	if !found {
   414  		return nil
   415  	}
   416  	return net.Nodes[i]
   417  }
   418  
   419  // GetNodeByName gets the node with the given name, returning nil if the node does
   420  // not exist
   421  func (net *Network) GetNodeByName(name string) *Node {
   422  	net.lock.RLock()
   423  	defer net.lock.RUnlock()
   424  	return net.getNodeByName(name)
   425  }
   426  
   427  func (net *Network) getNodeByName(name string) *Node {
   428  	for _, node := range net.Nodes {
   429  		if node.Config.Name == name {
   430  			return node
   431  		}
   432  	}
   433  	return nil
   434  }
   435  
   436  // GetNodeIDs returns the IDs of all existing nodes
   437  // Nodes can optionally be excluded by specifying their enode.ID.
   438  func (net *Network) GetNodeIDs(excludeIDs ...enode.ID) []enode.ID {
   439  	net.lock.RLock()
   440  	defer net.lock.RUnlock()
   441  
   442  	return net.getNodeIDs(excludeIDs)
   443  }
   444  
   445  func (net *Network) getNodeIDs(excludeIDs []enode.ID) []enode.ID {
   446  	// Get all current nodeIDs
   447  	nodeIDs := make([]enode.ID, 0, len(net.nodeMap))
   448  	for id := range net.nodeMap {
   449  		nodeIDs = append(nodeIDs, id)
   450  	}
   451  
   452  	if len(excludeIDs) > 0 {
   453  		// Return the difference of nodeIDs and excludeIDs
   454  		return filterIDs(nodeIDs, excludeIDs)
   455  	}
   456  	return nodeIDs
   457  }
   458  
   459  // GetNodes returns the existing nodes.
   460  // Nodes can optionally be excluded by specifying their enode.ID.
   461  func (net *Network) GetNodes(excludeIDs ...enode.ID) []*Node {
   462  	net.lock.RLock()
   463  	defer net.lock.RUnlock()
   464  
   465  	return net.getNodes(excludeIDs)
   466  }
   467  
   468  func (net *Network) getNodes(excludeIDs []enode.ID) []*Node {
   469  	if len(excludeIDs) > 0 {
   470  		nodeIDs := net.getNodeIDs(excludeIDs)
   471  		return net.getNodesByID(nodeIDs)
   472  	}
   473  	return net.Nodes
   474  }
   475  
   476  // GetNodesByID returns existing nodes with the given enode.IDs.
   477  // If a node doesn't exist with a given enode.ID, it is ignored.
   478  func (net *Network) GetNodesByID(nodeIDs []enode.ID) []*Node {
   479  	net.lock.RLock()
   480  	defer net.lock.RUnlock()
   481  
   482  	return net.getNodesByID(nodeIDs)
   483  }
   484  
   485  func (net *Network) getNodesByID(nodeIDs []enode.ID) []*Node {
   486  	nodes := make([]*Node, 0, len(nodeIDs))
   487  	for _, id := range nodeIDs {
   488  		node := net.getNode(id)
   489  		if node != nil {
   490  			nodes = append(nodes, node)
   491  		}
   492  	}
   493  
   494  	return nodes
   495  }
   496  
   497  // GetNodesByProperty returns existing nodes that have the given property string registered in their NodeConfig
   498  func (net *Network) GetNodesByProperty(property string) []*Node {
   499  	net.lock.RLock()
   500  	defer net.lock.RUnlock()
   501  
   502  	return net.getNodesByProperty(property)
   503  }
   504  
   505  func (net *Network) getNodesByProperty(property string) []*Node {
   506  	nodes := make([]*Node, 0, len(net.propertyMap[property]))
   507  	for _, nodeIndex := range net.propertyMap[property] {
   508  		nodes = append(nodes, net.Nodes[nodeIndex])
   509  	}
   510  
   511  	return nodes
   512  }
   513  
   514  // GetNodeIDsByProperty returns existing node's enode IDs that have the given property string registered in the NodeConfig
   515  func (net *Network) GetNodeIDsByProperty(property string) []enode.ID {
   516  	net.lock.RLock()
   517  	defer net.lock.RUnlock()
   518  
   519  	return net.getNodeIDsByProperty(property)
   520  }
   521  
   522  func (net *Network) getNodeIDsByProperty(property string) []enode.ID {
   523  	nodeIDs := make([]enode.ID, 0, len(net.propertyMap[property]))
   524  	for _, nodeIndex := range net.propertyMap[property] {
   525  		node := net.Nodes[nodeIndex]
   526  		nodeIDs = append(nodeIDs, node.ID())
   527  	}
   528  
   529  	return nodeIDs
   530  }
   531  
   532  // GetRandomUpNode returns a random node on the network, which is running.
   533  func (net *Network) GetRandomUpNode(excludeIDs ...enode.ID) *Node {
   534  	net.lock.RLock()
   535  	defer net.lock.RUnlock()
   536  	return net.getRandomUpNode(excludeIDs...)
   537  }
   538  
   539  // GetRandomUpNode returns a random node on the network, which is running.
   540  func (net *Network) getRandomUpNode(excludeIDs ...enode.ID) *Node {
   541  	return net.getRandomNode(net.getUpNodeIDs(), excludeIDs)
   542  }
   543  
   544  func (net *Network) getUpNodeIDs() (ids []enode.ID) {
   545  	for _, node := range net.Nodes {
   546  		if node.Up() {
   547  			ids = append(ids, node.ID())
   548  		}
   549  	}
   550  	return ids
   551  }
   552  
   553  // GetRandomDownNode returns a random node on the network, which is stopped.
   554  func (net *Network) GetRandomDownNode(excludeIDs ...enode.ID) *Node {
   555  	net.lock.RLock()
   556  	defer net.lock.RUnlock()
   557  	return net.getRandomNode(net.getDownNodeIDs(), excludeIDs)
   558  }
   559  
   560  func (net *Network) getDownNodeIDs() (ids []enode.ID) {
   561  	for _, node := range net.Nodes {
   562  		if !node.Up() {
   563  			ids = append(ids, node.ID())
   564  		}
   565  	}
   566  	return ids
   567  }
   568  
   569  // GetRandomNode returns a random node on the network, regardless of whether it is running or not
   570  func (net *Network) GetRandomNode(excludeIDs ...enode.ID) *Node {
   571  	net.lock.RLock()
   572  	defer net.lock.RUnlock()
   573  	return net.getRandomNode(net.getNodeIDs(nil), excludeIDs) // no need to exclude twice
   574  }
   575  
   576  func (net *Network) getRandomNode(ids []enode.ID, excludeIDs []enode.ID) *Node {
   577  	filtered := filterIDs(ids, excludeIDs)
   578  
   579  	l := len(filtered)
   580  	if l == 0 {
   581  		return nil
   582  	}
   583  	return net.getNode(filtered[rand.Intn(l)])
   584  }
   585  
   586  func filterIDs(ids []enode.ID, excludeIDs []enode.ID) []enode.ID {
   587  	exclude := make(map[enode.ID]bool)
   588  	for _, id := range excludeIDs {
   589  		exclude[id] = true
   590  	}
   591  	var filtered []enode.ID
   592  	for _, id := range ids {
   593  		if _, found := exclude[id]; !found {
   594  			filtered = append(filtered, id)
   595  		}
   596  	}
   597  	return filtered
   598  }
   599  
   600  // GetConn returns the connection which exists between "one" and "other"
   601  // regardless of which node initiated the connection
   602  func (net *Network) GetConn(oneID, otherID enode.ID) *Conn {
   603  	net.lock.RLock()
   604  	defer net.lock.RUnlock()
   605  	return net.getConn(oneID, otherID)
   606  }
   607  
   608  // GetOrCreateConn is like GetConn but creates the connection if it doesn't
   609  // already exist
   610  func (net *Network) GetOrCreateConn(oneID, otherID enode.ID) (*Conn, error) {
   611  	net.lock.Lock()
   612  	defer net.lock.Unlock()
   613  	return net.getOrCreateConn(oneID, otherID)
   614  }
   615  
   616  func (net *Network) getOrCreateConn(oneID, otherID enode.ID) (*Conn, error) {
   617  	if conn := net.getConn(oneID, otherID); conn != nil {
   618  		return conn, nil
   619  	}
   620  
   621  	one := net.getNode(oneID)
   622  	if one == nil {
   623  		return nil, fmt.Errorf("node %v does not exist", oneID)
   624  	}
   625  	other := net.getNode(otherID)
   626  	if other == nil {
   627  		return nil, fmt.Errorf("node %v does not exist", otherID)
   628  	}
   629  	conn := &Conn{
   630  		One:   oneID,
   631  		Other: otherID,
   632  		one:   one,
   633  		other: other,
   634  	}
   635  	label := ConnLabel(oneID, otherID)
   636  	net.connMap[label] = len(net.Conns)
   637  	net.Conns = append(net.Conns, conn)
   638  	return conn, nil
   639  }
   640  
   641  func (net *Network) getConn(oneID, otherID enode.ID) *Conn {
   642  	label := ConnLabel(oneID, otherID)
   643  	i, found := net.connMap[label]
   644  	if !found {
   645  		return nil
   646  	}
   647  	return net.Conns[i]
   648  }
   649  
   650  // InitConn(one, other) retrieves the connection model for the connection between
   651  // peers one and other, or creates a new one if it does not exist
   652  // the order of nodes does not matter, i.e., Conn(i,j) == Conn(j, i)
   653  // it checks if the connection is already up, and if the nodes are running
   654  // NOTE:
   655  // it also checks whether there has been recent attempt to connect the peers
   656  // this is cheating as the simulation is used as an oracle and know about
   657  // remote peers attempt to connect to a node which will then not initiate the connection
   658  func (net *Network) InitConn(oneID, otherID enode.ID) (*Conn, error) {
   659  	net.lock.Lock()
   660  	defer net.lock.Unlock()
   661  	return net.initConn(oneID, otherID)
   662  }
   663  
   664  func (net *Network) initConn(oneID, otherID enode.ID) (*Conn, error) {
   665  	if oneID == otherID {
   666  		return nil, fmt.Errorf("refusing to connect to self %v", oneID)
   667  	}
   668  	conn, err := net.getOrCreateConn(oneID, otherID)
   669  	if err != nil {
   670  		return nil, err
   671  	}
   672  	if conn.Up {
   673  		return nil, fmt.Errorf("%v and %v already connected", oneID, otherID)
   674  	}
   675  	if time.Since(conn.initiated) < DialBanTimeout {
   676  		return nil, fmt.Errorf("connection between %v and %v recently attempted", oneID, otherID)
   677  	}
   678  
   679  	err = conn.nodesUp()
   680  	if err != nil {
   681  		log.Trace("Nodes not up", "err", err)
   682  		return nil, fmt.Errorf("nodes not up: %v", err)
   683  	}
   684  	log.Debug("Connection initiated", "id", oneID, "other", otherID)
   685  	conn.initiated = time.Now()
   686  	return conn, nil
   687  }
   688  
   689  // Shutdown stops all nodes in the network and closes the quit channel
   690  func (net *Network) Shutdown() {
   691  	for _, node := range net.Nodes {
   692  		log.Debug("Stopping node", "id", node.ID())
   693  		if err := node.Stop(); err != nil {
   694  			log.Warn("Can't stop node", "id", node.ID(), "err", err)
   695  		}
   696  		// If the node has the close method, call it.
   697  		if closer, ok := node.Node.(io.Closer); ok {
   698  			if err := closer.Close(); err != nil {
   699  				log.Warn("Can't close node", "id", node.ID(), "err", err)
   700  			}
   701  		}
   702  	}
   703  	close(net.quitc)
   704  }
   705  
   706  // Reset resets all network properties:
   707  // empties the nodes and the connection list
   708  func (net *Network) Reset() {
   709  	net.lock.Lock()
   710  	defer net.lock.Unlock()
   711  
   712  	//re-initialize the maps
   713  	net.connMap = make(map[string]int)
   714  	net.nodeMap = make(map[enode.ID]int)
   715  	net.propertyMap = make(map[string][]int)
   716  
   717  	net.Nodes = nil
   718  	net.Conns = nil
   719  }
   720  
   721  // Node is a wrapper around adapters.Node which is used to track the status
   722  // of a node in the network
   723  type Node struct {
   724  	adapters.Node `json:"-"`
   725  
   726  	// Config if the config used to created the node
   727  	Config *adapters.NodeConfig `json:"config"`
   728  
   729  	// up tracks whether or not the node is running
   730  	up   bool
   731  	upMu *sync.RWMutex
   732  }
   733  
   734  func newNode(an adapters.Node, ac *adapters.NodeConfig, up bool) *Node {
   735  	return &Node{Node: an, Config: ac, up: up, upMu: new(sync.RWMutex)}
   736  }
   737  
   738  func (n *Node) copy() *Node {
   739  	configCpy := *n.Config
   740  	return newNode(n.Node, &configCpy, n.Up())
   741  }
   742  
   743  // Up returns whether the node is currently up (online)
   744  func (n *Node) Up() bool {
   745  	n.upMu.RLock()
   746  	defer n.upMu.RUnlock()
   747  	return n.up
   748  }
   749  
   750  // SetUp sets the up (online) status of the nodes with the given value
   751  func (n *Node) SetUp(up bool) {
   752  	n.upMu.Lock()
   753  	defer n.upMu.Unlock()
   754  	n.up = up
   755  }
   756  
   757  // ID returns the ID of the node
   758  func (n *Node) ID() enode.ID {
   759  	return n.Config.ID
   760  }
   761  
   762  // String returns a log-friendly string
   763  func (n *Node) String() string {
   764  	return fmt.Sprintf("Node %v", n.ID().TerminalString())
   765  }
   766  
   767  // NodeInfo returns information about the node
   768  func (n *Node) NodeInfo() *p2p.NodeInfo {
   769  	// avoid a panic if the node is not started yet
   770  	if n.Node == nil {
   771  		return nil
   772  	}
   773  	info := n.Node.NodeInfo()
   774  	info.Name = n.Config.Name
   775  	return info
   776  }
   777  
   778  // MarshalJSON implements the json.Marshaler interface so that the encoded
   779  // JSON includes the NodeInfo
   780  func (n *Node) MarshalJSON() ([]byte, error) {
   781  	return json.Marshal(struct {
   782  		Info   *p2p.NodeInfo        `json:"info,omitempty"`
   783  		Config *adapters.NodeConfig `json:"config,omitempty"`
   784  		Up     bool                 `json:"up"`
   785  	}{
   786  		Info:   n.NodeInfo(),
   787  		Config: n.Config,
   788  		Up:     n.Up(),
   789  	})
   790  }
   791  
   792  // UnmarshalJSON implements json.Unmarshaler interface so that we don't lose Node.up
   793  // status. IMPORTANT: The implementation is incomplete; we lose p2p.NodeInfo.
   794  func (n *Node) UnmarshalJSON(raw []byte) error {
   795  	// TODO: How should we turn back NodeInfo into n.Node?
   796  	// Ticket: https://github.com/ethersphere/go-ethereum/issues/1177
   797  	var node struct {
   798  		Config *adapters.NodeConfig `json:"config,omitempty"`
   799  		Up     bool                 `json:"up"`
   800  	}
   801  	if err := json.Unmarshal(raw, &node); err != nil {
   802  		return err
   803  	}
   804  	*n = *newNode(nil, node.Config, node.Up)
   805  	return nil
   806  }
   807  
   808  // Conn represents a connection between two nodes in the network
   809  type Conn struct {
   810  	// One is the node which initiated the connection
   811  	One enode.ID `json:"one"`
   812  
   813  	// Other is the node which the connection was made to
   814  	Other enode.ID `json:"other"`
   815  
   816  	// Up tracks whether or not the connection is active
   817  	Up bool `json:"up"`
   818  	// Registers when the connection was grabbed to dial
   819  	initiated time.Time
   820  
   821  	one   *Node
   822  	other *Node
   823  }
   824  
   825  // nodesUp returns whether both nodes are currently up
   826  func (c *Conn) nodesUp() error {
   827  	if !c.one.Up() {
   828  		return fmt.Errorf("one %v is not up", c.One)
   829  	}
   830  	if !c.other.Up() {
   831  		return fmt.Errorf("other %v is not up", c.Other)
   832  	}
   833  	return nil
   834  }
   835  
   836  // String returns a log-friendly string
   837  func (c *Conn) String() string {
   838  	return fmt.Sprintf("Conn %v->%v", c.One.TerminalString(), c.Other.TerminalString())
   839  }
   840  
   841  // Msg represents a p2p message sent between two nodes in the network
   842  type Msg struct {
   843  	One      enode.ID `json:"one"`
   844  	Other    enode.ID `json:"other"`
   845  	Protocol string   `json:"protocol"`
   846  	Code     uint64   `json:"code"`
   847  	Received bool     `json:"received"`
   848  }
   849  
   850  // String returns a log-friendly string
   851  func (m *Msg) String() string {
   852  	return fmt.Sprintf("Msg(%d) %v->%v", m.Code, m.One.TerminalString(), m.Other.TerminalString())
   853  }
   854  
   855  // ConnLabel generates a deterministic string which represents a connection
   856  // between two nodes, used to compare if two connections are between the same
   857  // nodes
   858  func ConnLabel(source, target enode.ID) string {
   859  	var first, second enode.ID
   860  	if bytes.Compare(source.Bytes(), target.Bytes()) > 0 {
   861  		first = target
   862  		second = source
   863  	} else {
   864  		first = source
   865  		second = target
   866  	}
   867  	return fmt.Sprintf("%v-%v", first, second)
   868  }
   869  
   870  // Snapshot represents the state of a network at a single point in time and can
   871  // be used to restore the state of a network
   872  type Snapshot struct {
   873  	Nodes []NodeSnapshot `json:"nodes,omitempty"`
   874  	Conns []Conn         `json:"conns,omitempty"`
   875  }
   876  
   877  // NodeSnapshot represents the state of a node in the network
   878  type NodeSnapshot struct {
   879  	Node Node `json:"node,omitempty"`
   880  
   881  	// Snapshots is arbitrary data gathered from calling node.Snapshots()
   882  	Snapshots map[string][]byte `json:"snapshots,omitempty"`
   883  }
   884  
   885  // Snapshot creates a network snapshot
   886  func (net *Network) Snapshot() (*Snapshot, error) {
   887  	return net.snapshot(nil, nil)
   888  }
   889  
   890  func (net *Network) SnapshotWithServices(addServices []string, removeServices []string) (*Snapshot, error) {
   891  	return net.snapshot(addServices, removeServices)
   892  }
   893  
   894  func (net *Network) snapshot(addServices []string, removeServices []string) (*Snapshot, error) {
   895  	net.lock.Lock()
   896  	defer net.lock.Unlock()
   897  	snap := &Snapshot{
   898  		Nodes: make([]NodeSnapshot, len(net.Nodes)),
   899  	}
   900  	for i, node := range net.Nodes {
   901  		snap.Nodes[i] = NodeSnapshot{Node: *node.copy()}
   902  		if !node.Up() {
   903  			continue
   904  		}
   905  		snapshots, err := node.Snapshots()
   906  		if err != nil {
   907  			return nil, err
   908  		}
   909  		snap.Nodes[i].Snapshots = snapshots
   910  		for _, addSvc := range addServices {
   911  			haveSvc := false
   912  			for _, svc := range snap.Nodes[i].Node.Config.Lifecycles {
   913  				if svc == addSvc {
   914  					haveSvc = true
   915  					break
   916  				}
   917  			}
   918  			if !haveSvc {
   919  				snap.Nodes[i].Node.Config.Lifecycles = append(snap.Nodes[i].Node.Config.Lifecycles, addSvc)
   920  			}
   921  		}
   922  		if len(removeServices) > 0 {
   923  			var cleanedServices []string
   924  			for _, svc := range snap.Nodes[i].Node.Config.Lifecycles {
   925  				haveSvc := false
   926  				for _, rmSvc := range removeServices {
   927  					if rmSvc == svc {
   928  						haveSvc = true
   929  						break
   930  					}
   931  				}
   932  				if !haveSvc {
   933  					cleanedServices = append(cleanedServices, svc)
   934  				}
   935  			}
   936  			snap.Nodes[i].Node.Config.Lifecycles = cleanedServices
   937  		}
   938  	}
   939  	for _, conn := range net.Conns {
   940  		if conn.Up {
   941  			snap.Conns = append(snap.Conns, *conn)
   942  		}
   943  	}
   944  	return snap, nil
   945  }
   946  
   947  // longrunning tests may need a longer timeout
   948  var snapshotLoadTimeout = 900 * time.Second
   949  
   950  // Load loads a network snapshot
   951  func (net *Network) Load(snap *Snapshot) error {
   952  	// Start nodes.
   953  	for _, n := range snap.Nodes {
   954  		if _, err := net.NewNodeWithConfig(n.Node.Config); err != nil {
   955  			return err
   956  		}
   957  		if !n.Node.Up() {
   958  			continue
   959  		}
   960  		if err := net.startWithSnapshots(n.Node.Config.ID, n.Snapshots); err != nil {
   961  			return err
   962  		}
   963  	}
   964  
   965  	// Prepare connection events counter.
   966  	allConnected := make(chan struct{}) // closed when all connections are established
   967  	done := make(chan struct{})         // ensures that the event loop goroutine is terminated
   968  	defer close(done)
   969  
   970  	// Subscribe to event channel.
   971  	// It needs to be done outside of the event loop goroutine (created below)
   972  	// to ensure that the event channel is blocking before connect calls are made.
   973  	events := make(chan *Event)
   974  	sub := net.Events().Subscribe(events)
   975  	defer sub.Unsubscribe()
   976  
   977  	go func() {
   978  		// Expected number of connections.
   979  		total := len(snap.Conns)
   980  		// Set of all established connections from the snapshot, not other connections.
   981  		// Key array element 0 is the connection One field value, and element 1 connection Other field.
   982  		connections := make(map[[2]enode.ID]struct{}, total)
   983  
   984  		for {
   985  			select {
   986  			case e := <-events:
   987  				// Ignore control events as they do not represent
   988  				// connect or disconnect (Up) state change.
   989  				if e.Control {
   990  					continue
   991  				}
   992  				// Detect only connection events.
   993  				if e.Type != EventTypeConn {
   994  					continue
   995  				}
   996  				connection := [2]enode.ID{e.Conn.One, e.Conn.Other}
   997  				// Nodes are still not connected or have been disconnected.
   998  				if !e.Conn.Up {
   999  					// Delete the connection from the set of established connections.
  1000  					// This will prevent false positive in case disconnections happen.
  1001  					delete(connections, connection)
  1002  					log.Warn("load snapshot: unexpected disconnection", "one", e.Conn.One, "other", e.Conn.Other)
  1003  					continue
  1004  				}
  1005  				// Check that the connection is from the snapshot.
  1006  				for _, conn := range snap.Conns {
  1007  					if conn.One == e.Conn.One && conn.Other == e.Conn.Other {
  1008  						// Add the connection to the set of established connections.
  1009  						connections[connection] = struct{}{}
  1010  						if len(connections) == total {
  1011  							// Signal that all nodes are connected.
  1012  							close(allConnected)
  1013  							return
  1014  						}
  1015  
  1016  						break
  1017  					}
  1018  				}
  1019  			case <-done:
  1020  				// Load function returned, terminate this goroutine.
  1021  				return
  1022  			}
  1023  		}
  1024  	}()
  1025  
  1026  	// Start connecting.
  1027  	for _, conn := range snap.Conns {
  1028  		if !net.GetNode(conn.One).Up() || !net.GetNode(conn.Other).Up() {
  1029  			//in this case, at least one of the nodes of a connection is not up,
  1030  			//so it would result in the snapshot `Load` to fail
  1031  			continue
  1032  		}
  1033  		if err := net.Connect(conn.One, conn.Other); err != nil {
  1034  			return err
  1035  		}
  1036  	}
  1037  
  1038  	select {
  1039  	// Wait until all connections from the snapshot are established.
  1040  	case <-allConnected:
  1041  	// Make sure that we do not wait forever.
  1042  	case <-time.After(snapshotLoadTimeout):
  1043  		return errors.New("snapshot connections not established")
  1044  	}
  1045  	return nil
  1046  }
  1047  
  1048  // Subscribe reads control events from a channel and executes them
  1049  func (net *Network) Subscribe(events chan *Event) {
  1050  	for {
  1051  		select {
  1052  		case event, ok := <-events:
  1053  			if !ok {
  1054  				return
  1055  			}
  1056  			if event.Control {
  1057  				net.executeControlEvent(event)
  1058  			}
  1059  		case <-net.quitc:
  1060  			return
  1061  		}
  1062  	}
  1063  }
  1064  
  1065  func (net *Network) executeControlEvent(event *Event) {
  1066  	log.Trace("Executing control event", "type", event.Type, "event", event)
  1067  	switch event.Type {
  1068  	case EventTypeNode:
  1069  		if err := net.executeNodeEvent(event); err != nil {
  1070  			log.Error("Error executing node event", "event", event, "err", err)
  1071  		}
  1072  	case EventTypeConn:
  1073  		if err := net.executeConnEvent(event); err != nil {
  1074  			log.Error("Error executing conn event", "event", event, "err", err)
  1075  		}
  1076  	case EventTypeMsg:
  1077  		log.Warn("Ignoring control msg event")
  1078  	}
  1079  }
  1080  
  1081  func (net *Network) executeNodeEvent(e *Event) error {
  1082  	if !e.Node.Up() {
  1083  		return net.Stop(e.Node.ID())
  1084  	}
  1085  
  1086  	if _, err := net.NewNodeWithConfig(e.Node.Config); err != nil {
  1087  		return err
  1088  	}
  1089  	return net.Start(e.Node.ID())
  1090  }
  1091  
  1092  func (net *Network) executeConnEvent(e *Event) error {
  1093  	if e.Conn.Up {
  1094  		return net.Connect(e.Conn.One, e.Conn.Other)
  1095  	}
  1096  	return net.Disconnect(e.Conn.One, e.Conn.Other)
  1097  }