github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/p2p/node_info.go (about) 1 package p2p 2 3 import ( 4 "crypto/ed25519" 5 "encoding/hex" 6 "fmt" 7 "net" 8 "strconv" 9 10 cfg "github.com/bytom/bytom/config" 11 "github.com/bytom/bytom/consensus" 12 "github.com/bytom/bytom/version" 13 ) 14 15 const maxNodeInfoSize = 10240 // 10Kb 16 17 // NodeInfo peer node info 18 type NodeInfo struct { 19 PubKey []byte `json:"pub_key"` 20 Moniker string `json:"moniker"` 21 Network string `json:"network"` 22 RemoteAddr string `json:"remote_addr"` 23 ListenAddr string `json:"listen_addr"` 24 Version string `json:"version"` // major.minor.revision 25 // other application specific data 26 // field 0: node service flags. field 1: node alias. 27 Other []string `json:"other"` 28 } 29 30 func NewNodeInfo(config *cfg.Config, pubkey ed25519.PublicKey, listenAddr string) *NodeInfo { 31 other := []string{strconv.FormatUint(uint64(consensus.DefaultServices), 10)} 32 if config.NodeAlias != "" { 33 other = append(other, config.NodeAlias) 34 } 35 return &NodeInfo{ 36 PubKey: pubkey, 37 Moniker: config.Moniker, 38 Network: config.ChainID, 39 ListenAddr: listenAddr, 40 Version: version.Version, 41 Other: other, 42 } 43 } 44 45 // CompatibleWith checks if two NodeInfo are compatible with eachother. 46 // CONTRACT: two nodes are compatible if the major version matches and network match 47 func (info *NodeInfo) CompatibleWith(other *NodeInfo) error { 48 compatible, err := version.CompatibleWith(other.Version) 49 if err != nil { 50 return err 51 } 52 if !compatible { 53 return fmt.Errorf("Peer is on a different major version. Peer version: %v, node version: %v", other.Version, info.Version) 54 } 55 56 if info.Network != other.Network { 57 return fmt.Errorf("Peer is on a different network. Peer network: %v, node network: %v", other.Network, info.Network) 58 } 59 return nil 60 } 61 62 func (info NodeInfo) DoFilter(ip string, pubKey string) error { 63 if hex.EncodeToString(info.PubKey) == pubKey { 64 return ErrConnectSelf 65 } 66 67 return nil 68 } 69 70 // ListenHost peer listener ip address 71 func (info *NodeInfo) listenHost() string { 72 host, _, _ := net.SplitHostPort(info.ListenAddr) 73 return host 74 } 75 76 // RemoteAddrHost peer external ip address 77 func (info *NodeInfo) RemoteAddrHost() string { 78 host, _, _ := net.SplitHostPort(info.RemoteAddr) 79 return host 80 } 81 82 // GetNetwork get node info network field 83 func (info *NodeInfo) GetNetwork() string { 84 return info.Network 85 } 86 87 // String representation 88 func (info NodeInfo) String() string { 89 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) 90 }