OSDN Git Service

Disconnect only for diff major version (#1203)
[bytom/bytom.git] / p2p / node_info.go
1 package p2p
2
3 import (
4         "fmt"
5         "net"
6         "strconv"
7         "strings"
8
9         crypto "github.com/tendermint/go-crypto"
10 )
11
12 const maxNodeInfoSize = 10240 // 10Kb
13
14 //NodeInfo peer node info
15 type NodeInfo struct {
16         PubKey     crypto.PubKeyEd25519 `json:"pub_key"`
17         Moniker    string               `json:"moniker"`
18         Network    string               `json:"network"`
19         RemoteAddr string               `json:"remote_addr"`
20         ListenAddr string               `json:"listen_addr"`
21         Version    string               `json:"version"` // major.minor.revision
22         Other      []string             `json:"other"`   // other application specific data
23 }
24
25 // CompatibleWith checks if two NodeInfo are compatible with eachother.
26 // CONTRACT: two nodes are compatible if the major version matches and network match
27 // and they have at least one channel in common.
28 func (info *NodeInfo) CompatibleWith(other *NodeInfo) error {
29         iMajor, _, _, err := splitVersion(info.Version)
30         if err != nil {
31                 return err
32         }
33         oMajor, _, _, err := splitVersion(other.Version)
34         if err != nil {
35                 return err
36         }
37         if iMajor != oMajor {
38                 return fmt.Errorf("Peer is on a different major version. Got %v, expected %v", oMajor, iMajor)
39         }
40
41         if info.Network != other.Network {
42                 return fmt.Errorf("Peer is on a different network. Got %v, expected %v", other.Network, info.Network)
43         }
44         return nil
45 }
46
47 //ListenHost peer listener ip address
48 func (info *NodeInfo) ListenHost() string {
49         host, _, _ := net.SplitHostPort(info.ListenAddr)
50         return host
51 }
52
53 //ListenPort peer listener port
54 func (info *NodeInfo) ListenPort() int {
55         _, port, _ := net.SplitHostPort(info.ListenAddr)
56         portInt, err := strconv.Atoi(port)
57         if err != nil {
58                 return -1
59         }
60         return portInt
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 //String representation
70 func (info NodeInfo) String() string {
71         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)
72 }
73
74 func splitVersion(version string) (string, string, string, error) {
75         spl := strings.Split(version, ".")
76         if len(spl) != 3 {
77                 return "", "", "", fmt.Errorf("Invalid version format %v", version)
78         }
79         return spl[0], spl[1], spl[2], nil
80 }