discv4cmd.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. package main
  17. import (
  18. "fmt"
  19. "net"
  20. "strings"
  21. "time"
  22. "github.com/ethereum/go-ethereum/cmd/devp2p/internal/v4test"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/crypto"
  25. "github.com/ethereum/go-ethereum/internal/flags"
  26. "github.com/ethereum/go-ethereum/p2p/discover"
  27. "github.com/ethereum/go-ethereum/p2p/enode"
  28. "github.com/ethereum/go-ethereum/params"
  29. "github.com/urfave/cli/v2"
  30. )
  31. var (
  32. discv4Command = &cli.Command{
  33. Name: "discv4",
  34. Usage: "Node Discovery v4 tools",
  35. Subcommands: []*cli.Command{
  36. discv4PingCommand,
  37. discv4RequestRecordCommand,
  38. discv4ResolveCommand,
  39. discv4ResolveJSONCommand,
  40. discv4CrawlCommand,
  41. discv4TestCommand,
  42. },
  43. }
  44. discv4PingCommand = &cli.Command{
  45. Name: "ping",
  46. Usage: "Sends ping to a node",
  47. Action: discv4Ping,
  48. ArgsUsage: "<node>",
  49. Flags: v4NodeFlags,
  50. }
  51. discv4RequestRecordCommand = &cli.Command{
  52. Name: "requestenr",
  53. Usage: "Requests a node record using EIP-868 enrRequest",
  54. Action: discv4RequestRecord,
  55. ArgsUsage: "<node>",
  56. Flags: v4NodeFlags,
  57. }
  58. discv4ResolveCommand = &cli.Command{
  59. Name: "resolve",
  60. Usage: "Finds a node in the DHT",
  61. Action: discv4Resolve,
  62. ArgsUsage: "<node>",
  63. Flags: v4NodeFlags,
  64. }
  65. discv4ResolveJSONCommand = &cli.Command{
  66. Name: "resolve-json",
  67. Usage: "Re-resolves nodes in a nodes.json file",
  68. Action: discv4ResolveJSON,
  69. Flags: v4NodeFlags,
  70. ArgsUsage: "<nodes.json file>",
  71. }
  72. discv4CrawlCommand = &cli.Command{
  73. Name: "crawl",
  74. Usage: "Updates a nodes.json file with random nodes found in the DHT",
  75. Action: discv4Crawl,
  76. Flags: flags.Merge(v4NodeFlags, []cli.Flag{crawlTimeoutFlag}),
  77. }
  78. discv4TestCommand = &cli.Command{
  79. Name: "test",
  80. Usage: "Runs tests against a node",
  81. Action: discv4Test,
  82. Flags: []cli.Flag{
  83. remoteEnodeFlag,
  84. testPatternFlag,
  85. testTAPFlag,
  86. testListen1Flag,
  87. testListen2Flag,
  88. },
  89. }
  90. )
  91. var (
  92. bootnodesFlag = &cli.StringFlag{
  93. Name: "bootnodes",
  94. Usage: "Comma separated nodes used for bootstrapping",
  95. }
  96. nodekeyFlag = &cli.StringFlag{
  97. Name: "nodekey",
  98. Usage: "Hex-encoded node key",
  99. }
  100. nodedbFlag = &cli.StringFlag{
  101. Name: "nodedb",
  102. Usage: "Nodes database location",
  103. }
  104. listenAddrFlag = &cli.StringFlag{
  105. Name: "addr",
  106. Usage: "Listening address",
  107. }
  108. crawlTimeoutFlag = &cli.DurationFlag{
  109. Name: "timeout",
  110. Usage: "Time limit for the crawl.",
  111. Value: 30 * time.Minute,
  112. }
  113. remoteEnodeFlag = &cli.StringFlag{
  114. Name: "remote",
  115. Usage: "Enode of the remote node under test",
  116. EnvVars: []string{"REMOTE_ENODE"},
  117. }
  118. )
  119. var v4NodeFlags = []cli.Flag{
  120. bootnodesFlag,
  121. nodekeyFlag,
  122. nodedbFlag,
  123. listenAddrFlag,
  124. }
  125. func discv4Ping(ctx *cli.Context) error {
  126. n := getNodeArg(ctx)
  127. disc := startV4(ctx)
  128. defer disc.Close()
  129. start := time.Now()
  130. if err := disc.Ping(n); err != nil {
  131. return fmt.Errorf("node didn't respond: %v", err)
  132. }
  133. fmt.Printf("node responded to ping (RTT %v).\n", time.Since(start))
  134. return nil
  135. }
  136. func discv4RequestRecord(ctx *cli.Context) error {
  137. n := getNodeArg(ctx)
  138. disc := startV4(ctx)
  139. defer disc.Close()
  140. respN, err := disc.RequestENR(n)
  141. if err != nil {
  142. return fmt.Errorf("can't retrieve record: %v", err)
  143. }
  144. fmt.Println(respN.String())
  145. return nil
  146. }
  147. func discv4Resolve(ctx *cli.Context) error {
  148. n := getNodeArg(ctx)
  149. disc := startV4(ctx)
  150. defer disc.Close()
  151. fmt.Println(disc.Resolve(n).String())
  152. return nil
  153. }
  154. func discv4ResolveJSON(ctx *cli.Context) error {
  155. if ctx.NArg() < 1 {
  156. return fmt.Errorf("need nodes file as argument")
  157. }
  158. nodesFile := ctx.Args().Get(0)
  159. inputSet := make(nodeSet)
  160. if common.FileExist(nodesFile) {
  161. inputSet = loadNodesJSON(nodesFile)
  162. }
  163. // Add extra nodes from command line arguments.
  164. var nodeargs []*enode.Node
  165. for i := 1; i < ctx.NArg(); i++ {
  166. n, err := parseNode(ctx.Args().Get(i))
  167. if err != nil {
  168. exit(err)
  169. }
  170. nodeargs = append(nodeargs, n)
  171. }
  172. // Run the crawler.
  173. disc := startV4(ctx)
  174. defer disc.Close()
  175. c := newCrawler(inputSet, disc, enode.IterNodes(nodeargs))
  176. c.revalidateInterval = 0
  177. output := c.run(0)
  178. writeNodesJSON(nodesFile, output)
  179. return nil
  180. }
  181. func discv4Crawl(ctx *cli.Context) error {
  182. if ctx.NArg() < 1 {
  183. return fmt.Errorf("need nodes file as argument")
  184. }
  185. nodesFile := ctx.Args().First()
  186. var inputSet nodeSet
  187. if common.FileExist(nodesFile) {
  188. inputSet = loadNodesJSON(nodesFile)
  189. }
  190. disc := startV4(ctx)
  191. defer disc.Close()
  192. c := newCrawler(inputSet, disc, disc.RandomNodes())
  193. c.revalidateInterval = 10 * time.Minute
  194. output := c.run(ctx.Duration(crawlTimeoutFlag.Name))
  195. writeNodesJSON(nodesFile, output)
  196. return nil
  197. }
  198. // discv4Test runs the protocol test suite.
  199. func discv4Test(ctx *cli.Context) error {
  200. // Configure test package globals.
  201. if !ctx.IsSet(remoteEnodeFlag.Name) {
  202. return fmt.Errorf("Missing -%v", remoteEnodeFlag.Name)
  203. }
  204. v4test.Remote = ctx.String(remoteEnodeFlag.Name)
  205. v4test.Listen1 = ctx.String(testListen1Flag.Name)
  206. v4test.Listen2 = ctx.String(testListen2Flag.Name)
  207. return runTests(ctx, v4test.AllTests)
  208. }
  209. // startV4 starts an ephemeral discovery V4 node.
  210. func startV4(ctx *cli.Context) *discover.UDPv4 {
  211. ln, config := makeDiscoveryConfig(ctx)
  212. socket := listen(ln, ctx.String(listenAddrFlag.Name))
  213. disc, err := discover.ListenV4(socket, ln, config)
  214. if err != nil {
  215. exit(err)
  216. }
  217. return disc
  218. }
  219. func makeDiscoveryConfig(ctx *cli.Context) (*enode.LocalNode, discover.Config) {
  220. var cfg discover.Config
  221. if ctx.IsSet(nodekeyFlag.Name) {
  222. key, err := crypto.HexToECDSA(ctx.String(nodekeyFlag.Name))
  223. if err != nil {
  224. exit(fmt.Errorf("-%s: %v", nodekeyFlag.Name, err))
  225. }
  226. cfg.PrivateKey = key
  227. } else {
  228. cfg.PrivateKey, _ = crypto.GenerateKey()
  229. }
  230. if commandHasFlag(ctx, bootnodesFlag) {
  231. bn, err := parseBootnodes(ctx)
  232. if err != nil {
  233. exit(err)
  234. }
  235. cfg.Bootnodes = bn
  236. }
  237. dbpath := ctx.String(nodedbFlag.Name)
  238. db, err := enode.OpenDB(dbpath)
  239. if err != nil {
  240. exit(err)
  241. }
  242. ln := enode.NewLocalNode(db, cfg.PrivateKey)
  243. return ln, cfg
  244. }
  245. func listen(ln *enode.LocalNode, addr string) *net.UDPConn {
  246. if addr == "" {
  247. addr = "0.0.0.0:0"
  248. }
  249. socket, err := net.ListenPacket("udp4", addr)
  250. if err != nil {
  251. exit(err)
  252. }
  253. usocket := socket.(*net.UDPConn)
  254. uaddr := socket.LocalAddr().(*net.UDPAddr)
  255. if uaddr.IP.IsUnspecified() {
  256. ln.SetFallbackIP(net.IP{127, 0, 0, 1})
  257. } else {
  258. ln.SetFallbackIP(uaddr.IP)
  259. }
  260. ln.SetFallbackUDP(uaddr.Port)
  261. return usocket
  262. }
  263. func parseBootnodes(ctx *cli.Context) ([]*enode.Node, error) {
  264. s := params.RinkebyBootnodes
  265. if ctx.IsSet(bootnodesFlag.Name) {
  266. input := ctx.String(bootnodesFlag.Name)
  267. if input == "" {
  268. return nil, nil
  269. }
  270. s = strings.Split(input, ",")
  271. }
  272. nodes := make([]*enode.Node, len(s))
  273. var err error
  274. for i, record := range s {
  275. nodes[i], err = parseNode(record)
  276. if err != nil {
  277. return nil, fmt.Errorf("invalid bootstrap node: %v", err)
  278. }
  279. }
  280. return nodes, nil
  281. }