You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

228 lines
5.9 KiB

  1. package p2p
  2. import (
  3. "context"
  4. "encoding/hex"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/url"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. "github.com/tendermint/tendermint/crypto"
  13. )
  14. const (
  15. // NodeIDByteLength is the length of a crypto.Address. Currently only 20.
  16. // FIXME: support other length addresses?
  17. NodeIDByteLength = crypto.AddressSize
  18. )
  19. var (
  20. // reNodeID is a regexp for valid node IDs.
  21. reNodeID = regexp.MustCompile(`^[0-9a-f]{40}$`)
  22. // stringHasScheme tries to detect URLs with schemes. It looks for a : before a / (if any).
  23. stringHasScheme = func(str string) bool {
  24. return strings.Contains(str, "://")
  25. }
  26. // reSchemeIsHost tries to detect URLs where the scheme part is instead a
  27. // hostname, i.e. of the form "host:80/path" where host: is a hostname.
  28. reSchemeIsHost = regexp.MustCompile(`^[^/:]+:\d+(/|$)`)
  29. )
  30. // NodeID is a hex-encoded crypto.Address. It must be lowercased
  31. // (for uniqueness) and of length 2*NodeIDByteLength.
  32. type NodeID string
  33. // NewNodeID returns a lowercased (normalized) NodeID, or errors if the
  34. // node ID is invalid.
  35. func NewNodeID(nodeID string) (NodeID, error) {
  36. n := NodeID(strings.ToLower(nodeID))
  37. return n, n.Validate()
  38. }
  39. // NodeIDFromPubKey creates a node ID from a given PubKey address.
  40. func NodeIDFromPubKey(pubKey crypto.PubKey) NodeID {
  41. return NodeID(hex.EncodeToString(pubKey.Address()))
  42. }
  43. // Bytes converts the node ID to its binary byte representation.
  44. func (id NodeID) Bytes() ([]byte, error) {
  45. bz, err := hex.DecodeString(string(id))
  46. if err != nil {
  47. return nil, fmt.Errorf("invalid node ID encoding: %w", err)
  48. }
  49. return bz, nil
  50. }
  51. // Validate validates the NodeID.
  52. func (id NodeID) Validate() error {
  53. switch {
  54. case len(id) == 0:
  55. return errors.New("empty node ID")
  56. case len(id) != 2*NodeIDByteLength:
  57. return fmt.Errorf("invalid node ID length %d, expected %d", len(id), 2*NodeIDByteLength)
  58. case !reNodeID.MatchString(string(id)):
  59. return fmt.Errorf("node ID can only contain lowercased hex digits")
  60. default:
  61. return nil
  62. }
  63. }
  64. // NodeAddress is a node address URL. It differs from a transport Endpoint in
  65. // that it contains the node's ID, and that the address hostname may be resolved
  66. // into multiple IP addresses (and thus multiple endpoints).
  67. //
  68. // If the URL is opaque, i.e. of the form "scheme:opaque", then the opaque part
  69. // is expected to contain a node ID.
  70. type NodeAddress struct {
  71. NodeID NodeID
  72. Protocol Protocol
  73. Hostname string
  74. Port uint16
  75. Path string
  76. }
  77. // ParseNodeAddress parses a node address URL into a NodeAddress, normalizing
  78. // and validating it.
  79. func ParseNodeAddress(urlString string) (NodeAddress, error) {
  80. // url.Parse requires a scheme, so if it fails to parse a scheme-less URL
  81. // we try to apply a default scheme.
  82. url, err := url.Parse(urlString)
  83. if (err != nil || url.Scheme == "") &&
  84. (!stringHasScheme(urlString) || reSchemeIsHost.MatchString(urlString)) {
  85. url, err = url.Parse(string(defaultProtocol) + "://" + urlString)
  86. }
  87. if err != nil {
  88. return NodeAddress{}, fmt.Errorf("invalid node address %q: %w", urlString, err)
  89. }
  90. address := NodeAddress{
  91. Protocol: Protocol(strings.ToLower(url.Scheme)),
  92. }
  93. // Opaque URLs are expected to contain only a node ID.
  94. if url.Opaque != "" {
  95. address.NodeID = NodeID(url.Opaque)
  96. return address, address.Validate()
  97. }
  98. // Otherwise, just parse a normal networked URL.
  99. if url.User != nil {
  100. address.NodeID = NodeID(strings.ToLower(url.User.Username()))
  101. }
  102. address.Hostname = strings.ToLower(url.Hostname())
  103. if portString := url.Port(); portString != "" {
  104. port64, err := strconv.ParseUint(portString, 10, 16)
  105. if err != nil {
  106. return NodeAddress{}, fmt.Errorf("invalid port %q: %w", portString, err)
  107. }
  108. address.Port = uint16(port64)
  109. }
  110. address.Path = url.Path
  111. if url.RawQuery != "" {
  112. address.Path += "?" + url.RawQuery
  113. }
  114. if url.Fragment != "" {
  115. address.Path += "#" + url.Fragment
  116. }
  117. if address.Path != "" {
  118. switch address.Path[0] {
  119. case '/', '#', '?':
  120. default:
  121. address.Path = "/" + address.Path
  122. }
  123. }
  124. return address, address.Validate()
  125. }
  126. // Resolve resolves a NodeAddress into a set of Endpoints, by expanding
  127. // out a DNS hostname to IP addresses.
  128. func (a NodeAddress) Resolve(ctx context.Context) ([]Endpoint, error) {
  129. if a.Protocol == "" {
  130. return nil, errors.New("address has no protocol")
  131. }
  132. // If there is no hostname, this is an opaque URL in the form
  133. // "scheme:opaque", and the opaque part is assumed to be node ID used as
  134. // Path.
  135. if a.Hostname == "" {
  136. if a.NodeID == "" {
  137. return nil, errors.New("local address has no node ID")
  138. }
  139. return []Endpoint{{
  140. Protocol: a.Protocol,
  141. Path: string(a.NodeID),
  142. }}, nil
  143. }
  144. ips, err := net.DefaultResolver.LookupIP(ctx, "ip", a.Hostname)
  145. if err != nil {
  146. return nil, err
  147. }
  148. endpoints := make([]Endpoint, len(ips))
  149. for i, ip := range ips {
  150. endpoints[i] = Endpoint{
  151. Protocol: a.Protocol,
  152. IP: ip,
  153. Port: a.Port,
  154. Path: a.Path,
  155. }
  156. }
  157. return endpoints, nil
  158. }
  159. // String formats the address as a URL string.
  160. func (a NodeAddress) String() string {
  161. u := url.URL{Scheme: string(a.Protocol)}
  162. if a.NodeID != "" {
  163. u.User = url.User(string(a.NodeID))
  164. }
  165. switch {
  166. case a.Hostname != "":
  167. if a.Port > 0 {
  168. u.Host = net.JoinHostPort(a.Hostname, strconv.Itoa(int(a.Port)))
  169. } else {
  170. u.Host = a.Hostname
  171. }
  172. u.Path = a.Path
  173. case a.Protocol != "" && (a.Path == "" || a.Path == string(a.NodeID)):
  174. u.User = nil
  175. u.Opaque = string(a.NodeID) // e.g. memory:id
  176. case a.Path != "" && a.Path[0] != '/':
  177. u.Path = "/" + a.Path // e.g. some/path
  178. default:
  179. u.Path = a.Path // e.g. /some/path
  180. }
  181. return strings.TrimPrefix(u.String(), "//")
  182. }
  183. // Validate validates a NodeAddress.
  184. func (a NodeAddress) Validate() error {
  185. if a.Protocol == "" {
  186. return errors.New("no protocol")
  187. }
  188. if a.NodeID == "" {
  189. return errors.New("no peer ID")
  190. } else if err := a.NodeID.Validate(); err != nil {
  191. return fmt.Errorf("invalid peer ID: %w", err)
  192. }
  193. if a.Port > 0 && a.Hostname == "" {
  194. return errors.New("cannot specify port without hostname")
  195. }
  196. return nil
  197. }