From 8083a8e7a69b4c1603e67d7bb31111cd144bfef8 Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Fri, 28 May 2021 22:00:55 +0530 Subject: [PATCH 01/26] Fix recover key stdin reader issue --- cmd/keys.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/keys.go b/cmd/keys.go index ad27931..2d0926d 100644 --- a/cmd/keys.go +++ b/cmd/keys.go @@ -84,7 +84,7 @@ func keysAdd() *cobra.Command { } if recovery { - mnemonic, err = input.GetString("Enter your bip39 mnemonic.", bufio.NewReader(os.Stdin)) + mnemonic, err = input.GetString("Enter your bip39 mnemonic.", reader) if err != nil { return err } From 227bddfe5d67190e8edc7908fdab1fd95a44655e Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Sun, 6 Jun 2021 19:54:55 +0530 Subject: [PATCH 02/26] Added proper validation for configuration and refactored code --- cmd/config.go | 35 +++--- cmd/keys.go | 85 ++++++------- cmd/start.go | 24 ++-- go.mod | 10 +- go.sum | 119 +++++++------------ lite/tx.go | 3 +- main.go | 7 +- types/config.go | 309 ++++++++++++++++++++++++++++++------------------ 8 files changed, 316 insertions(+), 276 deletions(-) diff --git a/cmd/config.go b/cmd/config.go index a64a08f..32b799a 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/spf13/viper" "github.com/sentinel-official/dvpn-node/types" ) @@ -28,24 +29,21 @@ func ConfigCmd() *cobra.Command { func configInit() *cobra.Command { cmd := &cobra.Command{ Use: "init", - Short: "Initialize the default configuration file", + Short: "Initialize the default configuration", RunE: func(cmd *cobra.Command, args []string) error { - home, err := cmd.Flags().GetString(flags.FlagHome) - if err != nil { - return err - } + var ( + home = viper.GetString(flags.FlagHome) + path = filepath.Join(home, types.ConfigFileName) + ) force, err := cmd.Flags().GetBool(types.FlagForce) if err != nil { return err } - path := filepath.Join(home, "config.toml") - if !force { - _, err = os.Stat(path) - if err == nil { - return fmt.Errorf("config file already exists at path '%s'", path) + if _, err = os.Stat(path); err == nil { + return fmt.Errorf("config file already exists at path %s", path) } } @@ -68,22 +66,17 @@ func configShow() *cobra.Command { Use: "show", Short: "Show the configuration", RunE: func(cmd *cobra.Command, args []string) error { - home, err := cmd.Flags().GetString(flags.FlagHome) - if err != nil { - return err - } + var ( + home = viper.GetString(flags.FlagHome) + path = filepath.Join(home, types.ConfigFileName) + ) - path := filepath.Join(home, "config.toml") - if _, err := os.Stat(path); err != nil { - return fmt.Errorf("config file does not exist at path '%s'", path) - } - - cfg := types.NewConfig() + cfg := types.NewConfig().WithDefaultValues() if err := cfg.LoadFromPath(path); err != nil { return err } - fmt.Println(cfg) + fmt.Println(cfg.String()) return nil }, } diff --git a/cmd/keys.go b/cmd/keys.go index 2d0926d..3afaba1 100644 --- a/cmd/keys.go +++ b/cmd/keys.go @@ -3,7 +3,6 @@ package cmd import ( "bufio" "fmt" - "os" "path/filepath" "github.com/cosmos/cosmos-sdk/client/flags" @@ -12,8 +11,10 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/go-bip39" + "github.com/pkg/errors" hubtypes "github.com/sentinel-official/hub/types" "github.com/spf13/cobra" + "github.com/spf13/viper" "github.com/sentinel-official/dvpn-node/types" ) @@ -40,20 +41,18 @@ func keysAdd() *cobra.Command { Short: "Add a key", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - home, err := cmd.Flags().GetString(flags.FlagHome) - if err != nil { - return err - } - - path := filepath.Join(home, "config.toml") - if _, err := os.Stat(path); err != nil { - return fmt.Errorf("config file does not exist at path '%s'", path) - } + var ( + home = viper.GetString(flags.FlagHome) + path = filepath.Join(home, types.ConfigFileName) + ) - cfg := types.NewConfig() + cfg := types.NewConfig().WithDefaultValues() if err := cfg.LoadFromPath(path); err != nil { return err } + if err := cfg.Validate(); err != nil { + return err + } recovery, err := cmd.Flags().GetBool(flagRecover) if err != nil { @@ -70,7 +69,7 @@ func keysAdd() *cobra.Command { } if _, err = kr.Key(args[0]); err == nil { - return fmt.Errorf("key already exists with name '%s'", args[0]) + return fmt.Errorf("key already exists with name %s", args[0]) } entropy, err := bip39.NewEntropy(256) @@ -84,13 +83,13 @@ func keysAdd() *cobra.Command { } if recovery { - mnemonic, err = input.GetString("Enter your bip39 mnemonic.", reader) + mnemonic, err = input.GetString("Enter your bip39 mnemonic", reader) if err != nil { return err } if !bip39.IsMnemonicValid(mnemonic) { - return fmt.Errorf("invalid bip39 mnemonic") + return errors.New("invalid bip39 mnemonic") } } @@ -128,20 +127,18 @@ func keysShow() *cobra.Command { Short: "Show a key", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - home, err := cmd.Flags().GetString(flags.FlagHome) - if err != nil { - return err - } - - path := filepath.Join(home, "config.toml") - if _, err := os.Stat(path); err != nil { - return fmt.Errorf("config file does not exist at path '%s'", path) - } + var ( + home = viper.GetString(flags.FlagHome) + path = filepath.Join(home, types.ConfigFileName) + ) - cfg := types.NewConfig() + cfg := types.NewConfig().WithDefaultValues() if err := cfg.LoadFromPath(path); err != nil { return err } + if err := cfg.Validate(); err != nil { + return err + } var ( reader = bufio.NewReader(cmd.InOrStdin()) @@ -172,20 +169,18 @@ func keysList() *cobra.Command { Use: "list", Short: "List all the keys", RunE: func(cmd *cobra.Command, args []string) error { - home, err := cmd.Flags().GetString(flags.FlagHome) - if err != nil { - return err - } - - path := filepath.Join(home, "config.toml") - if _, err := os.Stat(path); err != nil { - return fmt.Errorf("config file does not exist at path '%s'", path) - } + var ( + home = viper.GetString(flags.FlagHome) + path = filepath.Join(home, types.ConfigFileName) + ) - cfg := types.NewConfig() + cfg := types.NewConfig().WithDefaultValues() if err := cfg.LoadFromPath(path); err != nil { return err } + if err := cfg.Validate(); err != nil { + return err + } var ( reader = bufio.NewReader(cmd.InOrStdin()) @@ -196,12 +191,12 @@ func keysList() *cobra.Command { return err } - list, err := kr.List() + infos, err := kr.List() if err != nil { return err } - for _, info := range list { + for _, info := range infos { fmt.Printf("%s | %s | %s\n", info.GetName(), hubtypes.NodeAddress(info.GetAddress().Bytes()), info.GetAddress()) } @@ -219,20 +214,18 @@ func keysDelete() *cobra.Command { Short: "Delete a key", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - home, err := cmd.Flags().GetString(flags.FlagHome) - if err != nil { - return err - } - - path := filepath.Join(home, "config.toml") - if _, err := os.Stat(path); err != nil { - return fmt.Errorf("config file does not exist at path '%s'", path) - } + var ( + home = viper.GetString(flags.FlagHome) + path = filepath.Join(home, types.ConfigFileName) + ) - cfg := types.NewConfig() + cfg := types.NewConfig().WithDefaultValues() if err := cfg.LoadFromPath(path); err != nil { return err } + if err := cfg.Validate(); err != nil { + return err + } var ( reader = bufio.NewReader(cmd.InOrStdin()) diff --git a/cmd/start.go b/cmd/start.go index f06bff7..28d9f0f 100644 --- a/cmd/start.go +++ b/cmd/start.go @@ -18,6 +18,7 @@ import ( "github.com/sentinel-official/hub/params" hubtypes "github.com/sentinel-official/hub/types" "github.com/spf13/cobra" + "github.com/spf13/viper" "github.com/tendermint/tendermint/libs/log" rpchttp "github.com/tendermint/tendermint/rpc/client/http" @@ -36,18 +37,13 @@ func StartCmd() *cobra.Command { Use: "start", Short: "Start VPN node", RunE: func(cmd *cobra.Command, args []string) error { - home, err := cmd.Flags().GetString(flags.FlagHome) - if err != nil { - return err - } - - cfgFilePath := filepath.Join(home, types.ConfigFileName) - if _, err := os.Stat(cfgFilePath); err != nil { - return fmt.Errorf("config file does not exist at path %s", cfgFilePath) - } + var ( + home = viper.GetString(flags.FlagHome) + path = filepath.Join(home, types.ConfigFileName) + ) - cfg := types.NewConfig() - if err := cfg.LoadFromPath(cfgFilePath); err != nil { + cfg := types.NewConfig().WithDefaultValues() + if err := cfg.LoadFromPath(path); err != nil { return err } if err := cfg.Validate(); err != nil { @@ -84,7 +80,7 @@ func StartCmd() *cobra.Command { return err } - info, err := kr.Key(cfg.Node.From) + info, err := kr.Key(cfg.Keyring.From) if err != nil { return err } @@ -93,9 +89,9 @@ func StartCmd() *cobra.Command { WithAccountRetriever(authtypes.AccountRetriever{}). WithChainID(cfg.Chain.ID). WithClient(rpcclient). - WithFrom(cfg.Node.From). + WithFrom(cfg.Keyring.From). WithFromAddress(info.GetAddress()). - WithFromName(cfg.Node.From). + WithFromName(cfg.Keyring.From). WithGas(cfg.Chain.Gas). WithGasAdjustment(cfg.Chain.GasAdjustment). WithGasPrices(cfg.Chain.GasPrices). diff --git a/go.mod b/go.mod index 913746a..f8dcf09 100644 --- a/go.mod +++ b/go.mod @@ -4,11 +4,12 @@ go 1.16 require ( github.com/avast/retry-go v3.0.0+incompatible - github.com/cosmos/cosmos-sdk v0.42.4 + github.com/cosmos/cosmos-sdk v0.42.5 github.com/cosmos/go-bip39 v1.0.0 github.com/gorilla/mux v1.8.0 - github.com/pelletier/go-toml v1.9.1 - github.com/sentinel-official/hub v0.6.1 + github.com/pelletier/go-toml v1.9.2 + github.com/pkg/errors v0.9.1 + github.com/sentinel-official/hub v0.6.2 github.com/spf13/cobra v1.1.3 github.com/spf13/viper v1.7.1 github.com/tendermint/tendermint v0.34.10 @@ -17,6 +18,7 @@ require ( ) replace ( - github.com/cosmos/cosmos-sdk => github.com/sentinel-official/cosmos-sdk v0.42.5-sentinel + github.com/cosmos/cosmos-sdk => github.com/sentinel-official/cosmos-sdk v0.42.6-sentinel github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.3-alpha.regen.1 + google.golang.org/grpc => google.golang.org/grpc v1.33.2 ) diff --git a/go.sum b/go.sum index b28cd77..78f9ec6 100644 --- a/go.sum +++ b/go.sum @@ -1,4 +1,3 @@ -cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= @@ -43,8 +42,8 @@ github.com/apache/thrift v0.13.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= -github.com/armon/go-metrics v0.3.6 h1:x/tmtOF9cDBoXH7XoAGOz2qqm1DknFD1590XmD/DUJ8= -github.com/armon/go-metrics v0.3.6/go.mod h1:4O98XIr/9W0sxpJ8UaYkvjk10Iff7SnFrb4QAOwNTFc= +github.com/armon/go-metrics v0.3.8 h1:oOxq3KPj0WhCuy50EhzwiyMyG2ovRQZpZLXQuOh2a/M= +github.com/armon/go-metrics v0.3.8/go.mod h1:4O98XIr/9W0sxpJ8UaYkvjk10Iff7SnFrb4QAOwNTFc= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/aryann/difflib v0.0.0-20170710044230-e206f873d14a/go.mod h1:DAHtR1m6lCRdSC2Tm3DSWRPvIPr6xNKyeHdqDQSQT+A= github.com/avast/retry-go v3.0.0+incompatible h1:4SOWQ7Qs+oroOTQOYnAHqelpCO0biHSxpiH9JdtuBj0= @@ -85,14 +84,13 @@ github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XL github.com/circonus-labs/circonus-gometrics v2.3.1+incompatible/go.mod h1:nmEj6Dob7S7YxXgwXpfOuvO54S+tGdZdw9fuRZt25Ag= github.com/circonus-labs/circonusllhist v0.1.3/go.mod h1:kMXHVDlOchFAehlya5ePtbp5jckzBHf4XRpQvBOLI+I= github.com/clbanning/x2j v0.0.0-20191024224557-825249438eec/go.mod h1:jMjuTZXRI4dUb/I5gc9Hdhagfvm9+RyrPryS/auMzxE= -github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= github.com/confio/ics23/go v0.0.0-20200817220745-f173e6211efb/go.mod h1:E45NqnlpxGnpfTWL/xauN7MRwEE28T4Dd4uraToOaKg= -github.com/confio/ics23/go v0.6.3 h1:PuGK2V1NJWZ8sSkNDq91jgT/cahFEW9RGp4Y5jxulf0= github.com/confio/ics23/go v0.6.3/go.mod h1:E45NqnlpxGnpfTWL/xauN7MRwEE28T4Dd4uraToOaKg= +github.com/confio/ics23/go v0.6.6 h1:pkOy18YxxJ/r0XFDCnrl4Bjv6h4LkBSpLS6F38mrKL8= +github.com/confio/ics23/go v0.6.6/go.mod h1:E45NqnlpxGnpfTWL/xauN7MRwEE28T4Dd4uraToOaKg= github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= @@ -108,8 +106,9 @@ github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= github.com/cosmos/iavl v0.15.0-rc3.0.20201009144442-230e9bdf52cd/go.mod h1:3xOIaNNX19p0QrX0VqWa6voPRoJRGGYtny+DH8NEPvE= github.com/cosmos/iavl v0.15.0-rc5/go.mod h1:WqoPL9yPTQ85QBMT45OOUzPxG/U/JcJoN7uMjgxke/I= -github.com/cosmos/iavl v0.15.3 h1:xE9r6HW8GeKeoYJN4zefpljZ1oukVScP/7M8oj6SUts= github.com/cosmos/iavl v0.15.3/go.mod h1:OLjQiAQ4fGD2KDZooyJG9yz+p2ao2IAYSbke8mVvSA4= +github.com/cosmos/iavl v0.16.0 h1:ICIOB8xysirTX27GmVAaoeSpeozzgSu9d49w36xkVJA= +github.com/cosmos/iavl v0.16.0/go.mod h1:2A8O/Jz9YwtjqXMO0CjnnbTYEEaovE8jWcwrakH3PoE= github.com/cosmos/ledger-cosmos-go v0.11.1 h1:9JIYsGnXP613pb2vPjFeMMjBI5lEDsEaF6oYorTy6J4= github.com/cosmos/ledger-cosmos-go v0.11.1/go.mod h1:J8//BsAGTo3OC/vDLjMRFLW6q0WAaXvHnVc7ZmE8iUY= github.com/cosmos/ledger-go v0.9.2 h1:Nnao/dLwaVTk1Q5U9THldpUMMXU94BOTWPddSmVB6pI= @@ -147,12 +146,7 @@ github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFP github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= github.com/enigmampc/btcutil v1.0.3-0.20200723161021-e2fb6adb2a25 h1:2vLKys4RBU4pn2T/hjXMbvwTr1Cvy5THHrQkbeY9HRk= github.com/enigmampc/btcutil v1.0.3-0.20200723161021-e2fb6adb2a25/go.mod h1:hTr8+TLQmkUkgcuh3mcr5fjrT9c64ZzsBCdCEC6UppY= -github.com/envoyproxy/go-control-plane v0.6.9/go.mod h1:SBwIajubJHhxtWwsL9s8ss4safvEdbitLhGGK48rN6g= -github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= -github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/facebookgo/ensure v0.0.0-20160127193407-b4ab57deab51 h1:0JZ+dUmQeA8IIVUMzysrX4/AKuQwWhV2dYQuPZdvdSQ= github.com/facebookgo/ensure v0.0.0-20160127193407-b4ab57deab51/go.mod h1:Yg+htXGokKKdzcwhuNDwVvN+uBxDGXJ7G/VN1d8fa64= @@ -188,12 +182,10 @@ github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 h1:ZpnhV/YsD2/4cESfV5+ github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4= github.com/gogo/gateway v1.1.0 h1:u0SuhL9+Il+UbjM9VIE3ntfRujKbvVpFvNB4HbjeVQ0= github.com/gogo/gateway v1.1.0/go.mod h1:S7rR8FRQyG3QFESeSv4l2WnsyzlCLG0CzBbUUo/mbic= -github.com/gogo/googleapis v1.1.0/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= github.com/golang/mock v1.4.4 h1:l75CXGRSwbaYNpl/Z2X1XIIAMSCquvXgpVZDhwEIJsc= @@ -217,8 +209,8 @@ github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/golang/snappy v0.0.2 h1:aeE13tS0IiQgFjYdoL8qN3K1N2bXXtI6Vi51/y7BpMw= -github.com/golang/snappy v0.0.2/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.3-0.20201103224600-674baa8c7fc3 h1:ur2rms48b3Ep1dxh7aUV2FZEQ8jEVO2F6ILKx8ofkAg= +github.com/golang/snappy v0.0.3-0.20201103224600-674baa8c7fc3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0 h1:0udJVsspx3VBr5FwtLhQQtuAsVc79tTq0ocGIPAU6qo= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= @@ -227,11 +219,13 @@ github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= -github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/gofuzz v1.1.1-0.20200604201612-c04b05f3adfa h1:Q75Upo5UN4JbPFURXZ8nLKYUvF85dyFRop/vQ0Rv+64= +github.com/google/gofuzz v1.1.1-0.20200604201612-c04b05f3adfa/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/orderedcode v0.0.1 h1:UzfcAexk9Vhv8+9pNOgRu41f16lHq725vPwnSeiG/Us= github.com/google/orderedcode v0.0.1/go.mod h1:iVyU4/qPKHY5h/wSd6rZZCDcLJNxiWO6dvsYES2Sb20= @@ -258,8 +252,9 @@ github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/ad github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-middleware v1.2.1/go.mod h1:EaizFBKfUKtMIF5iaDEhniwNedqGo9FuLFzppDr3uwI= -github.com/grpc-ecosystem/go-grpc-middleware v1.2.2 h1:FlFbCRLd5Jr4iYXZufAvgWN6Ao0JrI5chLINnUXDDr0= github.com/grpc-ecosystem/go-grpc-middleware v1.2.2/go.mod h1:EaizFBKfUKtMIF5iaDEhniwNedqGo9FuLFzppDr3uwI= +github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 h1:+9834+KizmvFV7pXQGSXQTsaWhq2GjuNUt0aUU0YBYw= +github.com/grpc-ecosystem/go-grpc-middleware v1.3.0/go.mod h1:z0ButlSOZa5vEBq9m2m2hlwIgKw+rp3sdCBRoJY+30Y= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.8.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= @@ -345,11 +340,10 @@ github.com/libp2p/go-buffer-pool v0.0.2 h1:QNK2iAFa8gjAe1SPz6mHSMuCcjs+X1wlHzeOS github.com/libp2p/go-buffer-pool v0.0.2/go.mod h1:MvaB6xw5vOrDl8rYZGLFdKAuk/hRoRZd1Vi32+RXyFM= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= -github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= -github.com/magiconair/properties v1.8.4 h1:8KGKTcQQGm0Kv7vEbKFErAoAOFyyacLStRtQSeYtvkY= -github.com/magiconair/properties v1.8.4/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= +github.com/magiconair/properties v1.8.5 h1:b6kJs+EmPFMYGkow9GiUyCyOvIwYetYJ3fSaWak/Gls= +github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= @@ -371,8 +365,9 @@ github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eI github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/mitchellh/mapstructure v1.3.3 h1:SzB1nHZ2Xi+17FP0zVQBHIZqvwRN9408fJO8h+eeNA8= +github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= @@ -415,8 +410,8 @@ github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5/go.mod h1:/wsWhb9smxS github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw= github.com/openzipkin/zipkin-go v0.2.1/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= -github.com/otiai10/copy v1.4.2 h1:RTiz2sol3eoXPLF4o+YWqEybwfUa/Q2Nkc4ZIUs3fwI= -github.com/otiai10/copy v1.4.2/go.mod h1:XWfuS3CrI0R6IE0FbgHsEazaXO8G0LpMp9o8tos0x4E= +github.com/otiai10/copy v1.6.0 h1:IinKAryFFuPONZ7cm6T6E2QX/vcJwSnlaA5lfoaXIiQ= +github.com/otiai10/copy v1.6.0/go.mod h1:XWfuS3CrI0R6IE0FbgHsEazaXO8G0LpMp9o8tos0x4E= github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE= github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs= github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo= @@ -427,9 +422,9 @@ github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0Mw github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= -github.com/pelletier/go-toml v1.8.0/go.mod h1:D6yutnOGMveHEPV7VQOuvI/gXY61bv+9bAOTRnLElKs= -github.com/pelletier/go-toml v1.9.1 h1:a6qW1EVNZWH9WGI6CsYdD8WAylkoXBS5yv0XHlh17Tc= -github.com/pelletier/go-toml v1.9.1/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= +github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc= +github.com/pelletier/go-toml v1.9.2 h1:7NiByeVF4jKSG1lDF3X8LTIkq2/bu+1uYbIm1eS5tzk= +github.com/pelletier/go-toml v1.9.2/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac= github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 h1:q2e307iGHPdTGp0hoxKjt1H5pDo6utceo3dQVK3I5XQ= github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5/go.mod h1:jvVRKCrJTQWu0XVbaOlby/2lO20uSCHEMzzplHXte1o= @@ -451,8 +446,9 @@ github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5Fsn github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.8.0 h1:zvJNkoCFAnYFNC24FV8nW4JdRJ3GIFcLbg65lL/JDcw= github.com/prometheus/client_golang v1.8.0/go.mod h1:O9VU6huf47PktckDQfMTX0Y8tY0/7TSWwj+ITvv0TnM= +github.com/prometheus/client_golang v1.10.0 h1:/o0BDeWzLWXNZ+4q5gXltUvaMpJqckTa+jTNoB+z4cg= +github.com/prometheus/client_golang v1.10.0/go.mod h1:WJM3cc3yu7XKBKa/I8WeZm+V3eltZnBwfENSU7mdogU= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -468,16 +464,18 @@ github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt2 github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4= github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= github.com/prometheus/common v0.14.0/go.mod h1:U+gB1OBLb1lF3O42bTCL+FK18tX9Oar16Clt/msog/s= -github.com/prometheus/common v0.15.0 h1:4fgOnadei3EZvgRwxJ7RMpG1k1pOZth5Pc13tyspaKM= -github.com/prometheus/common v0.15.0/go.mod h1:U+gB1OBLb1lF3O42bTCL+FK18tX9Oar16Clt/msog/s= +github.com/prometheus/common v0.18.0/go.mod h1:U+gB1OBLb1lF3O42bTCL+FK18tX9Oar16Clt/msog/s= +github.com/prometheus/common v0.23.0 h1:GXWvPYuTUenIa+BhOq/x+L/QZzCqASkVRny5KTlPDGM= +github.com/prometheus/common v0.23.0/go.mod h1:H6QK/N6XVT42whUeIdI3dp36w49c+/iMDk7UAI2qm7Q= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= -github.com/prometheus/procfs v0.2.0 h1:wH4vA7pcjKuZzjF7lM8awk4fnuJO6idemZXoKnULUx4= github.com/prometheus/procfs v0.2.0/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/prometheus/procfs v0.6.0 h1:mxy4L2jP6qMonqmq+aTtOx1ifVWUgG/TAmntgbh3xv4= +github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= github.com/rakyll/statik v0.1.7 h1:OF3QCZUuyPxuGEP7B4ypUa7sB/iHtqOTDYZXGM8KOdQ= github.com/rakyll/statik v0.1.7/go.mod h1:AlZONWzMtEnMs7W4e/1LURLiI49pIMmp6V9Unghqrcc= @@ -494,8 +492,8 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rs/cors v1.7.0 h1:+88SsELBHx5r+hZ8TCkggzSstaWNbDvThkVK8H6f9ik= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= -github.com/rs/zerolog v1.20.0 h1:38k9hgtUBdxFwE34yS8rTHmHBa4eN16E4DJlv177LNs= -github.com/rs/zerolog v1.20.0/go.mod h1:IzD0RJ65iWH0w97OQQebJEvTZYvsCUm9WVLWBQrJRjo= +github.com/rs/zerolog v1.21.0 h1:Q3vdXlfLNT+OftyBHsU0Y445MD+8m8axjKgf2si0QcM= +github.com/rs/zerolog v1.21.0/go.mod h1:ZPhntP/xmq1nnND05hhpAh2QMhSsA4UN3MGZ6O2J3hM= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= @@ -504,10 +502,10 @@ github.com/sasha-s/go-deadlock v0.2.0/go.mod h1:StQn567HiB1fF2yJ44N9au7wOhrPS3iZ github.com/sasha-s/go-deadlock v0.2.1-0.20190427202633-1595213edefa h1:0U2s5loxrTy6/VgfVoLuVLFJcURKLH49ie0zSch7gh4= github.com/sasha-s/go-deadlock v0.2.1-0.20190427202633-1595213edefa/go.mod h1:F73l+cr82YSh10GxyRI6qZiCgK64VaZjwesgfQ1/iLM= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/sentinel-official/cosmos-sdk v0.42.5-sentinel h1:GJd65ZkV5bggGdgIew7XkHWCetz4sEP0cUSiYOUdHZQ= -github.com/sentinel-official/cosmos-sdk v0.42.5-sentinel/go.mod h1:I1Zw1zmU4rA/NITaakTb71pXQnQrWyFBhqo3WSeg0vA= -github.com/sentinel-official/hub v0.6.1 h1:zzolmPqaNpJojWcEbftYoxy9P2q4btv4/R/BvMnlUTM= -github.com/sentinel-official/hub v0.6.1/go.mod h1:AW49ee8S7m7VeIq3/XIq4r5Huu7JabGEhRJlMrzfthQ= +github.com/sentinel-official/cosmos-sdk v0.42.6-sentinel h1:c0umzLEXlYi5pPoi329i2ULMVUmAQg8Y1mtqH6HyREs= +github.com/sentinel-official/cosmos-sdk v0.42.6-sentinel/go.mod h1:3JyT+Ud7QRTO1/ikncNqVhaF526ZKNqh2HGMqXn+QHE= +github.com/sentinel-official/hub v0.6.2 h1:fquwPh7F6f124iQIletHW32QG67aWAb5C4kgj1RBE3g= +github.com/sentinel-official/hub v0.6.2/go.mod h1:OvUTO+3wTH+EBZY/WeEhezKPpVf13BYxK0yXD404AIg= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= @@ -556,7 +554,6 @@ github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoH github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= @@ -575,7 +572,6 @@ github.com/tendermint/go-amino v0.16.0/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoM github.com/tendermint/tendermint v0.34.0-rc4/go.mod h1:yotsojf2C1QBOw4dZrTcxbyxmPUrT4hNuOQWX9XUwB4= github.com/tendermint/tendermint v0.34.0-rc6/go.mod h1:ugzyZO5foutZImv0Iyx/gOFCX6mjJTgbLHTwi17VDVg= github.com/tendermint/tendermint v0.34.0/go.mod h1:Aj3PIipBFSNO21r+Lq3TtzQ+uKESxkbA3yo/INM4QwQ= -github.com/tendermint/tendermint v0.34.9/go.mod h1:kl4Z1JwGx1I+u1SXIzMDy7Z3T8LiMeCAOnzNn6AIMT4= github.com/tendermint/tendermint v0.34.10 h1:wBOc/It8sh/pVH9np2V5fBvRmIyFN/bUrGPx+eAHexs= github.com/tendermint/tendermint v0.34.10/go.mod h1:aeHL7alPh4uTBIJQ8mgFEE8VwJLXI1VD3rVOmH2Mcy0= github.com/tendermint/tm-db v0.6.2/go.mod h1:GYtQ67SUvATOcoY8/+x6ylk8Qo02BQyLrAs+yAcLvGI= @@ -643,7 +639,6 @@ golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE golang.org/x/exp v0.0.0-20200331195152-e8c3332aa8e5/go.mod h1:4M0jN8W1tt0AVLNr8HDosyJCDCDuyL9N9+3m7wDWgKw= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= -golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= @@ -661,7 +656,6 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -702,10 +696,10 @@ golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -746,9 +740,12 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210309074719-68d13333faf2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4 h1:EZ2mChiOa8udjfp6rRmswTbtZN/QzUQp4ptM4rnjHvc= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007 h1:gG67DSER+11cZvqIMb8S8bt0vZtiN6xWYARwirrOSfE= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= @@ -762,9 +759,7 @@ golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxb golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= @@ -777,7 +772,6 @@ golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgw golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190828213141-aed303cbaa74/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= @@ -801,7 +795,6 @@ google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -825,32 +818,10 @@ google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20201111145450-ac7456db90a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20201119123407-9b1e624d6bc4/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210114201628-6edceaf6022f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210406143921-e86de6bf7a46 h1:f4STrQZf8jaowsiUitigvrqMCCM4QJH1A2JCSI7U1ow= -google.golang.org/genproto v0.0.0-20210406143921-e86de6bf7a46/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= -google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= -google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.19.1/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.20.0/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM= -google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= -google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -google.golang.org/grpc v1.22.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= -google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= -google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= -google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.32.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= +google.golang.org/genproto v0.0.0-20210524171403-669157292da3 h1:xFyh6GBb+NO1L0xqb978I3sBPQpk6FrKO0jJGRvdj/0= +google.golang.org/genproto v0.0.0-20210524171403-669157292da3/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/grpc v1.33.2 h1:EQyQC3sa8M+p6Ulc8yy9SWSS2GVwyRc83gAbG8lrl4o= google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= -google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.37.0 h1:uSZWeQJX5j11bIQ4AJoj+McDBo29cY1MCoC1wO3ts+c= -google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -875,8 +846,9 @@ gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qS gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o= -gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno= gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/ini.v1 v1.61.0 h1:LBCdW4FmFYL4s/vDZD1RQYX7oAR6IjujCYgMdbHBR10= +gopkg.in/ini.v1 v1.61.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= @@ -893,7 +865,6 @@ gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/lite/tx.go b/lite/tx.go index f65afe6..3c1b9c3 100644 --- a/lite/tx.go +++ b/lite/tx.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/errors" + abcitypes "github.com/tendermint/tendermint/abci/types" ) func (c *Client) BroadcastTx(messages ...sdk.Msg) (res *sdk.TxResponse, err error) { @@ -55,7 +56,7 @@ func (c *Client) BroadcastTx(messages ...sdk.Msg) (res *sdk.TxResponse, err erro switch { case err != nil: return err - case res.Code == 0: + case res.Code == abcitypes.CodeTypeOK: return nil case res.Code == errors.ErrTxInMempoolCache.ABCICode(): return nil diff --git a/main.go b/main.go index dec3746..8051bb1 100644 --- a/main.go +++ b/main.go @@ -2,6 +2,7 @@ package main import ( "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/version" hubtypes "github.com/sentinel-official/hub/types" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -11,10 +12,12 @@ import ( "github.com/sentinel-official/dvpn-node/types" ) -func main() { +func init() { hubtypes.GetConfig().Seal() cobra.EnableCommandSorting = false +} +func main() { root := &cobra.Command{ Use: "sentinel-dvpn-node", SilenceUsage: true, @@ -27,6 +30,8 @@ func main() { wireguard.Command(), flags.LineBreak, cmd.StartCmd(), + flags.LineBreak, + version.NewVersionCommand(), ) root.PersistentFlags().String(flags.FlagHome, types.DefaultHomeDirectory, "home") diff --git a/types/config.go b/types/config.go index ba1d7bf..ccb69a3 100644 --- a/types/config.go +++ b/types/config.go @@ -2,16 +2,17 @@ package types import ( "bytes" - "encoding/json" "fmt" "io/ioutil" "strings" "text/template" "time" - "github.com/pelletier/go-toml" - - wgtypes "github.com/sentinel-official/dvpn-node/services/wireguard/types" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/pkg/errors" + hubtypes "github.com/sentinel-official/hub/types" + "github.com/spf13/viper" ) var ( @@ -30,17 +31,16 @@ peers = {{ .Handshake.Peers }} [keyring] backend = "{{ .Keyring.Backend }}" +from = "{{ .Keyring.From }}" [node] -from = "{{ .Node.From }}" -interval_sessions = {{ .Node.IntervalSessions }} -interval_status = {{ .Node.IntervalStatus }} +interval_sessions = "{{ .Node.IntervalSessions }}" +interval_status = "{{ .Node.IntervalStatus }}" listen_on = "{{ .Node.ListenOn }}" moniker = "{{ .Node.Moniker }}" price = "{{ .Node.Price }}" provider = "{{ .Node.Provider }}" remote_url = "{{ .Node.RemoteURL }}" -type = {{ .Node.Type }} `) t = func() *template.Template { @@ -53,148 +53,227 @@ type = {{ .Node.Type }} }() ) -type Config struct { - Chain struct { - GasAdjustment float64 `json:"gas_adjustment"` - GasPrices string `json:"gas_prices"` - Gas uint64 `json:"gas"` - ID string `json:"id"` - RPCAddress string `json:"rpc_address"` - SimulateAndExecute bool `json:"simulate_and_execute"` - } `json:"chain"` - Handshake struct { - Enable bool `json:"enable"` - Peers uint64 `json:"peers"` - } - Keyring struct { - Backend string `json:"backend"` - } - Node struct { - From string `json:"from"` - IntervalSessions int64 `json:"interval_sessions"` - IntervalStatus int64 `json:"interval_status"` - ListenOn string `json:"listen_on"` - Moniker string `json:"moniker"` - Price string `json:"price"` - Provider string `json:"provider"` - RemoteURL string `json:"remote_url"` - Type uint64 `json:"type"` - } `json:"node"` +type ChainConfig struct { + GasAdjustment float64 `mapstructure:"gas_adjustment"` + GasPrices string `mapstructure:"gas_prices"` + Gas uint64 `mapstructure:"gas"` + ID string `mapstructure:"id"` + RPCAddress string `mapstructure:"rpc_address"` + SimulateAndExecute bool `mapstructure:"simulate_and_execute"` } -func NewConfig() *Config { - return &Config{} +func NewChainConfig() *ChainConfig { + return &ChainConfig{} } -func (c *Config) WithDefaultValues() *Config { - c.Chain.Gas = 1e5 - c.Chain.GasAdjustment = 1.05 - c.Chain.GasPrices = "0.1tsent" - c.Chain.ID = "sentinel-turing-4" - c.Chain.RPCAddress = "https://rpc.turing.sentinel.co:443" - c.Chain.SimulateAndExecute = true - - c.Handshake.Enable = true - c.Handshake.Peers = 8 - - c.Keyring.Backend = "file" - - c.Node.From = "" - c.Node.IntervalSessions = 8 * time.Minute.Nanoseconds() - c.Node.IntervalStatus = 4 * time.Minute.Nanoseconds() - c.Node.ListenOn = "0.0.0.0:8585" - c.Node.Moniker = "" - c.Node.Price = "50tsent" - c.Node.Provider = "" - c.Node.RemoteURL = "" - c.Node.Type = wgtypes.Type +func (c *ChainConfig) Validate() error { + if c.GasAdjustment <= 0 { + return errors.New("gas_adjustment must be positive") + } + if _, err := sdk.ParseCoinsNormalized(c.GasPrices); err != nil { + return errors.Wrap(err, "invalid gas_prices") + } + if c.Gas <= 0 { + return errors.New("gas must be positive") + } + if c.ID == "" { + return errors.New("id cannot be empty") + } + if c.RPCAddress == "" { + return errors.New("rpc_address cannot be empty") + } + + return nil +} + +func (c *ChainConfig) WithDefaultValues() *ChainConfig { + c.GasAdjustment = 1.05 + c.GasPrices = "0.1udvpn" + c.Gas = 200000 + c.ID = "" + c.RPCAddress = "https://rpc.sentinel.co:443" + c.SimulateAndExecute = true return c } -func (c *Config) LoadFromPath(path string) error { - data, err := ioutil.ReadFile(path) - if err != nil { - return err - } +type HandshakeConfig struct { + Enable bool `mapstructure:"enable"` + Peers uint64 `mapstructure:"peers"` +} - if len(data) == 0 { - *c = Config{} - return nil - } +func NewHandshakeConfig() *HandshakeConfig { + return &HandshakeConfig{} +} - tree, err := toml.LoadBytes(data) - if err != nil { - return err +func (c *HandshakeConfig) Validate() error { + if c.Enable { + if c.Peers <= 0 { + return errors.New("peers must be positive") + } } - data, err = json.Marshal(tree.ToMap()) - if err != nil { - return err - } + return nil +} + +func (c *HandshakeConfig) WithDefaultValues() *HandshakeConfig { + c.Enable = true + c.Peers = 8 - return json.Unmarshal(data, c) + return c } -func (c *Config) SaveToPath(path string) error { - var buffer bytes.Buffer - if err := t.Execute(&buffer, c); err != nil { - return err - } +type KeyringConfig struct { + Backend string `mapstructure:"backend"` + From string `mapstructure:"from"` +} - return ioutil.WriteFile(path, buffer.Bytes(), 0600) +func NewKeyringConfig() *KeyringConfig { + return &KeyringConfig{} } -func (c *Config) String() string { - var buffer bytes.Buffer - if err := t.Execute(&buffer, c); err != nil { - panic(err) +func (c *KeyringConfig) Validate() error { + if c.Backend == "" { + return errors.New("backend cannot be empty") + } + if c.Backend != keyring.BackendFile && c.Backend != keyring.BackendTest { + return fmt.Errorf("unknown backend %s", c.Backend) + } + if c.From == "" { + return errors.New("from cannot be empty") } - return buffer.String() + return nil } -func (c *Config) Validate() error { - if c.Chain.GasAdjustment < 0 { - return fmt.Errorf("invalid chain->gas_adjustment; expected non-negative value") +func (c *KeyringConfig) WithDefaultValues() *KeyringConfig { + c.Backend = keyring.BackendFile + + return c +} + +type NodeConfig struct { + IntervalSessions time.Duration `mapstructure:"interval_sessions"` + IntervalStatus time.Duration `mapstructure:"interval_status"` + ListenOn string `mapstructure:"listen_on"` + Moniker string `mapstructure:"moniker"` + Price string `mapstructure:"price"` + Provider string `mapstructure:"provider"` + RemoteURL string `mapstructure:"remote_url"` +} + +func NewNodeConfig() *NodeConfig { + return &NodeConfig{} +} + +func (c *NodeConfig) Validate() error { + if c.IntervalSessions <= 0 { + return errors.New("interval_sessions must be positive") } - if c.Chain.ID == "" { - return fmt.Errorf("invalid chain->id; expected non-empty value") + if c.IntervalStatus <= 0 { + return errors.New("interval_status must be positive") } - if c.Chain.RPCAddress == "" { - return fmt.Errorf("invalid chain->rpc_address; expected non-empty value") + if c.ListenOn == "" { + return errors.New("listen_on cannot be empty") } - - if c.Handshake.Peers == 0 { - return fmt.Errorf("invalid handshake->peers; expected positive value") + if c.Price == "" && c.Provider == "" { + return errors.New("both price and provider cannot be empty") } - - if c.Keyring.Backend == "" { - return fmt.Errorf("invalid keyring->backend; expected non-empty value") + if c.Price != "" && c.Provider != "" { + return errors.New("either price or provider must be empty") + } + if _, err := sdk.ParseCoinNormalized(c.Price); err != nil { + return errors.Wrap(err, "invalid price") + } + if _, err := hubtypes.ProvAddressFromBech32(c.Provider); err != nil { + return errors.Wrap(err, "invalid provider") } + if c.RemoteURL == "" { + return errors.New("remote_url cannot be empty") + } + + return nil +} + +func (c *NodeConfig) WithDefaultValues() *NodeConfig { + c.IntervalSessions = 0.9 * 120 * time.Minute + c.IntervalStatus = 0.9 * 60 * time.Minute + c.ListenOn = "0.0.0.0:8585" + + return c +} + +type Config struct { + Chain *ChainConfig `mapstructure:"chain"` + Handshake *HandshakeConfig `mapstructure:"handshake"` + Keyring *KeyringConfig `mapstructure:"keyring"` + Node *NodeConfig `mapstructure:"node"` +} - if c.Node.From == "" { - return fmt.Errorf("invalid node->from; expected non-empty value") +func NewConfig() *Config { + return &Config{ + Chain: NewChainConfig(), + Handshake: NewHandshakeConfig(), + Keyring: NewKeyringConfig(), + Node: NewNodeConfig(), } - if c.Node.IntervalSessions <= 0 { - return fmt.Errorf("invalid node->interval_sessions; expected positive value") +} + +func (c *Config) Validate() error { + if err := c.Chain.Validate(); err != nil { + return errors.Wrapf(err, "invalid section chain") } - if c.Node.IntervalStatus <= 0 { - return fmt.Errorf("invalid node->interval_status; expected positive value") + if err := c.Handshake.Validate(); err != nil { + return errors.Wrapf(err, "invalid section handshake") } - if c.Node.ListenOn == "" { - return fmt.Errorf("invalid node->listen_on; expected non-empty value") + if err := c.Keyring.Validate(); err != nil { + return errors.Wrapf(err, "invalid section keyring") } - if (c.Node.Provider != "" && c.Node.Price != "") || - (c.Node.Provider == "" && c.Node.Price == "") { - return fmt.Errorf("invalid combination of node->provider and node->price; expected one of them to be empty") + if err := c.Node.Validate(); err != nil { + return errors.Wrapf(err, "invalid section node") } - if c.Node.RemoteURL == "" { - return fmt.Errorf("invalid node->remote_url; expected non-empty value") + + return nil +} + +func (c *Config) WithDefaultValues() *Config { + c.Chain = c.Chain.WithDefaultValues() + c.Handshake = c.Handshake.WithDefaultValues() + c.Keyring = c.Keyring.WithDefaultValues() + c.Node = c.Node.WithDefaultValues() + + return c +} + +func (c *Config) LoadFromPath(path string) error { + v := viper.New() + v.SetConfigFile(path) + + if err := v.ReadInConfig(); err != nil { + return err } - if c.Node.Type == 0 { - return fmt.Errorf("invalid node->type; expected positive value") + + if err := v.Unmarshal(c); err != nil { + return err } return nil } + +func (c *Config) SaveToPath(path string) error { + var buffer bytes.Buffer + if err := t.Execute(&buffer, c); err != nil { + return err + } + + return ioutil.WriteFile(path, buffer.Bytes(), 0600) +} + +func (c *Config) String() string { + var buffer bytes.Buffer + if err := t.Execute(&buffer, c); err != nil { + panic(err) + } + + return buffer.String() +} From a8e60a5f503dd0b5ce9617afd20a75ddad4de3e0 Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Sun, 6 Jun 2021 20:30:45 +0530 Subject: [PATCH 03/26] Added set configuration command --- cmd/config.go | 44 ++++++++++++++++++++++++++++++++++++++++---- cmd/keys.go | 30 +++++++++++++++++++++--------- cmd/start.go | 9 ++++++--- types/config.go | 28 +++++++++++++--------------- 4 files changed, 80 insertions(+), 31 deletions(-) diff --git a/cmd/config.go b/cmd/config.go index 32b799a..3e1061b 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -21,6 +21,7 @@ func ConfigCmd() *cobra.Command { cmd.AddCommand( configInit(), configShow(), + configSet(), ) return cmd @@ -30,7 +31,7 @@ func configInit() *cobra.Command { cmd := &cobra.Command{ Use: "init", Short: "Initialize the default configuration", - RunE: func(cmd *cobra.Command, args []string) error { + RunE: func(cmd *cobra.Command, _ []string) error { var ( home = viper.GetString(flags.FlagHome) path = filepath.Join(home, types.ConfigFileName) @@ -65,14 +66,17 @@ func configShow() *cobra.Command { cmd := &cobra.Command{ Use: "show", Short: "Show the configuration", - RunE: func(cmd *cobra.Command, args []string) error { + RunE: func(_ *cobra.Command, _ []string) error { var ( home = viper.GetString(flags.FlagHome) path = filepath.Join(home, types.ConfigFileName) ) - cfg := types.NewConfig().WithDefaultValues() - if err := cfg.LoadFromPath(path); err != nil { + v := viper.New() + v.SetConfigFile(path) + + cfg, err := types.ReadInConfig(v) + if err != nil { return err } @@ -83,3 +87,35 @@ func configShow() *cobra.Command { return cmd } + +func configSet() *cobra.Command { + cmd := &cobra.Command{ + Use: "set [key] [value]", + Short: "Set configuration", + Args: cobra.ExactArgs(2), + RunE: func(_ *cobra.Command, args []string) error { + var ( + home = viper.GetString(flags.FlagHome) + path = filepath.Join(home, types.ConfigFileName) + ) + + v := viper.New() + v.SetConfigFile(path) + + cfg, err := types.ReadInConfig(v) + if err != nil { + return err + } + + v.Set(args[0], args[1]) + + if err := v.Unmarshal(cfg); err != nil { + return err + } + + return cfg.SaveToPath(path) + }, + } + + return cmd +} diff --git a/cmd/keys.go b/cmd/keys.go index 3afaba1..da85f92 100644 --- a/cmd/keys.go +++ b/cmd/keys.go @@ -46,8 +46,11 @@ func keysAdd() *cobra.Command { path = filepath.Join(home, types.ConfigFileName) ) - cfg := types.NewConfig().WithDefaultValues() - if err := cfg.LoadFromPath(path); err != nil { + v := viper.New() + v.SetConfigFile(path) + + cfg, err := types.ReadInConfig(v) + if err != nil { return err } if err := cfg.Validate(); err != nil { @@ -132,8 +135,11 @@ func keysShow() *cobra.Command { path = filepath.Join(home, types.ConfigFileName) ) - cfg := types.NewConfig().WithDefaultValues() - if err := cfg.LoadFromPath(path); err != nil { + v := viper.New() + v.SetConfigFile(path) + + cfg, err := types.ReadInConfig(v) + if err != nil { return err } if err := cfg.Validate(); err != nil { @@ -168,14 +174,17 @@ func keysList() *cobra.Command { cmd := &cobra.Command{ Use: "list", Short: "List all the keys", - RunE: func(cmd *cobra.Command, args []string) error { + RunE: func(cmd *cobra.Command, _ []string) error { var ( home = viper.GetString(flags.FlagHome) path = filepath.Join(home, types.ConfigFileName) ) - cfg := types.NewConfig().WithDefaultValues() - if err := cfg.LoadFromPath(path); err != nil { + v := viper.New() + v.SetConfigFile(path) + + cfg, err := types.ReadInConfig(v) + if err != nil { return err } if err := cfg.Validate(); err != nil { @@ -219,8 +228,11 @@ func keysDelete() *cobra.Command { path = filepath.Join(home, types.ConfigFileName) ) - cfg := types.NewConfig().WithDefaultValues() - if err := cfg.LoadFromPath(path); err != nil { + v := viper.New() + v.SetConfigFile(path) + + cfg, err := types.ReadInConfig(v) + if err != nil { return err } if err := cfg.Validate(); err != nil { diff --git a/cmd/start.go b/cmd/start.go index 28d9f0f..1302981 100644 --- a/cmd/start.go +++ b/cmd/start.go @@ -36,14 +36,17 @@ func StartCmd() *cobra.Command { cmd := &cobra.Command{ Use: "start", Short: "Start VPN node", - RunE: func(cmd *cobra.Command, args []string) error { + RunE: func(cmd *cobra.Command, _ []string) error { var ( home = viper.GetString(flags.FlagHome) path = filepath.Join(home, types.ConfigFileName) ) - cfg := types.NewConfig().WithDefaultValues() - if err := cfg.LoadFromPath(path); err != nil { + v := viper.New() + v.SetConfigFile(path) + + cfg, err := types.ReadInConfig(v) + if err != nil { return err } if err := cfg.Validate(); err != nil { diff --git a/types/config.go b/types/config.go index ccb69a3..8f718dd 100644 --- a/types/config.go +++ b/types/config.go @@ -245,21 +245,6 @@ func (c *Config) WithDefaultValues() *Config { return c } -func (c *Config) LoadFromPath(path string) error { - v := viper.New() - v.SetConfigFile(path) - - if err := v.ReadInConfig(); err != nil { - return err - } - - if err := v.Unmarshal(c); err != nil { - return err - } - - return nil -} - func (c *Config) SaveToPath(path string) error { var buffer bytes.Buffer if err := t.Execute(&buffer, c); err != nil { @@ -277,3 +262,16 @@ func (c *Config) String() string { return buffer.String() } + +func ReadInConfig(v *viper.Viper) (*Config, error) { + cfg := NewConfig().WithDefaultValues() + if err := v.ReadInConfig(); err != nil { + return nil, err + } + + if err := v.Unmarshal(cfg); err != nil { + return nil, err + } + + return cfg, nil +} From 51eece2558b9e9517589bc392ef2081f40e09464 Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Sun, 6 Jun 2021 20:40:40 +0530 Subject: [PATCH 04/26] Fix validation of provider address --- cmd/config.go | 2 +- types/config.go | 12 ++++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/cmd/config.go b/cmd/config.go index 3e1061b..cd5e96b 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -91,7 +91,7 @@ func configShow() *cobra.Command { func configSet() *cobra.Command { cmd := &cobra.Command{ Use: "set [key] [value]", - Short: "Set configuration", + Short: "Set the configuration", Args: cobra.ExactArgs(2), RunE: func(_ *cobra.Command, args []string) error { var ( diff --git a/types/config.go b/types/config.go index 8f718dd..c559e37 100644 --- a/types/config.go +++ b/types/config.go @@ -182,11 +182,15 @@ func (c *NodeConfig) Validate() error { if c.Price != "" && c.Provider != "" { return errors.New("either price or provider must be empty") } - if _, err := sdk.ParseCoinNormalized(c.Price); err != nil { - return errors.Wrap(err, "invalid price") + if c.Price != "" { + if _, err := sdk.ParseCoinNormalized(c.Price); err != nil { + return errors.Wrap(err, "invalid price") + } } - if _, err := hubtypes.ProvAddressFromBech32(c.Provider); err != nil { - return errors.Wrap(err, "invalid provider") + if c.Provider != "" { + if _, err := hubtypes.ProvAddressFromBech32(c.Provider); err != nil { + return errors.Wrap(err, "invalid provider") + } } if c.RemoteURL == "" { return errors.New("remote_url cannot be empty") From c7d53026b1014f165cbcfbb848b752f5be3aa769 Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Sun, 6 Jun 2021 21:17:25 +0530 Subject: [PATCH 05/26] Modified output format for keys --- cmd/keys.go | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/cmd/keys.go b/cmd/keys.go index da85f92..cca088b 100644 --- a/cmd/keys.go +++ b/cmd/keys.go @@ -4,6 +4,7 @@ import ( "bufio" "fmt" "path/filepath" + "text/tabwriter" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/input" @@ -111,9 +112,11 @@ func keysAdd() *cobra.Command { return err } - fmt.Printf("Address: %s\n", hubtypes.NodeAddress(info.GetAddress().Bytes())) - fmt.Printf("Operator: %s\n", info.GetAddress()) - fmt.Printf("Mnemonic: %s\n", mnemonic) + fmt.Fprintf(cmd.ErrOrStderr(), "operator: %s\n", info.GetAddress()) + fmt.Fprintf(cmd.ErrOrStderr(), "address: %s\n", hubtypes.NodeAddress(info.GetAddress().Bytes())) + fmt.Fprintln(cmd.ErrOrStderr(), "") + fmt.Fprintln(cmd.ErrOrStderr(), "**Important** write this mnemonic phrase in a safe place") + fmt.Fprintln(cmd.ErrOrStderr(), mnemonic) return nil }, @@ -160,8 +163,8 @@ func keysShow() *cobra.Command { return err } - fmt.Printf("Address: %s\n", hubtypes.NodeAddress(info.GetAddress().Bytes())) - fmt.Printf("Operator: %s\n", info.GetAddress()) + fmt.Printf("operator: %s\n", info.GetAddress()) + fmt.Printf("address: %s\n", hubtypes.NodeAddress(info.GetAddress().Bytes())) return nil }, @@ -205,12 +208,13 @@ func keysList() *cobra.Command { return err } + w := tabwriter.NewWriter(cmd.OutOrStdout(), 1, 1, 1, ' ', 0) for _, info := range infos { - fmt.Printf("%s | %s | %s\n", - info.GetName(), hubtypes.NodeAddress(info.GetAddress().Bytes()), info.GetAddress()) + fmt.Fprintf(w, "%s\t%s\t%s\n", + info.GetName(), info.GetAddress(), hubtypes.NodeAddress(info.GetAddress().Bytes())) } - return nil + return w.Flush() }, } From fe006e9fd27000e79e216b8089179a9b048a5aa1 Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Wed, 9 Jun 2021 22:56:59 +0530 Subject: [PATCH 06/26] Using pointers in status response --- rest/status/handlers.go | 12 +++++++----- rest/status/requests.go | 1 - rest/status/responses.go | 6 +++--- 3 files changed, 10 insertions(+), 9 deletions(-) delete mode 100644 rest/status/requests.go diff --git a/rest/status/handlers.go b/rest/status/handlers.go index 59fe4ad..054ba27 100644 --- a/rest/status/handlers.go +++ b/rest/status/handlers.go @@ -3,25 +3,27 @@ package status import ( "net/http" + "github.com/cosmos/cosmos-sdk/version" + "github.com/sentinel-official/dvpn-node/context" "github.com/sentinel-official/dvpn-node/utils" ) func HandlerGetStatus(ctx *context.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - utils.WriteResultToResponse(w, http.StatusOK, ResponseGetStatus{ + utils.WriteResultToResponse(w, http.StatusOK, &ResponseGetStatus{ Address: ctx.Address().String(), - Bandwidth: Bandwidth{ + Bandwidth: &Bandwidth{ Upload: ctx.Bandwidth().Upload.Int64(), Download: ctx.Bandwidth().Download.Int64(), }, - Handshake: Handshake{ + Handshake: &Handshake{ Enable: ctx.Config().Handshake.Enable, Peers: ctx.Config().Handshake.Peers, }, IntervalSessions: ctx.IntervalSessions(), IntervalStatus: ctx.IntervalStatus(), - Location: Location{ + Location: &Location{ City: ctx.Location().City, Country: ctx.Location().Country, Latitude: ctx.Location().Latitude, @@ -33,7 +35,7 @@ func HandlerGetStatus(ctx *context.Context) http.HandlerFunc { Price: ctx.Price().String(), Provider: ctx.Provider().String(), Type: ctx.Type(), - Version: ctx.Version(), + Version: version.Version, }) } } diff --git a/rest/status/requests.go b/rest/status/requests.go deleted file mode 100644 index 6c12ae3..0000000 --- a/rest/status/requests.go +++ /dev/null @@ -1 +0,0 @@ -package status diff --git a/rest/status/responses.go b/rest/status/responses.go index 421a164..e1812ee 100644 --- a/rest/status/responses.go +++ b/rest/status/responses.go @@ -24,11 +24,11 @@ type ( type ( ResponseGetStatus struct { Address string `json:"address"` - Bandwidth Bandwidth `json:"bandwidth"` - Handshake Handshake `json:"handshake"` + Bandwidth *Bandwidth `json:"bandwidth"` + Handshake *Handshake `json:"handshake"` IntervalSessions time.Duration `json:"interval_sessions"` IntervalStatus time.Duration `json:"interval_status"` - Location Location `json:"location"` + Location *Location `json:"location"` Moniker string `json:"moniker"` Operator string `json:"operator"` Peers int `json:"peers"` From b93da409309b3b20b99a48dc382093714887d36f Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Wed, 9 Jun 2021 22:58:00 +0530 Subject: [PATCH 07/26] Using gRPC code instead of substring search --- lite/query.go | 10 +++++----- utils/errors.go | 7 ++++--- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/lite/query.go b/lite/query.go index 0225d54..3c84fa6 100644 --- a/lite/query.go +++ b/lite/query.go @@ -25,7 +25,7 @@ func (c *Client) QueryAccount(address sdk.AccAddress) (authtypes.AccountI, error res, err := qc.Account(context.Background(), &authtypes.QueryAccountRequest{Address: address.String()}) if err != nil { - return nil, utils.IsNotFoundError(err) + return nil, utils.ValidError(err) } if err := c.ctx.InterfaceRegistry.UnpackAny(res.Account, &account); err != nil { @@ -43,7 +43,7 @@ func (c *Client) QueryNode(address hubtypes.NodeAddress) (*nodetypes.Node, error res, err := qc.QueryNode(context.Background(), nodetypes.NewQueryNodeRequest(address)) if err != nil { - return nil, utils.IsNotFoundError(err) + return nil, utils.ValidError(err) } return &res.Node, nil @@ -57,7 +57,7 @@ func (c *Client) QuerySubscription(id uint64) (*subscriptiontypes.Subscription, res, err := qc.QuerySubscription(context.Background(), subscriptiontypes.NewQuerySubscriptionRequest(id)) if err != nil { - return nil, utils.IsNotFoundError(err) + return nil, utils.ValidError(err) } return &res.Subscription, nil @@ -71,7 +71,7 @@ func (c *Client) QueryQuota(id uint64, address sdk.AccAddress) (*subscriptiontyp res, err := qc.QueryQuota(context.Background(), subscriptiontypes.NewQueryQuotaRequest(id, address)) if err != nil { - return nil, utils.IsNotFoundError(err) + return nil, utils.ValidError(err) } return &res.Quota, nil @@ -85,7 +85,7 @@ func (c *Client) QuerySession(id uint64) (*sessiontypes.Session, error) { res, err := qc.QuerySession(context.Background(), sessiontypes.NewQuerySessionRequest(id)) if err != nil { - return nil, utils.IsNotFoundError(err) + return nil, utils.ValidError(err) } return &res.Session, nil diff --git a/utils/errors.go b/utils/errors.go index d0bc033..f88e911 100644 --- a/utils/errors.go +++ b/utils/errors.go @@ -1,11 +1,12 @@ package utils import ( - "strings" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) -func IsNotFoundError(v error) error { - if strings.Contains(v.Error(), "code = NotFound") { +func ValidError(v error) error { + if status.Code(v) == codes.NotFound { return nil } From baa0553d08259c8882a35c4015fd93d11b2ec850 Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Wed, 9 Jun 2021 22:58:39 +0530 Subject: [PATCH 08/26] Added more validation for add-session request body --- rest/session/requests.go | 14 +++++++++++--- rest/session/responses.go | 1 - 2 files changed, 11 insertions(+), 4 deletions(-) delete mode 100644 rest/session/responses.go diff --git a/rest/session/requests.go b/rest/session/requests.go index 63ffa66..d6f972a 100644 --- a/rest/session/requests.go +++ b/rest/session/requests.go @@ -1,9 +1,11 @@ package session import ( + "encoding/base64" "encoding/json" - "fmt" "net/http" + + "github.com/pkg/errors" ) type RequestAddSession struct { @@ -22,10 +24,16 @@ func NewRequestAddSession(r *http.Request) (*RequestAddSession, error) { func (r *RequestAddSession) Validate() error { if r.Key == "" { - return fmt.Errorf("invalid field key; expected non-empty value") + return errors.New("key cannot be empty") + } + if _, err := base64.StdEncoding.DecodeString(r.Key); err != nil { + return errors.Wrap(err, "invalid key") } if r.Signature == "" { - return fmt.Errorf("invalid field signature; expected non-empty value") + return errors.New("signature cannot be empty") + } + if _, err := base64.StdEncoding.DecodeString(r.Signature); err != nil { + return errors.Wrap(err, "invalid signature") } return nil diff --git a/rest/session/responses.go b/rest/session/responses.go deleted file mode 100644 index ab87616..0000000 --- a/rest/session/responses.go +++ /dev/null @@ -1 +0,0 @@ -package session From 1b096610caf5c8f6e62da225df5c5038b6b0299a Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Wed, 9 Jun 2021 22:59:39 +0530 Subject: [PATCH 09/26] Updated dependencies and using SpeedTest Go package --- go.mod | 5 +- go.sum | 10 ++- utils/bandwidth.go | 182 +++++++-------------------------------------- 3 files changed, 35 insertions(+), 162 deletions(-) diff --git a/go.mod b/go.mod index f8dcf09..9f5f227 100644 --- a/go.mod +++ b/go.mod @@ -9,12 +9,13 @@ require ( github.com/gorilla/mux v1.8.0 github.com/pelletier/go-toml v1.9.2 github.com/pkg/errors v0.9.1 - github.com/sentinel-official/hub v0.6.2 + github.com/sentinel-official/hub v0.6.3 + github.com/showwin/speedtest-go v1.1.2 github.com/spf13/cobra v1.1.3 github.com/spf13/viper v1.7.1 github.com/tendermint/tendermint v0.34.10 golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a - golang.org/x/sync v0.0.0-20210220032951-036812b2e83c + google.golang.org/grpc v1.38.0 ) replace ( diff --git a/go.sum b/go.sum index 78f9ec6..2567012 100644 --- a/go.sum +++ b/go.sum @@ -36,6 +36,7 @@ github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuy github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= +github.com/alecthomas/units v0.0.0-20201120081800-1786d5ef83d4/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= github.com/apache/thrift v0.13.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= @@ -504,8 +505,10 @@ github.com/sasha-s/go-deadlock v0.2.1-0.20190427202633-1595213edefa/go.mod h1:F7 github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/sentinel-official/cosmos-sdk v0.42.6-sentinel h1:c0umzLEXlYi5pPoi329i2ULMVUmAQg8Y1mtqH6HyREs= github.com/sentinel-official/cosmos-sdk v0.42.6-sentinel/go.mod h1:3JyT+Ud7QRTO1/ikncNqVhaF526ZKNqh2HGMqXn+QHE= -github.com/sentinel-official/hub v0.6.2 h1:fquwPh7F6f124iQIletHW32QG67aWAb5C4kgj1RBE3g= -github.com/sentinel-official/hub v0.6.2/go.mod h1:OvUTO+3wTH+EBZY/WeEhezKPpVf13BYxK0yXD404AIg= +github.com/sentinel-official/hub v0.6.3 h1:RuX6IysCECw7LJB7VZ5m5TjqNh3qiENoN2KP9kDSnfA= +github.com/sentinel-official/hub v0.6.3/go.mod h1:JtkCj0BnoanzVq7Wqx8bVlv15BZypvgk+lZdDiG04Ck= +github.com/showwin/speedtest-go v1.1.2 h1:QPWG8UWQaert3/F2Vm692GhHgM3+sHi5v7o5llG5JP4= +github.com/showwin/speedtest-go v1.1.2/go.mod h1:Evr4so/j097J4zgdEyYvaBhzyKMgrTNUOwFQcXqUUzc= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= @@ -696,9 +699,8 @@ golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201207232520-09787c993a3a h1:DcqTD9SDLc+1P/r1EmRBwnVsrOwW+kk2vWf9n+1sGhs= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= diff --git a/utils/bandwidth.go b/utils/bandwidth.go index feabce8..a6fa131 100644 --- a/utils/bandwidth.go +++ b/utils/bandwidth.go @@ -1,181 +1,51 @@ package utils import ( - "context" - "encoding/xml" - "fmt" - "io/ioutil" - "math" - "net/http" - "net/url" - "sort" - "strings" - "time" - - "golang.org/x/sync/errgroup" -) - -const ( - radius = 6378.137 - p = math.Pi / 180.0 + sdk "github.com/cosmos/cosmos-sdk/types" + hubtypes "github.com/sentinel-official/hub/types" + "github.com/showwin/speedtest-go/speedtest" ) -func distance(lat1, lon1, lat2, lon2 float64) float64 { - var ( - x1 = p * lat1 - y1 = p * lon1 - x2 = p * lat2 - y2 = p * lon2 - ) - - return radius * math.Acos( - math.Cos(y2-y1)* - math.Cos(x2)*math.Cos(x1)+ - math.Sin(x2)*math.Sin(x1), - ) -} - -type server struct { - URL string `xml:"url,attr"` - Latitude float64 `xml:"lat,attr"` - Longitude float64 `xml:"lon,attr"` - distance float64 -} - -func fetchServers() ([]server, error) { - resp, err := http.Get("https://c.speedtest.net/speedtest-servers-static.php") +func Bandwidth() (*hubtypes.Bandwidth, error) { + user, err := speedtest.FetchUserInfo() if err != nil { return nil, err } - defer func() { - if err := resp.Body.Close(); err != nil { - panic(err) - } - }() - - var result struct { - Servers []server `xml:"servers>server"` - } - - if err := xml.NewDecoder(resp.Body).Decode(&result); err != nil { + list, err := speedtest.FetchServerList(user) + if err != nil { return nil, err } - return result.Servers, nil -} - -func uploadBandwidth(s server, load, size int) (int64, error) { - var ( - client = http.Client{Timeout: 5 * time.Second} - data = url.Values{} - group, _ = errgroup.WithContext(context.Background()) - ) - - data.Add("content", strings.Repeat("0", size)) - - start := time.Now() - for i := 0; i < load; i++ { - group.Go(func() error { - resp, err := client.PostForm(s.URL, data) - if err != nil { - return err - } - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("recevied status code %d", resp.StatusCode) - } - - defer func() { - if err := resp.Body.Close(); err != nil { - panic(err) - } - }() - - _, _ = ioutil.ReadAll(resp.Body) - return nil - }) - } - - if err := group.Wait(); err != nil { - return 0, err + targets, err := list.FindServer(nil) + if err != nil { + return nil, err } - return int64(float64(load*size) / time.Since(start).Seconds()), nil -} - -func downloadBandwidth(s server, load, size int) (int64, error) { var ( - client = http.Client{Timeout: 5 * time.Second} - endpoint = fmt.Sprintf("%s/random%dx%d.jpg", strings.Split(s.URL, "/upload")[0], size, size) - group, _ = errgroup.WithContext(context.Background()) + upload int64 + download int64 ) - start := time.Now() - for i := 0; i < load; i++ { - group.Go(func() error { - resp, err := client.Get(endpoint) - if err != nil { - return err - } - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("recevied status code %d", resp.StatusCode) - } - - defer func() { - if err := resp.Body.Close(); err != nil { - panic(err) - } - }() - - _, _ = ioutil.ReadAll(resp.Body) - return nil - }) - } - - if err := group.Wait(); err != nil { - return 0, err - } - - return int64(float64(load*2*size*size) / time.Since(start).Seconds()), nil -} - -func Bandwidth() (upload, download int64, err error) { - location, err := FetchGeoIPLocation() - if err != nil { - return 0, 0, err - } - - servers, err := fetchServers() - if err != nil { - return 0, 0, err - } - - for i := 0; i < len(servers); i++ { - servers[i].distance = distance( - location.Latitude, location.Longitude, - servers[i].Latitude, servers[i].Longitude, - ) - } - - sort.Slice(servers, func(i, j int) bool { - return servers[i].distance < servers[j].distance - }) + for _, target := range targets { + if err := target.PingTest(); err != nil { + return nil, err + } - for i := range servers[:8] { - upload, err = uploadBandwidth(servers[i], 8, 4*1e6) - if err == nil { - break + if err := target.DownloadTest(false); err != nil { + return nil, err } - } - for i := range servers[:8] { - download, err = downloadBandwidth(servers[i], 8, 1500) - if err == nil { - break + if err := target.UploadTest(false); err != nil { + return nil, err } - fmt.Println(err) + upload += int64((target.ULSpeed * 1e6) / 8) + download += int64((target.DLSpeed * 1e6) / 8) } - return upload, download, nil + return &hubtypes.Bandwidth{ + Upload: sdk.NewInt(upload), + Download: sdk.NewInt(download), + }, nil } From cf3195e191a18321b86b90bae36498ba6eb5cb09 Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Wed, 9 Jun 2021 23:00:55 +0530 Subject: [PATCH 10/26] Using viper for reading the config file and added more validation --- services/wireguard/cli/config.go | 82 +++++++++++++++++++---------- services/wireguard/types/config.go | 83 ++++++++++++++---------------- services/wireguard/wireguard.go | 15 ++++-- 3 files changed, 105 insertions(+), 75 deletions(-) diff --git a/services/wireguard/cli/config.go b/services/wireguard/cli/config.go index bdda91e..73fdcef 100644 --- a/services/wireguard/cli/config.go +++ b/services/wireguard/cli/config.go @@ -7,48 +7,45 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" + "github.com/spf13/viper" - wgt "github.com/sentinel-official/dvpn-node/services/wireguard/types" + wgtypes "github.com/sentinel-official/dvpn-node/services/wireguard/types" "github.com/sentinel-official/dvpn-node/types" ) func configCmd() *cobra.Command { cmd := &cobra.Command{ Use: "config", - Short: "Config", + Short: "Configuration sub-commands", } cmd.AddCommand( - configInitCmd(), - configShowCmd(), + configInit(), + configShow(), + configSet(), ) return cmd } -func configInitCmd() *cobra.Command { +func configInit() *cobra.Command { cmd := &cobra.Command{ Use: "init", - Short: "Init", + Short: "Init the configuration", RunE: func(cmd *cobra.Command, args []string) error { - home, err := cmd.Flags().GetString(flags.FlagHome) - if err != nil { - return err - } + var ( + home = viper.GetString(flags.FlagHome) + path = filepath.Join(home, wgtypes.ConfigFileName) + ) force, err := cmd.Flags().GetBool(types.FlagForce) if err != nil { return err } - var ( - configPath = filepath.Join(home, wgt.ConfigFileName) - ) - if !force { - _, err = os.Stat(configPath) - if err == nil { - return fmt.Errorf("config file already exists at path '%s'", configPath) + if _, err = os.Stat(path); err == nil { + return fmt.Errorf("config file already exists at path %s", path) } } @@ -56,8 +53,8 @@ func configInitCmd() *cobra.Command { return err } - config := wgt.NewConfig().WithDefaultValues() - return config.SaveToPath(configPath) + config := wgtypes.NewConfig().WithDefaultValues() + return config.SaveToPath(path) }, } @@ -66,27 +63,58 @@ func configInitCmd() *cobra.Command { return cmd } -func configShowCmd() *cobra.Command { +func configShow() *cobra.Command { cmd := &cobra.Command{ Use: "show", - Short: "Show", + Short: "Show the configuration", RunE: func(cmd *cobra.Command, args []string) error { - home, err := cmd.Flags().GetString(flags.FlagHome) + var ( + home = viper.GetString(flags.FlagHome) + path = filepath.Join(home, wgtypes.ConfigFileName) + ) + + v := viper.New() + v.SetConfigFile(path) + + cfg, err := wgtypes.ReadInConfig(v) if err != nil { return err } + fmt.Println(cfg.String()) + return nil + }, + } + + return cmd +} + +func configSet() *cobra.Command { + cmd := &cobra.Command{ + Use: "set [key] [value]", + Short: "Set the configuration", + Args: cobra.ExactArgs(2), + RunE: func(_ *cobra.Command, args []string) error { var ( - config = wgt.NewConfig() - configPath = filepath.Join(home, wgt.ConfigFileName) + home = viper.GetString(flags.FlagHome) + path = filepath.Join(home, wgtypes.ConfigFileName) ) - if err := config.LoadFromPath(configPath); err != nil { + v := viper.New() + v.SetConfigFile(path) + + cfg, err := wgtypes.ReadInConfig(v) + if err != nil { return err } - fmt.Println(config) - return nil + v.Set(args[0], args[1]) + + if err := v.Unmarshal(cfg); err != nil { + return err + } + + return cfg.SaveToPath(path) }, } diff --git a/services/wireguard/types/config.go b/services/wireguard/types/config.go index 48dbace..3d2b9cb 100644 --- a/services/wireguard/types/config.go +++ b/services/wireguard/types/config.go @@ -2,21 +2,25 @@ package types import ( "bytes" - crand "crypto/rand" - "encoding/json" - "fmt" + "crypto/rand" "io/ioutil" "math/big" "strings" "text/template" - "github.com/pelletier/go-toml" + "github.com/pkg/errors" + "github.com/spf13/viper" ) var ( ct = strings.TrimSpace(` +# Name of the network interface interface = "{{ .Interface }}" + +# Port number to accept the incoming connections listen_port = {{ .ListenPort }} + +# Server private key private_key = "{{ .PrivateKey }}" `) @@ -31,53 +35,48 @@ private_key = "{{ .PrivateKey }}" ) type Config struct { - Interface string `json:"interface"` - ListenPort uint16 `json:"listen_port"` - PrivateKey string `json:"private_key"` + Interface string `mapstructure:"interface"` + ListenPort uint16 `mapstructure:"listen_port"` + PrivateKey string `mapstructure:"private_key"` } func NewConfig() *Config { return &Config{} } -func (c *Config) WithDefaultValues() *Config { - c.Interface = "wg0" - - n, _ := crand.Int(crand.Reader, big.NewInt(1<<16-1<<10)) - c.ListenPort = uint16(n.Int64() + 1<<10) - - key, err := NewPrivateKey() - if err != nil { - panic(err) +func (c *Config) Validate() error { + if c.Interface == "" { + return errors.New("interface cannot be empty") + } + if c.ListenPort == 0 { + return errors.New("listen_port cannot be zero") + } + if c.PrivateKey == "" { + return errors.New("private_key cannot be empty") + } + if _, err := KeyFromString(c.PrivateKey); err != nil { + return errors.Wrap(err, "invalid private_key") } - c.PrivateKey = key.String() - - return c + return nil } -func (c *Config) LoadFromPath(path string) error { - data, err := ioutil.ReadFile(path) +func (c *Config) WithDefaultValues() *Config { + n, err := rand.Int(rand.Reader, big.NewInt(1<<16-1<<10)) if err != nil { - return err - } - - if len(data) == 0 { - *c = Config{} - return nil + panic(err) } - tree, err := toml.LoadBytes(data) + key, err := NewPrivateKey() if err != nil { - return err + panic(err) } - data, err = json.Marshal(tree.ToMap()) - if err != nil { - return err - } + c.Interface = "wg0" + c.ListenPort = uint16(n.Int64() + 1<<10) + c.PrivateKey = key.String() - return json.Unmarshal(data, c) + return c } func (c *Config) SaveToPath(path string) error { @@ -98,16 +97,14 @@ func (c *Config) String() string { return buffer.String() } -func (c *Config) Validate() error { - if c.Interface == "" { - return fmt.Errorf("invalid interface; expected non-empty value") +func ReadInConfig(v *viper.Viper) (*Config, error) { + cfg := NewConfig().WithDefaultValues() + if err := v.ReadInConfig(); err != nil { + return nil, err } - if c.ListenPort == 0 { - return fmt.Errorf("invalid listen_port; expected positive value") - } - if c.PrivateKey == "" { - return fmt.Errorf("invalid private_key; expected non-empty value") + if err := v.Unmarshal(cfg); err != nil { + return nil, err } - return nil + return cfg, nil } diff --git a/services/wireguard/wireguard.go b/services/wireguard/wireguard.go index e254e25..15604a1 100644 --- a/services/wireguard/wireguard.go +++ b/services/wireguard/wireguard.go @@ -13,6 +13,8 @@ import ( "strings" "text/template" + "github.com/spf13/viper" + wgtypes "github.com/sentinel-official/dvpn-node/services/wireguard/types" "github.com/sentinel-official/dvpn-node/types" ) @@ -45,9 +47,12 @@ func (w *WireGuard) Type() uint64 { return wgtypes.Type } -func (w *WireGuard) Init(home string) error { - configFilePath := filepath.Join(home, wgtypes.ConfigFileName) - if err := w.cfg.LoadFromPath(configFilePath); err != nil { +func (w *WireGuard) Init(home string) (err error) { + v := viper.New() + v.SetConfigFile(filepath.Join(home, wgtypes.ConfigFileName)) + + w.cfg, err = wgtypes.ReadInConfig(v) + if err != nil { return err } @@ -61,8 +66,8 @@ func (w *WireGuard) Init(home string) error { return err } - configFilePath = fmt.Sprintf("/etc/wireguard/%s.conf", w.cfg.Interface) - if err := ioutil.WriteFile(configFilePath, buffer.Bytes(), 0600); err != nil { + path := fmt.Sprintf("/etc/wireguard/%s.conf", w.cfg.Interface) + if err := ioutil.WriteFile(path, buffer.Bytes(), 0600); err != nil { return err } From 3d58850fe8e5e6b446692e49a225b29549e7063f Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Wed, 9 Jun 2021 23:01:16 +0530 Subject: [PATCH 11/26] Added comments for the config keys --- types/config.go | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/types/config.go b/types/config.go index c559e37..ae13f21 100644 --- a/types/config.go +++ b/types/config.go @@ -18,28 +18,58 @@ import ( var ( ct = strings.TrimSpace(` [chain] +# Gas adjustment factor gas_adjustment = {{ .Chain.GasAdjustment }} + +# Gas limit to set per transaction gas = {{ .Chain.Gas }} + +# Gas prices to determine the transaction fee gas_prices = "{{ .Chain.GasPrices }}" + +# The network chain ID id = "{{ .Chain.ID }}" + +# Tendermint RPC interface for the chain rpc_address = "{{ .Chain.RPCAddress }}" + +# Calculate the transaction fee by simulating it simulate_and_execute = {{ .Chain.SimulateAndExecute }} [handshake] +# Enable Handshake DNS resolver enable = {{ .Handshake.Enable }} + +# Number of peers peers = {{ .Handshake.Peers }} [keyring] +# Underlying storage mechanism for keys backend = "{{ .Keyring.Backend }}" + +# Name of the key with which to sign from = "{{ .Keyring.From }}" [node] +# Time interval between each update_sessions transactions interval_sessions = "{{ .Node.IntervalSessions }}" + +# Time interval between each update_status transactions interval_status = "{{ .Node.IntervalStatus }}" + +# API listen-address listen_on = "{{ .Node.ListenOn }}" + +# Name of the node moniker = "{{ .Node.Moniker }}" + +# Per Gigabyte price to charge against the provided bandwidth price = "{{ .Node.Price }}" + +# Address of the provider the node wants to operate under provider = "{{ .Node.Provider }}" + +# Public URL of the node remote_url = "{{ .Node.RemoteURL }}" `) @@ -272,7 +302,6 @@ func ReadInConfig(v *viper.Viper) (*Config, error) { if err := v.ReadInConfig(); err != nil { return nil, err } - if err := v.Unmarshal(cfg); err != nil { return nil, err } From 76c4bd2130881679338d5aa73fd1fbdc75050a9f Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Wed, 9 Jun 2021 23:02:01 +0530 Subject: [PATCH 12/26] Removed context --- cmd/start.go | 10 ++------ context/context.go | 62 +++++++++++++++------------------------------- 2 files changed, 22 insertions(+), 50 deletions(-) diff --git a/cmd/start.go b/cmd/start.go index 1302981..de7f17c 100644 --- a/cmd/start.go +++ b/cmd/start.go @@ -16,7 +16,6 @@ import ( "github.com/gorilla/mux" "github.com/sentinel-official/hub" "github.com/sentinel-official/hub/params" - hubtypes "github.com/sentinel-official/hub/types" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/tendermint/tendermint/libs/log" @@ -113,14 +112,12 @@ func StartCmd() *cobra.Command { return fmt.Errorf("account does not exist with address %s", client.FromAddress()) } - logger.Info("Fetching the GeoIP location") location, err := utils.FetchGeoIPLocation() if err != nil { return err } - logger.Info("Calculating the bandwidth") - upload, download, err := utils.Bandwidth() + bandwidth, err := utils.Bandwidth() if err != nil { return err } @@ -131,12 +128,10 @@ func StartCmd() *cobra.Command { } } - logger.Info("Initializing the service", "type", service.Type()) if err := service.Init(home); err != nil { return err } - logger.Info("Starting the service", "type", service.Type()) if err := service.Start(); err != nil { return err } @@ -154,10 +149,9 @@ func StartCmd() *cobra.Command { WithRouter(router). WithConfig(cfg). WithClient(client). - WithHome(home). WithLocation(location). WithSessions(types.NewSessions()). - WithBandwidth(hubtypes.NewBandwidthFromInt64(upload, download)) + WithBandwidth(bandwidth) n := node.NewNode(ctx) if err := n.Initialize(); err != nil { diff --git a/context/context.go b/context/context.go index a51d64b..6277a41 100644 --- a/context/context.go +++ b/context/context.go @@ -1,7 +1,6 @@ package context import ( - "context" "time" sdk "github.com/cosmos/cosmos-sdk/types" @@ -14,58 +13,45 @@ import ( ) type Context struct { - home string - ctx context.Context logger log.Logger service types.Service + bandwidth *hubtypes.Bandwidth client *lite.Client config *types.Config + location *types.GeoIPLocation router *mux.Router sessions *types.Sessions - location *types.GeoIPLocation - bandwidth hubtypes.Bandwidth } func NewContext() *Context { - return &Context{ - ctx: context.Background(), - } + return &Context{} } -func (c *Context) WithBandwidth(v hubtypes.Bandwidth) *Context { c.bandwidth = v; return c } +func (c *Context) WithBandwidth(v *hubtypes.Bandwidth) *Context { c.bandwidth = v; return c } func (c *Context) WithClient(v *lite.Client) *Context { c.client = v; return c } func (c *Context) WithConfig(v *types.Config) *Context { c.config = v; return c } -func (c *Context) WithContext(v context.Context) *Context { c.ctx = v; return c } -func (c *Context) WithHome(v string) *Context { c.home = v; return c } func (c *Context) WithLocation(v *types.GeoIPLocation) *Context { c.location = v; return c } func (c *Context) WithLogger(v log.Logger) *Context { c.logger = v; return c } func (c *Context) WithRouter(v *mux.Router) *Context { c.router = v; return c } func (c *Context) WithService(v types.Service) *Context { c.service = v; return c } func (c *Context) WithSessions(v *types.Sessions) *Context { c.sessions = v; return c } -func (c *Context) WithValue(key, value interface{}) *Context { - c.WithContext(context.WithValue(c.ctx, key, value)) - return c -} - -func (c *Context) Address() hubtypes.NodeAddress { return c.Operator().Bytes() } -func (c *Context) Bandwidth() hubtypes.Bandwidth { return c.bandwidth } -func (c *Context) Type() uint64 { return c.service.Type() } -func (c *Context) Client() *lite.Client { return c.client } -func (c *Context) Config() *types.Config { return c.config } -func (c *Context) Context() context.Context { return c.ctx } -func (c *Context) Home() string { return c.home } -func (c *Context) ListenOn() string { return c.Config().Node.ListenOn } -func (c *Context) Location() *types.GeoIPLocation { return c.location } -func (c *Context) Logger() log.Logger { return c.logger } -func (c *Context) Moniker() string { return c.Config().Node.Moniker } -func (c *Context) Operator() sdk.AccAddress { return c.client.FromAddress() } -func (c *Context) RemoteURL() string { return c.Config().Node.RemoteURL } -func (c *Context) Router() *mux.Router { return c.router } -func (c *Context) Service() types.Service { return c.service } -func (c *Context) Sessions() *types.Sessions { return c.sessions } -func (c *Context) Value(key interface{}) interface{} { return c.ctx.Value(key) } -func (c *Context) Version() string { return types.Version } +func (c *Context) Address() hubtypes.NodeAddress { return c.Operator().Bytes() } +func (c *Context) Bandwidth() *hubtypes.Bandwidth { return c.bandwidth } +func (c *Context) Type() uint64 { return c.service.Type() } +func (c *Context) Client() *lite.Client { return c.client } +func (c *Context) Config() *types.Config { return c.config } +func (c *Context) IntervalSessions() time.Duration { return c.Config().Node.IntervalSessions } +func (c *Context) IntervalStatus() time.Duration { return c.Config().Node.IntervalStatus } +func (c *Context) ListenOn() string { return c.Config().Node.ListenOn } +func (c *Context) Location() *types.GeoIPLocation { return c.location } +func (c *Context) Logger() log.Logger { return c.logger } +func (c *Context) Moniker() string { return c.Config().Node.Moniker } +func (c *Context) Operator() sdk.AccAddress { return c.client.FromAddress() } +func (c *Context) RemoteURL() string { return c.Config().Node.RemoteURL } +func (c *Context) Router() *mux.Router { return c.router } +func (c *Context) Service() types.Service { return c.service } +func (c *Context) Sessions() *types.Sessions { return c.sessions } func (c *Context) Provider() hubtypes.ProvAddress { if c.Config().Node.Provider == "" { @@ -92,11 +78,3 @@ func (c *Context) Price() sdk.Coins { return coins } - -func (c *Context) IntervalSessions() time.Duration { - return time.Duration(c.Config().Node.IntervalSessions) -} - -func (c *Context) IntervalStatus() time.Duration { - return time.Duration(c.Config().Node.IntervalStatus) -} From 1020b3ad8465bc5da11af78744157774343ed7b3 Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Wed, 9 Jun 2021 23:03:44 +0530 Subject: [PATCH 13/26] Added more useful methods for identifying a session --- types/session.go | 68 +++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 58 insertions(+), 10 deletions(-) diff --git a/types/session.go b/types/session.go index 170a9d1..4d77deb 100644 --- a/types/session.go +++ b/types/session.go @@ -1,12 +1,26 @@ package types import ( + "fmt" + "reflect" "sync" "time" sdk "github.com/cosmos/cosmos-sdk/types" ) +func withTypePrefix(v interface{}) string { + t := reflect.TypeOf(v).String() + switch v := v.(type) { + case string: + return t + v + case fmt.Stringer: + return t + v.String() + default: + return "" + } +} + type Session struct { ID uint64 `json:"id,omitempty"` Key string `json:"key,omitempty"` @@ -18,30 +32,64 @@ type Session struct { } type Sessions struct { - m map[string]Session + m map[string]interface{} mutex sync.Mutex } func NewSessions() *Sessions { return &Sessions{ - m: make(map[string]Session), + m: make(map[string]interface{}), } } -func (s *Sessions) Put(v Session) { +func (s *Sessions) delete(v *Session) { s.mutex.Lock() defer s.mutex.Unlock() - s.m[v.Key] = v + delete(s.m, withTypePrefix(v.Key)) + delete(s.m, withTypePrefix(v.Address)) } -func (s *Sessions) Get(v string) Session { - return s.m[v] -} - -func (s *Sessions) Delete(v string) { +func (s *Sessions) Put(v *Session) { s.mutex.Lock() defer s.mutex.Unlock() - delete(s.m, v) + s.m[withTypePrefix(v.Key)] = v + s.m[withTypePrefix(v.Address)] = v.Key +} + +func (s *Sessions) GetForKey(k string) *Session { + v, ok := s.m[withTypePrefix(k)] + if !ok { + return nil + } + + return v.(*Session) +} + +func (s *Sessions) GetForAddress(k sdk.AccAddress) *Session { + v, ok := s.m[withTypePrefix(k)] + if !ok { + return nil + } + + return s.GetForKey(v.(string)) +} + +func (s *Sessions) DeleteForKey(k string) { + v := s.GetForKey(k) + if v == nil { + return + } + + s.delete(v) +} + +func (s *Sessions) DeleteForAddress(k sdk.AccAddress) { + v := s.GetForAddress(k) + if v == nil { + return + } + + s.delete(v) } From 454fc002a422a8b85cdb3dcbcd49534431a649a3 Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Wed, 9 Jun 2021 23:06:01 +0530 Subject: [PATCH 14/26] Removing inactive peer from list --- node/jobs.go | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/node/jobs.go b/node/jobs.go index 03201a4..13de5a0 100644 --- a/node/jobs.go +++ b/node/jobs.go @@ -11,8 +11,6 @@ import ( ) func (n *Node) jobUpdateStatus() error { - n.Logger().Info("starting a job", "name", "update_status", "interval", n.IntervalStatus()) - t := time.NewTicker(n.IntervalStatus()) for ; ; <-t.C { if err := n.updateStatus(); err != nil { @@ -22,12 +20,10 @@ func (n *Node) jobUpdateStatus() error { } func (n *Node) jobUpdateSessions() error { - n.Logger().Info("starting a job", "name", "update_sessions", "interval", n.IntervalSessions()) - t := time.NewTicker(n.IntervalSessions()) for ; ; <-t.C { var ( - items []types.Session + items []*types.Session ) peers, err := n.Service().Peers() @@ -36,32 +32,35 @@ func (n *Node) jobUpdateSessions() error { } for _, peer := range peers { - var ( - item = n.Sessions().Get(peer.Key) - consumed = sdk.NewInt(peer.Upload + peer.Download) - ) + item := n.Sessions().GetForKey(peer.Key) + if item == nil { + continue + } session, err := n.Client().QuerySession(item.ID) if err != nil { return err } - if session.Status.Equal(hubtypes.Inactive) || consumed.GT(item.Available) { - n.Logger().Info("inactive session", "value", item, "consumed", consumed) + var ( + consumed = sdk.NewInt(peer.Upload + peer.Download) + inactive = session.Status.Equal(hubtypes.StatusInactive) || + peer.Download == session.Bandwidth.Upload.Int64() + ) + if inactive || consumed.GT(item.Available) { key, err := base64.StdEncoding.DecodeString(peer.Key) if err != nil { return err } - if err := n.Service().RemovePeer(key); err != nil { return err } - n.Sessions().Delete(peer.Key) + n.Sessions().DeleteForKey(item.Key) + n.Sessions().DeleteForAddress(item.Address) } - - if session.Status.Equal(hubtypes.Inactive) { + if inactive { continue } @@ -70,7 +69,10 @@ func (n *Node) jobUpdateSessions() error { items = append(items, item) } - if err := n.updateSessions(items); err != nil { + if len(items) == 0 { + continue + } + if err := n.updateSessions(items...); err != nil { return err } } From 542cc5923d12edb1ba83306f4f4f260e22b7dd8b Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Wed, 9 Jun 2021 23:09:49 +0530 Subject: [PATCH 15/26] Updated add-session handler with more verification --- rest/session/handlers.go | 120 ++++++++++++++++++++++++--------------- 1 file changed, 73 insertions(+), 47 deletions(-) diff --git a/rest/session/handlers.go b/rest/session/handlers.go index 6098b1d..9163011 100644 --- a/rest/session/handlers.go +++ b/rest/session/handlers.go @@ -2,7 +2,7 @@ package session import ( "encoding/base64" - "encoding/hex" + "fmt" "net" "net/http" "strconv" @@ -25,135 +25,161 @@ func handlerAddSession(ctx *context.Context) http.HandlerFunc { return } if err := body.Validate(); err != nil { - utils.WriteErrorToResponse(w, http.StatusBadRequest, 2, err.Error()) + utils.WriteErrorToResponse(w, http.StatusBadRequest, 1, err.Error()) return } var ( - vars = mux.Vars(r) + vars = mux.Vars(r) + key, _ = base64.StdEncoding.DecodeString(body.Key) + signature, _ = base64.StdEncoding.DecodeString(body.Signature) ) - address, err := hex.DecodeString(vars["address"]) + address, err := sdk.AccAddressFromBech32(vars["address"]) if err != nil { - utils.WriteErrorToResponse(w, http.StatusBadRequest, 2, err.Error()) + utils.WriteErrorToResponse(w, http.StatusBadRequest, 1, err.Error()) return } id, err := strconv.ParseUint(vars["id"], 10, 64) if err != nil { - utils.WriteErrorToResponse(w, http.StatusBadRequest, 2, err.Error()) - return - } - - key, err := base64.StdEncoding.DecodeString(body.Key) - if err != nil { - utils.WriteErrorToResponse(w, http.StatusBadRequest, 2, err.Error()) + utils.WriteErrorToResponse(w, http.StatusBadRequest, 1, err.Error()) return } - signature, err := base64.StdEncoding.DecodeString(body.Signature) + account, err := ctx.Client().QueryAccount(address) if err != nil { - utils.WriteErrorToResponse(w, http.StatusBadRequest, 2, err.Error()) + utils.WriteErrorToResponse(w, http.StatusInternalServerError, 2, err.Error()) return } - - account, err := ctx.Client().QueryAccount(address) - if err != nil { - utils.WriteErrorToResponse(w, http.StatusInternalServerError, 3, err.Error()) + if account == nil { + utils.WriteErrorToResponse(w, http.StatusNotFound, 2, "account does not exist") return } - if account == nil || account.GetPubKey() == nil { - utils.WriteErrorToResponse(w, http.StatusNotFound, 3, "account does not exist") + if account.GetPubKey() == nil { + utils.WriteErrorToResponse(w, http.StatusNotFound, 2, "public key does not exist") return } if ok := account.GetPubKey().VerifySignature(sdk.Uint64ToBigEndian(id), signature); !ok { - utils.WriteErrorToResponse(w, http.StatusBadRequest, 3, "failed to verify signature") + utils.WriteErrorToResponse(w, http.StatusBadRequest, 2, "failed to verify signature") return } + if item := ctx.Sessions().GetForAddress(address); item != nil { + session, err := ctx.Client().QuerySession(item.ID) + if err != nil { + utils.WriteErrorToResponse(w, http.StatusInternalServerError, 3, err.Error()) + return + } + if session == nil { + utils.WriteErrorToResponse(w, http.StatusNotFound, 3, "session does not exist") + return + } + if session.Status.Equal(hubtypes.StatusActive) { + utils.WriteErrorToResponse(w, http.StatusBadRequest, 3, fmt.Sprintf("invalid session status %s", session.Status)) + return + } + + ctx.Sessions().DeleteForAddress(address) + } + + if item := ctx.Sessions().GetForKey(body.Key); item != nil { + session, err := ctx.Client().QuerySession(item.ID) + if err != nil { + utils.WriteErrorToResponse(w, http.StatusInternalServerError, 4, err.Error()) + return + } + if session == nil { + utils.WriteErrorToResponse(w, http.StatusNotFound, 4, "session does not exist") + return + } + if session.Status.Equal(hubtypes.StatusActive) { + utils.WriteErrorToResponse(w, http.StatusBadRequest, 4, fmt.Sprintf("invalid session status %s", session.Status)) + return + } + + ctx.Sessions().DeleteForKey(body.Key) + } + session, err := ctx.Client().QuerySession(id) if err != nil { - utils.WriteErrorToResponse(w, http.StatusInternalServerError, 4, err.Error()) + utils.WriteErrorToResponse(w, http.StatusInternalServerError, 5, err.Error()) return } if session == nil { - utils.WriteErrorToResponse(w, http.StatusNotFound, 4, "session does not exist") + utils.WriteErrorToResponse(w, http.StatusNotFound, 5, "session does not exist") return } if !session.Status.Equal(hubtypes.StatusActive) { - utils.WriteErrorToResponse(w, http.StatusBadRequest, 4, "invalid session status") + utils.WriteErrorToResponse(w, http.StatusBadRequest, 5, fmt.Sprintf("invalid session status %s", session.Status)) + return + } + if session.Address != address.String() { + utils.WriteErrorToResponse(w, http.StatusBadRequest, 5, "account address mismatch") return } subscription, err := ctx.Client().QuerySubscription(session.Subscription) if err != nil { - utils.WriteErrorToResponse(w, http.StatusInternalServerError, 5, err.Error()) + utils.WriteErrorToResponse(w, http.StatusInternalServerError, 6, err.Error()) return } if subscription == nil { - utils.WriteErrorToResponse(w, http.StatusNotFound, 5, "subscription does not exist") + utils.WriteErrorToResponse(w, http.StatusNotFound, 6, "subscription does not exist") return } if !subscription.Status.Equal(hubtypes.Active) { - utils.WriteErrorToResponse(w, http.StatusBadRequest, 5, "invalid subscription status") + utils.WriteErrorToResponse(w, http.StatusBadRequest, 6, fmt.Sprintf("invalid subscription status %s", subscription.Status)) return } if subscription.Plan == 0 { if subscription.Node != ctx.Address().String() { - utils.WriteErrorToResponse(w, http.StatusBadRequest, 6, "node address mismatch") + utils.WriteErrorToResponse(w, http.StatusBadRequest, 7, "node address mismatch") return } } else { ok, err := ctx.Client().HasNodeForPlan(id, ctx.Address()) if err != nil { - utils.WriteErrorToResponse(w, http.StatusInternalServerError, 6, err.Error()) + utils.WriteErrorToResponse(w, http.StatusInternalServerError, 7, err.Error()) return } if !ok { - utils.WriteErrorToResponse(w, http.StatusBadRequest, 6, "node does not exist for plan") + utils.WriteErrorToResponse(w, http.StatusBadRequest, 7, "node address mismatch") return } } quota, err := ctx.Client().QueryQuota(subscription.Id, address) if err != nil { - utils.WriteErrorToResponse(w, http.StatusInternalServerError, 7, err.Error()) + utils.WriteErrorToResponse(w, http.StatusInternalServerError, 8, err.Error()) return } if quota == nil { - utils.WriteErrorToResponse(w, http.StatusNotFound, 7, "quota does not exist") + utils.WriteErrorToResponse(w, http.StatusNotFound, 8, "quota does not exist") return } if quota.Consumed.GTE(quota.Allocated) { - utils.WriteErrorToResponse(w, http.StatusBadRequest, 7, "invalid quota") + utils.WriteErrorToResponse(w, http.StatusBadRequest, 8, "quota exceeded") return } - if ctx.Sessions().Get(body.Key).Key != "" { - utils.WriteErrorToResponse(w, http.StatusConflict, 8, "duplicate key") + result, err := ctx.Service().AddPeer(key) + if err != nil { + utils.WriteErrorToResponse(w, http.StatusInternalServerError, 9, err.Error()) return } - var ( - item = types.Session{ + ctx.Sessions().Put( + &types.Session{ ID: id, Key: body.Key, Address: address, Available: quota.Allocated.Sub(quota.Consumed), ConnectedAt: time.Now(), - } + }, ) - ctx.Sessions().Put(item) - ctx.Logger().Info("added session", "value", item) - - result, err := ctx.Service().AddPeer(key) - if err != nil { - utils.WriteErrorToResponse(w, http.StatusInternalServerError, 9, err.Error()) - return - } - result = append(result, net.ParseIP(ctx.Location().IP).To4()...) result = append(result, ctx.Service().Info()...) utils.WriteResultToResponse(w, http.StatusCreated, result) From 9bca01a1faaad7f92aa24d12a2e01326e5ead7c5 Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Wed, 9 Jun 2021 23:10:15 +0530 Subject: [PATCH 16/26] Refactored some code --- lite/tx.go | 40 +++++++++------------ node/node.go | 55 ++++++++++------------------- services/wireguard/types/crypto.go | 2 +- services/wireguard/types/ip_pool.go | 8 +++-- 4 files changed, 41 insertions(+), 64 deletions(-) diff --git a/lite/tx.go b/lite/tx.go index 3c1b9c3..4d9bf5e 100644 --- a/lite/tx.go +++ b/lite/tx.go @@ -1,12 +1,11 @@ package lite import ( - "fmt" - "github.com/avast/retry-go" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/errors" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/pkg/errors" abcitypes "github.com/tendermint/tendermint/abci/types" ) @@ -20,8 +19,7 @@ func (c *Client) BroadcastTx(messages ...sdk.Msg) (res *sdk.TxResponse, err erro } var ( - name = c.From() - txf = c.txf. + txf = c.txf. WithAccountNumber(account.GetAccountNumber()). WithSequence(account.GetSequence()) ) @@ -40,7 +38,7 @@ func (c *Client) BroadcastTx(messages ...sdk.Msg) (res *sdk.TxResponse, err erro return nil, err } - if err := tx.Sign(txf, name, txb, true); err != nil { + if err := tx.Sign(txf, c.From(), txb, true); err != nil { return nil, err } @@ -49,23 +47,19 @@ func (c *Client) BroadcastTx(messages ...sdk.Msg) (res *sdk.TxResponse, err erro return nil, err } - err = retry.Do( - func() error { - res, err = c.ctx.BroadcastTx(txBytes) - - switch { - case err != nil: - return err - case res.Code == abcitypes.CodeTypeOK: - return nil - case res.Code == errors.ErrTxInMempoolCache.ABCICode(): - return nil - default: - return fmt.Errorf(res.RawLog) - } - }, - retry.Attempts(5), - ) + err = retry.Do(func() error { + res, err = c.ctx.BroadcastTx(txBytes) + switch { + case err != nil: + return err + case res.Code == abcitypes.CodeTypeOK: + return nil + case res.Code == sdkerrors.ErrTxInMempoolCache.ABCICode(): + return nil + default: + return errors.New(res.RawLog) + } + }, retry.Attempts(5)) return res, err } diff --git a/node/node.go b/node/node.go index 71b2826..5042129 100644 --- a/node/node.go +++ b/node/node.go @@ -5,10 +5,12 @@ import ( "path" "time" + "github.com/cosmos/cosmos-sdk/client/flags" sdk "github.com/cosmos/cosmos-sdk/types" hubtypes "github.com/sentinel-official/hub/types" nodetypes "github.com/sentinel-official/hub/x/node/types" sessiontypes "github.com/sentinel-official/hub/x/session/types" + "github.com/spf13/viper" "github.com/sentinel-official/dvpn-node/context" "github.com/sentinel-official/dvpn-node/types" @@ -23,15 +25,16 @@ func NewNode(ctx *context.Context) *Node { } func (n *Node) Initialize() error { - res, err := n.Client().QueryNode(n.Address()) + result, err := n.Client().QueryNode(n.Address()) if err != nil { return err } - if res == nil { + + if result == nil { return n.register() } - return n.update() + return n.updateInfo() } func (n *Node) Start() error { @@ -48,16 +51,15 @@ func (n *Node) Start() error { }() var ( - certFile = path.Join(n.Home(), "tls.crt") - keyFile = path.Join(n.Home(), "tls.key") + certFile = path.Join(viper.GetString(flags.FlagHome), "tls.crt") + keyFile = path.Join(viper.GetString(flags.FlagHome), "tls.key") ) - n.Logger().Info("started REST API server", "address", n.ListenOn()) return http.ListenAndServeTLS(n.ListenOn(), certFile, keyFile, n.Router()) } func (n *Node) register() error { - res, err := n.Client().BroadcastTx( + _, err := n.Client().BroadcastTx( nodetypes.NewMsgRegisterRequest( n.Operator(), n.Provider(), @@ -65,16 +67,12 @@ func (n *Node) register() error { n.RemoteURL(), ), ) - if err != nil { - return err - } - n.Logger().Info("registered node", "tx_hash", res.TxHash) - return nil + return err } -func (n *Node) update() error { - res, err := n.Client().BroadcastTx( +func (n *Node) updateInfo() error { + _, err := n.Client().BroadcastTx( nodetypes.NewMsgUpdateRequest( n.Address(), n.Provider(), @@ -82,34 +80,22 @@ func (n *Node) update() error { n.RemoteURL(), ), ) - if err != nil { - return err - } - n.Logger().Info("updated node information", "tx_hash", res.TxHash) - return nil + return err } func (n *Node) updateStatus() error { - res, err := n.Client().BroadcastTx( + _, err := n.Client().BroadcastTx( nodetypes.NewMsgSetStatusRequest( n.Address(), hubtypes.StatusActive, ), ) - if err != nil { - return err - } - n.Logger().Info("updated node status", "tx_hash", res.TxHash) - return nil + return err } -func (n *Node) updateSessions(items []types.Session) error { - if len(items) == 0 { - return nil - } - +func (n *Node) updateSessions(items ...*types.Session) error { messages := make([]sdk.Msg, 0, len(items)) for _, item := range items { messages = append(messages, @@ -125,11 +111,6 @@ func (n *Node) updateSessions(items []types.Session) error { ) } - res, err := n.Client().BroadcastTx(messages...) - if err != nil { - return err - } - - n.Logger().Info("updated sessions", "tx_hash", res.TxHash) - return nil + _, err := n.Client().BroadcastTx(messages...) + return err } diff --git a/services/wireguard/types/crypto.go b/services/wireguard/types/crypto.go index 2c5d414..d346580 100644 --- a/services/wireguard/types/crypto.go +++ b/services/wireguard/types/crypto.go @@ -19,7 +19,7 @@ type ( func KeyFromBytes(b []byte) (*Key, error) { if len(b) != KeyLength { - return nil, fmt.Errorf("invalid bytes length") + return nil, fmt.Errorf("invalid bytes length %d", len(b)) } var key Key diff --git a/services/wireguard/types/ip_pool.go b/services/wireguard/types/ip_pool.go index b075873..9eb7276 100644 --- a/services/wireguard/types/ip_pool.go +++ b/services/wireguard/types/ip_pool.go @@ -1,9 +1,10 @@ package types import ( - "fmt" "net" "sync" + + "github.com/pkg/errors" ) type IPv4Pool struct { @@ -32,7 +33,7 @@ func (p *IPv4Pool) Get() (ip IPv4, err error) { p.current = p.current.Next() } if !p.Net.Contains(p.current.IP()) { - return ip, fmt.Errorf("ipv4 pool is pull") + return ip, errors.New("ipv4 pool is pull") } ip, p.current = p.current, p.current.Next() @@ -86,7 +87,7 @@ func (p *IPv6Pool) Get() (ip IPv6, err error) { if len(p.available) == 0 { if !p.Net.Contains(p.current.IP()) { - return ip, fmt.Errorf("ipv6 pool is pull") + return ip, errors.New("ipv6 pool is pull") } ip, p.current = p.current, p.current.Next() @@ -138,6 +139,7 @@ func (p *IPPool) Get() (IPv4, IPv6, error) { v6, err := p.V6.Get() if err != nil { p.V4.Release(v4) + return IPv4{}, IPv6{}, err } From e652165be50d0db8f63522d55150c0904c830959 Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Wed, 9 Jun 2021 23:10:31 +0530 Subject: [PATCH 17/26] Updated Makefile with version --- .gitignore | 5 +++-- Makefile | 29 ++++++++++++++--------------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/.gitignore b/.gitignore index 5fa0185..2d340a3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ -/bin/ +.DS_Store* /.idea/ -.DS_Store* \ No newline at end of file +/bin/ +/vendor/ diff --git a/Makefile b/Makefile index 2542eed..a5de337 100644 --- a/Makefile +++ b/Makefile @@ -1,27 +1,26 @@ PACKAGES := $(shell go list ./...) VERSION := $(shell git rev-parse --short HEAD) +COMMIT := $(shell git log -1 --format='%H') -BUILD_TAGS := netgo -BUILD_TAGS := $(strip ${BUILD_TAGS}) - +BUILD_TAGS := $(strip netgo) LD_FLAGS := -s -w \ - -X github.com/sentinel-official/dvpn-node/types.Version=${VERSION} - -BUILD_FLAGS := -tags "${BUILD_TAGS}" -ldflags "${LD_FLAGS}" + -X github.com/cosmos/cosmos-sdk/version.Name=sentinel \ + -X github.com/cosmos/cosmos-sdk/version.AppName=sentinel-dvpn-node \ + -X github.com/cosmos/cosmos-sdk/version.Version=${VERSION} \ + -X github.com/cosmos/cosmos-sdk/version.Commit=${COMMIT} \ + -X github.com/cosmos/cosmos-sdk/version.BuildTags=${BUILD_TAGS} -all: mod_verify test benchmark install +.PHONY: all +all: test benchmark install -install: mod_verify - go build -mod=readonly ${BUILD_FLAGS} -o ${GOPATH}/bin/sentinel-dvpn-node main.go +.PHONY: install +install: + go build -mod=readonly -tags="${BUILD_TAGS}" -ldflags="${LD_FLAGS}" -o ${GOPATH}/bin/sentinel-dvpn-node main.go +.PHONY: test test: @go test -mod=readonly -cover ${PACKAGES} +.PHONY: benchmark benchmark: @go test -mod=readonly -bench=. ${PACKAGES} - -mod_verify: - @echo "Ensure dependencies have not been modified" - @go mod verify - -.PHONY: all install test benchmark mod_verify From 0cba62a218ba63f2d65f25d926b525d49fa4a276 Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Thu, 10 Jun 2021 00:00:36 +0530 Subject: [PATCH 18/26] Removed toml package dependency --- go.mod | 1 - go.sum | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 9f5f227..be561da 100644 --- a/go.mod +++ b/go.mod @@ -7,7 +7,6 @@ require ( github.com/cosmos/cosmos-sdk v0.42.5 github.com/cosmos/go-bip39 v1.0.0 github.com/gorilla/mux v1.8.0 - github.com/pelletier/go-toml v1.9.2 github.com/pkg/errors v0.9.1 github.com/sentinel-official/hub v0.6.3 github.com/showwin/speedtest-go v1.1.2 diff --git a/go.sum b/go.sum index 2567012..c8be21c 100644 --- a/go.sum +++ b/go.sum @@ -423,9 +423,8 @@ github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0Mw github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pelletier/go-toml v1.8.1 h1:1Nf83orprkJyknT6h7zbuEGUEjcyVlCxSUGTENmNCRM= github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc= -github.com/pelletier/go-toml v1.9.2 h1:7NiByeVF4jKSG1lDF3X8LTIkq2/bu+1uYbIm1eS5tzk= -github.com/pelletier/go-toml v1.9.2/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac= github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 h1:q2e307iGHPdTGp0hoxKjt1H5pDo6utceo3dQVK3I5XQ= github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5/go.mod h1:jvVRKCrJTQWu0XVbaOlby/2lO20uSCHEMzzplHXte1o= From 7e681a9534b2e0e337dabdeaf7c42df25c29e532 Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Thu, 10 Jun 2021 00:32:49 +0530 Subject: [PATCH 19/26] Added some badges --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 3ce7800..95cf60d 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,10 @@ # Sentinel dVPN Node +[![Tag](https://img.shields.io/github/tag/sentinel-official/dvpn-node.svg)](https://github.com/sentinel-official/dvpn-node/releases/latest) +[![GoReportCard](https://goreportcard.com/badge/github.com/sentinel-official/dvpn-node)](https://goreportcard.com/report/github.com/sentinel-official/dvpn-node) +[![Licence](https://img.shields.io/github/license/sentinel-official/dvpn-node.svg)](https://github.com/sentinel-official/dvpn-node/blob/development/LICENSE) +[![LoC](https://tokei.rs/b1/github/sentinel-official/dvpn-node)](https://github.com/sentinel-official/dvpn-node) + * [Setup](https://github.com/sentinel-official/docs/tree/master/guides/nodes/dVPN/SETUP.md "Setup") * [Configuration](https://github.com/sentinel-official/docs/tree/master/guides/nodes/dVPN/CONFIGURATION.md "Configuration") * [Start](https://github.com/sentinel-official/docs/tree/master/guides/nodes/dVPN/START.md "Start") From 85ec150930438218bf531d62bc58c607509943ce Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Thu, 10 Jun 2021 00:36:22 +0530 Subject: [PATCH 20/26] Create LICENCE --- LICENSE | 201 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 201 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..52172b7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [2017] [Sentinel] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. From 96664aca3407f0992995de067a93fad1b24940f3 Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Thu, 10 Jun 2021 03:06:29 +0530 Subject: [PATCH 21/26] Added ZeroLogger and some logs --- cmd/start.go | 29 ++++++++++++++++++++++------- go.mod | 1 + lite/client.go | 10 +++++++--- lite/query.go | 5 +++++ lite/tx.go | 5 +++++ main.go | 2 ++ node/jobs.go | 4 ++++ node/node.go | 12 ++++++++++++ types/keys.go | 7 +++++-- utils/logger.go | 41 +++++++++++++++++++++++++++++++++++++++++ 10 files changed, 104 insertions(+), 12 deletions(-) create mode 100644 utils/logger.go diff --git a/cmd/start.go b/cmd/start.go index de7f17c..ecfcbbb 100644 --- a/cmd/start.go +++ b/cmd/start.go @@ -3,7 +3,6 @@ package cmd import ( "bufio" "fmt" - "os" "os/exec" "path/filepath" "strings" @@ -11,14 +10,12 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/std" - sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/gorilla/mux" "github.com/sentinel-official/hub" "github.com/sentinel-official/hub/params" "github.com/spf13/cobra" "github.com/spf13/viper" - "github.com/tendermint/tendermint/libs/log" rpchttp "github.com/tendermint/tendermint/rpc/client/http" "github.com/sentinel-official/dvpn-node/context" @@ -41,30 +38,39 @@ func StartCmd() *cobra.Command { path = filepath.Join(home, types.ConfigFileName) ) + logger, err := utils.PrepareLogger() + if err != nil { + return err + } + v := viper.New() v.SetConfigFile(path) + logger.Info("Reading configuration file", "path", path) cfg, err := types.ReadInConfig(v) if err != nil { return err } + + logger.Info("Validating configuration", "data", cfg) if err := cfg.Validate(); err != nil { return err } - ipv4Pool, err := wgtypes.NewIPv4PoolFromCIDR("10.8.0.2/24") + logger.Info("Creating IPv4 pool", "CIDR", types.DefaultIPv4CIDR) + ipv4Pool, err := wgtypes.NewIPv4PoolFromCIDR(types.DefaultIPv4CIDR) if err != nil { return err } - ipv6Pool, err := wgtypes.NewIPv6PoolFromCIDR("fd86:ea04:1115::2/120") + logger.Info("Creating IPv6 pool", "CIDR", types.DefaultIPv6CIDR) + ipv6Pool, err := wgtypes.NewIPv6PoolFromCIDR(types.DefaultIPv6CIDR) if err != nil { return err } var ( encoding = params.MakeEncodingConfig() - logger = log.NewTMLogger(log.NewSyncWriter(os.Stdout)) service = wireguard.NewWireGuard(wgtypes.NewIPPool(ipv4Pool, ipv6Pool)) reader = bufio.NewReader(cmd.InOrStdin()) ) @@ -72,12 +78,14 @@ func StartCmd() *cobra.Command { std.RegisterInterfaces(encoding.InterfaceRegistry) hub.ModuleBasics.RegisterInterfaces(encoding.InterfaceRegistry) + logger.Info("Initializing RPC HTTP client", "address", cfg.Chain.RPCAddress, "endpoint", "/websocket") rpcclient, err := rpchttp.New(cfg.Chain.RPCAddress, "/websocket") if err != nil { return err } - kr, err := keyring.New(sdk.KeyringServiceName(), cfg.Keyring.Backend, home, reader) + logger.Info("Initializing keyring", "name", types.KeyringName, "backend", cfg.Keyring.Backend) + kr, err := keyring.New(types.KeyringName, cfg.Keyring.Backend, home, reader) if err != nil { return err } @@ -100,6 +108,7 @@ func StartCmd() *cobra.Command { WithInterfaceRegistry(encoding.InterfaceRegistry). WithKeyring(kr). WithLegacyAmino(encoding.Amino). + WithLogger(logger). WithNodeURI(cfg.Chain.RPCAddress). WithSimulateAndExecute(cfg.Chain.SimulateAndExecute). WithTxConfig(encoding.TxConfig) @@ -112,15 +121,19 @@ func StartCmd() *cobra.Command { return fmt.Errorf("account does not exist with address %s", client.FromAddress()) } + logger.Info("Fetching GeoIP location info...") location, err := utils.FetchGeoIPLocation() if err != nil { return err } + logger.Info("GeoIP location info", "city", location.City, "country", location.Country) + logger.Info("Performing internet speed test...") bandwidth, err := utils.Bandwidth() if err != nil { return err } + logger.Info("Internet speed test result", "data", bandwidth) if cfg.Handshake.Enable { if err := runHandshakeDaemon(cfg.Handshake.Peers); err != nil { @@ -128,10 +141,12 @@ func StartCmd() *cobra.Command { } } + logger.Info("Initializing underlying VPN service", "type", service.Type()) if err := service.Init(home); err != nil { return err } + logger.Info("Starting underlying VPN service", "type", service.Type()) if err := service.Start(); err != nil { return err } diff --git a/go.mod b/go.mod index be561da..a69aa3b 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( github.com/cosmos/go-bip39 v1.0.0 github.com/gorilla/mux v1.8.0 github.com/pkg/errors v0.9.1 + github.com/rs/zerolog v1.21.0 github.com/sentinel-official/hub v0.6.3 github.com/showwin/speedtest-go v1.1.2 github.com/spf13/cobra v1.1.3 diff --git a/lite/client.go b/lite/client.go index abfdedc..2db0f68 100644 --- a/lite/client.go +++ b/lite/client.go @@ -13,13 +13,15 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" + "github.com/tendermint/tendermint/libs/log" rpcclient "github.com/tendermint/tendermint/rpc/client" ) type Client struct { - ctx client.Context - txf tx.Factory - mutex sync.Mutex + ctx client.Context + txf tx.Factory + logger log.Logger + mutex sync.Mutex } func NewClient() *Client { @@ -58,6 +60,7 @@ func (c *Client) WithInput(v io.Reader) *Client { c.ctx.Input func (c *Client) WithJSONMarshaler(v codec.JSONMarshaler) *Client { c.ctx.JSONMarshaler = v; return c } func (c *Client) WithKeyringDir(v string) *Client { c.ctx.KeyringDir = v; return c } func (c *Client) WithLegacyAmino(v *codec.LegacyAmino) *Client { c.ctx.LegacyAmino = v; return c } +func (c *Client) WithLogger(v log.Logger) *Client { c.logger = v; return c } func (c *Client) WithNodeURI(v string) *Client { c.ctx.NodeURI = v; return c } func (c *Client) WithOffline(v bool) *Client { c.ctx.Offline = v; return c } func (c *Client) WithOutput(v io.Writer) *Client { c.ctx.Output = v; return c } @@ -131,6 +134,7 @@ func (c *Client) WithTxConfig(v client.TxConfig) *Client { } func (c *Client) AccountRetriever() client.AccountRetriever { return c.ctx.AccountRetriever } +func (c *Client) BroadcastMode() string { return c.ctx.BroadcastMode } func (c *Client) ChainID() string { return c.ctx.ChainID } func (c *Client) Client() rpcclient.Client { return c.ctx.Client } func (c *Client) From() string { return c.ctx.From } diff --git a/lite/query.go b/lite/query.go index 3c84fa6..76d7210 100644 --- a/lite/query.go +++ b/lite/query.go @@ -22,6 +22,7 @@ func (c *Client) QueryAccount(address sdk.AccAddress) (authtypes.AccountI, error qc = authtypes.NewQueryClient(c.ctx) ) + c.logger.Info("Querying account", "address", address) res, err := qc.Account(context.Background(), &authtypes.QueryAccountRequest{Address: address.String()}) if err != nil { @@ -40,6 +41,7 @@ func (c *Client) QueryNode(address hubtypes.NodeAddress) (*nodetypes.Node, error qc = nodetypes.NewQueryServiceClient(c.ctx) ) + c.logger.Info("Querying node", "address", address) res, err := qc.QueryNode(context.Background(), nodetypes.NewQueryNodeRequest(address)) if err != nil { @@ -54,6 +56,7 @@ func (c *Client) QuerySubscription(id uint64) (*subscriptiontypes.Subscription, qc = subscriptiontypes.NewQueryServiceClient(c.ctx) ) + c.logger.Info("Querying subscription", "id", id) res, err := qc.QuerySubscription(context.Background(), subscriptiontypes.NewQuerySubscriptionRequest(id)) if err != nil { @@ -68,6 +71,7 @@ func (c *Client) QueryQuota(id uint64, address sdk.AccAddress) (*subscriptiontyp qc = subscriptiontypes.NewQueryServiceClient(c.ctx) ) + c.logger.Info("Querying quota", "id", id, "address", address) res, err := qc.QueryQuota(context.Background(), subscriptiontypes.NewQueryQuotaRequest(id, address)) if err != nil { @@ -82,6 +86,7 @@ func (c *Client) QuerySession(id uint64) (*sessiontypes.Session, error) { qc = sessiontypes.NewQueryServiceClient(c.ctx) ) + c.logger.Info("Querying session", "id", id) res, err := qc.QuerySession(context.Background(), sessiontypes.NewQuerySessionRequest(id)) if err != nil { diff --git a/lite/tx.go b/lite/tx.go index 4d9bf5e..f442af3 100644 --- a/lite/tx.go +++ b/lite/tx.go @@ -33,6 +33,9 @@ func (c *Client) BroadcastTx(messages ...sdk.Msg) (res *sdk.TxResponse, err erro txf = txf.WithGas(adjusted) } + c.logger.Info("Preparing transaction with data", "gas", txf.Gas(), + "messages", len(messages), "sequence", txf.Sequence()) + txb, err := tx.BuildUnsignedTx(txf, messages...) if err != nil { return nil, err @@ -47,6 +50,7 @@ func (c *Client) BroadcastTx(messages ...sdk.Msg) (res *sdk.TxResponse, err erro return nil, err } + c.logger.Info("Broadcasting transaction", "mode", c.BroadcastMode(), "size", len(txBytes)) err = retry.Do(func() error { res, err = c.ctx.BroadcastTx(txBytes) switch { @@ -61,5 +65,6 @@ func (c *Client) BroadcastTx(messages ...sdk.Msg) (res *sdk.TxResponse, err erro } }, retry.Attempts(5)) + c.logger.Info("Transaction result", "tx_hash", res.TxHash, "code", res.Code, "codespace", res.Codespace) return res, err } diff --git a/main.go b/main.go index 8051bb1..ead551b 100644 --- a/main.go +++ b/main.go @@ -35,9 +35,11 @@ func main() { ) root.PersistentFlags().String(flags.FlagHome, types.DefaultHomeDirectory, "home") + root.PersistentFlags().String(flags.FlagLogFormat, "plain", "log format") root.PersistentFlags().String(flags.FlagLogLevel, "info", "log level") _ = viper.BindPFlag(flags.FlagHome, root.PersistentFlags().Lookup(flags.FlagHome)) + _ = viper.BindPFlag(flags.FlagLogFormat, root.PersistentFlags().Lookup(flags.FlagLogFormat)) _ = viper.BindPFlag(flags.FlagLogLevel, root.PersistentFlags().Lookup(flags.FlagLogLevel)) _ = root.Execute() diff --git a/node/jobs.go b/node/jobs.go index 13de5a0..90998f1 100644 --- a/node/jobs.go +++ b/node/jobs.go @@ -11,6 +11,8 @@ import ( ) func (n *Node) jobUpdateStatus() error { + n.Logger().Info("Starting job", "name", "update_status", "interval", n.IntervalStatus()) + t := time.NewTicker(n.IntervalStatus()) for ; ; <-t.C { if err := n.updateStatus(); err != nil { @@ -20,6 +22,8 @@ func (n *Node) jobUpdateStatus() error { } func (n *Node) jobUpdateSessions() error { + n.Logger().Info("Starting job", "name", "update_sessions", "interval", n.IntervalSessions()) + t := time.NewTicker(n.IntervalSessions()) for ; ; <-t.C { var ( diff --git a/node/node.go b/node/node.go index 5042129..9dddd47 100644 --- a/node/node.go +++ b/node/node.go @@ -25,6 +25,8 @@ func NewNode(ctx *context.Context) *Node { } func (n *Node) Initialize() error { + n.Logger().Info("Initializing...") + result, err := n.Client().QueryNode(n.Address()) if err != nil { return err @@ -38,6 +40,8 @@ func (n *Node) Initialize() error { } func (n *Node) Start() error { + n.Logger().Info("Starting...") + go func() { if err := n.jobUpdateStatus(); err != nil { panic(err) @@ -59,6 +63,8 @@ func (n *Node) Start() error { } func (n *Node) register() error { + n.Logger().Info("Registering node...") + _, err := n.Client().BroadcastTx( nodetypes.NewMsgRegisterRequest( n.Operator(), @@ -72,6 +78,8 @@ func (n *Node) register() error { } func (n *Node) updateInfo() error { + n.Logger().Info("Updating node info...") + _, err := n.Client().BroadcastTx( nodetypes.NewMsgUpdateRequest( n.Address(), @@ -85,6 +93,8 @@ func (n *Node) updateInfo() error { } func (n *Node) updateStatus() error { + n.Logger().Info("Updating node status...") + _, err := n.Client().BroadcastTx( nodetypes.NewMsgSetStatusRequest( n.Address(), @@ -96,6 +106,8 @@ func (n *Node) updateStatus() error { } func (n *Node) updateSessions(items ...*types.Session) error { + n.Logger().Info("Updating sessions...") + messages := make([]sdk.Msg, 0, len(items)) for _, item := range items { messages = append(messages, diff --git a/types/keys.go b/types/keys.go index c2fba63..a13b984 100644 --- a/types/keys.go +++ b/types/keys.go @@ -6,8 +6,11 @@ import ( ) const ( - ConfigFileName = "config.toml" - FlagForce = "force" + ConfigFileName = "config.toml" + FlagForce = "force" + KeyringName = "sentinel" + DefaultIPv4CIDR = "10.8.0.2/24" + DefaultIPv6CIDR = "fd86:ea04:1115::2/120" ) var ( diff --git a/utils/logger.go b/utils/logger.go new file mode 100644 index 0000000..99d01af --- /dev/null +++ b/utils/logger.go @@ -0,0 +1,41 @@ +package utils + +import ( + "io" + "os" + "time" + + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/server" + "github.com/rs/zerolog" + "github.com/spf13/viper" + "github.com/tendermint/tendermint/config" + "github.com/tendermint/tendermint/libs/log" +) + +func PrepareLogger() (log.Logger, error) { + var ( + format = viper.GetString(flags.FlagLogFormat) + level = viper.GetString(flags.FlagLogLevel) + writer io.Writer = os.Stderr + ) + + if format == config.LogFormatPlain { + writer = zerolog.ConsoleWriter{ + Out: os.Stderr, + TimeFormat: time.RFC3339, + } + } + + logLevel, err := zerolog.ParseLevel(level) + if err != nil { + return nil, err + } + + return &server.ZeroLogWrapper{ + Logger: zerolog.New(writer). + Level(logLevel). + With().Timestamp(). + Logger(), + }, nil +} From c382b3eaad397e4832835ca74e72a5c72ffbbb1f Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Fri, 11 Jun 2021 02:04:42 +0530 Subject: [PATCH 22/26] Renamed import log to tmlog --- cmd/start.go | 30 +++++++++++++++--------------- context/context.go | 8 ++++---- lite/client.go | 7 ++++--- lite/query.go | 10 +++++----- lite/tx.go | 6 +++--- node/jobs.go | 4 ++-- node/node.go | 12 ++++++------ utils/logger.go | 4 ++-- 8 files changed, 41 insertions(+), 40 deletions(-) diff --git a/cmd/start.go b/cmd/start.go index ecfcbbb..0f4476a 100644 --- a/cmd/start.go +++ b/cmd/start.go @@ -38,7 +38,7 @@ func StartCmd() *cobra.Command { path = filepath.Join(home, types.ConfigFileName) ) - logger, err := utils.PrepareLogger() + log, err := utils.PrepareLogger() if err != nil { return err } @@ -46,24 +46,24 @@ func StartCmd() *cobra.Command { v := viper.New() v.SetConfigFile(path) - logger.Info("Reading configuration file", "path", path) + log.Info("Reading configuration file", "path", path) cfg, err := types.ReadInConfig(v) if err != nil { return err } - logger.Info("Validating configuration", "data", cfg) + log.Info("Validating configuration", "data", cfg) if err := cfg.Validate(); err != nil { return err } - logger.Info("Creating IPv4 pool", "CIDR", types.DefaultIPv4CIDR) + log.Info("Creating IPv4 pool", "CIDR", types.DefaultIPv4CIDR) ipv4Pool, err := wgtypes.NewIPv4PoolFromCIDR(types.DefaultIPv4CIDR) if err != nil { return err } - logger.Info("Creating IPv6 pool", "CIDR", types.DefaultIPv6CIDR) + log.Info("Creating IPv6 pool", "CIDR", types.DefaultIPv6CIDR) ipv6Pool, err := wgtypes.NewIPv6PoolFromCIDR(types.DefaultIPv6CIDR) if err != nil { return err @@ -78,13 +78,13 @@ func StartCmd() *cobra.Command { std.RegisterInterfaces(encoding.InterfaceRegistry) hub.ModuleBasics.RegisterInterfaces(encoding.InterfaceRegistry) - logger.Info("Initializing RPC HTTP client", "address", cfg.Chain.RPCAddress, "endpoint", "/websocket") + log.Info("Initializing RPC HTTP client", "address", cfg.Chain.RPCAddress, "endpoint", "/websocket") rpcclient, err := rpchttp.New(cfg.Chain.RPCAddress, "/websocket") if err != nil { return err } - logger.Info("Initializing keyring", "name", types.KeyringName, "backend", cfg.Keyring.Backend) + log.Info("Initializing keyring", "name", types.KeyringName, "backend", cfg.Keyring.Backend) kr, err := keyring.New(types.KeyringName, cfg.Keyring.Backend, home, reader) if err != nil { return err @@ -108,7 +108,7 @@ func StartCmd() *cobra.Command { WithInterfaceRegistry(encoding.InterfaceRegistry). WithKeyring(kr). WithLegacyAmino(encoding.Amino). - WithLogger(logger). + WithLogger(log). WithNodeURI(cfg.Chain.RPCAddress). WithSimulateAndExecute(cfg.Chain.SimulateAndExecute). WithTxConfig(encoding.TxConfig) @@ -121,19 +121,19 @@ func StartCmd() *cobra.Command { return fmt.Errorf("account does not exist with address %s", client.FromAddress()) } - logger.Info("Fetching GeoIP location info...") + log.Info("Fetching GeoIP location info...") location, err := utils.FetchGeoIPLocation() if err != nil { return err } - logger.Info("GeoIP location info", "city", location.City, "country", location.Country) + log.Info("GeoIP location info", "city", location.City, "country", location.Country) - logger.Info("Performing internet speed test...") + log.Info("Performing internet speed test...") bandwidth, err := utils.Bandwidth() if err != nil { return err } - logger.Info("Internet speed test result", "data", bandwidth) + log.Info("Internet speed test result", "data", bandwidth) if cfg.Handshake.Enable { if err := runHandshakeDaemon(cfg.Handshake.Peers); err != nil { @@ -141,12 +141,12 @@ func StartCmd() *cobra.Command { } } - logger.Info("Initializing underlying VPN service", "type", service.Type()) + log.Info("Initializing underlying VPN service", "type", service.Type()) if err := service.Init(home); err != nil { return err } - logger.Info("Starting underlying VPN service", "type", service.Type()) + log.Info("Starting underlying VPN service", "type", service.Type()) if err := service.Start(); err != nil { return err } @@ -159,7 +159,7 @@ func StartCmd() *cobra.Command { rest.RegisterRoutes(ctx, router) ctx = ctx. - WithLogger(logger). + WithLogger(log). WithService(service). WithRouter(router). WithConfig(cfg). diff --git a/context/context.go b/context/context.go index 6277a41..51c1f8a 100644 --- a/context/context.go +++ b/context/context.go @@ -6,14 +6,14 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/gorilla/mux" hubtypes "github.com/sentinel-official/hub/types" - "github.com/tendermint/tendermint/libs/log" + tmlog "github.com/tendermint/tendermint/libs/log" "github.com/sentinel-official/dvpn-node/lite" "github.com/sentinel-official/dvpn-node/types" ) type Context struct { - logger log.Logger + logger tmlog.Logger service types.Service bandwidth *hubtypes.Bandwidth client *lite.Client @@ -31,7 +31,7 @@ func (c *Context) WithBandwidth(v *hubtypes.Bandwidth) *Context { c.bandwidth = func (c *Context) WithClient(v *lite.Client) *Context { c.client = v; return c } func (c *Context) WithConfig(v *types.Config) *Context { c.config = v; return c } func (c *Context) WithLocation(v *types.GeoIPLocation) *Context { c.location = v; return c } -func (c *Context) WithLogger(v log.Logger) *Context { c.logger = v; return c } +func (c *Context) WithLogger(v tmlog.Logger) *Context { c.logger = v; return c } func (c *Context) WithRouter(v *mux.Router) *Context { c.router = v; return c } func (c *Context) WithService(v types.Service) *Context { c.service = v; return c } func (c *Context) WithSessions(v *types.Sessions) *Context { c.sessions = v; return c } @@ -45,7 +45,7 @@ func (c *Context) IntervalSessions() time.Duration { return c.Config().Node.Inte func (c *Context) IntervalStatus() time.Duration { return c.Config().Node.IntervalStatus } func (c *Context) ListenOn() string { return c.Config().Node.ListenOn } func (c *Context) Location() *types.GeoIPLocation { return c.location } -func (c *Context) Logger() log.Logger { return c.logger } +func (c *Context) Log() tmlog.Logger { return c.logger } func (c *Context) Moniker() string { return c.Config().Node.Moniker } func (c *Context) Operator() sdk.AccAddress { return c.client.FromAddress() } func (c *Context) RemoteURL() string { return c.Config().Node.RemoteURL } diff --git a/lite/client.go b/lite/client.go index 2db0f68..5dde6e0 100644 --- a/lite/client.go +++ b/lite/client.go @@ -13,14 +13,14 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" - "github.com/tendermint/tendermint/libs/log" + tmlog "github.com/tendermint/tendermint/libs/log" rpcclient "github.com/tendermint/tendermint/rpc/client" ) type Client struct { ctx client.Context txf tx.Factory - logger log.Logger + logger tmlog.Logger mutex sync.Mutex } @@ -60,7 +60,7 @@ func (c *Client) WithInput(v io.Reader) *Client { c.ctx.Input func (c *Client) WithJSONMarshaler(v codec.JSONMarshaler) *Client { c.ctx.JSONMarshaler = v; return c } func (c *Client) WithKeyringDir(v string) *Client { c.ctx.KeyringDir = v; return c } func (c *Client) WithLegacyAmino(v *codec.LegacyAmino) *Client { c.ctx.LegacyAmino = v; return c } -func (c *Client) WithLogger(v log.Logger) *Client { c.logger = v; return c } +func (c *Client) WithLogger(v tmlog.Logger) *Client { c.logger = v; return c } func (c *Client) WithNodeURI(v string) *Client { c.ctx.NodeURI = v; return c } func (c *Client) WithOffline(v bool) *Client { c.ctx.Offline = v; return c } func (c *Client) WithOutput(v io.Writer) *Client { c.ctx.Output = v; return c } @@ -140,5 +140,6 @@ func (c *Client) Client() rpcclient.Client { return c.ctx.Clien func (c *Client) From() string { return c.ctx.From } func (c *Client) FromAddress() sdk.AccAddress { return c.ctx.FromAddress } func (c *Client) Keyring() keyring.Keyring { return c.ctx.Keyring } +func (c *Client) Log() tmlog.Logger { return c.logger } func (c *Client) TxConfig() client.TxConfig { return c.ctx.TxConfig } func (c *Client) SimulateAndExecute() bool { return c.txf.SimulateAndExecute() } diff --git a/lite/query.go b/lite/query.go index 76d7210..778a00d 100644 --- a/lite/query.go +++ b/lite/query.go @@ -22,7 +22,7 @@ func (c *Client) QueryAccount(address sdk.AccAddress) (authtypes.AccountI, error qc = authtypes.NewQueryClient(c.ctx) ) - c.logger.Info("Querying account", "address", address) + c.Log().Info("Querying account", "address", address) res, err := qc.Account(context.Background(), &authtypes.QueryAccountRequest{Address: address.String()}) if err != nil { @@ -41,7 +41,7 @@ func (c *Client) QueryNode(address hubtypes.NodeAddress) (*nodetypes.Node, error qc = nodetypes.NewQueryServiceClient(c.ctx) ) - c.logger.Info("Querying node", "address", address) + c.Log().Info("Querying node", "address", address) res, err := qc.QueryNode(context.Background(), nodetypes.NewQueryNodeRequest(address)) if err != nil { @@ -56,7 +56,7 @@ func (c *Client) QuerySubscription(id uint64) (*subscriptiontypes.Subscription, qc = subscriptiontypes.NewQueryServiceClient(c.ctx) ) - c.logger.Info("Querying subscription", "id", id) + c.Log().Info("Querying subscription", "id", id) res, err := qc.QuerySubscription(context.Background(), subscriptiontypes.NewQuerySubscriptionRequest(id)) if err != nil { @@ -71,7 +71,7 @@ func (c *Client) QueryQuota(id uint64, address sdk.AccAddress) (*subscriptiontyp qc = subscriptiontypes.NewQueryServiceClient(c.ctx) ) - c.logger.Info("Querying quota", "id", id, "address", address) + c.Log().Info("Querying quota", "id", id, "address", address) res, err := qc.QueryQuota(context.Background(), subscriptiontypes.NewQueryQuotaRequest(id, address)) if err != nil { @@ -86,7 +86,7 @@ func (c *Client) QuerySession(id uint64) (*sessiontypes.Session, error) { qc = sessiontypes.NewQueryServiceClient(c.ctx) ) - c.logger.Info("Querying session", "id", id) + c.Log().Info("Querying session", "id", id) res, err := qc.QuerySession(context.Background(), sessiontypes.NewQuerySessionRequest(id)) if err != nil { diff --git a/lite/tx.go b/lite/tx.go index f442af3..a6a4e29 100644 --- a/lite/tx.go +++ b/lite/tx.go @@ -33,7 +33,7 @@ func (c *Client) BroadcastTx(messages ...sdk.Msg) (res *sdk.TxResponse, err erro txf = txf.WithGas(adjusted) } - c.logger.Info("Preparing transaction with data", "gas", txf.Gas(), + c.Log().Info("Preparing transaction with data", "gas", txf.Gas(), "messages", len(messages), "sequence", txf.Sequence()) txb, err := tx.BuildUnsignedTx(txf, messages...) @@ -50,7 +50,7 @@ func (c *Client) BroadcastTx(messages ...sdk.Msg) (res *sdk.TxResponse, err erro return nil, err } - c.logger.Info("Broadcasting transaction", "mode", c.BroadcastMode(), "size", len(txBytes)) + c.Log().Info("Broadcasting transaction", "mode", c.BroadcastMode(), "size", len(txBytes)) err = retry.Do(func() error { res, err = c.ctx.BroadcastTx(txBytes) switch { @@ -65,6 +65,6 @@ func (c *Client) BroadcastTx(messages ...sdk.Msg) (res *sdk.TxResponse, err erro } }, retry.Attempts(5)) - c.logger.Info("Transaction result", "tx_hash", res.TxHash, "code", res.Code, "codespace", res.Codespace) + c.Log().Info("Transaction result", "tx_hash", res.TxHash, "code", res.Code, "codespace", res.Codespace) return res, err } diff --git a/node/jobs.go b/node/jobs.go index 90998f1..955ed9d 100644 --- a/node/jobs.go +++ b/node/jobs.go @@ -11,7 +11,7 @@ import ( ) func (n *Node) jobUpdateStatus() error { - n.Logger().Info("Starting job", "name", "update_status", "interval", n.IntervalStatus()) + n.Log().Info("Starting job", "name", "update_status", "interval", n.IntervalStatus()) t := time.NewTicker(n.IntervalStatus()) for ; ; <-t.C { @@ -22,7 +22,7 @@ func (n *Node) jobUpdateStatus() error { } func (n *Node) jobUpdateSessions() error { - n.Logger().Info("Starting job", "name", "update_sessions", "interval", n.IntervalSessions()) + n.Log().Info("Starting job", "name", "update_sessions", "interval", n.IntervalSessions()) t := time.NewTicker(n.IntervalSessions()) for ; ; <-t.C { diff --git a/node/node.go b/node/node.go index 9dddd47..70e0673 100644 --- a/node/node.go +++ b/node/node.go @@ -25,7 +25,7 @@ func NewNode(ctx *context.Context) *Node { } func (n *Node) Initialize() error { - n.Logger().Info("Initializing...") + n.Log().Info("Initializing...") result, err := n.Client().QueryNode(n.Address()) if err != nil { @@ -40,7 +40,7 @@ func (n *Node) Initialize() error { } func (n *Node) Start() error { - n.Logger().Info("Starting...") + n.Log().Info("Starting...") go func() { if err := n.jobUpdateStatus(); err != nil { @@ -63,7 +63,7 @@ func (n *Node) Start() error { } func (n *Node) register() error { - n.Logger().Info("Registering node...") + n.Log().Info("Registering node...") _, err := n.Client().BroadcastTx( nodetypes.NewMsgRegisterRequest( @@ -78,7 +78,7 @@ func (n *Node) register() error { } func (n *Node) updateInfo() error { - n.Logger().Info("Updating node info...") + n.Log().Info("Updating node info...") _, err := n.Client().BroadcastTx( nodetypes.NewMsgUpdateRequest( @@ -93,7 +93,7 @@ func (n *Node) updateInfo() error { } func (n *Node) updateStatus() error { - n.Logger().Info("Updating node status...") + n.Log().Info("Updating node status...") _, err := n.Client().BroadcastTx( nodetypes.NewMsgSetStatusRequest( @@ -106,7 +106,7 @@ func (n *Node) updateStatus() error { } func (n *Node) updateSessions(items ...*types.Session) error { - n.Logger().Info("Updating sessions...") + n.Log().Info("Updating sessions...") messages := make([]sdk.Msg, 0, len(items)) for _, item := range items { diff --git a/utils/logger.go b/utils/logger.go index 99d01af..ea67410 100644 --- a/utils/logger.go +++ b/utils/logger.go @@ -10,10 +10,10 @@ import ( "github.com/rs/zerolog" "github.com/spf13/viper" "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/libs/log" + tmlog "github.com/tendermint/tendermint/libs/log" ) -func PrepareLogger() (log.Logger, error) { +func PrepareLogger() (tmlog.Logger, error) { var ( format = viper.GetString(flags.FlagLogFormat) level = viper.GetString(flags.FlagLogLevel) From 6ddc2e194e7aabe1a59c751315075d88c3f95ed3 Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Fri, 11 Jun 2021 03:58:13 +0530 Subject: [PATCH 23/26] Added RWMutex for sessions and added more info log --- context/context.go | 1 - node/jobs.go | 26 +++++++++++++++++----- rest/session/handlers.go | 4 ++++ rest/status/handlers.go | 2 +- types/session.go | 48 +++++++++++++++++++++++++++------------- 5 files changed, 59 insertions(+), 22 deletions(-) diff --git a/context/context.go b/context/context.go index 51c1f8a..7360a3d 100644 --- a/context/context.go +++ b/context/context.go @@ -38,7 +38,6 @@ func (c *Context) WithSessions(v *types.Sessions) *Context { c.sessions = v func (c *Context) Address() hubtypes.NodeAddress { return c.Operator().Bytes() } func (c *Context) Bandwidth() *hubtypes.Bandwidth { return c.bandwidth } -func (c *Context) Type() uint64 { return c.service.Type() } func (c *Context) Client() *lite.Client { return c.client } func (c *Context) Config() *types.Config { return c.config } func (c *Context) IntervalSessions() time.Duration { return c.Config().Node.IntervalSessions } diff --git a/node/jobs.go b/node/jobs.go index 955ed9d..b2a7963 100644 --- a/node/jobs.go +++ b/node/jobs.go @@ -34,10 +34,12 @@ func (n *Node) jobUpdateSessions() error { if err != nil { return err } + n.Log().Info("Connected peers", "count", len(peers)) for _, peer := range peers { item := n.Sessions().GetForKey(peer.Key) if item == nil { + n.Log().Error("Unknown connected peer", "info", peer) continue } @@ -47,24 +49,38 @@ func (n *Node) jobUpdateSessions() error { } var ( - consumed = sdk.NewInt(peer.Upload + peer.Download) - inactive = session.Status.Equal(hubtypes.StatusInactive) || - peer.Download == session.Bandwidth.Upload.Int64() + remove, skip = false, false + consumed = sdk.NewInt(peer.Upload + peer.Download) ) - if inactive || consumed.GT(item.Available) { + switch { + case session.Status.Equal(hubtypes.StatusInactive): + remove, skip = true, true + n.Log().Info("Invalid session status", "peer", peer, "item", item, "session", session) + case peer.Download == session.Bandwidth.Upload.Int64(): + remove, skip = true, true + n.Log().Info("Stale peer connection", "peer", peer, "item", item, "session", session) + case consumed.GT(item.Available): + remove, skip = true, false + n.Log().Info("Peer quota exceeded", "peer", peer, "item", item, "session", session) + } + + if remove { key, err := base64.StdEncoding.DecodeString(peer.Key) if err != nil { return err } + if err := n.Service().RemovePeer(key); err != nil { return err } + n.Log().Info("Removed peer for underlying service...") n.Sessions().DeleteForKey(item.Key) n.Sessions().DeleteForAddress(item.Address) + n.Log().Info("Removed session...") } - if inactive { + if skip { continue } diff --git a/rest/session/handlers.go b/rest/session/handlers.go index 9163011..cb9be53 100644 --- a/rest/session/handlers.go +++ b/rest/session/handlers.go @@ -164,11 +164,13 @@ func handlerAddSession(ctx *context.Context) http.HandlerFunc { return } + ctx.Log().Info("Adding new peer", "key", key) result, err := ctx.Service().AddPeer(key) if err != nil { utils.WriteErrorToResponse(w, http.StatusInternalServerError, 9, err.Error()) return } + ctx.Log().Info("Added new peer", "key", key, "count", ctx.Service().PeersCount()) ctx.Sessions().Put( &types.Session{ @@ -179,6 +181,8 @@ func handlerAddSession(ctx *context.Context) http.HandlerFunc { ConnectedAt: time.Now(), }, ) + ctx.Log().Info("Added new session", "id", id, + "address", address, "count", ctx.Sessions().Len()) result = append(result, net.ParseIP(ctx.Location().IP).To4()...) result = append(result, ctx.Service().Info()...) diff --git a/rest/status/handlers.go b/rest/status/handlers.go index 054ba27..a995bd9 100644 --- a/rest/status/handlers.go +++ b/rest/status/handlers.go @@ -34,7 +34,7 @@ func HandlerGetStatus(ctx *context.Context) http.HandlerFunc { Peers: ctx.Service().PeersCount(), Price: ctx.Price().String(), Provider: ctx.Provider().String(), - Type: ctx.Type(), + Type: ctx.Service().Type(), Version: version.Version, }) } diff --git a/types/session.go b/types/session.go index 4d77deb..36247e9 100644 --- a/types/session.go +++ b/types/session.go @@ -32,8 +32,8 @@ type Session struct { } type Sessions struct { - m map[string]interface{} - mutex sync.Mutex + sync.RWMutex + m map[string]interface{} } func NewSessions() *Sessions { @@ -42,23 +42,18 @@ func NewSessions() *Sessions { } } -func (s *Sessions) delete(v *Session) { - s.mutex.Lock() - defer s.mutex.Unlock() - - delete(s.m, withTypePrefix(v.Key)) - delete(s.m, withTypePrefix(v.Address)) -} - func (s *Sessions) Put(v *Session) { - s.mutex.Lock() - defer s.mutex.Unlock() + s.Lock() + defer s.Unlock() s.m[withTypePrefix(v.Key)] = v s.m[withTypePrefix(v.Address)] = v.Key } func (s *Sessions) GetForKey(k string) *Session { + s.RLock() + defer s.RUnlock() + v, ok := s.m[withTypePrefix(k)] if !ok { return nil @@ -68,12 +63,28 @@ func (s *Sessions) GetForKey(k string) *Session { } func (s *Sessions) GetForAddress(k sdk.AccAddress) *Session { + s.RLock() + defer s.RUnlock() + v, ok := s.m[withTypePrefix(k)] if !ok { return nil } - return s.GetForKey(v.(string)) + v, ok = s.m[withTypePrefix(v.(string))] + if !ok { + return nil + } + + return v.(*Session) +} + +func (s *Sessions) Delete(v *Session) { + s.Lock() + defer s.Unlock() + + delete(s.m, withTypePrefix(v.Key)) + delete(s.m, withTypePrefix(v.Address)) } func (s *Sessions) DeleteForKey(k string) { @@ -82,7 +93,7 @@ func (s *Sessions) DeleteForKey(k string) { return } - s.delete(v) + s.Delete(v) } func (s *Sessions) DeleteForAddress(k sdk.AccAddress) { @@ -91,5 +102,12 @@ func (s *Sessions) DeleteForAddress(k sdk.AccAddress) { return } - s.delete(v) + s.Delete(v) +} + +func (s *Sessions) Len() int { + s.RLock() + defer s.RUnlock() + + return len(s.m) / 2 } From 955c04259dbd26031c7a630dffe943b2d5b370d6 Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Fri, 11 Jun 2021 04:11:57 +0530 Subject: [PATCH 24/26] Added JSON tags for config --- services/wireguard/types/config.go | 6 ++--- types/config.go | 42 +++++++++++++++--------------- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/services/wireguard/types/config.go b/services/wireguard/types/config.go index 3d2b9cb..2bcdf48 100644 --- a/services/wireguard/types/config.go +++ b/services/wireguard/types/config.go @@ -35,9 +35,9 @@ private_key = "{{ .PrivateKey }}" ) type Config struct { - Interface string `mapstructure:"interface"` - ListenPort uint16 `mapstructure:"listen_port"` - PrivateKey string `mapstructure:"private_key"` + Interface string `json:"interface" mapstructure:"interface"` + ListenPort uint16 `json:"listen_port" mapstructure:"listen_port"` + PrivateKey string `json:"private_key" mapstructure:"private_key"` } func NewConfig() *Config { diff --git a/types/config.go b/types/config.go index ae13f21..e7b69a1 100644 --- a/types/config.go +++ b/types/config.go @@ -84,12 +84,12 @@ remote_url = "{{ .Node.RemoteURL }}" ) type ChainConfig struct { - GasAdjustment float64 `mapstructure:"gas_adjustment"` - GasPrices string `mapstructure:"gas_prices"` - Gas uint64 `mapstructure:"gas"` - ID string `mapstructure:"id"` - RPCAddress string `mapstructure:"rpc_address"` - SimulateAndExecute bool `mapstructure:"simulate_and_execute"` + GasAdjustment float64 `json:"gas_adjustment" mapstructure:"gas_adjustment"` + GasPrices string `json:"gas_prices" mapstructure:"gas_prices"` + Gas uint64 `json:"gas" mapstructure:"gas"` + ID string `json:"id" mapstructure:"id"` + RPCAddress string `json:"rpc_address" mapstructure:"rpc_address"` + SimulateAndExecute bool `json:"simulate_and_execute" mapstructure:"simulate_and_execute"` } func NewChainConfig() *ChainConfig { @@ -128,8 +128,8 @@ func (c *ChainConfig) WithDefaultValues() *ChainConfig { } type HandshakeConfig struct { - Enable bool `mapstructure:"enable"` - Peers uint64 `mapstructure:"peers"` + Enable bool `json:"enable" mapstructure:"enable"` + Peers uint64 `json:"peers" mapstructure:"peers"` } func NewHandshakeConfig() *HandshakeConfig { @@ -154,8 +154,8 @@ func (c *HandshakeConfig) WithDefaultValues() *HandshakeConfig { } type KeyringConfig struct { - Backend string `mapstructure:"backend"` - From string `mapstructure:"from"` + Backend string `json:"backend" mapstructure:"backend"` + From string `json:"from" mapstructure:"from"` } func NewKeyringConfig() *KeyringConfig { @@ -183,13 +183,13 @@ func (c *KeyringConfig) WithDefaultValues() *KeyringConfig { } type NodeConfig struct { - IntervalSessions time.Duration `mapstructure:"interval_sessions"` - IntervalStatus time.Duration `mapstructure:"interval_status"` - ListenOn string `mapstructure:"listen_on"` - Moniker string `mapstructure:"moniker"` - Price string `mapstructure:"price"` - Provider string `mapstructure:"provider"` - RemoteURL string `mapstructure:"remote_url"` + IntervalSessions time.Duration `json:"interval_sessions" mapstructure:"interval_sessions"` + IntervalStatus time.Duration `json:"interval_status" mapstructure:"interval_status"` + ListenOn string `json:"listen_on" mapstructure:"listen_on"` + Moniker string `json:"moniker" mapstructure:"moniker"` + Price string `json:"price" mapstructure:"price"` + Provider string `json:"provider" mapstructure:"provider"` + RemoteURL string `json:"remote_url" mapstructure:"remote_url"` } func NewNodeConfig() *NodeConfig { @@ -238,10 +238,10 @@ func (c *NodeConfig) WithDefaultValues() *NodeConfig { } type Config struct { - Chain *ChainConfig `mapstructure:"chain"` - Handshake *HandshakeConfig `mapstructure:"handshake"` - Keyring *KeyringConfig `mapstructure:"keyring"` - Node *NodeConfig `mapstructure:"node"` + Chain *ChainConfig `json:"chain" mapstructure:"chain"` + Handshake *HandshakeConfig `json:"handshake" mapstructure:"handshake"` + Keyring *KeyringConfig `json:"keyring" mapstructure:"keyring"` + Node *NodeConfig `json:"node" mapstructure:"node"` } func NewConfig() *Config { From 77168c7e81351590698b531315f2c612e1c9b1b9 Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Fri, 11 Jun 2021 23:45:00 +0530 Subject: [PATCH 25/26] Added height for transaction result info log --- lite/tx.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lite/tx.go b/lite/tx.go index a6a4e29..e4a4e6d 100644 --- a/lite/tx.go +++ b/lite/tx.go @@ -65,6 +65,7 @@ func (c *Client) BroadcastTx(messages ...sdk.Msg) (res *sdk.TxResponse, err erro } }, retry.Attempts(5)) - c.Log().Info("Transaction result", "tx_hash", res.TxHash, "code", res.Code, "codespace", res.Codespace) + c.Log().Info("Transaction result", "tx_hash", res.TxHash, + "code", res.Code, "codespace", res.Codespace, "height", res.Height) return res, err } From c0cdcf5a57b3f90c48d7c1184111b1965c8cabeb Mon Sep 17 00:00:00 2001 From: Srinivas Baride Date: Sat, 12 Jun 2021 01:45:18 +0530 Subject: [PATCH 26/26] Fixed inaccurate condition for stale peers and added more info log --- lite/client.go | 19 +++++++++---------- lite/tx.go | 3 ++- node/jobs.go | 2 +- rest/session/handlers.go | 4 ++-- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/lite/client.go b/lite/client.go index 5dde6e0..74e0237 100644 --- a/lite/client.go +++ b/lite/client.go @@ -133,13 +133,12 @@ func (c *Client) WithTxConfig(v client.TxConfig) *Client { return c } -func (c *Client) AccountRetriever() client.AccountRetriever { return c.ctx.AccountRetriever } -func (c *Client) BroadcastMode() string { return c.ctx.BroadcastMode } -func (c *Client) ChainID() string { return c.ctx.ChainID } -func (c *Client) Client() rpcclient.Client { return c.ctx.Client } -func (c *Client) From() string { return c.ctx.From } -func (c *Client) FromAddress() sdk.AccAddress { return c.ctx.FromAddress } -func (c *Client) Keyring() keyring.Keyring { return c.ctx.Keyring } -func (c *Client) Log() tmlog.Logger { return c.logger } -func (c *Client) TxConfig() client.TxConfig { return c.ctx.TxConfig } -func (c *Client) SimulateAndExecute() bool { return c.txf.SimulateAndExecute() } +func (c *Client) BroadcastMode() string { return c.ctx.BroadcastMode } +func (c *Client) ChainID() string { return c.ctx.ChainID } +func (c *Client) Client() rpcclient.Client { return c.ctx.Client } +func (c *Client) From() string { return c.ctx.From } +func (c *Client) FromAddress() sdk.AccAddress { return c.ctx.FromAddress } +func (c *Client) Keyring() keyring.Keyring { return c.ctx.Keyring } +func (c *Client) Log() tmlog.Logger { return c.logger } +func (c *Client) TxConfig() client.TxConfig { return c.ctx.TxConfig } +func (c *Client) SimulateAndExecute() bool { return c.txf.SimulateAndExecute() } diff --git a/lite/tx.go b/lite/tx.go index e4a4e6d..90bbe30 100644 --- a/lite/tx.go +++ b/lite/tx.go @@ -13,7 +13,7 @@ func (c *Client) BroadcastTx(messages ...sdk.Msg) (res *sdk.TxResponse, err erro c.mutex.Lock() defer c.mutex.Unlock() - account, err := c.AccountRetriever().GetAccount(c.ctx, c.FromAddress()) + account, err := c.QueryAccount(c.FromAddress()) if err != nil { return nil, err } @@ -25,6 +25,7 @@ func (c *Client) BroadcastTx(messages ...sdk.Msg) (res *sdk.TxResponse, err erro ) if c.SimulateAndExecute() { + c.Log().Info("Calculating the gas by simulating the transaction...") _, adjusted, err := tx.CalculateGas(c.ctx.QueryWithData, txf, messages...) if err != nil { return nil, err diff --git a/node/jobs.go b/node/jobs.go index b2a7963..f9311df 100644 --- a/node/jobs.go +++ b/node/jobs.go @@ -57,7 +57,7 @@ func (n *Node) jobUpdateSessions() error { case session.Status.Equal(hubtypes.StatusInactive): remove, skip = true, true n.Log().Info("Invalid session status", "peer", peer, "item", item, "session", session) - case peer.Download == session.Bandwidth.Upload.Int64(): + case peer.Download == session.Bandwidth.Upload.Int64() && session.StatusAt.After(item.ConnectedAt): remove, skip = true, true n.Log().Info("Stale peer connection", "peer", peer, "item", item, "session", session) case consumed.GT(item.Available): diff --git a/rest/session/handlers.go b/rest/session/handlers.go index cb9be53..0b6551e 100644 --- a/rest/session/handlers.go +++ b/rest/session/handlers.go @@ -164,13 +164,13 @@ func handlerAddSession(ctx *context.Context) http.HandlerFunc { return } - ctx.Log().Info("Adding new peer", "key", key) + ctx.Log().Info("Adding new peer", "key", body.Key) result, err := ctx.Service().AddPeer(key) if err != nil { utils.WriteErrorToResponse(w, http.StatusInternalServerError, 9, err.Error()) return } - ctx.Log().Info("Added new peer", "key", key, "count", ctx.Service().PeersCount()) + ctx.Log().Info("Added new peer", "key", body.Key, "count", ctx.Service().PeersCount()) ctx.Sessions().Put( &types.Session{