github.com/xfond/eth-implementation@v1.8.9-0.20180514135602-f6bc65fc6811/cmd/p2psim/main.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of go-ethereum.
     3  //
     4  // go-ethereum is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU 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  // go-ethereum 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 General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU General Public License
    15  // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // p2psim provides a command-line client for a simulation HTTP API.
    18  //
    19  // Here is an example of creating a 2 node network with the first node
    20  // connected to the second:
    21  //
    22  //     $ p2psim node create
    23  //     Created node01
    24  //
    25  //     $ p2psim node start node01
    26  //     Started node01
    27  //
    28  //     $ p2psim node create
    29  //     Created node02
    30  //
    31  //     $ p2psim node start node02
    32  //     Started node02
    33  //
    34  //     $ p2psim node connect node01 node02
    35  //     Connected node01 to node02
    36  //
    37  package main
    38  
    39  import (
    40  	"context"
    41  	"encoding/json"
    42  	"fmt"
    43  	"io"
    44  	"os"
    45  	"strings"
    46  	"text/tabwriter"
    47  
    48  	"github.com/ethereum/go-ethereum/crypto"
    49  	"github.com/ethereum/go-ethereum/p2p"
    50  	"github.com/ethereum/go-ethereum/p2p/discover"
    51  	"github.com/ethereum/go-ethereum/p2p/simulations"
    52  	"github.com/ethereum/go-ethereum/p2p/simulations/adapters"
    53  	"github.com/ethereum/go-ethereum/rpc"
    54  	"gopkg.in/urfave/cli.v1"
    55  )
    56  
    57  var client *simulations.Client
    58  
    59  func main() {
    60  	app := cli.NewApp()
    61  	app.Usage = "devp2p simulation command-line client"
    62  	app.Flags = []cli.Flag{
    63  		cli.StringFlag{
    64  			Name:   "api",
    65  			Value:  "http://localhost:8888",
    66  			Usage:  "simulation API URL",
    67  			EnvVar: "P2PSIM_API_URL",
    68  		},
    69  	}
    70  	app.Before = func(ctx *cli.Context) error {
    71  		client = simulations.NewClient(ctx.GlobalString("api"))
    72  		return nil
    73  	}
    74  	app.Commands = []cli.Command{
    75  		{
    76  			Name:   "show",
    77  			Usage:  "show network information",
    78  			Action: showNetwork,
    79  		},
    80  		{
    81  			Name:   "events",
    82  			Usage:  "stream network events",
    83  			Action: streamNetwork,
    84  			Flags: []cli.Flag{
    85  				cli.BoolFlag{
    86  					Name:  "current",
    87  					Usage: "get existing nodes and conns first",
    88  				},
    89  				cli.StringFlag{
    90  					Name:  "filter",
    91  					Value: "",
    92  					Usage: "message filter",
    93  				},
    94  			},
    95  		},
    96  		{
    97  			Name:   "snapshot",
    98  			Usage:  "create a network snapshot to stdout",
    99  			Action: createSnapshot,
   100  		},
   101  		{
   102  			Name:   "load",
   103  			Usage:  "load a network snapshot from stdin",
   104  			Action: loadSnapshot,
   105  		},
   106  		{
   107  			Name:   "node",
   108  			Usage:  "manage simulation nodes",
   109  			Action: listNodes,
   110  			Subcommands: []cli.Command{
   111  				{
   112  					Name:   "list",
   113  					Usage:  "list nodes",
   114  					Action: listNodes,
   115  				},
   116  				{
   117  					Name:   "create",
   118  					Usage:  "create a node",
   119  					Action: createNode,
   120  					Flags: []cli.Flag{
   121  						cli.StringFlag{
   122  							Name:  "name",
   123  							Value: "",
   124  							Usage: "node name",
   125  						},
   126  						cli.StringFlag{
   127  							Name:  "services",
   128  							Value: "",
   129  							Usage: "node services (comma separated)",
   130  						},
   131  						cli.StringFlag{
   132  							Name:  "key",
   133  							Value: "",
   134  							Usage: "node private key (hex encoded)",
   135  						},
   136  					},
   137  				},
   138  				{
   139  					Name:      "show",
   140  					ArgsUsage: "<node>",
   141  					Usage:     "show node information",
   142  					Action:    showNode,
   143  				},
   144  				{
   145  					Name:      "start",
   146  					ArgsUsage: "<node>",
   147  					Usage:     "start a node",
   148  					Action:    startNode,
   149  				},
   150  				{
   151  					Name:      "stop",
   152  					ArgsUsage: "<node>",
   153  					Usage:     "stop a node",
   154  					Action:    stopNode,
   155  				},
   156  				{
   157  					Name:      "connect",
   158  					ArgsUsage: "<node> <peer>",
   159  					Usage:     "connect a node to a peer node",
   160  					Action:    connectNode,
   161  				},
   162  				{
   163  					Name:      "disconnect",
   164  					ArgsUsage: "<node> <peer>",
   165  					Usage:     "disconnect a node from a peer node",
   166  					Action:    disconnectNode,
   167  				},
   168  				{
   169  					Name:      "rpc",
   170  					ArgsUsage: "<node> <method> [<args>]",
   171  					Usage:     "call a node RPC method",
   172  					Action:    rpcNode,
   173  					Flags: []cli.Flag{
   174  						cli.BoolFlag{
   175  							Name:  "subscribe",
   176  							Usage: "method is a subscription",
   177  						},
   178  					},
   179  				},
   180  			},
   181  		},
   182  	}
   183  	app.Run(os.Args)
   184  }
   185  
   186  func showNetwork(ctx *cli.Context) error {
   187  	if len(ctx.Args()) != 0 {
   188  		return cli.ShowCommandHelp(ctx, ctx.Command.Name)
   189  	}
   190  	network, err := client.GetNetwork()
   191  	if err != nil {
   192  		return err
   193  	}
   194  	w := tabwriter.NewWriter(ctx.App.Writer, 1, 2, 2, ' ', 0)
   195  	defer w.Flush()
   196  	fmt.Fprintf(w, "NODES\t%d\n", len(network.Nodes))
   197  	fmt.Fprintf(w, "CONNS\t%d\n", len(network.Conns))
   198  	return nil
   199  }
   200  
   201  func streamNetwork(ctx *cli.Context) error {
   202  	if len(ctx.Args()) != 0 {
   203  		return cli.ShowCommandHelp(ctx, ctx.Command.Name)
   204  	}
   205  	events := make(chan *simulations.Event)
   206  	sub, err := client.SubscribeNetwork(events, simulations.SubscribeOpts{
   207  		Current: ctx.Bool("current"),
   208  		Filter:  ctx.String("filter"),
   209  	})
   210  	if err != nil {
   211  		return err
   212  	}
   213  	defer sub.Unsubscribe()
   214  	enc := json.NewEncoder(ctx.App.Writer)
   215  	for {
   216  		select {
   217  		case event := <-events:
   218  			if err := enc.Encode(event); err != nil {
   219  				return err
   220  			}
   221  		case err := <-sub.Err():
   222  			return err
   223  		}
   224  	}
   225  }
   226  
   227  func createSnapshot(ctx *cli.Context) error {
   228  	if len(ctx.Args()) != 0 {
   229  		return cli.ShowCommandHelp(ctx, ctx.Command.Name)
   230  	}
   231  	snap, err := client.CreateSnapshot()
   232  	if err != nil {
   233  		return err
   234  	}
   235  	return json.NewEncoder(os.Stdout).Encode(snap)
   236  }
   237  
   238  func loadSnapshot(ctx *cli.Context) error {
   239  	if len(ctx.Args()) != 0 {
   240  		return cli.ShowCommandHelp(ctx, ctx.Command.Name)
   241  	}
   242  	snap := &simulations.Snapshot{}
   243  	if err := json.NewDecoder(os.Stdin).Decode(snap); err != nil {
   244  		return err
   245  	}
   246  	return client.LoadSnapshot(snap)
   247  }
   248  
   249  func listNodes(ctx *cli.Context) error {
   250  	if len(ctx.Args()) != 0 {
   251  		return cli.ShowCommandHelp(ctx, ctx.Command.Name)
   252  	}
   253  	nodes, err := client.GetNodes()
   254  	if err != nil {
   255  		return err
   256  	}
   257  	w := tabwriter.NewWriter(ctx.App.Writer, 1, 2, 2, ' ', 0)
   258  	defer w.Flush()
   259  	fmt.Fprintf(w, "NAME\tPROTOCOLS\tID\n")
   260  	for _, node := range nodes {
   261  		fmt.Fprintf(w, "%s\t%s\t%s\n", node.Name, strings.Join(protocolList(node), ","), node.ID)
   262  	}
   263  	return nil
   264  }
   265  
   266  func protocolList(node *p2p.NodeInfo) []string {
   267  	protos := make([]string, 0, len(node.Protocols))
   268  	for name := range node.Protocols {
   269  		protos = append(protos, name)
   270  	}
   271  	return protos
   272  }
   273  
   274  func createNode(ctx *cli.Context) error {
   275  	if len(ctx.Args()) != 0 {
   276  		return cli.ShowCommandHelp(ctx, ctx.Command.Name)
   277  	}
   278  	config := &adapters.NodeConfig{
   279  		Name: ctx.String("name"),
   280  	}
   281  	if key := ctx.String("key"); key != "" {
   282  		privKey, err := crypto.HexToECDSA(key)
   283  		if err != nil {
   284  			return err
   285  		}
   286  		config.ID = discover.PubkeyID(&privKey.PublicKey)
   287  		config.PrivateKey = privKey
   288  	}
   289  	if services := ctx.String("services"); services != "" {
   290  		config.Services = strings.Split(services, ",")
   291  	}
   292  	node, err := client.CreateNode(config)
   293  	if err != nil {
   294  		return err
   295  	}
   296  	fmt.Fprintln(ctx.App.Writer, "Created", node.Name)
   297  	return nil
   298  }
   299  
   300  func showNode(ctx *cli.Context) error {
   301  	args := ctx.Args()
   302  	if len(args) != 1 {
   303  		return cli.ShowCommandHelp(ctx, ctx.Command.Name)
   304  	}
   305  	nodeName := args[0]
   306  	node, err := client.GetNode(nodeName)
   307  	if err != nil {
   308  		return err
   309  	}
   310  	w := tabwriter.NewWriter(ctx.App.Writer, 1, 2, 2, ' ', 0)
   311  	defer w.Flush()
   312  	fmt.Fprintf(w, "NAME\t%s\n", node.Name)
   313  	fmt.Fprintf(w, "PROTOCOLS\t%s\n", strings.Join(protocolList(node), ","))
   314  	fmt.Fprintf(w, "ID\t%s\n", node.ID)
   315  	fmt.Fprintf(w, "ENODE\t%s\n", node.Enode)
   316  	for name, proto := range node.Protocols {
   317  		fmt.Fprintln(w)
   318  		fmt.Fprintf(w, "--- PROTOCOL INFO: %s\n", name)
   319  		fmt.Fprintf(w, "%v\n", proto)
   320  		fmt.Fprintf(w, "---\n")
   321  	}
   322  	return nil
   323  }
   324  
   325  func startNode(ctx *cli.Context) error {
   326  	args := ctx.Args()
   327  	if len(args) != 1 {
   328  		return cli.ShowCommandHelp(ctx, ctx.Command.Name)
   329  	}
   330  	nodeName := args[0]
   331  	if err := client.StartNode(nodeName); err != nil {
   332  		return err
   333  	}
   334  	fmt.Fprintln(ctx.App.Writer, "Started", nodeName)
   335  	return nil
   336  }
   337  
   338  func stopNode(ctx *cli.Context) error {
   339  	args := ctx.Args()
   340  	if len(args) != 1 {
   341  		return cli.ShowCommandHelp(ctx, ctx.Command.Name)
   342  	}
   343  	nodeName := args[0]
   344  	if err := client.StopNode(nodeName); err != nil {
   345  		return err
   346  	}
   347  	fmt.Fprintln(ctx.App.Writer, "Stopped", nodeName)
   348  	return nil
   349  }
   350  
   351  func connectNode(ctx *cli.Context) error {
   352  	args := ctx.Args()
   353  	if len(args) != 2 {
   354  		return cli.ShowCommandHelp(ctx, ctx.Command.Name)
   355  	}
   356  	nodeName := args[0]
   357  	peerName := args[1]
   358  	if err := client.ConnectNode(nodeName, peerName); err != nil {
   359  		return err
   360  	}
   361  	fmt.Fprintln(ctx.App.Writer, "Connected", nodeName, "to", peerName)
   362  	return nil
   363  }
   364  
   365  func disconnectNode(ctx *cli.Context) error {
   366  	args := ctx.Args()
   367  	if len(args) != 2 {
   368  		return cli.ShowCommandHelp(ctx, ctx.Command.Name)
   369  	}
   370  	nodeName := args[0]
   371  	peerName := args[1]
   372  	if err := client.DisconnectNode(nodeName, peerName); err != nil {
   373  		return err
   374  	}
   375  	fmt.Fprintln(ctx.App.Writer, "Disconnected", nodeName, "from", peerName)
   376  	return nil
   377  }
   378  
   379  func rpcNode(ctx *cli.Context) error {
   380  	args := ctx.Args()
   381  	if len(args) < 2 {
   382  		return cli.ShowCommandHelp(ctx, ctx.Command.Name)
   383  	}
   384  	nodeName := args[0]
   385  	method := args[1]
   386  	rpcClient, err := client.RPCClient(context.Background(), nodeName)
   387  	if err != nil {
   388  		return err
   389  	}
   390  	if ctx.Bool("subscribe") {
   391  		return rpcSubscribe(rpcClient, ctx.App.Writer, method, args[3:]...)
   392  	}
   393  	var result interface{}
   394  	params := make([]interface{}, len(args[3:]))
   395  	for i, v := range args[3:] {
   396  		params[i] = v
   397  	}
   398  	if err := rpcClient.Call(&result, method, params...); err != nil {
   399  		return err
   400  	}
   401  	return json.NewEncoder(ctx.App.Writer).Encode(result)
   402  }
   403  
   404  func rpcSubscribe(client *rpc.Client, out io.Writer, method string, args ...string) error {
   405  	parts := strings.SplitN(method, "_", 2)
   406  	namespace := parts[0]
   407  	method = parts[1]
   408  	ch := make(chan interface{})
   409  	subArgs := make([]interface{}, len(args)+1)
   410  	subArgs[0] = method
   411  	for i, v := range args {
   412  		subArgs[i+1] = v
   413  	}
   414  	sub, err := client.Subscribe(context.Background(), namespace, ch, subArgs...)
   415  	if err != nil {
   416  		return err
   417  	}
   418  	defer sub.Unsubscribe()
   419  	enc := json.NewEncoder(out)
   420  	for {
   421  		select {
   422  		case v := <-ch:
   423  			if err := enc.Encode(v); err != nil {
   424  				return err
   425  			}
   426  		case err := <-sub.Err():
   427  			return err
   428  		}
   429  	}
   430  }