discv4cmd.go 8.79 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
// Copyright 2019 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// go-ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.

package main

import (
	"fmt"
	"net"
22
	"strconv"
23 24 25
	"strings"
	"time"

26
	"github.com/ethereum/go-ethereum/cmd/devp2p/internal/v4test"
27
	"github.com/ethereum/go-ethereum/common"
28
	"github.com/ethereum/go-ethereum/crypto"
29
	"github.com/ethereum/go-ethereum/internal/flags"
30 31 32
	"github.com/ethereum/go-ethereum/p2p/discover"
	"github.com/ethereum/go-ethereum/p2p/enode"
	"github.com/ethereum/go-ethereum/params"
33
	"github.com/urfave/cli/v2"
34 35 36
)

var (
37
	discv4Command = &cli.Command{
38 39
		Name:  "discv4",
		Usage: "Node Discovery v4 tools",
40
		Subcommands: []*cli.Command{
41 42 43
			discv4PingCommand,
			discv4RequestRecordCommand,
			discv4ResolveCommand,
44
			discv4ResolveJSONCommand,
45
			discv4CrawlCommand,
46
			discv4TestCommand,
47 48
		},
	}
49
	discv4PingCommand = &cli.Command{
50 51 52 53
		Name:      "ping",
		Usage:     "Sends ping to a node",
		Action:    discv4Ping,
		ArgsUsage: "<node>",
54
		Flags:     discoveryNodeFlags,
55
	}
56
	discv4RequestRecordCommand = &cli.Command{
57 58 59 60
		Name:      "requestenr",
		Usage:     "Requests a node record using EIP-868 enrRequest",
		Action:    discv4RequestRecord,
		ArgsUsage: "<node>",
61
		Flags:     discoveryNodeFlags,
62
	}
63
	discv4ResolveCommand = &cli.Command{
64 65 66 67
		Name:      "resolve",
		Usage:     "Finds a node in the DHT",
		Action:    discv4Resolve,
		ArgsUsage: "<node>",
68
		Flags:     discoveryNodeFlags,
69
	}
70
	discv4ResolveJSONCommand = &cli.Command{
71 72 73
		Name:      "resolve-json",
		Usage:     "Re-resolves nodes in a nodes.json file",
		Action:    discv4ResolveJSON,
74
		Flags:     discoveryNodeFlags,
75
		ArgsUsage: "<nodes.json file>",
76
	}
77
	discv4CrawlCommand = &cli.Command{
78 79 80
		Name:   "crawl",
		Usage:  "Updates a nodes.json file with random nodes found in the DHT",
		Action: discv4Crawl,
81
		Flags:  flags.Merge(discoveryNodeFlags, []cli.Flag{crawlTimeoutFlag, crawlParallelismFlag}),
82
	}
83
	discv4TestCommand = &cli.Command{
84 85 86
		Name:   "test",
		Usage:  "Runs tests against a node",
		Action: discv4Test,
87 88 89 90 91 92 93
		Flags: []cli.Flag{
			remoteEnodeFlag,
			testPatternFlag,
			testTAPFlag,
			testListen1Flag,
			testListen2Flag,
		},
94
	}
95 96
)

97
var (
98
	bootnodesFlag = &cli.StringFlag{
99 100 101
		Name:  "bootnodes",
		Usage: "Comma separated nodes used for bootstrapping",
	}
102
	nodekeyFlag = &cli.StringFlag{
103 104 105
		Name:  "nodekey",
		Usage: "Hex-encoded node key",
	}
106
	nodedbFlag = &cli.StringFlag{
107 108 109
		Name:  "nodedb",
		Usage: "Nodes database location",
	}
110
	listenAddrFlag = &cli.StringFlag{
111 112 113
		Name:  "addr",
		Usage: "Listening address",
	}
114 115 116 117
	extAddrFlag = &cli.StringFlag{
		Name:  "extaddr",
		Usage: "UDP endpoint announced in ENR. You can provide a bare IP address or IP:port as the value of this flag.",
	}
118
	crawlTimeoutFlag = &cli.DurationFlag{
119 120 121 122
		Name:  "timeout",
		Usage: "Time limit for the crawl.",
		Value: 30 * time.Minute,
	}
123 124 125 126 127
	crawlParallelismFlag = &cli.IntFlag{
		Name:  "parallel",
		Usage: "How many parallel discoveries to attempt.",
		Value: 16,
	}
128 129 130 131
	remoteEnodeFlag = &cli.StringFlag{
		Name:    "remote",
		Usage:   "Enode of the remote node under test",
		EnvVars: []string{"REMOTE_ENODE"},
132
	}
133
)
134

