16 "github.com/vapor/common"
17 "github.com/vapor/crypto"
20 // Node represents a host on the network.
21 // The public fields of Node may not be modified.
23 IP net.IP // len 4 for IPv4 or 16 for IPv6
24 UDP, TCP uint16 // port numbers
25 ID NodeID // the node's public key
27 // Network-related fields are contained in nodeNetGuts.
28 // These fields are not supposed to be used off the
29 // Network.loop goroutine.
33 // NewNode creates a new node. It is mostly meant to be used for
35 func NewNode(id NodeID, ip net.IP, udpPort, tcpPort uint16) *Node {
36 if ipv4 := ip.To4(); ipv4 != nil {
44 nodeNetGuts: nodeNetGuts{sha: crypto.Sha256Hash(id[:])},
48 func (n *Node) addr() *net.UDPAddr {
49 return &net.UDPAddr{IP: n.IP, Port: int(n.UDP)}
52 func (n *Node) setAddr(a *net.UDPAddr) {
54 if ipv4 := a.IP.To4(); ipv4 != nil {
57 n.UDP = uint16(a.Port)
60 // compares the given address against the stored values.
61 func (n *Node) addrEqual(a *net.UDPAddr) bool {
63 if ipv4 := a.IP.To4(); ipv4 != nil {
66 return n.UDP == uint16(a.Port) && n.IP.Equal(ip)
69 // Incomplete returns true for nodes with no IP address.
70 func (n *Node) Incomplete() bool {
74 // checks whether n is a valid complete node.
75 func (n *Node) validateComplete() error {
77 return errors.New("incomplete node")
80 return errors.New("missing UDP port")
83 return errors.New("missing TCP port")
85 if n.IP.IsMulticast() || n.IP.IsUnspecified() {
86 return errors.New("invalid IP (multicast/unspecified)")
88 //_, err := n.ID.Pubkey() // validate the key (on curve, etc.)
92 // The string representation of a Node is a URL.
93 // Please see ParseNode for a description of the format.
94 func (n *Node) String() string {
95 u := url.URL{Scheme: "enode"}
97 u.Host = fmt.Sprintf("%x", n.ID[:])
99 addr := net.TCPAddr{IP: n.IP, Port: int(n.TCP)}
100 u.User = url.User(fmt.Sprintf("%x", n.ID[:]))
101 u.Host = addr.String()
103 u.RawQuery = "discport=" + strconv.Itoa(int(n.UDP))
109 var incompleteNodeURL = regexp.MustCompile("(?i)^(?:enode://)?([0-9a-f]+)$")
111 // ParseNode parses a node designator.
113 // There are two basic forms of node designators
114 // - incomplete nodes, which only have the public key (node ID)
115 // - complete nodes, which contain the public key and IP/Port information
117 // For incomplete nodes, the designator must look like one of these
119 // enode://<hex node id>
122 // For complete nodes, the node ID is encoded in the username portion
123 // of the URL, separated from the host by an @ sign. The hostname can
124 // only be given as an IP address, DNS domain names are not allowed.
125 // The port in the host name section is the TCP listening port. If the
126 // TCP and UDP (discovery) ports differ, the UDP port is specified as
127 // query parameter "discport".
129 // In the following example, the node URL describes
130 // a node with IP address 10.3.58.6, TCP listening port 30303
131 // and UDP discovery port 30301.
133 // enode://<hex node id>@10.3.58.6:30303?discport=30301
134 func ParseNode(rawurl string) (*Node, error) {
135 if m := incompleteNodeURL.FindStringSubmatch(rawurl); m != nil {
136 id, err := HexID(m[1])
138 return nil, fmt.Errorf("invalid node ID (%v)", err)
140 return NewNode(id, nil, 0, 0), nil
142 return parseComplete(rawurl)
145 func parseComplete(rawurl string) (*Node, error) {
149 tcpPort, udpPort uint64
151 u, err := url.Parse(rawurl)
155 if u.Scheme != "enode" {
156 return nil, errors.New("invalid URL scheme, want \"enode\"")
158 // Parse the Node ID from the user portion.
160 return nil, errors.New("does not contain node ID")
162 if id, err = HexID(u.User.String()); err != nil {
163 return nil, fmt.Errorf("invalid node ID (%v)", err)
165 // Parse the IP address.
166 host, port, err := net.SplitHostPort(u.Host)
168 return nil, fmt.Errorf("invalid host: %v", err)
170 if ip = net.ParseIP(host); ip == nil {
171 return nil, errors.New("invalid IP address")
173 // Ensure the IP is 4 bytes long for IPv4 addresses.
174 if ipv4 := ip.To4(); ipv4 != nil {
177 // Parse the port numbers.
178 if tcpPort, err = strconv.ParseUint(port, 10, 16); err != nil {
179 return nil, errors.New("invalid port")
183 if qv.Get("discport") != "" {
184 udpPort, err = strconv.ParseUint(qv.Get("discport"), 10, 16)
186 return nil, errors.New("invalid discport in query")
189 return NewNode(id, ip, uint16(udpPort), uint16(tcpPort)), nil
192 // MustParseNode parses a node URL. It panics if the URL is not valid.
193 func MustParseNode(rawurl string) *Node {
194 n, err := ParseNode(rawurl)
196 panic("invalid node URL: " + err.Error())
201 // MarshalText implements encoding.TextMarshaler.
202 func (n *Node) MarshalText() ([]byte, error) {
203 return []byte(n.String()), nil
206 // UnmarshalText implements encoding.TextUnmarshaler.
207 func (n *Node) UnmarshalText(text []byte) error {
208 dec, err := ParseNode(string(text))
215 // type nodeQueue []*Node
217 // // pushNew adds n to the end if it is not present.
218 // func (nl *nodeList) appendNew(n *Node) {
219 // for _, entry := range n {
224 // *nq = append(*nq, n)
227 // // popRandom removes a random node. Nodes closer to
228 // // to the head of the beginning of the have a slightly higher probability.
229 // func (nl *nodeList) popRandom() *Node {
230 // ix := rand.Intn(len(*nq))
231 // //TODO: probability as mentioned above.
232 // nl.removeIndex(ix)
235 // func (nl *nodeList) removeIndex(i int) *Node {
237 // if len(*slice) <= i {
240 // *nl = append(slice[:i], slice[i+1:]...)
243 const nodeIDBits = 32
245 // NodeID is a unique identifier for each node.
246 // The node identifier is a marshaled elliptic curve public key.
249 // NodeID prints as a long hexadecimal number.
250 func (n NodeID) String() string {
251 return fmt.Sprintf("%x", n[:])
254 // The Go syntax representation of a NodeID is a call to HexID.
255 func (n NodeID) GoString() string {
256 return fmt.Sprintf("discover.HexID(\"%x\")", n[:])
259 // TerminalString returns a shortened hex string for terminal logging.
260 func (n NodeID) TerminalString() string {
261 return hex.EncodeToString(n[:8])
264 // HexID converts a hex string to a NodeID.
265 // The string may be prefixed with 0x.
266 func HexID(in string) (NodeID, error) {
268 b, err := hex.DecodeString(strings.TrimPrefix(in, "0x"))
271 } else if len(b) != len(id) {
272 return id, fmt.Errorf("wrong length, want %d hex chars", len(id)*2)
278 // ByteID converts a []byte to a NodeID.
279 func ByteID(in []byte) NodeID {
287 // MustHexID converts a hex string to a NodeID.
288 // It panics if the string is not a valid NodeID.
289 func MustHexID(in string) NodeID {
297 // PubkeyID returns a marshaled representation of the given public key.
298 func PubkeyID(pub *ecdsa.PublicKey) NodeID {
300 pbytes := elliptic.Marshal(pub.Curve, pub.X, pub.Y)
301 if len(pbytes)-1 != len(id) {
302 panic(fmt.Errorf("need %d bit pubkey, got %d bits", (len(id)+1)*8, len(pbytes)))
304 copy(id[:], pbytes[1:])
308 //// Pubkey returns the public key represented by the node ID.
309 ////// It returns an error if the ID is not a point on the curve.
310 //func (id NodeID) Pubkey() (*ecdsa.PublicKey, error) {
311 // p := &ecdsa.PublicKey{Curve: crypto.S256(), X: new(big.Int), Y: new(big.Int)}
312 // half := len(id) / 2
313 // p.X.SetBytes(id[:half])
314 // p.Y.SetBytes(id[half:])
315 // if !p.Curve.IsOnCurve(p.X, p.Y) {
316 // return nil, errors.New("id is invalid secp256k1 curve point")
321 //func (id NodeID) mustPubkey() ecdsa.PublicKey {
322 // pk, err := id.Pubkey()
329 // recoverNodeID computes the public key used to sign the
330 // given hash from the signature.
331 //func recoverNodeID(hash, sig []byte) (id NodeID, err error) {
332 // pubkey, err := crypto.Ecrecover(hash, sig)
336 // if len(pubkey)-1 != len(id) {
337 // return id, fmt.Errorf("recovered pubkey has %d bits, want %d bits", len(pubkey)*8, (len(id)+1)*8)
339 // for i := range id {
340 // id[i] = pubkey[i+1]
345 // distcmp compares the distances a->target and b->target.
346 // Returns -1 if a is closer to target, 1 if b is closer to target
347 // and 0 if they are equal.
348 func distcmp(target, a, b common.Hash) int {
349 for i := range target {
350 da := a[i] ^ target[i]
351 db := b[i] ^ target[i]
361 // table of leading zero counts for bytes [0..255]
362 var lzcount = [256]int{
363 8, 7, 6, 6, 5, 5, 5, 5,
364 4, 4, 4, 4, 4, 4, 4, 4,
365 3, 3, 3, 3, 3, 3, 3, 3,
366 3, 3, 3, 3, 3, 3, 3, 3,
367 2, 2, 2, 2, 2, 2, 2, 2,
368 2, 2, 2, 2, 2, 2, 2, 2,
369 2, 2, 2, 2, 2, 2, 2, 2,
370 2, 2, 2, 2, 2, 2, 2, 2,
371 1, 1, 1, 1, 1, 1, 1, 1,
372 1, 1, 1, 1, 1, 1, 1, 1,
373 1, 1, 1, 1, 1, 1, 1, 1,
374 1, 1, 1, 1, 1, 1, 1, 1,
375 1, 1, 1, 1, 1, 1, 1, 1,
376 1, 1, 1, 1, 1, 1, 1, 1,
377 1, 1, 1, 1, 1, 1, 1, 1,
378 1, 1, 1, 1, 1, 1, 1, 1,
379 0, 0, 0, 0, 0, 0, 0, 0,
380 0, 0, 0, 0, 0, 0, 0, 0,
381 0, 0, 0, 0, 0, 0, 0, 0,
382 0, 0, 0, 0, 0, 0, 0, 0,
383 0, 0, 0, 0, 0, 0, 0, 0,
384 0, 0, 0, 0, 0, 0, 0, 0,
385 0, 0, 0, 0, 0, 0, 0, 0,
386 0, 0, 0, 0, 0, 0, 0, 0,
387 0, 0, 0, 0, 0, 0, 0, 0,
388 0, 0, 0, 0, 0, 0, 0, 0,
389 0, 0, 0, 0, 0, 0, 0, 0,
390 0, 0, 0, 0, 0, 0, 0, 0,
391 0, 0, 0, 0, 0, 0, 0, 0,
392 0, 0, 0, 0, 0, 0, 0, 0,
393 0, 0, 0, 0, 0, 0, 0, 0,
394 0, 0, 0, 0, 0, 0, 0, 0,
397 // logdist returns the logarithmic distance between a and b, log2(a ^ b).
398 func logdist(a, b common.Hash) int {
412 // hashAtDistance returns a random hash such that logdist(a, b) == n
413 func hashAtDistance(a common.Hash, n int) (b common.Hash) {
417 // flip bit at position n, fill the rest with random bits
419 pos := len(a) - n/8 - 1
420 bit := byte(0x01) << (byte(n%8) - 1)
425 b[pos] = a[pos]&^bit | ^a[pos]&bit // TODO: randomize end bits
426 for i := pos + 1; i < len(a); i++ {
427 b[i] = byte(rand.Intn(255))