node.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. // type nodeQueue []*Node
  202. //
  203. // // pushNew adds n to the end if it is not present.
  204. // func (nl *nodeList) appendNew(n *Node) {
  205. // for _, entry := range n {
  206. // if entry == n {
  207. // return
  208. // }
  209. // }
  210. // *nq = append(*nq, n)
  211. // }
  212. //
  213. // // popRandom removes a random node. Nodes closer to
  214. // // to the head of the beginning of the have a slightly higher probability.
  215. // func (nl *nodeList) popRandom() *Node {
  216. // ix := rand.Intn(len(*nq))
  217. // //TODO: probability as mentioned above.
  218. // nl.removeIndex(ix)
  219. // }
  220. //
  221. // func (nl *nodeList) removeIndex(i int) *Node {
  222. // slice = *nl
  223. // if len(*slice) <= i {
  224. // return nil
  225. // }
  226. // *nl = append(slice[:i], slice[i+1:]...)
  227. // }
  228. const nodeIDBits = 512
  229. // NodeID is a unique identifier for each node.
  230. // The node identifier is a marshaled elliptic curve public key.
  231. type NodeID [nodeIDBits / 8]byte
  232. // NodeID prints as a long hexadecimal number.
  233. func (n NodeID) String() string {
  234. return fmt.Sprintf("%x", n[:])
  235. }
  236. // The Go syntax representation of a NodeID is a call to HexID.
  237. func (n NodeID) GoString() string {
  238. return fmt.Sprintf("discover.HexID(\"%x\")", n[:])
  239. }
  240. // HexID converts a hex string to a NodeID.
  241. // The string may be prefixed with 0x.
  242. func HexID(in string) (NodeID, error) {
  243. var id NodeID
  244. b, err := hex.DecodeString(strings.TrimPrefix(in, "0x"))
  245. if err != nil {
  246. return id, err
  247. } else if len(b) != len(id) {
  248. return id, fmt.Errorf("wrong length, want %d hex chars", len(id)*2)
  249. }
  250. copy(id[:], b)
  251. return id, nil
  252. }
  253. // MustHexID converts a hex string to a NodeID.
  254. // It panics if the string is not a valid NodeID.
  255. func MustHexID(in string) NodeID {
  256. id, err := HexID(in)
  257. if err != nil {
  258. panic(err)
  259. }
  260. return id
  261. }
  262. // PubkeyID returns a marshaled representation of the given public key.
  263. func PubkeyID(pub *ecdsa.PublicKey) NodeID {
  264. var id NodeID
  265. pbytes := elliptic.Marshal(pub.Curve, pub.X, pub.Y)
  266. if len(pbytes)-1 != len(id) {
  267. panic(fmt.Errorf("need %d bit pubkey, got %d bits", (len(id)+1)*8, len(pbytes)))
  268. }
  269. copy(id[:], pbytes[1:])
  270. return id
  271. }
  272. // Pubkey returns the public key represented by the node ID.
  273. // It returns an error if the ID is not a point on the curve.
  274. func (id NodeID) Pubkey() (*ecdsa.PublicKey, error) {
  275. p := &ecdsa.PublicKey{Curve: crypto.S256(), X: new(big.Int), Y: new(big.Int)}
  276. half := len(id) / 2
  277. p.X.SetBytes(id[:half])
  278. p.Y.SetBytes(id[half:])
  279. if !p.Curve.IsOnCurve(p.X, p.Y) {
  280. return nil, errors.New("id is invalid secp256k1 curve point")
  281. }
  282. return p, nil
  283. }
  284. func (id NodeID) mustPubkey() ecdsa.PublicKey {
  285. pk, err := id.Pubkey()
  286. if err != nil {
  287. panic(err)
  288. }
  289. return *pk
  290. }
  291. // recoverNodeID computes the public key used to sign the
  292. // given hash from the signature.
  293. func recoverNodeID(hash, sig []byte) (id NodeID, err error) {
  294. pubkey, err := crypto.Ecrecover(hash, sig)
  295. if err != nil {
  296. return id, err
  297. }
  298. if len(pubkey)-1 != len(id) {
  299. return id, fmt.Errorf("recovered pubkey has %d bits, want %d bits", len(pubkey)*8, (len(id)+1)*8)
  300. }
  301. for i := range id {
  302. id[i] = pubkey[i+1]
  303. }
  304. return id, nil
  305. }
  306. // distcmp compares the distances a->target and b->target.
  307. // Returns -1 if a is closer to target, 1 if b is closer to target
  308. // and 0 if they are equal.
  309. func distcmp(target, a, b common.Hash) int {
  310. for i := range target {
  311. da := a[i] ^ target[i]
  312. db := b[i] ^ target[i]
  313. if da > db {
  314. return 1
  315. } else if da < db {
  316. return -1
  317. }
  318. }
  319. return 0
  320. }
  321. // table of leading zero counts for bytes [0..255]
  322. var lzcount = [256]int{
  323. 8, 7, 6, 6, 5, 5, 5, 5,
  324. 4, 4, 4, 4, 4, 4, 4, 4,
  325. 3, 3, 3, 3, 3, 3, 3, 3,
  326. 3, 3, 3, 3, 3, 3, 3, 3,
  327. 2, 2, 2, 2, 2, 2, 2, 2,
  328. 2, 2, 2, 2, 2, 2, 2, 2,
  329. 2, 2, 2, 2, 2, 2, 2, 2,
  330. 2, 2, 2, 2, 2, 2, 2, 2,
  331. 1, 1, 1, 1, 1, 1, 1, 1,
  332. 1, 1, 1, 1, 1, 1, 1, 1,
  333. 1, 1, 1, 1, 1, 1, 1, 1,
  334. 1, 1, 1, 1, 1, 1, 1, 1,
  335. 1, 1, 1, 1, 1, 1, 1, 1,
  336. 1, 1, 1, 1, 1, 1, 1, 1,
  337. 1, 1, 1, 1, 1, 1, 1, 1,
  338. 1, 1, 1, 1, 1, 1, 1, 1,
  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. 0, 0, 0, 0, 0, 0, 0, 0,
  350. 0, 0, 0, 0, 0, 0, 0, 0,
  351. 0, 0, 0, 0, 0, 0, 0, 0,
  352. 0, 0, 0, 0, 0, 0, 0, 0,
  353. 0, 0, 0, 0, 0, 0, 0, 0,
  354. 0, 0, 0, 0, 0, 0, 0, 0,
  355. }
  356. // logdist returns the logarithmic distance between a and b, log2(a ^ b).
  357. func logdist(a, b common.Hash) int {
  358. lz := 0
  359. for i := range a {
  360. x := a[i] ^ b[i]
  361. if x == 0 {
  362. lz += 8
  363. } else {
  364. lz += lzcount[x]
  365. break
  366. }
  367. }
  368. return len(a)*8 - lz
  369. }
  370. // hashAtDistance returns a random hash such that logdist(a, b) == n
  371. func hashAtDistance(a common.Hash, n int) (b common.Hash) {
  372. if n == 0 {
  373. return a
  374. }
  375. // flip bit at position n, fill the rest with random bits
  376. b = a
  377. pos := len(a) - n/8 - 1
  378. bit := byte(0x01) << (byte(n%8) - 1)
  379. if bit == 0 {
  380. pos++
  381. bit = 0x80
  382. }
  383. b[pos] = a[pos]&^bit | ^a[pos]&bit // TODO: randomize end bits
  384. for i := pos + 1; i < len(a); i++ {
  385. b[i] = byte(rand.Intn(255))
  386. }
  387. return b
  388. }