Skip to content

Commit b7394d7

Browse files
authored
p2p/discover: add initial discovery v5 implementation (#20750)
This adds an implementation of the current discovery v5 spec. There is full integration with cmd/devp2p and enode.Iterator in this version. In theory we could enable the new protocol as a replacement of discovery v4 at any time. In practice, there will likely be a few more changes to the spec and implementation before this can happen.
1 parent 671f22b commit b7394d7

19 files changed

Lines changed: 2970 additions & 74 deletions

‎cmd/devp2p/crawl.go‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,13 @@ import (
2020
"time"
2121

2222
"github.com/ethereum/go-ethereum/log"
23-
"github.com/ethereum/go-ethereum/p2p/discover"
2423
"github.com/ethereum/go-ethereum/p2p/enode"
2524
)
2625

2726
type crawler struct {
2827
input nodeSet
2928
output nodeSet
30-
disc *discover.UDPv4
29+
disc resolver
3130
iters []enode.Iterator
3231
inputIter enode.Iterator
3332
ch chan *enode.Node
@@ -37,7 +36,11 @@ type crawler struct {
3736
revalidateInterval time.Duration
3837
}
3938

40-
func newCrawler(input nodeSet, disc *discover.UDPv4, iters ...enode.Iterator) *crawler {
39+
type resolver interface {
40+
RequestENR(*enode.Node) (*enode.Node, error)
41+
}
42+
43+
func newCrawler(input nodeSet, disc resolver, iters ...enode.Iterator) *crawler {
4144
c := &crawler{
4245
input: input,
4346
output: make(nodeSet, len(input)),

‎cmd/devp2p/discv4cmd.go‎

Lines changed: 62 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,18 @@ var (
8181
Name: "bootnodes",
8282
Usage: "Comma separated nodes used for bootstrapping",
8383
}
84+
nodekeyFlag = cli.StringFlag{
85+
Name: "nodekey",
86+
Usage: "Hex-encoded node key",
87+
}
88+
nodedbFlag = cli.StringFlag{
89+
Name: "nodedb",
90+
Usage: "Nodes database location",
91+
}
92+
listenAddrFlag = cli.StringFlag{
93+
Name: "addr",
94+
Usage: "Listening address",
95+
}
8496
crawlTimeoutFlag = cli.DurationFlag{
8597
Name: "timeout",
8698
Usage: "Time limit for the crawl.",
@@ -172,55 +184,74 @@ func discv4Crawl(ctx *cli.Context) error {
172184
return nil
173185
}
174186

175-
func parseBootnodes(ctx *cli.Context) ([]*enode.Node, error) {
176-
s := params.RinkebyBootnodes
177-
if ctx.IsSet(bootnodesFlag.Name) {
178-
s = strings.Split(ctx.String(bootnodesFlag.Name), ",")
179-
}
180-
nodes := make([]*enode.Node, len(s))
181-
var err error
182-
for i, record := range s {
183-
nodes[i], err = parseNode(record)
184-
if err != nil {
185-
return nil, fmt.Errorf("invalid bootstrap node: %v", err)
186-
}
187-
}
188-
return nodes, nil
189-
}
190-
191187
// startV4 starts an ephemeral discovery V4 node.
192188
func startV4(ctx *cli.Context) *discover.UDPv4 {
193-
socket, ln, cfg, err := listen()
189+
ln, config := makeDiscoveryConfig(ctx)
190+
socket := listen(ln, ctx.String(listenAddrFlag.Name))
191+
disc, err := discover.ListenV4(socket, ln, config)
194192
if err != nil {
195193
exit(err)
196194
}
195+
return disc
196+
}
197+
198+
func makeDiscoveryConfig(ctx *cli.Context) (*enode.LocalNode, discover.Config) {
199+
var cfg discover.Config
200+
201+
if ctx.IsSet(nodekeyFlag.Name) {
202+
key, err := crypto.HexToECDSA(ctx.String(nodekeyFlag.Name))
203+
if err != nil {
204+
exit(fmt.Errorf("-%s: %v", nodekeyFlag.Name, err))
205+
}
206+
cfg.PrivateKey = key
207+
} else {
208+
cfg.PrivateKey, _ = crypto.GenerateKey()
209+
}
210+
197211
if commandHasFlag(ctx, bootnodesFlag) {
198212
bn, err := parseBootnodes(ctx)
199213
if err != nil {
200214
exit(err)
201215
}
202216
cfg.Bootnodes = bn
203217
}
204-
disc, err := discover.ListenV4(socket, ln, cfg)
218+
219+
dbpath := ctx.String(nodedbFlag.Name)
220+
db, err := enode.OpenDB(dbpath)
205221
if err != nil {
206222
exit(err)
207223
}
208-
return disc
209-
}
210-
211-
func listen() (*net.UDPConn, *enode.LocalNode, discover.Config, error) {
212-
var cfg discover.Config
213-
cfg.PrivateKey, _ = crypto.GenerateKey()
214-
db, _ := enode.OpenDB("")
215224
ln := enode.NewLocalNode(db, cfg.PrivateKey)
225+
return ln, cfg
226+
}
216227

217-
socket, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IP{0, 0, 0, 0}})
228+
func listen(ln *enode.LocalNode, addr string) *net.UDPConn {
229+
if addr == "" {
230+
addr = "0.0.0.0:0"
231+
}
232+
socket, err := net.ListenPacket("udp4", addr)
218233
if err != nil {
219-
db.Close()
220-
return nil, nil, cfg, err
234+
exit(err)
221235
}
222-
addr := socket.LocalAddr().(*net.UDPAddr)
236+
usocket := socket.(*net.UDPConn)
237+
uaddr := socket.LocalAddr().(*net.UDPAddr)
223238
ln.SetFallbackIP(net.IP{127, 0, 0, 1})
224-
ln.SetFallbackUDP(addr.Port)
225-
return socket, ln, cfg, nil
239+
ln.SetFallbackUDP(uaddr.Port)
240+
return usocket
241+
}
242+
243+
func parseBootnodes(ctx *cli.Context) ([]*enode.Node, error) {
244+
s := params.RinkebyBootnodes
245+
if ctx.IsSet(bootnodesFlag.Name) {
246+
s = strings.Split(ctx.String(bootnodesFlag.Name), ",")
247+
}
248+
nodes := make([]*enode.Node, len(s))
249+
var err error
250+
for i, record := range s {
251+
nodes[i], err = parseNode(record)
252+
if err != nil {
253+
return nil, fmt.Errorf("invalid bootstrap node: %v", err)
254+
}
255+
}
256+
return nodes, nil
226257
}

‎cmd/devp2p/discv5cmd.go‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
// Copyright 2019 The go-ethereum Authors
2+
// This file is part of go-ethereum.
3+
//
4+
// go-ethereum is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU 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+
// go-ethereum 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 General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU General Public License
15+
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
16+
17+
package main
18+
19+
import (
20+
"fmt"
21+
"time"
22+
23+
"github.com/ethereum/go-ethereum/common"
24+
"github.com/ethereum/go-ethereum/p2p/discover"
25+
"gopkg.in/urfave/cli.v1"
26+
)
27+
28+
var (
29+
discv5Command = cli.Command{
30+
Name: "discv5",
31+
Usage: "Node Discovery v5 tools",
32+
Subcommands: []cli.Command{
33+
discv5PingCommand,
34+
discv5ResolveCommand,
35+
discv5CrawlCommand,
36+
discv5ListenCommand,
37+
},
38+
}
39+
discv5PingCommand = cli.Command{
40+
Name: "ping",
41+
Usage: "Sends ping to a node",
42+
Action: discv5Ping,
43+
}
44+
discv5ResolveCommand = cli.Command{
45+
Name: "resolve",
46+
Usage: "Finds a node in the DHT",
47+
Action: discv5Resolve,
48+
Flags: []cli.Flag{bootnodesFlag},
49+
}
50+
discv5CrawlCommand = cli.Command{
51+
Name: "crawl",
52+
Usage: "Updates a nodes.json file with random nodes found in the DHT",
53+
Action: discv5Crawl,
54+
Flags: []cli.Flag{bootnodesFlag, crawlTimeoutFlag},
55+
}
56+
discv5ListenCommand = cli.Command{
57+
Name: "listen",
58+
Usage: "Runs a node",
59+
Action: discv5Listen,
60+
Flags: []cli.Flag{
61+
bootnodesFlag,
62+
nodekeyFlag,
63+
nodedbFlag,
64+
listenAddrFlag,
65+
},
66+
}
67+
)
68+
69+
func discv5Ping(ctx *cli.Context) error {
70+
n := getNodeArg(ctx)
71+
disc := startV5(ctx)
72+
defer disc.Close()
73+
74+
fmt.Println(disc.Ping(n))
75+
return nil
76+
}
77+
78+
func discv5Resolve(ctx *cli.Context) error {
79+
n := getNodeArg(ctx)
80+
disc := startV5(ctx)
81+
defer disc.Close()
82+
83+
fmt.Println(disc.Resolve(n))
84+
return nil
85+
}
86+
87+
func discv5Crawl(ctx *cli.Context) error {
88+
if ctx.NArg() < 1 {
89+
return fmt.Errorf("need nodes file as argument")
90+
}
91+
nodesFile := ctx.Args().First()
92+
var inputSet nodeSet
93+
if common.FileExist(nodesFile) {
94+
inputSet = loadNodesJSON(nodesFile)
95+
}
96+
97+
disc := startV5(ctx)
98+
defer disc.Close()
99+
c := newCrawler(inputSet, disc, disc.RandomNodes())
100+
c.revalidateInterval = 10 * time.Minute
101+
output := c.run(ctx.Duration(crawlTimeoutFlag.Name))
102+
writeNodesJSON(nodesFile, output)
103+
return nil
104+
}
105+
106+
func discv5Listen(ctx *cli.Context) error {
107+
disc := startV5(ctx)
108+
defer disc.Close()
109+
110+
fmt.Println(disc.Self())
111+
select {}
112+
}
113+
114+
// startV5 starts an ephemeral discovery v5 node.
115+
func startV5(ctx *cli.Context) *discover.UDPv5 {
116+
ln, config := makeDiscoveryConfig(ctx)
117+
socket := listen(ln, ctx.String(listenAddrFlag.Name))
118+
disc, err := discover.ListenV5(socket, ln, config)
119+
if err != nil {
120+
exit(err)
121+
}
122+
return disc
123+
}

‎cmd/devp2p/main.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ func init() {
5959
app.Commands = []cli.Command{
6060
enrdumpCommand,
6161
discv4Command,
62+
discv5Command,
6263
dnsCommand,
6364
nodesetCommand,
6465
}

‎p2p/discover/common.go‎

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,10 @@ import (
2020
"crypto/ecdsa"
2121
"net"
2222

23+
"github.com/ethereum/go-ethereum/common/mclock"
2324
"github.com/ethereum/go-ethereum/log"
2425
"github.com/ethereum/go-ethereum/p2p/enode"
26+
"github.com/ethereum/go-ethereum/p2p/enr"
2527
"github.com/ethereum/go-ethereum/p2p/netutil"
2628
)
2729

@@ -39,10 +41,25 @@ type Config struct {
3941
PrivateKey *ecdsa.PrivateKey
4042

4143
// These settings are optional:
42-
NetRestrict *netutil.Netlist // network whitelist
43-
Bootnodes []*enode.Node // list of bootstrap nodes
44-
Unhandled chan<- ReadPacket // unhandled packets are sent on this channel
45-
Log log.Logger // if set, log messages go here
44+
NetRestrict *netutil.Netlist // network whitelist
45+
Bootnodes []*enode.Node // list of bootstrap nodes
46+
Unhandled chan<- ReadPacket // unhandled packets are sent on this channel
47+
Log log.Logger // if set, log messages go here
48+
ValidSchemes enr.IdentityScheme // allowed identity schemes
49+
Clock mclock.Clock
50+
}
51+
52+
func (cfg Config) withDefaults() Config {
53+
if cfg.Log == nil {
54+
cfg.Log = log.Root()
55+
}
56+
if cfg.ValidSchemes == nil {
57+
cfg.ValidSchemes = enode.ValidSchemes
58+
}
59+
if cfg.Clock == nil {
60+
cfg.Clock = mclock.System{}
61+
}
62+
return cfg
4663
}
4764

4865
// ListenUDP starts listening for discovery packets on the given UDP socket.
@@ -51,8 +68,15 @@ func ListenUDP(c UDPConn, ln *enode.LocalNode, cfg Config) (*UDPv4, error) {
5168
}
5269

5370
// ReadPacket is a packet that couldn't be handled. Those packets are sent to the unhandled
54-
// channel if configured. This is exported for internal use, do not use this type.
71+
// channel if configured.
5572
type ReadPacket struct {
5673
Data []byte
5774
Addr *net.UDPAddr
5875
}
76+
77+
func min(x, y int) int {
78+
if x > y {
79+
return y
80+
}
81+
return x
82+
}

‎p2p/discover/lookup.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ func (it *lookup) query(n *node, reply chan<- []*node) {
150150
} else if len(r) == 0 {
151151
fails++
152152
it.tab.db.UpdateFindFails(n.ID(), n.IP(), fails)
153-
it.tab.log.Trace("Findnode failed", "id", n.ID(), "failcount", fails, "err", err)
153+
it.tab.log.Trace("Findnode failed", "id", n.ID(), "failcount", fails, "results", len(r), "err", err)
154154
if fails >= maxFindnodeFailures {
155155
it.tab.log.Trace("Too many findnode failures, dropping", "id", n.ID(), "failcount", fails)
156156
it.tab.delete(n)

‎p2p/discover/node.go‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package discover
1818

1919
import (
2020
"crypto/ecdsa"
21+
"crypto/elliptic"
2122
"errors"
2223
"math/big"
2324
"net"
@@ -45,13 +46,13 @@ func encodePubkey(key *ecdsa.PublicKey) encPubkey {
4546
return e
4647
}
4748

48-
func decodePubkey(e encPubkey) (*ecdsa.PublicKey, error) {
49-
p := &ecdsa.PublicKey{Curve: crypto.S256(), X: new(big.Int), Y: new(big.Int)}
49+
func decodePubkey(curve elliptic.Curve, e encPubkey) (*ecdsa.PublicKey, error) {
50+
p := &ecdsa.PublicKey{Curve: curve, X: new(big.Int), Y: new(big.Int)}
5051
half := len(e) / 2
5152
p.X.SetBytes(e[:half])
5253
p.Y.SetBytes(e[half:])
5354
if !p.Curve.IsOnCurve(p.X, p.Y) {
54-
return nil, errors.New("invalid secp256k1 curve point")
55+
return nil, errors.New("invalid curve point")
5556
}
5657
return p, nil
5758
}

‎p2p/discover/table.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,10 @@ func (tab *Table) len() (n int) {
424424
// bucket returns the bucket for the given node ID hash.
425425
func (tab *Table) bucket(id enode.ID) *bucket {
426426
d := enode.LogDist(tab.self().ID(), id)
427+
return tab.bucketAtDistance(d)
428+
}
429+
430+
func (tab *Table) bucketAtDistance(d int) *bucket {
427431
if d <= bucketMinDistance {
428432
return tab.buckets[0]
429433
}

0 commit comments

Comments
 (0)