135
var discoveryNodeFlags = []cli.Flag{
136 137 138 139
	bootnodesFlag,
	nodekeyFlag,
	nodedbFlag,
	listenAddrFlag,
140
	extAddrFlag,
141 142
}

143
func discv4Ping(ctx *cli.Context) error {
144 145
	n := getNodeArg(ctx)
	disc := startV4(ctx)
146 147 148 149 150 151 152 153 154 155 156
	defer disc.Close()

	start := time.Now()
	if err := disc.Ping(n); err != nil {
		return fmt.Errorf("node didn't respond: %v", err)
	}
	fmt.Printf("node responded to ping (RTT %v).\n", time.Since(start))
	return nil
}

func discv4RequestRecord(ctx *cli.Context) error {
157 158
	n := getNodeArg(ctx)
	disc := startV4(ctx)
159 160 161 162 163 164 165 166 167 168 169
	defer disc.Close()

	respN, err := disc.RequestENR(n)
	if err != nil {
		return fmt.Errorf("can't retrieve record: %v", err)
	}
	fmt.Println(respN.String())
	return nil
}

func discv4Resolve(ctx *cli.Context) error {
170 171
	n := getNodeArg(ctx)
	disc := startV4(ctx)
172 173 174 175 176 177
	defer disc.Close()

	fmt.Println(disc.Resolve(n).String())
	return nil
}

178 179 180
func discv4ResolveJSON(ctx *cli.Context) error {
	if ctx.NArg() < 1 {
		return fmt.Errorf("need nodes file as argument")
181
	}
182 183 184 185
	nodesFile := ctx.Args().Get(0)
	inputSet := make(nodeSet)
	if common.FileExist(nodesFile) {
		inputSet = loadNodesJSON(nodesFile)
186
	}
187 188 189

	// Add extra nodes from command line arguments.
	var nodeargs []*enode.Node
190 191
	for i := 1; i < ctx.NArg(); i++ {
		n, err := parseNode(ctx.Args().Get(i))
192
		if err != nil {
193
			exit(err)
194
		}
195
		nodeargs = append(nodeargs, n)
196 197
	}

198 199 200 201 202
	// Run the crawler.
	disc := startV4(ctx)
	defer disc.Close()
	c := newCrawler(inputSet, disc, enode.IterNodes(nodeargs))
	c.revalidateInterval = 0
203
	output := c.run(0, 1)
204 205 206 207 208 209 210 211 212 213 214 215
	writeNodesJSON(nodesFile, output)
	return nil
}

func discv4Crawl(ctx *cli.Context) error {
	if ctx.NArg() < 1 {
		return fmt.Errorf("need nodes file as argument")
	}
	nodesFile := ctx.Args().First()
	var inputSet nodeSet
	if common.FileExist(nodesFile) {
		inputSet = loadNodesJSON(nodesFile)
216
	}
217 218 219 220 221

	disc := startV4(ctx)
	defer disc.Close()
	c := newCrawler(inputSet, disc, disc.RandomNodes())
	c.revalidateInterval = 10 * time.Minute
222
	output := c.run(ctx.Duration(crawlTimeoutFlag.Name), ctx.Int(crawlParallelismFlag.Name))
223
	writeNodesJSON(nodesFile, output)
224
	return nil
225 226
}

227
// discv4Test runs the protocol test suite.
228 229 230 231 232 233 234 235
func discv4Test(ctx *cli.Context) error {
	// Configure test package globals.
	if !ctx.IsSet(remoteEnodeFlag.Name) {
		return fmt.Errorf("Missing -%v", remoteEnodeFlag.Name)
	}
	v4test.Remote = ctx.String(remoteEnodeFlag.Name)
	v4test.Listen1 = ctx.String(testListen1Flag.Name)
	v4test.Listen2 = ctx.String(testListen2Flag.Name)
236
	return runTests(ctx, v4test.AllTests)
237 238
}

