discv4cmd.go 7.3 KB

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