urlv4.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. "blockchain-go/common/math"
  27. "blockchain-go/p2p/enr"
  28. "github.com/ethereum/go-ethereum/crypto"
  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. func NodeFromConn(pubkey *ecdsa.PublicKey, conn net.Conn) *Node {
  77. var ip net.IP
  78. var port int
  79. if tcp, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
  80. ip = tcp.IP
  81. port = tcp.Port
  82. }
  83. return NewV4(pubkey, ip, port, port)
  84. }
  85. // NewV4 creates a node from discovery v4 node information. The record
  86. // contained in the node has a zero-length signature.
  87. func NewV4(pubkey *ecdsa.PublicKey, ip net.IP, tcp, udp int) *Node {
  88. var r enr.Record
  89. if len(ip) > 0 {
  90. r.Set(enr.IP(ip))
  91. }
  92. if udp != 0 {
  93. r.Set(enr.UDP(udp))
  94. }
  95. if tcp != 0 {
  96. r.Set(enr.TCP(tcp))
  97. }
  98. signV4Compat(&r, pubkey)
  99. n, err := New(v4CompatID{}, &r)
  100. if err != nil {
  101. panic(err)
  102. }
  103. return n
  104. }
  105. // isNewV4 returns true for nodes created by NewV4.
  106. func isNewV4(n *Node) bool {
  107. var k s256raw
  108. return n.r.IdentityScheme() == "" && n.r.Load(&k) == nil && len(n.r.Signature()) == 0
  109. }
  110. func parseComplete(rawurl string) (*Node, error) {
  111. var (
  112. id *ecdsa.PublicKey
  113. tcpPort, udpPort uint64
  114. )
  115. u, err := url.Parse(rawurl)
  116. if err != nil {
  117. return nil, err
  118. }
  119. if u.Scheme != "enode" {
  120. return nil, errors.New("invalid URL scheme, want \"enode\"")
  121. }
  122. // Parse the Node ID from the user portion.
  123. if u.User == nil {
  124. return nil, errors.New("does not contain node ID")
  125. }
  126. if id, err = parsePubkey(u.User.String()); err != nil {
  127. return nil, fmt.Errorf("invalid public key (%v)", err)
  128. }
  129. // Parse the IP address.
  130. ip := net.ParseIP(u.Hostname())
  131. if ip == nil {
  132. ips, err := lookupIPFunc(u.Hostname())
  133. if err != nil {
  134. return nil, err
  135. }
  136. ip = ips[0]
  137. }
  138. // Ensure the IP is 4 bytes long for IPv4 addresses.
  139. if ipv4 := ip.To4(); ipv4 != nil {
  140. ip = ipv4
  141. }
  142. // Parse the port numbers.
  143. if tcpPort, err = strconv.ParseUint(u.Port(), 10, 16); err != nil {
  144. return nil, errors.New("invalid port")
  145. }
  146. udpPort = tcpPort
  147. qv := u.Query()
  148. if qv.Get("discport") != "" {
  149. udpPort, err = strconv.ParseUint(qv.Get("discport"), 10, 16)
  150. if err != nil {
  151. return nil, errors.New("invalid discport in query")
  152. }
  153. }
  154. return NewV4(id, ip, int(tcpPort), int(udpPort)), nil
  155. }
  156. // parsePubkey parses a hex-encoded secp256k1 public key.
  157. func parsePubkey(in string) (*ecdsa.PublicKey, error) {
  158. b, err := hex.DecodeString(in)
  159. if err != nil {
  160. return nil, err
  161. } else if len(b) != 64 {
  162. return nil, fmt.Errorf("wrong length, want %d hex chars", 128)
  163. }
  164. b = append([]byte{0x4}, b...)
  165. return crypto.UnmarshalPubkey(b)
  166. }
  167. func (n *Node) URLv4() string {
  168. var (
  169. scheme enr.ID
  170. nodeid string
  171. key ecdsa.PublicKey
  172. )
  173. n.Load(&scheme)
  174. n.Load((*Secp256k1)(&key))
  175. switch {
  176. case scheme == "v4" || key != ecdsa.PublicKey{}:
  177. nodeid = fmt.Sprintf("%x", crypto.FromECDSAPub(&key)[1:])
  178. default:
  179. nodeid = fmt.Sprintf("%s.%x", scheme, n.id[:])
  180. }
  181. u := url.URL{Scheme: "enode"}
  182. if n.Incomplete() {
  183. u.Host = nodeid
  184. } else {
  185. addr := net.TCPAddr{IP: n.IP(), Port: n.TCP()}
  186. u.User = url.User(nodeid)
  187. u.Host = addr.String()
  188. if n.UDP() != n.TCP() {
  189. u.RawQuery = "discport=" + strconv.Itoa(n.UDP())
  190. }
  191. }
  192. return u.String()
  193. }
  194. // PubkeyToIDV4 derives the v4 node address from the given public key.
  195. func PubkeyToIDV4(key *ecdsa.PublicKey) ID {
  196. e := make([]byte, 64)
  197. math.ReadBits(key.X, e[:len(e)/2])
  198. math.ReadBits(key.Y, e[len(e)/2:])
  199. return ID(crypto.Keccak256Hash(e))
  200. }