239 240
// startV4 starts an ephemeral discovery V4 node.
func startV4(ctx *cli.Context) *discover.UDPv4 {
241
	ln, config := makeDiscoveryConfig(ctx)
242
	socket := listen(ctx, ln)
243
	disc, err := discover.ListenV4(socket, ln, config)
244 245 246
	if err != nil {
		exit(err)
	}
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
	return disc
}

func makeDiscoveryConfig(ctx *cli.Context) (*enode.LocalNode, discover.Config) {
	var cfg discover.Config

	if ctx.IsSet(nodekeyFlag.Name) {
		key, err := crypto.HexToECDSA(ctx.String(nodekeyFlag.Name))
		if err != nil {
			exit(fmt.Errorf("-%s: %v", nodekeyFlag.Name, err))
		}
		cfg.PrivateKey = key
	} else {
		cfg.PrivateKey, _ = crypto.GenerateKey()
	}

263 264 265 266 267 268 269
	if commandHasFlag(ctx, bootnodesFlag) {
		bn, err := parseBootnodes(ctx)
		if err != nil {
			exit(err)
		}
		cfg.Bootnodes = bn
	}
270 271 272

	dbpath := ctx.String(nodedbFlag.Name)
	db, err := enode.OpenDB(dbpath)
273 274 275
	if err != nil {
		exit(err)
	}
276
	ln := enode.NewLocalNode(db, cfg.PrivateKey)
277 278
	return ln, cfg
}
279

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
func parseExtAddr(spec string) (ip net.IP, port int, ok bool) {
	ip = net.ParseIP(spec)
	if ip != nil {
		return ip, 0, true
	}
	host, portstr, err := net.SplitHostPort(spec)
	if err != nil {
		return nil, 0, false
	}
	ip = net.ParseIP(host)
	if ip == nil {
		return nil, 0, false
	}
	port, err = strconv.Atoi(portstr)
	if err != nil {
		return nil, 0, false
	}
	return ip, port, true
}

func listen(ctx *cli.Context, ln *enode.LocalNode) *net.UDPConn {
	addr := ctx.String(listenAddrFlag.Name)
302 303 304 305
	if addr == "" {
		addr = "0.0.0.0:0"
	}
	socket, err := net.ListenPacket("udp4", addr)
306
	if err != nil {
307
		exit(err)
308
	}
309 310

	// Configure UDP endpoint in ENR from listener address.
311 312
	usocket := socket.(*net.UDPConn)
	uaddr := socket.LocalAddr().(*net.UDPAddr)
313 314 315 316 317
	if uaddr.IP.IsUnspecified() {
		ln.SetFallbackIP(net.IP{127, 0, 0, 1})
	} else {
		ln.SetFallbackIP(uaddr.IP)
	}
318
	ln.SetFallbackUDP(uaddr.Port)
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334

	// If an ENR endpoint is set explicitly on the command-line, override
	// the information from the listening address. Note this is careful not
	// to set the UDP port if the external address doesn't have it.
	extAddr := ctx.String(extAddrFlag.Name)
	if extAddr != "" {
		ip, port, ok := parseExtAddr(extAddr)
		if !ok {
			exit(fmt.Errorf("-%s: invalid external address %q", extAddrFlag.Name, extAddr))
		}
		ln.SetStaticIP(ip)
		if port != 0 {
			ln.SetFallbackUDP(port)
		}
	}

335 336 337 338 339 340
	return usocket
}

func parseBootnodes(ctx *cli.Context) ([]*enode.Node, error) {
	s := params.RinkebyBootnodes
	if ctx.IsSet(bootnodesFlag.Name) {
341 342 343 344 345
		input := ctx.String(bootnodesFlag.Name)
		if input == "" {
			return nil, nil
		}
		s = strings.Split(input, ",")
346 347 348 349 350 351 352 353 354 355
	}
	nodes := make([]*enode.Node, len(s))
	var err error
	for i, record := range s {
		nodes[i], err = parseNode(record)
		if err != nil {
			return nil, fmt.Errorf("invalid bootstrap node: %v", err)
		}
	}
	return nodes, nil
356
}