github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/p2p/discv5/node.go (about) 1 // Copyright 2018 The go-ethereum Authors 2 // Copyright 2019 The go-aigar Authors 3 // This file is part of the go-aigar library. 4 // 5 // The go-aigar library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-aigar library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>. 17 18 package discv5 19 20 import ( 21 "crypto/ecdsa" 22 "crypto/elliptic" 23 "encoding/hex" 24 "errors" 25 "fmt" 26 "math/big" 27 "math/rand" 28 "net" 29 "net/url" 30 "regexp" 31 "strconv" 32 "strings" 33 34 "github.com/AigarNetwork/aigar/common" 35 "github.com/AigarNetwork/aigar/crypto" 36 ) 37 38 // Node represents a host on the network. 39 // The public fields of Node may not be modified. 40 type Node struct { 41 IP net.IP // len 4 for IPv4 or 16 for IPv6 42 UDP, TCP uint16 // port numbers 43 ID NodeID // the node's public key 44 45 // Network-related fields are contained in nodeNetGuts. 46 // These fields are not supposed to be used off the 47 // Network.loop goroutine. 48 nodeNetGuts 49 } 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 nodeNetGuts: nodeNetGuts{sha: crypto.Keccak256Hash(id[:])}, 63 } 64 } 65 66 func (n *Node) addr() *net.UDPAddr { 67 return &net.UDPAddr{IP: n.IP, Port: int(n.UDP)} 68 } 69 70 func (n *Node) setAddr(a *net.UDPAddr) { 71 n.IP = a.IP 72 if ipv4 := a.IP.To4(); ipv4 != nil { 73 n.IP = ipv4 74 } 75 n.UDP = uint16(a.Port) 76 } 77 78 // compares the given address against the stored values. 79 func (n *Node) addrEqual(a *net.UDPAddr) bool { 80 ip := a.IP 81 if ipv4 := a.IP.To4(); ipv4 != nil { 82 ip = ipv4 83 } 84 return n.UDP == uint16(a.Port) && n.IP.Equal(ip) 85 } 86 87 // Incomplete returns true for nodes with no IP address. 88 func (n *Node) Incomplete() bool { 89 return n.IP == nil 90 } 91 92 // checks whether n is a valid complete node. 93 func (n *Node) validateComplete() error { 94 if n.Incomplete() { 95 return errors.New("incomplete node") 96 } 97 if n.UDP == 0 { 98 return errors.New("missing UDP port") 99 } 100 if n.TCP == 0 { 101 return errors.New("missing TCP port") 102 } 103 if n.IP.IsMulticast() || n.IP.IsUnspecified() { 104 return errors.New("invalid IP (multicast/unspecified)") 105 } 106 _, err := n.ID.Pubkey() // validate the key (on curve, etc.) 107 return err 108 } 109 110 // The string representation of a Node is a URL. 111 // Please see ParseNode for a description of the format. 112 func (n *Node) String() string { 113 u := url.URL{Scheme: "enode"} 114 if n.Incomplete() { 115 u.Host = fmt.Sprintf("%x", n.ID[:]) 116 } else { 117 addr := net.TCPAddr{IP: n.IP, Port: int(n.TCP)} 118 u.User = url.User(fmt.Sprintf("%x", n.ID[:])) 119 u.Host = addr.String() 120 if n.UDP != n.TCP { 121 u.RawQuery = "discport=" + strconv.Itoa(int(n.UDP)) 122 } 123 } 124 return u.String() 125 } 126 127 var incompleteNodeURL = regexp.MustCompile("(?i)^(?:enode://)?([0-9a-f]+)$") 128 129 // ParseNode parses a node designator. 130 // 131 // There are two basic forms of node designators 132 // - incomplete nodes, which only have the public key (node ID) 133 // - complete nodes, which contain the public key and IP/Port information 134 // 135 // For incomplete nodes, the designator must look like one of these 136 // 137 // enode://<hex node id> 138 // <hex node id> 139 // 140 // For complete nodes, the node ID is encoded in the username portion 141 // of the URL, separated from the host by an @ sign. The hostname can 142 // only be given as an IP address, DNS domain names are not allowed. 143 // The port in the host name section is the TCP listening port. If the 144 // TCP and UDP (discovery) ports differ, the UDP port is specified as 145 // query parameter "discport". 146 // 147 // In the following example, the node URL describes 148 // a node with IP address 10.3.58.6, TCP listening port 30303 149 // and UDP discovery port 30301. 150 // 151 // enode://<hex node id>@10.3.58.6:30303?discport=30301 152 func ParseNode(rawurl string) (*Node, error) { 153 if m := incompleteNodeURL.FindStringSubmatch(rawurl); m != nil { 154 id, err := HexID(m[1]) 155 if err != nil { 156 return nil, fmt.Errorf("invalid node ID (%v)", err) 157 } 158 return NewNode(id, nil, 0, 0), nil 159 } 160 return parseComplete(rawurl) 161 } 162 163 func parseComplete(rawurl string) (*Node, error) { 164 var ( 165 id NodeID 166 ip net.IP 167 tcpPort, udpPort uint64 168 ) 169 u, err := url.Parse(rawurl) 170 if err != nil { 171 return nil, err 172 } 173 if u.Scheme != "enode" { 174 return nil, errors.New("invalid URL scheme, want \"enode\"") 175 } 176 // Parse the Node ID from the user portion. 177 if u.User == nil { 178 return nil, errors.New("does not contain node ID") 179 } 180 if id, err = HexID(u.User.String()); err != nil { 181 return nil, fmt.Errorf("invalid node ID (%v)", err) 182 } 183 // Parse the IP address. 184 host, port, err := net.SplitHostPort(u.Host) 185 if err != nil { 186 return nil, fmt.Errorf("invalid host: %v", err) 187 } 188 if ip = net.ParseIP(host); ip == nil { 189 return nil, errors.New("invalid IP address") 190 } 191 // Ensure the IP is 4 bytes long for IPv4 addresses. 192 if ipv4 := ip.To4(); ipv4 != nil { 193 ip = ipv4 194 } 195 // Parse the port numbers. 196 if tcpPort, err = strconv.ParseUint(port, 10, 16); err != nil { 197 return nil, errors.New("invalid port") 198 } 199 udpPort = tcpPort 200 qv := u.Query() 201 if qv.Get("discport") != "" { 202 udpPort, err = strconv.ParseUint(qv.Get("discport"), 10, 16) 203 if err != nil { 204 return nil, errors.New("invalid discport in query") 205 } 206 } 207 return NewNode(id, ip, uint16(udpPort), uint16(tcpPort)), nil 208 } 209 210 // MustParseNode parses a node URL. It panics if the URL is not valid. 211 func MustParseNode(rawurl string) *Node { 212 n, err := ParseNode(rawurl) 213 if err != nil { 214 panic("invalid node URL: " + err.Error()) 215 } 216 return n 217 } 218 219 // MarshalText implements encoding.TextMarshaler. 220 func (n *Node) MarshalText() ([]byte, error) { 221 return []byte(n.String()), nil 222 } 223 224 // UnmarshalText implements encoding.TextUnmarshaler. 225 func (n *Node) UnmarshalText(text []byte) error { 226 dec, err := ParseNode(string(text)) 227 if err == nil { 228 *n = *dec 229 } 230 return err 231 } 232 233 // type nodeQueue []*Node 234 // 235 // // pushNew adds n to the end if it is not present. 236 // func (nl *nodeList) appendNew(n *Node) { 237 // for _, entry := range n { 238 // if entry == n { 239 // return 240 // } 241 // } 242 // *nq = append(*nq, n) 243 // } 244 // 245 // // popRandom removes a random node. Nodes closer to 246 // // to the head of the beginning of the have a slightly higher probability. 247 // func (nl *nodeList) popRandom() *Node { 248 // ix := rand.Intn(len(*nq)) 249 // //TODO: probability as mentioned above. 250 // nl.removeIndex(ix) 251 // } 252 // 253 // func (nl *nodeList) removeIndex(i int) *Node { 254 // slice = *nl 255 // if len(*slice) <= i { 256 // return nil 257 // } 258 // *nl = append(slice[:i], slice[i+1:]...) 259 // } 260 261 const nodeIDBits = 512 262 263 // NodeID is a unique identifier for each node. 264 // The node identifier is a marshaled elliptic curve public key. 265 type NodeID [nodeIDBits / 8]byte 266 267 // NodeID prints as a long hexadecimal number. 268 func (n NodeID) String() string { 269 return fmt.Sprintf("%x", n[:]) 270 } 271 272 // The Go syntax representation of a NodeID is a call to HexID. 273 func (n NodeID) GoString() string { 274 return fmt.Sprintf("discover.HexID(\"%x\")", n[:]) 275 } 276 277 // TerminalString returns a shortened hex string for terminal logging. 278 func (n NodeID) TerminalString() string { 279 return hex.EncodeToString(n[:8]) 280 } 281 282 // HexID converts a hex string to a NodeID. 283 // The string may be prefixed with 0x. 284 func HexID(in string) (NodeID, error) { 285 var id NodeID 286 b, err := hex.DecodeString(strings.TrimPrefix(in, "0x")) 287 if err != nil { 288 return id, err 289 } else if len(b) != len(id) { 290 return id, fmt.Errorf("wrong length, want %d hex chars", len(id)*2) 291 } 292 copy(id[:], b) 293 return id, nil 294 } 295 296 // MustHexID converts a hex string to a NodeID. 297 // It panics if the string is not a valid NodeID. 298 func MustHexID(in string) NodeID { 299 id, err := HexID(in) 300 if err != nil { 301 panic(err) 302 } 303 return id 304 } 305 306 // PubkeyID returns a marshaled representation of the given public key. 307 func PubkeyID(pub *ecdsa.PublicKey) NodeID { 308 var id NodeID 309 pbytes := elliptic.Marshal(pub.Curve, pub.X, pub.Y) 310 if len(pbytes)-1 != len(id) { 311 panic(fmt.Errorf("need %d bit pubkey, got %d bits", (len(id)+1)*8, len(pbytes))) 312 } 313 copy(id[:], pbytes[1:]) 314 return id 315 } 316 317 // Pubkey returns the public key represented by the node ID. 318 // It returns an error if the ID is not a point on the curve. 319 func (n NodeID) Pubkey() (*ecdsa.PublicKey, error) { 320 p := &ecdsa.PublicKey{Curve: crypto.S256(), X: new(big.Int), Y: new(big.Int)} 321 half := len(n) / 2 322 p.X.SetBytes(n[:half]) 323 p.Y.SetBytes(n[half:]) 324 if !p.Curve.IsOnCurve(p.X, p.Y) { 325 return nil, errors.New("id is invalid secp256k1 curve point") 326 } 327 return p, nil 328 } 329 330 func (id NodeID) mustPubkey() ecdsa.PublicKey { 331 pk, err := id.Pubkey() 332 if err != nil { 333 panic(err) 334 } 335 return *pk 336 } 337 338 // recoverNodeID computes the public key used to sign the 339 // given hash from the signature. 340 func recoverNodeID(hash, sig []byte) (id NodeID, err error) { 341 pubkey, err := crypto.Ecrecover(hash, sig) 342 if err != nil { 343 return id, err 344 } 345 if len(pubkey)-1 != len(id) { 346 return id, fmt.Errorf("recovered pubkey has %d bits, want %d bits", len(pubkey)*8, (len(id)+1)*8) 347 } 348 for i := range id { 349 id[i] = pubkey[i+1] 350 } 351 return id, nil 352 } 353 354 // distcmp compares the distances a->target and b->target. 355 // Returns -1 if a is closer to target, 1 if b is closer to target 356 // and 0 if they are equal. 357 func distcmp(target, a, b common.Hash) int { 358 for i := range target { 359 da := a[i] ^ target[i] 360 db := b[i] ^ target[i] 361 if da > db { 362 return 1 363 } else if da < db { 364 return -1 365 } 366 } 367 return 0 368 } 369 370 // table of leading zero counts for bytes [0..255] 371 var lzcount = [256]int{ 372 8, 7, 6, 6, 5, 5, 5, 5, 373 4, 4, 4, 4, 4, 4, 4, 4, 374 3, 3, 3, 3, 3, 3, 3, 3, 375 3, 3, 3, 3, 3, 3, 3, 3, 376 2, 2, 2, 2, 2, 2, 2, 2, 377 2, 2, 2, 2, 2, 2, 2, 2, 378 2, 2, 2, 2, 2, 2, 2, 2, 379 2, 2, 2, 2, 2, 2, 2, 2, 380 1, 1, 1, 1, 1, 1, 1, 1, 381 1, 1, 1, 1, 1, 1, 1, 1, 382 1, 1, 1, 1, 1, 1, 1, 1, 383 1, 1, 1, 1, 1, 1, 1, 1, 384 1, 1, 1, 1, 1, 1, 1, 1, 385 1, 1, 1, 1, 1, 1, 1, 1, 386 1, 1, 1, 1, 1, 1, 1, 1, 387 1, 1, 1, 1, 1, 1, 1, 1, 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, 395 0, 0, 0, 0, 0, 0, 0, 0, 396 0, 0, 0, 0, 0, 0, 0, 0, 397 0, 0, 0, 0, 0, 0, 0, 0, 398 0, 0, 0, 0, 0, 0, 0, 0, 399 0, 0, 0, 0, 0, 0, 0, 0, 400 0, 0, 0, 0, 0, 0, 0, 0, 401 0, 0, 0, 0, 0, 0, 0, 0, 402 0, 0, 0, 0, 0, 0, 0, 0, 403 0, 0, 0, 0, 0, 0, 0, 0, 404 } 405 406 // logdist returns the logarithmic distance between a and b, log2(a ^ b). 407 func logdist(a, b common.Hash) int { 408 lz := 0 409 for i := range a { 410 x := a[i] ^ b[i] 411 if x == 0 { 412 lz += 8 413 } else { 414 lz += lzcount[x] 415 break 416 } 417 } 418 return len(a)*8 - lz 419 } 420 421 // hashAtDistance returns a random hash such that logdist(a, b) == n 422 func hashAtDistance(a common.Hash, n int) (b common.Hash) { 423 if n == 0 { 424 return a 425 } 426 // flip bit at position n, fill the rest with random bits 427 b = a 428 pos := len(a) - n/8 - 1 429 bit := byte(0x01) << (byte(n%8) - 1) 430 if bit == 0 { 431 pos++ 432 bit = 0x80 433 } 434 b[pos] = a[pos]&^bit | ^a[pos]&bit // TODO: randomize end bits 435 for i := pos + 1; i < len(a); i++ { 436 b[i] = byte(rand.Intn(255)) 437 } 438 return b 439 }