github.com/jincm/wesharechain@v0.0.0-20210122032815-1537409ce26a/chain/swarm/network/simulation/node.go (about)

     1  // Copyright 2018 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 simulation
    18  
    19  import (
    20  	"encoding/json"
    21  	"errors"
    22  	"io/ioutil"
    23  	"math/rand"
    24  	"os"
    25  	"time"
    26  
    27  	"github.com/ethereum/go-ethereum/log"
    28  	"github.com/ethereum/go-ethereum/p2p/enode"
    29  	"github.com/ethereum/go-ethereum/p2p/simulations"
    30  	"github.com/ethereum/go-ethereum/p2p/simulations/adapters"
    31  )
    32  
    33  // NodeIDs returns NodeIDs for all nodes in the network.
    34  func (s *Simulation) NodeIDs() (ids []enode.ID) {
    35  	nodes := s.Net.GetNodes()
    36  	ids = make([]enode.ID, len(nodes))
    37  	for i, node := range nodes {
    38  		ids[i] = node.ID()
    39  	}
    40  	return ids
    41  }
    42  
    43  // UpNodeIDs returns NodeIDs for nodes that are up in the network.
    44  func (s *Simulation) UpNodeIDs() (ids []enode.ID) {
    45  	nodes := s.Net.GetNodes()
    46  	for _, node := range nodes {
    47  		if node.Up() {
    48  			ids = append(ids, node.ID())
    49  		}
    50  	}
    51  	return ids
    52  }
    53  
    54  // DownNodeIDs returns NodeIDs for nodes that are stopped in the network.
    55  func (s *Simulation) DownNodeIDs() (ids []enode.ID) {
    56  	nodes := s.Net.GetNodes()
    57  	for _, node := range nodes {
    58  		if !node.Up() {
    59  			ids = append(ids, node.ID())
    60  		}
    61  	}
    62  	return ids
    63  }
    64  
    65  // AddNodeOption defines the option that can be passed
    66  // to Simulation.AddNode method.
    67  type AddNodeOption func(*adapters.NodeConfig)
    68  
    69  // AddNodeWithMsgEvents sets the EnableMsgEvents option
    70  // to NodeConfig.
    71  func AddNodeWithMsgEvents(enable bool) AddNodeOption {
    72  	return func(o *adapters.NodeConfig) {
    73  		o.EnableMsgEvents = enable
    74  	}
    75  }
    76  
    77  // AddNodeWithService specifies a service that should be
    78  // started on a node. This option can be repeated as variadic
    79  // argument toe AddNode and other add node related methods.
    80  // If AddNodeWithService is not specified, all services will be started.
    81  func AddNodeWithService(serviceName string) AddNodeOption {
    82  	return func(o *adapters.NodeConfig) {
    83  		o.Services = append(o.Services, serviceName)
    84  	}
    85  }
    86  
    87  // AddNode creates a new node with random configuration,
    88  // applies provided options to the config and adds the node to network.
    89  // By default all services will be started on a node. If one or more
    90  // AddNodeWithService option are provided, only specified services will be started.
    91  func (s *Simulation) AddNode(opts ...AddNodeOption) (id enode.ID, err error) {
    92  	conf := adapters.RandomNodeConfig()
    93  	for _, o := range opts {
    94  		o(conf)
    95  	}
    96  	if len(conf.Services) == 0 {
    97  		conf.Services = s.serviceNames
    98  	}
    99  	node, err := s.Net.NewNodeWithConfig(conf)
   100  	if err != nil {
   101  		return id, err
   102  	}
   103  	return node.ID(), s.Net.Start(node.ID())
   104  }
   105  
   106  // AddNodes creates new nodes with random configurations,
   107  // applies provided options to the config and adds nodes to network.
   108  func (s *Simulation) AddNodes(count int, opts ...AddNodeOption) (ids []enode.ID, err error) {
   109  	ids = make([]enode.ID, 0, count)
   110  	for i := 0; i < count; i++ {
   111  		id, err := s.AddNode(opts...)
   112  		if err != nil {
   113  			return nil, err
   114  		}
   115  		ids = append(ids, id)
   116  	}
   117  	return ids, nil
   118  }
   119  
   120  // AddNodesAndConnectFull is a helpper method that combines
   121  // AddNodes and ConnectNodesFull. Only new nodes will be connected.
   122  func (s *Simulation) AddNodesAndConnectFull(count int, opts ...AddNodeOption) (ids []enode.ID, err error) {
   123  	if count < 2 {
   124  		return nil, errors.New("count of nodes must be at least 2")
   125  	}
   126  	ids, err = s.AddNodes(count, opts...)
   127  	if err != nil {
   128  		return nil, err
   129  	}
   130  	err = s.Net.ConnectNodesFull(ids)
   131  	if err != nil {
   132  		return nil, err
   133  	}
   134  	return ids, nil
   135  }
   136  
   137  // AddNodesAndConnectChain is a helpper method that combines
   138  // AddNodes and ConnectNodesChain. The chain will be continued from the last
   139  // added node, if there is one in simulation using ConnectToLastNode method.
   140  func (s *Simulation) AddNodesAndConnectChain(count int, opts ...AddNodeOption) (ids []enode.ID, err error) {
   141  	if count < 2 {
   142  		return nil, errors.New("count of nodes must be at least 2")
   143  	}
   144  	id, err := s.AddNode(opts...)
   145  	if err != nil {
   146  		return nil, err
   147  	}
   148  	err = s.Net.ConnectToLastNode(id)
   149  	if err != nil {
   150  		return nil, err
   151  	}
   152  	ids, err = s.AddNodes(count-1, opts...)
   153  	if err != nil {
   154  		return nil, err
   155  	}
   156  	ids = append([]enode.ID{id}, ids...)
   157  	err = s.Net.ConnectNodesChain(ids)
   158  	if err != nil {
   159  		return nil, err
   160  	}
   161  	return ids, nil
   162  }
   163  
   164  // AddNodesAndConnectRing is a helpper method that combines
   165  // AddNodes and ConnectNodesRing.
   166  func (s *Simulation) AddNodesAndConnectRing(count int, opts ...AddNodeOption) (ids []enode.ID, err error) {
   167  	if count < 2 {
   168  		return nil, errors.New("count of nodes must be at least 2")
   169  	}
   170  	ids, err = s.AddNodes(count, opts...)
   171  	if err != nil {
   172  		return nil, err
   173  	}
   174  	err = s.Net.ConnectNodesRing(ids)
   175  	if err != nil {
   176  		return nil, err
   177  	}
   178  	return ids, nil
   179  }
   180  
   181  // AddNodesAndConnectStar is a helpper method that combines
   182  // AddNodes and ConnectNodesStar.
   183  func (s *Simulation) AddNodesAndConnectStar(count int, opts ...AddNodeOption) (ids []enode.ID, err error) {
   184  	if count < 2 {
   185  		return nil, errors.New("count of nodes must be at least 2")
   186  	}
   187  	ids, err = s.AddNodes(count, opts...)
   188  	if err != nil {
   189  		return nil, err
   190  	}
   191  	err = s.Net.ConnectNodesStar(ids[1:], ids[0])
   192  	if err != nil {
   193  		return nil, err
   194  	}
   195  	return ids, nil
   196  }
   197  
   198  // UploadSnapshot uploads a snapshot to the simulation
   199  // This method tries to open the json file provided, applies the config to all nodes
   200  // and then loads the snapshot into the Simulation network
   201  func (s *Simulation) UploadSnapshot(snapshotFile string, opts ...AddNodeOption) error {
   202  	f, err := os.Open(snapshotFile)
   203  	if err != nil {
   204  		return err
   205  	}
   206  	defer func() {
   207  		err := f.Close()
   208  		if err != nil {
   209  			log.Error("Error closing snapshot file", "err", err)
   210  		}
   211  	}()
   212  	jsonbyte, err := ioutil.ReadAll(f)
   213  	if err != nil {
   214  		return err
   215  	}
   216  	var snap simulations.Snapshot
   217  	err = json.Unmarshal(jsonbyte, &snap)
   218  	if err != nil {
   219  		return err
   220  	}
   221  
   222  	//the snapshot probably has the property EnableMsgEvents not set
   223  	//just in case, set it to true!
   224  	//(we need this to wait for messages before uploading)
   225  	for i := range snap.Nodes {
   226  		snap.Nodes[i].Node.Config.EnableMsgEvents = true
   227  		snap.Nodes[i].Node.Config.Services = s.serviceNames
   228  		for _, o := range opts {
   229  			o(snap.Nodes[i].Node.Config)
   230  		}
   231  	}
   232  
   233  	log.Info("Waiting for p2p connections to be established...")
   234  
   235  	//now we can load the snapshot
   236  	err = s.Net.Load(&snap)
   237  	if err != nil {
   238  		return err
   239  	}
   240  	log.Info("Snapshot loaded")
   241  	return nil
   242  }
   243  
   244  // StartNode starts a node by NodeID.
   245  func (s *Simulation) StartNode(id enode.ID) (err error) {
   246  	return s.Net.Start(id)
   247  }
   248  
   249  // StartRandomNode starts a random node.
   250  func (s *Simulation) StartRandomNode() (id enode.ID, err error) {
   251  	n := s.Net.GetRandomDownNode()
   252  	if n == nil {
   253  		return id, ErrNodeNotFound
   254  	}
   255  	return n.ID(), s.Net.Start(n.ID())
   256  }
   257  
   258  // StartRandomNodes starts random nodes.
   259  func (s *Simulation) StartRandomNodes(count int) (ids []enode.ID, err error) {
   260  	ids = make([]enode.ID, 0, count)
   261  	for i := 0; i < count; i++ {
   262  		n := s.Net.GetRandomDownNode()
   263  		if n == nil {
   264  			return nil, ErrNodeNotFound
   265  		}
   266  		err = s.Net.Start(n.ID())
   267  		if err != nil {
   268  			return nil, err
   269  		}
   270  		ids = append(ids, n.ID())
   271  	}
   272  	return ids, nil
   273  }
   274  
   275  // StopNode stops a node by NodeID.
   276  func (s *Simulation) StopNode(id enode.ID) (err error) {
   277  	return s.Net.Stop(id)
   278  }
   279  
   280  // StopRandomNode stops a random node.
   281  func (s *Simulation) StopRandomNode() (id enode.ID, err error) {
   282  	n := s.Net.GetRandomUpNode()
   283  	if n == nil {
   284  		return id, ErrNodeNotFound
   285  	}
   286  	return n.ID(), s.Net.Stop(n.ID())
   287  }
   288  
   289  // StopRandomNodes stops random nodes.
   290  func (s *Simulation) StopRandomNodes(count int) (ids []enode.ID, err error) {
   291  	ids = make([]enode.ID, 0, count)
   292  	for i := 0; i < count; i++ {
   293  		n := s.Net.GetRandomUpNode()
   294  		if n == nil {
   295  			return nil, ErrNodeNotFound
   296  		}
   297  		err = s.Net.Stop(n.ID())
   298  		if err != nil {
   299  			return nil, err
   300  		}
   301  		ids = append(ids, n.ID())
   302  	}
   303  	return ids, nil
   304  }
   305  
   306  // seed the random generator for Simulation.randomNode.
   307  func init() {
   308  	rand.Seed(time.Now().UnixNano())
   309  }