node.go 11 KB

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