node.go 11 KB

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