OSDN Git Service

c8ee30d671028bc2dd89daebc09759ac0cfbd3ef
[bytom/bytom.git] / p2p / node_info.go
1 package p2p
2
3 import (
4         "fmt"
5         "net"
6
7         "github.com/tendermint/go-crypto"
8
9         cfg "github.com/bytom/config"
10         "github.com/bytom/version"
11 )
12
13 const maxNodeInfoSize = 10240 // 10Kb
14
15 //NodeInfo peer node info
16 type NodeInfo struct {
17         PubKey     crypto.PubKeyEd25519 `json:"pub_key"`
18         Moniker    string               `json:"moniker"`
19         Network    string               `json:"network"`
20         RemoteAddr string               `json:"remote_addr"`
21         ListenAddr string               `json:"listen_addr"`
22         Version    string               `json:"version"` // major.minor.revision
23         Other      []string             `json:"other"`   // other application specific data
24 }
25
26 func NewNodeInfo(config *cfg.Config, pubkey crypto.PubKeyEd25519, listenAddr string) *NodeInfo {
27         return &NodeInfo{
28                 PubKey:     pubkey,
29                 Moniker:    config.Moniker,
30                 Network:    config.ChainID,
31                 ListenAddr: listenAddr,
32                 Version:    version.Version,
33         }
34 }
35
36 // CompatibleWith checks if two NodeInfo are compatible with eachother.
37 // CONTRACT: two nodes are compatible if the major version matches and network match
38 func (info *NodeInfo) CompatibleWith(other *NodeInfo) error {
39         compatible, err := version.CompatibleWith(other.Version)
40         if err != nil {
41                 return err
42         }
43         if !compatible {
44                 return fmt.Errorf("Peer is on a different major version. Peer version: %v, node version: %v", other.Version, info.Version)
45         }
46
47         if info.Network != other.Network {
48                 return fmt.Errorf("Peer is on a different network. Peer network: %v, node network: %v", other.Network, info.Network)
49         }
50         return nil
51 }
52
53 func (info *NodeInfo) getPubkey() crypto.PubKeyEd25519 {
54         return info.PubKey
55 }
56
57 //ListenHost peer listener ip address
58 func (info *NodeInfo) listenHost() string {
59         host, _, _ := net.SplitHostPort(info.ListenAddr)
60         return host
61 }
62
63 //RemoteAddrHost peer external ip address
64 func (info *NodeInfo) remoteAddrHost() string {
65         host, _, _ := net.SplitHostPort(info.RemoteAddr)
66         return host
67 }
68
69 //GetNetwork get node info network field
70 func (info *NodeInfo) GetNetwork() string {
71         return info.Network
72 }
73
74 //String representation
75 func (info NodeInfo) String() string {
76         return fmt.Sprintf("NodeInfo{pk: %v, moniker: %v, network: %v [listen %v], version: %v (%v)}", info.PubKey, info.Moniker, info.Network, info.ListenAddr, info.Version, info.Other)
77 }