nodesetcmd.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. "errors"
  19. "fmt"
  20. "net"
  21. "sort"
  22. "strconv"
  23. "strings"
  24. "time"
  25. "github.com/ethereum/go-ethereum/core/forkid"
  26. "github.com/ethereum/go-ethereum/p2p/enr"
  27. "github.com/ethereum/go-ethereum/params"
  28. "github.com/ethereum/go-ethereum/rlp"
  29. "gopkg.in/urfave/cli.v1"
  30. )
  31. var (
  32. nodesetCommand = cli.Command{
  33. Name: "nodeset",
  34. Usage: "Node set tools",
  35. Subcommands: []cli.Command{
  36. nodesetInfoCommand,
  37. nodesetFilterCommand,
  38. },
  39. }
  40. nodesetInfoCommand = cli.Command{
  41. Name: "info",
  42. Usage: "Shows statistics about a node set",
  43. Action: nodesetInfo,
  44. ArgsUsage: "<nodes.json>",
  45. }
  46. nodesetFilterCommand = cli.Command{
  47. Name: "filter",
  48. Usage: "Filters a node set",
  49. Action: nodesetFilter,
  50. ArgsUsage: "<nodes.json> filters..",
  51. SkipFlagParsing: true,
  52. }
  53. )
  54. func nodesetInfo(ctx *cli.Context) error {
  55. if ctx.NArg() < 1 {
  56. return fmt.Errorf("need nodes file as argument")
  57. }
  58. ns := loadNodesJSON(ctx.Args().First())
  59. fmt.Printf("Set contains %d nodes.\n", len(ns))
  60. showAttributeCounts(ns)
  61. return nil
  62. }
  63. // showAttributeCounts prints the distribution of ENR attributes in a node set.
  64. func showAttributeCounts(ns nodeSet) {
  65. attrcount := make(map[string]int)
  66. var attrlist []interface{}
  67. for _, n := range ns {
  68. r := n.N.Record()
  69. attrlist = r.AppendElements(attrlist[:0])[1:]
  70. for i := 0; i < len(attrlist); i += 2 {
  71. key := attrlist[i].(string)
  72. attrcount[key]++
  73. }
  74. }
  75. var keys []string
  76. var maxlength int
  77. for key := range attrcount {
  78. keys = append(keys, key)
  79. if len(key) > maxlength {
  80. maxlength = len(key)
  81. }
  82. }
  83. sort.Strings(keys)
  84. fmt.Println("ENR attribute counts:")
  85. for _, key := range keys {
  86. fmt.Printf("%s%s: %d\n", strings.Repeat(" ", maxlength-len(key)+1), key, attrcount[key])
  87. }
  88. }
  89. func nodesetFilter(ctx *cli.Context) error {
  90. if ctx.NArg() < 1 {
  91. return fmt.Errorf("need nodes file as argument")
  92. }
  93. // Parse -limit.
  94. limit, err := parseFilterLimit(ctx.Args().Tail())
  95. if err != nil {
  96. return err
  97. }
  98. // Parse the filters.
  99. filter, err := andFilter(ctx.Args().Tail())
  100. if err != nil {
  101. return err
  102. }
  103. // Load nodes and apply filters.
  104. ns := loadNodesJSON(ctx.Args().First())
  105. result := make(nodeSet)
  106. for id, n := range ns {
  107. if filter(n) {
  108. result[id] = n
  109. }
  110. }
  111. if limit >= 0 {
  112. result = result.topN(limit)
  113. }
  114. writeNodesJSON("-", result)
  115. return nil
  116. }
  117. type nodeFilter func(nodeJSON) bool
  118. type nodeFilterC struct {
  119. narg int
  120. fn func([]string) (nodeFilter, error)
  121. }
  122. var filterFlags = map[string]nodeFilterC{
  123. "-limit": {1, trueFilter}, // needed to skip over -limit
  124. "-ip": {1, ipFilter},
  125. "-min-age": {1, minAgeFilter},
  126. "-eth-network": {1, ethFilter},
  127. "-les-server": {0, lesFilter},
  128. "-snap": {0, snapFilter},
  129. }
  130. // parseFilters parses nodeFilters from args.
  131. func parseFilters(args []string) ([]nodeFilter, error) {
  132. var filters []nodeFilter
  133. for len(args) > 0 {
  134. fc, ok := filterFlags[args[0]]
  135. if !ok {
  136. return nil, fmt.Errorf("invalid filter %q", args[0])
  137. }
  138. if len(args)-1 < fc.narg {
  139. return nil, fmt.Errorf("filter %q wants %d arguments, have %d", args[0], fc.narg, len(args)-1)
  140. }
  141. filter, err := fc.fn(args[1 : 1+fc.narg])
  142. if err != nil {
  143. return nil, fmt.Errorf("%s: %v", args[0], err)
  144. }
  145. filters = append(filters, filter)
  146. args = args[1+fc.narg:]
  147. }
  148. return filters, nil
  149. }
  150. // parseFilterLimit parses the -limit option in args. It returns -1 if there is no limit.
  151. func parseFilterLimit(args []string) (int, error) {
  152. limit := -1
  153. for i, arg := range args {
  154. if arg == "-limit" {
  155. if i == len(args)-1 {
  156. return -1, errors.New("-limit requires an argument")
  157. }
  158. n, err := strconv.Atoi(args[i+1])
  159. if err != nil {
  160. return -1, fmt.Errorf("invalid -limit %q", args[i+1])
  161. }
  162. limit = n
  163. }
  164. }
  165. return limit, nil
  166. }
  167. // andFilter parses node filters in args and and returns a single filter that requires all
  168. // of them to match.
  169. func andFilter(args []string) (nodeFilter, error) {
  170. checks, err := parseFilters(args)
  171. if err != nil {
  172. return nil, err
  173. }
  174. f := func(n nodeJSON) bool {
  175. for _, filter := range checks {
  176. if !filter(n) {
  177. return false
  178. }
  179. }
  180. return true
  181. }
  182. return f, nil
  183. }
  184. func trueFilter(args []string) (nodeFilter, error) {
  185. return func(n nodeJSON) bool { return true }, nil
  186. }
  187. func ipFilter(args []string) (nodeFilter, error) {
  188. _, cidr, err := net.ParseCIDR(args[0])
  189. if err != nil {
  190. return nil, err
  191. }
  192. f := func(n nodeJSON) bool { return cidr.Contains(n.N.IP()) }
  193. return f, nil
  194. }
  195. func minAgeFilter(args []string) (nodeFilter, error) {
  196. minage, err := time.ParseDuration(args[0])
  197. if err != nil {
  198. return nil, err
  199. }
  200. f := func(n nodeJSON) bool {
  201. age := n.LastResponse.Sub(n.FirstResponse)
  202. return age >= minage
  203. }
  204. return f, nil
  205. }
  206. func ethFilter(args []string) (nodeFilter, error) {
  207. var filter forkid.Filter
  208. switch args[0] {
  209. case "mainnet":
  210. filter = forkid.NewStaticFilter(params.MainnetChainConfig, params.MainnetGenesisHash)
  211. case "rinkeby":
  212. filter = forkid.NewStaticFilter(params.RinkebyChainConfig, params.RinkebyGenesisHash)
  213. case "goerli":
  214. filter = forkid.NewStaticFilter(params.GoerliChainConfig, params.GoerliGenesisHash)
  215. case "ropsten":
  216. filter = forkid.NewStaticFilter(params.RopstenChainConfig, params.RopstenGenesisHash)
  217. default:
  218. return nil, fmt.Errorf("unknown network %q", args[0])
  219. }
  220. f := func(n nodeJSON) bool {
  221. var eth struct {
  222. ForkID forkid.ID
  223. Tail []rlp.RawValue `rlp:"tail"`
  224. }
  225. if n.N.Load(enr.WithEntry("eth", &eth)) != nil {
  226. return false
  227. }
  228. return filter(eth.ForkID) == nil
  229. }
  230. return f, nil
  231. }
  232. func lesFilter(args []string) (nodeFilter, error) {
  233. f := func(n nodeJSON) bool {
  234. var les struct {
  235. Tail []rlp.RawValue `rlp:"tail"`
  236. }
  237. return n.N.Load(enr.WithEntry("les", &les)) == nil
  238. }
  239. return f, nil
  240. }
  241. func snapFilter(args []string) (nodeFilter, error) {
  242. f := func(n nodeJSON) bool {
  243. var snap struct {
  244. Tail []rlp.RawValue `rlp:"tail"`
  245. }
  246. return n.N.Load(enr.WithEntry("snap", &snap)) == nil
  247. }
  248. return f, nil
  249. }