github.com/murrekatt/go-ethereum@v1.5.8-0.20170123175102-fc52f2c007fb/p2p/discover/node.go (about)

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