7 "github.com/bytom/errors"
8 "github.com/bytom/netsync"
10 "github.com/bytom/version"
13 // NetInfo indicate net information
15 Listening bool `json:"listening"`
16 Syncing bool `json:"syncing"`
17 Mining bool `json:"mining"`
18 PeerCount int `json:"peer_count"`
19 CurrentBlock uint64 `json:"current_block"`
20 HighestBlock uint64 `json:"highest_block"`
21 NetWorkID string `json:"network_id"`
22 Version string `json:"version"`
25 // GetNodeInfo return net information
26 func (a *API) GetNodeInfo() *NetInfo {
28 Listening: a.sync.Switch().IsListening(),
29 Syncing: !a.sync.IsCaughtUp(),
30 Mining: a.cpuMiner.IsMining(),
31 PeerCount: len(a.sync.Switch().Peers().List()),
32 CurrentBlock: a.chain.BestBlockHeight(),
33 NetWorkID: a.sync.NodeInfo().Network,
34 Version: version.Version,
36 if bestPeer := a.sync.BestPeer(); bestPeer != nil {
37 info.HighestBlock = bestPeer.Height
39 if info.CurrentBlock > info.HighestBlock {
40 info.HighestBlock = info.CurrentBlock
45 // return the currently connected peers with net address
46 func (a *API) getPeerInfoByAddr(addr string) *netsync.PeerInfo {
47 peerInfos := a.sync.GetPeerInfos()
48 for _, peerInfo := range peerInfos {
49 if peerInfo.RemoteAddr == addr {
56 // disconnect peer by the peer id
57 func (a *API) disconnectPeerById(peerID string) error {
58 return a.sync.StopPeer(peerID)
61 // connect peer b y net address
62 func (a *API) connectPeerByIpAndPort(ip string, port uint16) (*netsync.PeerInfo, error) {
63 netIp := net.ParseIP(ip)
65 return nil, errors.New("invalid ip address")
68 addr := p2p.NewNetAddressIPPort(netIp, port)
71 if err := sw.DialPeerWithAddress(addr); err != nil {
72 return nil, errors.Wrap(err, "can not connect to the address")
74 peer := a.getPeerInfoByAddr(addr.String())
76 return nil, errors.New("the peer is disconnected again")
81 // getNetInfo return network information
82 func (a *API) getNetInfo() Response {
83 return NewSuccessResponse(a.GetNodeInfo())
86 // isMining return is in mining or not
87 func (a *API) isMining() Response {
88 IsMining := map[string]bool{"is_mining": a.IsMining()}
89 return NewSuccessResponse(IsMining)
92 // IsMining return mining status
93 func (a *API) IsMining() bool {
94 return a.cpuMiner.IsMining()
97 // return the peers of current node
98 func (a *API) listPeers() Response {
99 return NewSuccessResponse(a.sync.GetPeerInfos())
103 func (a *API) disconnectPeer(ctx context.Context, ins struct {
104 PeerID string `json:"peer_id"`
106 if err := a.disconnectPeerById(ins.PeerID); err != nil {
107 return NewErrorResponse(err)
109 return NewSuccessResponse(nil)
112 // connect peer by ip and port
113 func (a *API) connectPeer(ctx context.Context, ins struct {
114 Ip string `json:"ip"`
115 Port uint16 `json:"port"`
117 if peer, err := a.connectPeerByIpAndPort(ins.Ip, ins.Port); err != nil {
118 return NewErrorResponse(err)
120 return NewSuccessResponse(peer)