discv4cmd.go 7.9 KB

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