urlv4.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package enode
  17. import (
  18. "crypto/ecdsa"
  19. "encoding/hex"
  20. "errors"
  21. "fmt"
  22. "net"
  23. "net/url"
  24. "regexp"
  25. "strconv"
  26. "github.com/ethereum/go-ethereum/common/math"
  27. "github.com/ethereum/go-ethereum/crypto"
  28. "github.com/ethereum/go-ethereum/p2p/enr"
  29. )
  30. var (
  31. incompleteNodeURL = regexp.MustCompile("(?i)^(?:enode://)?([0-9a-f]+)$")
  32. lookupIPFunc = net.LookupIP
  33. )
  34. // MustParseV4 parses a node URL. It panics if the URL is not valid.
  35. func MustParseV4(rawurl string) *Node {
  36. n, err := ParseV4(rawurl)
  37. if err != nil {
  38. panic("invalid node URL: " + err.Error())
  39. }
  40. return n
  41. }
  42. // ParseV4 parses a node URL.
  43. //
  44. // There are two basic forms of node URLs:
  45. //
  46. // - incomplete nodes, which only have the public key (node ID)
  47. // - complete nodes, which contain the public key and IP/Port information
  48. //
  49. // For incomplete nodes, the designator must look like one of these
  50. //
  51. // enode://<hex node id>
  52. // <hex node id>
  53. //
  54. // For complete nodes, the node ID is encoded in the username portion
  55. // of the URL, separated from the host by an @ sign. The hostname can
  56. // only be given as an IP address or using DNS domain name.
  57. // The port in the host name section is the TCP listening port. If the
  58. // TCP and UDP (discovery) ports differ, the UDP port is specified as
  59. // query parameter "discport".
  60. //
  61. // In the following example, the node URL describes
  62. // a node with IP address 10.3.58.6, TCP listening port 30303
  63. // and UDP discovery port 30301.
  64. //
  65. // enode://<hex node id>@10.3.58.6:30303?discport=30301
  66. func ParseV4(rawurl string) (*Node, error) {
  67. if m := incompleteNodeURL.FindStringSubmatch(rawurl); m != nil {
  68. id, err := parsePubkey(m[1])
  69. if err != nil {
  70. return nil, fmt.Errorf("invalid public key (%v)", err)
  71. }
  72. return NewV4(id, nil, 0, 0), nil
  73. }
  74. return parseComplete(rawurl)
  75. }
  76. // NewV4 creates a node from discovery v4 node information. The record
  77. // contained in the node has a zero-length signature.
  78. func NewV4(pubkey *ecdsa.PublicKey, ip net.IP, tcp, udp int) *Node {
  79. var r enr.Record
  80. if len(ip) > 0 {
  81. r.Set(enr.IP(ip))
  82. }
  83. if udp != 0 {
  84. r.Set(enr.UDP(udp))
  85. }
  86. if tcp != 0 {
  87. r.Set(enr.TCP(tcp))
  88. }
  89. signV4Compat(&r, pubkey)
  90. n, err := New(v4CompatID{}, &r)
  91. if err != nil {
  92. panic(err)
  93. }
  94. return n
  95. }
  96. // isNewV4 returns true for nodes created by NewV4.
  97. func isNewV4(n *Node) bool {
  98. var k s256raw
  99. return n.r.IdentityScheme() == "" && n.r.Load(&k) == nil && len(n.r.Signature()) == 0
  100. }
  101. func parseComplete(rawurl string) (*Node, error) {
  102. var (
  103. id *ecdsa.PublicKey
  104. tcpPort, udpPort uint64
  105. )
  106. u, err := url.Parse(rawurl)
  107. if err != nil {
  108. return nil, err
  109. }
  110. if u.Scheme != "enode" {
  111. return nil, errors.New("invalid URL scheme, want \"enode\"")
  112. }
  113. // Parse the Node ID from the user portion.
  114. if u.User == nil {
  115. return nil, errors.New("does not contain node ID")
  116. }
  117. if id, err = parsePubkey(u.User.String()); err != nil {
  118. return nil, fmt.Errorf("invalid public key (%v)", err)
  119. }
  120. // Parse the IP address.
  121. ip := net.ParseIP(u.Hostname())
  122. if ip == nil {
  123. ips, err := lookupIPFunc(u.Hostname())
  124. if err != nil {
  125. return nil, err
  126. }
  127. ip = ips[0]
  128. }
  129. // Ensure the IP is 4 bytes long for IPv4 addresses.
  130. if ipv4 := ip.To4(); ipv4 != nil {
  131. ip = ipv4
  132. }
  133. // Parse the port numbers.
  134. if tcpPort, err = strconv.ParseUint(u.Port(), 10, 16); err != nil {
  135. return nil, errors.New("invalid port")
  136. }
  137. udpPort = tcpPort
  138. qv := u.Query()
  139. if qv.Get("discport") != "" {
  140. udpPort, err = strconv.ParseUint(qv.Get("discport"), 10, 16)
  141. if err != nil {
  142. return nil, errors.New("invalid discport in query")
  143. }
  144. }
  145. return NewV4(id, ip, int(tcpPort), int(udpPort)), nil
  146. }
  147. // parsePubkey parses a hex-encoded secp256k1 public key.
  148. func parsePubkey(in string) (*ecdsa.PublicKey, error) {
  149. b, err := hex.DecodeString(in)
  150. if err != nil {
  151. return nil, err
  152. } else if len(b) != 64 {
  153. return nil, fmt.Errorf("wrong length, want %d hex chars", 128)
  154. }
  155. b = append([]byte{0x4}, b...)
  156. return crypto.UnmarshalPubkey(b)
  157. }
  158. func (n *Node) URLv4() string {
  159. var (
  160. scheme enr.ID
  161. nodeid string
  162. key ecdsa.PublicKey
  163. )
  164. n.Load(&scheme)
  165. n.Load((*Secp256k1)(&key))
  166. switch {
  167. case scheme == "v4" || key != ecdsa.PublicKey{}:
  168. nodeid = fmt.Sprintf("%x", crypto.FromECDSAPub(&key)[1:])
  169. default:
  170. nodeid = fmt.Sprintf("%s.%x", scheme, n.id[:])
  171. }
  172. u := url.URL{Scheme: "enode"}
  173. if n.Incomplete() {
  174. u.Host = nodeid
  175. } else {
  176. addr := net.TCPAddr{IP: n.IP(), Port: n.TCP()}
  177. u.User = url.User(nodeid)
  178. u.Host = addr.String()
  179. if n.UDP() != n.TCP() {
  180. u.RawQuery = "discport=" + strconv.Itoa(n.UDP())
  181. }
  182. }
  183. return u.String()
  184. }
  185. // PubkeyToIDV4 derives the v4 node address from the given public key.
  186. func PubkeyToIDV4(key *ecdsa.PublicKey) ID {
  187. e := make([]byte, 64)
  188. math.ReadBits(key.X, e[:len(e)/2])
  189. math.ReadBits(key.Y, e[len(e)/2:])
  190. return ID(crypto.Keccak256Hash(e))
  191. }