node.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. "time"
  31. "github.com/ethereum/go-ethereum/common"
  32. "github.com/ethereum/go-ethereum/crypto"
  33. "github.com/ethereum/go-ethereum/crypto/secp256k1"
  34. )
  35. const NodeIDBits = 512
  36. // Node represents a host on the network.
  37. // The fields of Node may not be modified.
  38. type Node struct {
  39. IP net.IP // len 4 for IPv4 or 16 for IPv6
  40. UDP, TCP uint16 // port numbers
  41. ID NodeID // the node's public key
  42. // This is a cached copy of sha3(ID) which is used for node
  43. // distance calculations. This is part of Node in order to make it
  44. // possible to write tests that need a node at a certain distance.
  45. // In those tests, the content of sha will not actually correspond
  46. // with ID.
  47. sha common.Hash
  48. // Time when the node was added to the table.
  49. addedAt time.Time
  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. // MarshalText implements encoding.TextMarshaler.
  194. func (n *Node) MarshalText() ([]byte, error) {
  195. return []byte(n.String()), nil
  196. }
  197. // UnmarshalText implements encoding.TextUnmarshaler.
  198. func (n *Node) UnmarshalText(text []byte) error {
  199. dec, err := ParseNode(string(text))
  200. if err == nil {
  201. *n = *dec
  202. }
  203. return err
  204. }
  205. // NodeID is a unique identifier for each node.
  206. // The node identifier is a marshaled elliptic curve public key.
  207. type NodeID [NodeIDBits / 8]byte
  208. // Bytes returns a byte slice representation of the NodeID
  209. func (n NodeID) Bytes() []byte {
  210. return n[:]
  211. }
  212. // NodeID prints as a long hexadecimal number.
  213. func (n NodeID) String() string {
  214. return fmt.Sprintf("%x", n[:])
  215. }
  216. // The Go syntax representation of a NodeID is a call to HexID.
  217. func (n NodeID) GoString() string {
  218. return fmt.Sprintf("discover.HexID(\"%x\")", n[:])
  219. }
  220. // TerminalString returns a shortened hex string for terminal logging.
  221. func (n NodeID) TerminalString() string {
  222. return hex.EncodeToString(n[:8])
  223. }
  224. // MarshalText implements the encoding.TextMarshaler interface.
  225. func (n NodeID) MarshalText() ([]byte, error) {
  226. return []byte(hex.EncodeToString(n[:])), nil
  227. }
  228. // UnmarshalText implements the encoding.TextUnmarshaler interface.
  229. func (n *NodeID) UnmarshalText(text []byte) error {
  230. id, err := HexID(string(text))
  231. if err != nil {
  232. return err
  233. }
  234. *n = id
  235. return nil
  236. }
  237. // BytesID converts a byte slice to a NodeID
  238. func BytesID(b []byte) (NodeID, error) {
  239. var id NodeID
  240. if len(b) != len(id) {
  241. return id, fmt.Errorf("wrong length, want %d bytes", len(id))
  242. }
  243. copy(id[:], b)
  244. return id, nil
  245. }
  246. // MustBytesID converts a byte slice to a NodeID.
  247. // It panics if the byte slice is not a valid NodeID.
  248. func MustBytesID(b []byte) NodeID {
  249. id, err := BytesID(b)
  250. if err != nil {
  251. panic(err)
  252. }
  253. return id
  254. }
  255. // HexID converts a hex string to a NodeID.
  256. // The string may be prefixed with 0x.
  257. func HexID(in string) (NodeID, error) {
  258. var id NodeID
  259. b, err := hex.DecodeString(strings.TrimPrefix(in, "0x"))
  260. if err != nil {
  261. return id, err
  262. } else if len(b) != len(id) {
  263. return id, fmt.Errorf("wrong length, want %d hex chars", len(id)*2)
  264. }
  265. copy(id[:], b)
  266. return id, nil
  267. }
  268. // MustHexID converts a hex string to a NodeID.
  269. // It panics if the string is not a valid NodeID.
  270. func MustHexID(in string) NodeID {
  271. id, err := HexID(in)
  272. if err != nil {
  273. panic(err)
  274. }
  275. return id
  276. }
  277. // PubkeyID returns a marshaled representation of the given public key.
  278. func PubkeyID(pub *ecdsa.PublicKey) NodeID {
  279. var id NodeID
  280. pbytes := elliptic.Marshal(pub.Curve, pub.X, pub.Y)
  281. if len(pbytes)-1 != len(id) {
  282. panic(fmt.Errorf("need %d bit pubkey, got %d bits", (len(id)+1)*8, len(pbytes)))
  283. }
  284. copy(id[:], pbytes[1:])
  285. return id
  286. }
  287. // Pubkey returns the public key represented by the node ID.
  288. // It returns an error if the ID is not a point on the curve.
  289. func (id NodeID) Pubkey() (*ecdsa.PublicKey, error) {
  290. p := &ecdsa.PublicKey{Curve: crypto.S256(), X: new(big.Int), Y: new(big.Int)}
  291. half := len(id) / 2
  292. p.X.SetBytes(id[:half])
  293. p.Y.SetBytes(id[half:])
  294. if !p.Curve.IsOnCurve(p.X, p.Y) {
  295. return nil, errors.New("id is invalid secp256k1 curve point")
  296. }
  297. return p, nil
  298. }
  299. // recoverNodeID computes the public key used to sign the
  300. // given hash from the signature.
  301. func recoverNodeID(hash, sig []byte) (id NodeID, err error) {
  302. pubkey, err := secp256k1.RecoverPubkey(hash, sig)
  303. if err != nil {
  304. return id, err
  305. }
  306. if len(pubkey)-1 != len(id) {
  307. return id, fmt.Errorf("recovered pubkey has %d bits, want %d bits", len(pubkey)*8, (len(id)+1)*8)
  308. }
  309. for i := range id {
  310. id[i] = pubkey[i+1]
  311. }
  312. return id, nil
  313. }
  314. // distcmp compares the distances a->target and b->target.
  315. // Returns -1 if a is closer to target, 1 if b is closer to target
  316. // and 0 if they are equal.
  317. func distcmp(target, a, b common.Hash) int {
  318. for i := range target {
  319. da := a[i] ^ target[i]
  320. db := b[i] ^ target[i]
  321. if da > db {
  322. return 1
  323. } else if da < db {
  324. return -1
  325. }
  326. }
  327. return 0
  328. }
  329. // table of leading zero counts for bytes [0..255]
  330. var lzcount = [256]int{
  331. 8, 7, 6, 6, 5, 5, 5, 5,
  332. 4, 4, 4, 4, 4, 4, 4, 4,
  333. 3, 3, 3, 3, 3, 3, 3, 3,
  334. 3, 3, 3, 3, 3, 3, 3, 3,
  335. 2, 2, 2, 2, 2, 2, 2, 2,
  336. 2, 2, 2, 2, 2, 2, 2, 2,
  337. 2, 2, 2, 2, 2, 2, 2, 2,
  338. 2, 2, 2, 2, 2, 2, 2, 2,
  339. 1, 1, 1, 1, 1, 1, 1, 1,
  340. 1, 1, 1, 1, 1, 1, 1, 1,
  341. 1, 1, 1, 1, 1, 1, 1, 1,
  342. 1, 1, 1, 1, 1, 1, 1, 1,
  343. 1, 1, 1, 1, 1, 1, 1, 1,
  344. 1, 1, 1, 1, 1, 1, 1, 1,
  345. 1, 1, 1, 1, 1, 1, 1, 1,
  346. 1, 1, 1, 1, 1, 1, 1, 1,
  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. 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. }
  364. // logdist returns the logarithmic distance between a and b, log2(a ^ b).
  365. func logdist(a, b common.Hash) int {
  366. lz := 0
  367. for i := range a {
  368. x := a[i] ^ b[i]
  369. if x == 0 {
  370. lz += 8
  371. } else {
  372. lz += lzcount[x]
  373. break
  374. }
  375. }
  376. return len(a)*8 - lz
  377. }
  378. // hashAtDistance returns a random hash such that logdist(a, b) == n
  379. func hashAtDistance(a common.Hash, n int) (b common.Hash) {
  380. if n == 0 {
  381. return a
  382. }
  383. // flip bit at position n, fill the rest with random bits
  384. b = a
  385. pos := len(a) - n/8 - 1
  386. bit := byte(0x01) << (byte(n%8) - 1)
  387. if bit == 0 {
  388. pos++
  389. bit = 0x80
  390. }
  391. b[pos] = a[pos]&^bit | ^a[pos]&bit // TODO: randomize end bits
  392. for i := pos + 1; i < len(a); i++ {
  393. b[i] = byte(rand.Intn(255))
  394. }
  395. return b
  396. }