Skip to content

Commit 8564eb9

Browse files
committed
p2p/discover: add node URL functions, distinguish TCP/UDP ports
The discovery RPC protocol does not yet distinguish TCP and UDP ports. But it can't hurt to do so in our internal model.
1 parent 56f777b commit 8564eb9

8 files changed

Lines changed: 532 additions & 326 deletions

File tree

‎p2p/discover/node.go‎

Lines changed: 289 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,289 @@
1+
package discover
2+
3+
import (
4+
"crypto/ecdsa"
5+
"crypto/elliptic"
6+
"encoding/hex"
7+
"errors"
8+
"fmt"
9+
"io"
10+
"math/rand"
11+
"net"
12+
"net/url"
13+
"strconv"
14+
"strings"
15+
"time"
16+
17+
"github.com/ethereum/go-ethereum/crypto/secp256k1"
18+
"github.com/ethereum/go-ethereum/rlp"
19+
)
20+
21+
// Node represents a host on the network.
22+
type Node struct {
23+
ID NodeID
24+
IP net.IP
25+
26+
DiscPort int // UDP listening port for discovery protocol
27+
TCPPort int // TCP listening port for RLPx
28+
29+
active time.Time
30+
}
31+
32+
func newNode(id NodeID, addr *net.UDPAddr) *Node {
33+
return &Node{
34+
ID: id,
35+
IP: addr.IP,
36+
DiscPort: addr.Port,
37+
TCPPort: addr.Port,
38+
active: time.Now(),
39+
}
40+
}
41+
42+
func (n *Node) isValid() bool {
43+
// TODO: don't accept localhost, LAN addresses from internet hosts
44+
return !n.IP.IsMulticast() && !n.IP.IsUnspecified() && n.TCPPort != 0 && n.DiscPort != 0
45+
}
46+
47+
// The string representation of a Node is a URL.
48+
// Please see ParseNode for a description of the format.
49+
func (n *Node) String() string {
50+
addr := net.TCPAddr{IP: n.IP, Port: n.TCPPort}
51+
u := url.URL{
52+
Scheme: "enode",
53+
User: url.User(fmt.Sprintf("%x", n.ID[:])),
54+
Host: addr.String(),
55+
}
56+
if n.DiscPort != n.TCPPort {
57+
u.RawQuery = "discport=" + strconv.Itoa(n.DiscPort)
58+
}
59+
return u.String()
60+
}
61+
62+
// ParseNode parses a node URL.
63+
//
64+
// A node URL has scheme "enode".
65+
//
66+
// The hexadecimal node ID is encoded in the username portion of the
67+
// URL, separated from the host by an @ sign. The hostname can only be
68+
// given as an IP address, DNS domain names are not allowed. The port
69+
// in the host name section is the TCP listening port. If the TCP and
70+
// UDP (discovery) ports differ, the UDP port is specified as query
71+
// parameter "discport".
72+
//
73+
// In the following example, the node URL describes
74+
// a node with IP address 10.3.58.6, TCP listening port 30303
75+
// and UDP discovery port 30301.
76+
//
77+
// enode://<hex node id>@10.3.58.6:30303?discport=30301
78+
func ParseNode(rawurl string) (*Node, error) {
79+
var n Node
80+
u, err := url.Parse(rawurl)
81+
if u.Scheme != "enode" {
82+
return nil, errors.New("invalid URL scheme, want \"enode\"")
83+
}
84+
if u.User == nil {
85+
return nil, errors.New("does not contain node ID")
86+
}
87+
if n.ID, err = HexID(u.User.String()); err != nil {
88+
return nil, fmt.Errorf("invalid node ID (%v)", err)
89+
}
90+
ip, port, err := net.SplitHostPort(u.Host)
91+
if err != nil {
92+
return nil, fmt.Errorf("invalid host: %v", err)
93+
}
94+
if n.IP = net.ParseIP(ip); n.IP == nil {
95+
return nil, errors.New("invalid IP address")
96+
}
97+
if n.TCPPort, err = strconv.Atoi(port); err != nil {
98+
return nil, errors.New("invalid port")
99+
}
100+
qv := u.Query()
101+
if qv.Get("discport") == "" {
102+
n.DiscPort = n.TCPPort
103+
} else {
104+
if n.DiscPort, err = strconv.Atoi(qv.Get("discport")); err != nil {
105+
return nil, errors.New("invalid discport in query")
106+
}
107+
}
108+
return &n, nil
109+
}
110+
111+
// MustParseNode parses a node URL. It panics if the URL is not valid.
112+
func MustParseNode(rawurl string) *Node {
113+
n, err := ParseNode(rawurl)
114+
if err != nil {
115+
panic("invalid node URL: " + err.Error())
116+
}
117+
return n
118+
}
119+
120+
func (n Node) EncodeRLP(w io.Writer) error {
121+
return rlp.Encode(w, rpcNode{IP: n.IP.String(), Port: uint16(n.TCPPort), ID: n.ID})
122+
}
123+
func (n *Node) DecodeRLP(s *rlp.Stream) (err error) {
124+
var ext rpcNode
125+
if err = s.Decode(&ext); err == nil {
126+
n.TCPPort = int(ext.Port)
127+
n.DiscPort = int(ext.Port)
128+
n.ID = ext.ID
129+
if n.IP = net.ParseIP(ext.IP); n.IP == nil {
130+
return errors.New("invalid IP string")
131+
}
132+
}
133+
return err
134+
}
135+
136+
// NodeID is a unique identifier for each node.
137+
// The node identifier is a marshaled elliptic curve public key.
138+
type NodeID [512 / 8]byte
139+
140+
// NodeID prints as a long hexadecimal number.
141+
func (n NodeID) String() string {
142+
return fmt.Sprintf("%#x", n[:])
143+
}
144+
145+
// The Go syntax representation of a NodeID is a call to HexID.
146+
func (n NodeID) GoString() string {
147+
return fmt.Sprintf("discover.HexID(\"%#x\")", n[:])
148+
}
149+
150+
// HexID converts a hex string to a NodeID.
151+
// The string may be prefixed with 0x.
152+
func HexID(in string) (NodeID, error) {
153+
if strings.HasPrefix(in, "0x") {
154+
in = in[2:]
155+
}
156+
var id NodeID
157+
b, err := hex.DecodeString(in)
158+
if err != nil {
159+
return id, err
160+
} else if len(b) != len(id) {
161+
return id, fmt.Errorf("wrong length, need %d hex bytes", len(id))
162+
}
163+
copy(id[:], b)
164+
return id, nil
165+
}
166+
167+
// MustHexID converts a hex string to a NodeID.
168+
// It panics if the string is not a valid NodeID.
169+
func MustHexID(in string) NodeID {
170+
id, err := HexID(in)
171+
if err != nil {
172+
panic(err)
173+
}
174+
return id
175+
}
176+
177+
// PubkeyID returns a marshaled representation of the given public key.
178+
func PubkeyID(pub *ecdsa.PublicKey) NodeID {
179+
var id NodeID
180+
pbytes := elliptic.Marshal(pub.Curve, pub.X, pub.Y)
181+
if len(pbytes)-1 != len(id) {
182+
panic(fmt.Errorf("need %d bit pubkey, got %d bits", (len(id)+1)*8, len(pbytes)))
183+
}
184+
copy(id[:], pbytes[1:])
185+
return id
186+
}
187+
188+
// recoverNodeID computes the public key used to sign the
189+
// given hash from the signature.
190+
func recoverNodeID(hash, sig []byte) (id NodeID, err error) {
191+
pubkey, err := secp256k1.RecoverPubkey(hash, sig)
192+
if err != nil {
193+
return id, err
194+
}
195+
if len(pubkey)-1 != len(id) {
196+
return id, fmt.Errorf("recovered pubkey has %d bits, want %d bits", len(pubkey)*8, (len(id)+1)*8)
197+
}
198+
for i := range id {
199+
id[i] = pubkey[i+1]
200+
}
201+
return id, nil
202+
}
203+
204+
// distcmp compares the distances a->target and b->target.
205+
// Returns -1 if a is closer to target, 1 if b is closer to target
206+
// and 0 if they are equal.
207+
func distcmp(target, a, b NodeID) int {
208+
for i := range target {
209+
da := a[i] ^ target[i]
210+
db := b[i] ^ target[i]
211+
if da > db {
212+
return 1
213+
} else if da < db {
214+
return -1
215+
}
216+
}
217+
return 0
218+
}
219+
220+
// table of leading zero counts for bytes [0..255]
221+
var lzcount = [256]int{
222+
8, 7, 6, 6, 5, 5, 5, 5,
223+
4, 4, 4, 4, 4, 4, 4, 4,
224+
3, 3, 3, 3, 3, 3, 3, 3,
225+
3, 3, 3, 3, 3, 3, 3, 3,
226+
2, 2, 2, 2, 2, 2, 2, 2,
227+
2, 2, 2, 2, 2, 2, 2, 2,
228+
2, 2, 2, 2, 2, 2, 2, 2,
229+
2, 2, 2, 2, 2, 2, 2, 2,
230+
1, 1, 1, 1, 1, 1, 1, 1,
231+
1, 1, 1, 1, 1, 1, 1, 1,
232+
1, 1, 1, 1, 1, 1, 1, 1,
233+
1, 1, 1, 1, 1, 1, 1, 1,
234+
1, 1, 1, 1, 1, 1, 1, 1,
235+
1, 1, 1, 1, 1, 1, 1, 1,
236+
1, 1, 1, 1, 1, 1, 1, 1,
237+
1, 1, 1, 1, 1, 1, 1, 1,
238+
0, 0, 0, 0, 0, 0, 0, 0,
239+
0, 0, 0, 0, 0, 0, 0, 0,
240+
0, 0, 0, 0, 0, 0, 0, 0,
241+
0, 0, 0, 0, 0, 0, 0, 0,
242+
0, 0, 0, 0, 0, 0, 0, 0,
243+
0, 0, 0, 0, 0, 0, 0, 0,
244+
0, 0, 0, 0, 0, 0, 0, 0,
245+
0, 0, 0, 0, 0, 0, 0, 0,
246+
0, 0, 0, 0, 0, 0, 0, 0,
247+
0, 0, 0, 0, 0, 0, 0, 0,
248+
0, 0, 0, 0, 0, 0, 0, 0,
249+
0, 0, 0, 0, 0, 0, 0, 0,
250+
0, 0, 0, 0, 0, 0, 0, 0,
251+
0, 0, 0, 0, 0, 0, 0, 0,
252+
0, 0, 0, 0, 0, 0, 0, 0,
253+
0, 0, 0, 0, 0, 0, 0, 0,
254+
}
255+
256+
// logdist returns the logarithmic distance between a and b, log2(a ^ b).
257+
func logdist(a, b NodeID) int {
258+
lz := 0
259+
for i := range a {
260+
x := a[i] ^ b[i]
261+
if x == 0 {
262+
lz += 8
263+
} else {
264+
lz += lzcount[x]
265+
break
266+
}
267+
}
268+
return len(a)*8 - lz
269+
}
270+
271+
// randomID returns a random NodeID such that logdist(a, b) == n
272+
func randomID(a NodeID, n int) (b NodeID) {
273+
if n == 0 {
274+
return a
275+
}
276+
// flip bit at position n, fill the rest with random bits
277+
b = a
278+
pos := len(a) - n/8 - 1
279+
bit := byte(0x01) << (byte(n%8) - 1)
280+
if bit == 0 {
281+
pos++
282+
bit = 0x80
283+
}
284+
b[pos] = a[pos]&^bit | ^a[pos]&bit // TODO: randomize end bits
285+
for i := pos + 1; i < len(a); i++ {
286+
b[i] = byte(rand.Intn(255))
287+
}
288+
return b
289+
}

0 commit comments

Comments
 (0)