node.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. // Copyright 2015 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 discover
  17. import (
  18. "crypto/ecdsa"
  19. "crypto/elliptic"
  20. "encoding/hex"
  21. "errors"
  22. "fmt"
  23. "math/big"
  24. "math/rand"
  25. "net"
  26. "net/url"
  27. "regexp"
  28. "strconv"
  29. "strings"
  30. "github.com/ethereum/go-ethereum/common"
  31. "github.com/ethereum/go-ethereum/crypto"
  32. "github.com/ethereum/go-ethereum/crypto/secp256k1"
  33. )
  34. const NodeIDBits = 512
  35. // Node represents a host on the network.
  36. // The fields of Node may not be modified.
  37. type Node struct {
  38. IP net.IP // len 4 for IPv4 or 16 for IPv6
  39. UDP, TCP uint16 // port numbers
  40. ID NodeID // the node's public key
  41. // This is a cached copy of sha3(ID) which is used for node
  42. // distance calculations. This is part of Node in order to make it
  43. // possible to write tests that need a node at a certain distance.
  44. // In those tests, the content of sha will not actually correspond
  45. // with ID.
  46. sha common.Hash
  47. // whether this node is currently being pinged in order to replace
  48. // it in a bucket
  49. contested bool
  50. }
  51. // NewNode creates a new node. It is mostly meant to be used for
  52. // testing purposes.
  53. func NewNode(id NodeID, ip net.IP, udpPort, tcpPort uint16) *Node {
  54. if ipv4 := ip.To4(); ipv4 != nil {
  55. ip = ipv4
  56. }
  57. return &Node{
  58. IP: ip,
  59. UDP: udpPort,
  60. TCP: tcpPort,
  61. ID: id,
  62. sha: crypto.Keccak256Hash(id[:]),
  63. }
  64. }
  65. func (n *Node) addr() *net.UDPAddr {
  66. return &net.UDPAddr{IP: n.IP, Port: int(n.UDP)}
  67. }
  68. // Incomplete returns true for nodes with no IP address.
  69. func (n *Node) Incomplete() bool {
  70. return n.IP == nil
  71. }
  72. // checks whether n is a valid complete node.
  73. func (n *Node) validateComplete() error {
  74. if n.Incomplete() {
  75. return errors.New("incomplete node")
  76. }
  77. if n.UDP == 0 {
  78. return errors.New("missing UDP port")
  79. }
  80. if n.TCP == 0 {
  81. return errors.New("missing TCP port")
  82. }
  83. if n.IP.IsMulticast() || n.IP.IsUnspecified() {
  84. return errors.New("invalid IP (multicast/unspecified)")
  85. }
  86. _, err := n.ID.Pubkey() // validate the key (on curve, etc.)
  87. return err
  88. }
  89. // The string representation of a Node is a URL.
  90. // Please see ParseNode for a description of the format.
  91. func (n *Node) String() string {
  92. u := url.URL{Scheme: "enode"}
  93. if n.Incomplete() {
  94. u.Host = fmt.Sprintf("%x", n.ID[:])
  95. } else {
  96. addr := net.TCPAddr{IP: n.IP, Port: int(n.TCP)}
  97. u.User = url.User(fmt.Sprintf("%x", n.ID[:]))
  98. u.Host = addr.String()
  99. if n.UDP != n.TCP {
  100. u.RawQuery = "discport=" + strconv.Itoa(int(n.UDP))
  101. }
  102. }
  103. return u.String()
  104. }
  105. var incompleteNodeURL = regexp.MustCompile("(?i)^(?:enode://)?([0-9a-f]+)$")
  106. // ParseNode parses a node designator.
  107. //
  108. // There are two basic forms of node designators
  109. // - incomplete nodes, which only have the public key (node ID)
  110. // - complete nodes, which contain the public key and IP/Port information
  111. //
  112. // For incomplete nodes, the designator must look like one of these
  113. //
  114. // enode://<hex node id>
  115. // <hex node id>
  116. //
  117. // For complete nodes, the node ID is encoded in the username portion
  118. // of the URL, separated from the host by an @ sign. The hostname can
  119. // only be given as an IP address, DNS domain names are not allowed.
  120. // The port in the host name section is the TCP listening port. If the
  121. // TCP and UDP (discovery) ports differ, the UDP port is specified as
  122. // query parameter "discport".
  123. //
  124. // In the following example, the node URL describes
  125. // a node with IP address 10.3.58.6, TCP listening port 30303
  126. // and UDP discovery port 30301.
  127. //
  128. // enode://<hex node id>@10.3.58.6:30303?discport=30301
  129. func ParseNode(rawurl string) (*Node, error) {
  130. if m := incompleteNodeURL.FindStringSubmatch(rawurl); m != nil {
  131. id, err := HexID(m[1])
  132. if err != nil {
  133. return nil, fmt.Errorf("invalid node ID (%v)", err)
  134. }
  135. return NewNode(id, nil, 0, 0), nil
  136. }
  137. return parseComplete(rawurl)
  138. }
  139. func parseComplete(rawurl string) (*Node, error) {
  140. var (
  141. id NodeID
  142. ip net.IP
  143. tcpPort, udpPort uint64
  144. )
  145. u, err := url.Parse(rawurl)
  146. if err != nil {
  147. return nil, err
  148. }
  149. if u.Scheme != "enode" {
  150. return nil, errors.New("invalid URL scheme, want \"enode\"")
  151. }
  152. // Parse the Node ID from the user portion.
  153. if u.User == nil {
  154. return nil, errors.New("does not contain node ID")
  155. }
  156. if id, err = HexID(u.User.String()); err != nil {
  157. return nil, fmt.Errorf("invalid node ID (%v)", err)
  158. }
  159. // Parse the IP address.
  160. host, port, err := net.SplitHostPort(u.Host)
  161. if err != nil {
  162. return nil, fmt.Errorf("invalid host: %v", err)
  163. }
  164. if ip = net.ParseIP(host); ip == nil {
  165. return nil, errors.New("invalid IP address")
  166. }
  167. // Ensure the IP is 4 bytes long for IPv4 addresses.
  168. if ipv4 := ip.To4(); ipv4 != nil {
  169. ip = ipv4
  170. }
  171. // Parse the port numbers.
  172. if tcpPort, err = strconv.ParseUint(port, 10, 16); err != nil {
  173. return nil, errors.New("invalid port")
  174. }
  175. udpPort = tcpPort
  176. qv := u.Query()
  177. if qv.Get("discport") != "" {
  178. udpPort, err = strconv.ParseUint(qv.Get("discport"), 10, 16)
  179. if err != nil {
  180. return nil, errors.New("invalid discport in query")
  181. }
  182. }
  183. return NewNode(id, ip, uint16(udpPort), uint16(tcpPort)), nil
  184. }
  185. // MustParseNode parses a node URL. It panics if the URL is not valid.
  186. func MustParseNode(rawurl string) *Node {
  187. n, err := ParseNode(rawurl)
  188. if err != nil {
  189. panic("invalid node URL: " + err.Error())
  190. }
  191. return n
  192. }
  193. // NodeID is a unique identifier for each node.
  194. // The node identifier is a marshaled elliptic curve public key.
  195. type NodeID [NodeIDBits / 8]byte
  196. // NodeID prints as a long hexadecimal number.
  197. func (n NodeID) String() string {
  198. return fmt.Sprintf("%x", n[:])
  199. }
  200. // The Go syntax representation of a NodeID is a call to HexID.
  201. func (n NodeID) GoString() string {
  202. return fmt.Sprintf("discover.HexID(\"%x\")", n[:])
  203. }
  204. // TerminalString returns a shortened hex string for terminal logging.
  205. func (n NodeID) TerminalString() string {
  206. return hex.EncodeToString(n[:8])
  207. }
  208. // HexID converts a hex string to a NodeID.
  209. // The string may be prefixed with 0x.
  210. func HexID(in string) (NodeID, error) {
  211. var id NodeID
  212. b, err := hex.DecodeString(strings.TrimPrefix(in, "0x"))
  213. if err != nil {
  214. return id, err
  215. } else if len(b) != len(id) {
  216. return id, fmt.Errorf("wrong length, want %d hex chars", len(id)*2)
  217. }
  218. copy(id[:], b)
  219. return id, nil
  220. }
  221. // MustHexID converts a hex string to a NodeID.
  222. // It panics if the string is not a valid NodeID.
  223. func MustHexID(in string) NodeID {
  224. id, err := HexID(in)
  225. if err != nil {
  226. panic(err)
  227. }
  228. return id
  229. }
  230. // PubkeyID returns a marshaled representation of the given public key.
  231. func PubkeyID(pub *ecdsa.PublicKey) NodeID {
  232. var id NodeID
  233. pbytes := elliptic.Marshal(pub.Curve, pub.X, pub.Y)
  234. if len(pbytes)-1 != len(id) {
  235. panic(fmt.Errorf("need %d bit pubkey, got %d bits", (len(id)+1)*8, len(pbytes)))
  236. }
  237. copy(id[:], pbytes[1:])
  238. return id
  239. }
  240. // Pubkey returns the public key represented by the node ID.
  241. // It returns an error if the ID is not a point on the curve.
  242. func (id NodeID) Pubkey() (*ecdsa.PublicKey, error) {
  243. p := &ecdsa.PublicKey{Curve: crypto.S256(), X: new(big.Int), Y: new(big.Int)}
  244. half := len(id) / 2
  245. p.X.SetBytes(id[:half])
  246. p.Y.SetBytes(id[half:])
  247. if !p.Curve.IsOnCurve(p.X, p.Y) {
  248. return nil, errors.New("id is invalid secp256k1 curve point")
  249. }
  250. return p, nil
  251. }
  252. // recoverNodeID computes the public key used to sign the
  253. // given hash from the signature.
  254. func recoverNodeID(hash, sig []byte) (id NodeID, err error) {
  255. pubkey, err := secp256k1.RecoverPubkey(hash, sig)
  256. if err != nil {
  257. return id, err
  258. }
  259. if len(pubkey)-1 != len(id) {
  260. return id, fmt.Errorf("recovered pubkey has %d bits, want %d bits", len(pubkey)*8, (len(id)+1)*8)
  261. }
  262. for i := range id {
  263. id[i] = pubkey[i+1]
  264. }
  265. return id, nil
  266. }
  267. // distcmp compares the distances a->target and b->target.
  268. // Returns -1 if a is closer to target, 1 if b is closer to target
  269. // and 0 if they are equal.
  270. func distcmp(target, a, b common.Hash) int {
  271. for i := range target {
  272. da := a[i] ^ target[i]
  273. db := b[i] ^ target[i]
  274. if da > db {
  275. return 1
  276. } else if da < db {
  277. return -1
  278. }
  279. }
  280. return 0
  281. }
  282. // table of leading zero counts for bytes [0..255]
  283. var lzcount = [256]int{
  284. 8, 7, 6, 6, 5, 5, 5, 5,
  285. 4, 4, 4, 4, 4, 4, 4, 4,
  286. 3, 3, 3, 3, 3, 3, 3, 3,
  287. 3, 3, 3, 3, 3, 3, 3, 3,
  288. 2, 2, 2, 2, 2, 2, 2, 2,
  289. 2, 2, 2, 2, 2, 2, 2, 2,
  290. 2, 2, 2, 2, 2, 2, 2, 2,
  291. 2, 2, 2, 2, 2, 2, 2, 2,
  292. 1, 1, 1, 1, 1, 1, 1, 1,
  293. 1, 1, 1, 1, 1, 1, 1, 1,
  294. 1, 1, 1, 1, 1, 1, 1, 1,
  295. 1, 1, 1, 1, 1, 1, 1, 1,
  296. 1, 1, 1, 1, 1, 1, 1, 1,
  297. 1, 1, 1, 1, 1, 1, 1, 1,
  298. 1, 1, 1, 1, 1, 1, 1, 1,
  299. 1, 1, 1, 1, 1, 1, 1, 1,
  300. 0, 0, 0, 0, 0, 0, 0, 0,
  301. 0, 0, 0, 0, 0, 0, 0, 0,
  302. 0, 0, 0, 0, 0, 0, 0, 0,
  303. 0, 0, 0, 0, 0, 0, 0, 0,
  304. 0, 0, 0, 0, 0, 0, 0, 0,
  305. 0, 0, 0, 0, 0, 0, 0, 0,
  306. 0, 0, 0, 0, 0, 0, 0, 0,
  307. 0, 0, 0, 0, 0, 0, 0, 0,
  308. 0, 0, 0, 0, 0, 0, 0, 0,
  309. 0, 0, 0, 0, 0, 0, 0, 0,
  310. 0, 0, 0, 0, 0, 0, 0, 0,
  311. 0, 0, 0, 0, 0, 0, 0, 0,
  312. 0, 0, 0, 0, 0, 0, 0, 0,
  313. 0, 0, 0, 0, 0, 0, 0, 0,
  314. 0, 0, 0, 0, 0, 0, 0, 0,
  315. 0, 0, 0, 0, 0, 0, 0, 0,
  316. }
  317. // logdist returns the logarithmic distance between a and b, log2(a ^ b).
  318. func logdist(a, b common.Hash) int {
  319. lz := 0
  320. for i := range a {
  321. x := a[i] ^ b[i]
  322. if x == 0 {
  323. lz += 8
  324. } else {
  325. lz += lzcount[x]
  326. break
  327. }
  328. }
  329. return len(a)*8 - lz
  330. }
  331. // hashAtDistance returns a random hash such that logdist(a, b) == n
  332. func hashAtDistance(a common.Hash, n int) (b common.Hash) {
  333. if n == 0 {
  334. return a
  335. }
  336. // flip bit at position n, fill the rest with random bits
  337. b = a
  338. pos := len(a) - n/8 - 1
  339. bit := byte(0x01) << (byte(n%8) - 1)
  340. if bit == 0 {
  341. pos++
  342. bit = 0x80
  343. }
  344. b[pos] = a[pos]&^bit | ^a[pos]&bit // TODO: randomize end bits
  345. for i := pos + 1; i < len(a); i++ {
  346. b[i] = byte(rand.Intn(255))
  347. }
  348. return b
  349. }