github.com/palisadeinc/bor@v0.0.0-20230615125219-ab7196213d15/internal/cli/peers_list.go (about)

     1  package cli
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"github.com/ethereum/go-ethereum/internal/cli/flagset"
     9  	"github.com/ethereum/go-ethereum/internal/cli/server/proto"
    10  )
    11  
    12  // PeersListCommand is the command to group the peers commands
    13  type PeersListCommand struct {
    14  	*Meta2
    15  }
    16  
    17  // MarkDown implements cli.MarkDown interface
    18  func (p *PeersListCommand) MarkDown() string {
    19  	items := []string{
    20  		"# Peers add",
    21  		"The ```peers list``` command lists the connected peers.",
    22  		p.Flags().MarkDown(),
    23  	}
    24  
    25  	return strings.Join(items, "\n\n")
    26  }
    27  
    28  // Help implements the cli.Command interface
    29  func (p *PeersListCommand) Help() string {
    30  	return `Usage: bor peers list
    31  
    32    Lists the connected peers
    33  
    34    ` + p.Flags().Help()
    35  }
    36  
    37  func (p *PeersListCommand) Flags() *flagset.Flagset {
    38  	flags := p.NewFlagSet("peers list")
    39  
    40  	return flags
    41  }
    42  
    43  // Synopsis implements the cli.Command interface
    44  func (c *PeersListCommand) Synopsis() string {
    45  	return ""
    46  }
    47  
    48  // Run implements the cli.Command interface
    49  func (c *PeersListCommand) Run(args []string) int {
    50  	flags := c.Flags()
    51  	if err := flags.Parse(args); err != nil {
    52  		c.UI.Error(err.Error())
    53  		return 1
    54  	}
    55  
    56  	borClt, err := c.BorConn()
    57  	if err != nil {
    58  		c.UI.Error(err.Error())
    59  		return 1
    60  	}
    61  
    62  	req := &proto.PeersListRequest{}
    63  	resp, err := borClt.PeersList(context.Background(), req)
    64  
    65  	if err != nil {
    66  		c.UI.Error(err.Error())
    67  		return 1
    68  	}
    69  
    70  	c.UI.Output(formatPeers(resp.Peers))
    71  
    72  	return 0
    73  }
    74  
    75  func formatPeers(peers []*proto.Peer) string {
    76  	if len(peers) == 0 {
    77  		return "No peers found"
    78  	}
    79  
    80  	rows := make([]string, len(peers)+1)
    81  	rows[0] = "ID|Enode|Name|Caps|Static|Trusted"
    82  
    83  	for i, d := range peers {
    84  		enode := strings.TrimPrefix(d.Enode, "enode://")
    85  
    86  		rows[i+1] = fmt.Sprintf("%s|%s|%s|%s|%v|%v",
    87  			d.Id,
    88  			enode[:10],
    89  			d.Name,
    90  			strings.Join(d.Caps, ","),
    91  			d.Static,
    92  			d.Trusted)
    93  	}
    94  
    95  	return formatList(rows)
    96  }