diff --git a/.golangci/v1.27.0.yml b/.golangci/v1.27.0.yml index 0684bd75..c803e877 100644 --- a/.golangci/v1.27.0.yml +++ b/.golangci/v1.27.0.yml @@ -54,7 +54,7 @@ linters: - maligned - misspell - nakedret - - nestif + #- nestif #- nolintlint - prealloc - rowserrcheck diff --git a/LICENSE b/LICENSE index 261eeb9e..4abffa66 100644 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright [2019] [Sentinel] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/app/app.go b/app.go similarity index 90% rename from app/app.go rename to app.go index 3c3a693e..fc06e724 100644 --- a/app/app.go +++ b/app.go @@ -1,4 +1,4 @@ -package app +package hub import ( "encoding/json" @@ -28,9 +28,8 @@ import ( "github.com/tendermint/tendermint/libs/log" db "github.com/tendermint/tm-db" - "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/deposit" - "github.com/sentinel-official/hub/x/vpn" + "github.com/sentinel-official/hub/x/dvpn" + "github.com/sentinel-official/hub/x/dvpn/deposit" ) const ( @@ -54,8 +53,7 @@ var ( slashing.AppModuleBasic{}, crisis.AppModuleBasic{}, gov.NewAppModuleBasic(client.ProposalHandler, distribution.ProposalHandler), - deposit.AppModuleBasic{}, - vpn.AppModuleBasic{}, + dvpn.AppModuleBasic{}, ) moduleAccountPermissions = map[string][]string{ @@ -73,7 +71,6 @@ func MakeCodec() *codec.Codec { var cdc = codec.New() sdk.RegisterCodec(cdc) - types.RegisterCodec(cdc) codec.RegisterCrypto(cdc) codec.RegisterEvidences(cdc) ModuleBasics.RegisterCodec(cdc) @@ -99,13 +96,13 @@ type App struct { slashingKeeper slashing.Keeper crisisKeeper crisis.Keeper govKeeper gov.Keeper - depositKeeper deposit.Keeper - vpnKeeper vpn.Keeper + dVPNKeeper dvpn.Keeper } func NewApp(logger log.Logger, db db.DB, tracer io.Writer, latest bool, invarCheckPeriod uint, options ...func(*baseapp.BaseApp)) *App { cdc := MakeCodec() + baseApp := baseapp.NewBaseApp(appName, logger, db, auth.DefaultTxDecoder(cdc), options...) baseApp.SetCommitMultiStoreTracer(tracer) baseApp.SetAppVersion(version.Version) @@ -113,7 +110,7 @@ func NewApp(logger log.Logger, db db.DB, tracer io.Writer, latest bool, invarChe keys := sdk.NewKVStoreKeys(baseapp.MainStoreKey, params.StoreKey, auth.StoreKey, supply.StoreKey, staking.StoreKey, mint.StoreKey, distribution.StoreKey, slashing.StoreKey, gov.StoreKey, - deposit.StoreKey, vpn.StoreKeyNode, vpn.StoreKeySubscription, vpn.StoreKeySession, + dvpn.StoreKey, ) transientKeys := sdk.NewTransientStoreKeys(params.TStoreKey, staking.TStoreKey) @@ -196,15 +193,11 @@ func NewApp(logger log.Logger, db db.DB, tracer io.Writer, latest bool, invarChe govRouter) app.stakingKeeper = *stakingKeeper.SetHooks( staking.NewMultiStakingHooks(app.distributionKeeper.Hooks(), app.slashingKeeper.Hooks())) - app.depositKeeper = deposit.NewKeeper(app.cdc, - keys[deposit.StoreKey], + app.dVPNKeeper = dvpn.NewKeeper(app.cdc, + keys[dvpn.StoreKey], + app.paramsKeeper, + app.bankKeeper, app.supplyKeeper) - app.vpnKeeper = vpn.NewKeeper(app.cdc, - keys[vpn.StoreKeyNode], - keys[vpn.StoreKeySubscription], - keys[vpn.StoreKeySession], - app.paramsKeeper.Subspace(vpn.DefaultParamspace), - app.depositKeeper) app.manager = module.NewManager( genaccounts.NewAppModule(app.accountKeeper), @@ -218,17 +211,16 @@ func NewApp(logger log.Logger, db db.DB, tracer io.Writer, latest bool, invarChe slashing.NewAppModule(app.slashingKeeper, app.stakingKeeper), crisis.NewAppModule(&app.crisisKeeper), gov.NewAppModule(app.govKeeper, app.supplyKeeper), - deposit.NewAppModule(app.depositKeeper), - vpn.NewAppModule(app.vpnKeeper), + dvpn.NewAppModule(app.dVPNKeeper), ) // NOTE: order is very important here - app.manager.SetOrderBeginBlockers(mint.ModuleName, distribution.ModuleName, slashing.ModuleName) - app.manager.SetOrderEndBlockers(crisis.ModuleName, gov.ModuleName, staking.ModuleName, vpn.ModuleName) + app.manager.SetOrderBeginBlockers(mint.ModuleName, distribution.ModuleName, slashing.ModuleName, dvpn.ModuleName) + app.manager.SetOrderEndBlockers(crisis.ModuleName, gov.ModuleName, staking.ModuleName) app.manager.SetOrderInitGenesis( genaccounts.ModuleName, distribution.ModuleName, staking.ModuleName, auth.ModuleName, bank.ModuleName, slashing.ModuleName, gov.ModuleName, mint.ModuleName, - supply.ModuleName, crisis.ModuleName, genutil.ModuleName, deposit.ModuleName, vpn.ModuleName, + supply.ModuleName, crisis.ModuleName, genutil.ModuleName, dvpn.ModuleName, ) app.manager.RegisterInvariants(&app.crisisKeeper) diff --git a/cmd/sentinel-hub-cli/main.go b/cmd/sentinel-hub-cli/main.go index 55e6e271..6a9a0db5 100644 --- a/cmd/sentinel-hub-cli/main.go +++ b/cmd/sentinel-hub-cli/main.go @@ -8,27 +8,23 @@ import ( "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/lcd" "github.com/cosmos/cosmos-sdk/client/rpc" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/x/auth" authCli "github.com/cosmos/cosmos-sdk/x/auth/client/cli" authRest "github.com/cosmos/cosmos-sdk/x/auth/client/rest" - "github.com/cosmos/cosmos-sdk/x/bank" bankCli "github.com/cosmos/cosmos-sdk/x/bank/client/cli" "github.com/spf13/cobra" "github.com/spf13/viper" - "github.com/tendermint/go-amino" "github.com/tendermint/tendermint/libs/cli" + "github.com/sentinel-official/hub" "github.com/sentinel-official/hub/types" - - hub "github.com/sentinel-official/hub/app" ) func main() { cdc := hub.MakeCodec() - config := sdk.GetConfig() + config := types.GetConfig() config.SetBech32PrefixForAccount(types.Bech32PrefixAccAddr, types.Bech32PrefixAccPub) config.SetBech32PrefixForValidator(types.Bech32PrefixValAddr, types.Bech32PrefixValPub) config.SetBech32PrefixForConsensusNode(types.Bech32PrefixConsAddr, types.Bech32PrefixConsPub) @@ -48,13 +44,12 @@ func main() { cmd.AddCommand( rpc.StatusCommand(), client.ConfigCmd(hub.DefaultCLIHome), + client.LineBreak, + keys.Commands(), queryCmd(cdc), txCmd(cdc), - client.LineBreak, lcd.ServeCommand(cdc, registerRoutes), client.LineBreak, - keys.Commands(), - client.LineBreak, version.Cmd, client.NewCompletionCmd(cmd, true), ) @@ -65,7 +60,7 @@ func main() { } } -func queryCmd(cdc *amino.Codec) *cobra.Command { +func queryCmd(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "query", Aliases: []string{"q"}, @@ -73,12 +68,12 @@ func queryCmd(cdc *amino.Codec) *cobra.Command { } cmd.AddCommand( - authCli.GetAccountCmd(cdc), - client.LineBreak, - rpc.ValidatorCommand(cdc), rpc.BlockCommand(), - authCli.QueryTxsByEventsCmd(cdc), + rpc.ValidatorCommand(cdc), + client.LineBreak, + authCli.GetAccountCmd(cdc), authCli.QueryTxCmd(cdc), + authCli.QueryTxsByEventsCmd(cdc), client.LineBreak, ) @@ -86,31 +81,23 @@ func queryCmd(cdc *amino.Codec) *cobra.Command { return cmd } -func txCmd(cdc *amino.Codec) *cobra.Command { +func txCmd(cdc *codec.Codec) *cobra.Command { cmd := &cobra.Command{ Use: "tx", Short: "Transaction sub-commands", } cmd.AddCommand( - bankCli.SendTxCmd(cdc), - client.LineBreak, authCli.GetSignCommand(cdc), authCli.GetMultiSignCommand(cdc), - client.LineBreak, - authCli.GetBroadcastCommand(cdc), authCli.GetEncodeCommand(cdc), + authCli.GetBroadcastCommand(cdc), + client.LineBreak, + bankCli.SendTxCmd(cdc), client.LineBreak, ) hub.ModuleBasics.AddTxCommands(cmd, cdc) - - for _, cmd := range cmd.Commands() { - if cmd.Use == auth.ModuleName || cmd.Use == bank.ModuleName { - cmd.RemoveCommand(cmd) - } - } - return cmd } diff --git a/cmd/sentinel-hub-daemon/main.go b/cmd/sentinel-hub-daemon/main.go index a8d487bb..9dba1e15 100644 --- a/cmd/sentinel-hub-daemon/main.go +++ b/cmd/sentinel-hub-daemon/main.go @@ -8,7 +8,6 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/genaccounts" genaccountsCli "github.com/cosmos/cosmos-sdk/x/genaccounts/client/cli" genutilCli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" @@ -21,7 +20,7 @@ import ( tm "github.com/tendermint/tendermint/types" db "github.com/tendermint/tm-db" - hub "github.com/sentinel-official/hub/app" + "github.com/sentinel-official/hub" "github.com/sentinel-official/hub/types" ) @@ -36,7 +35,7 @@ var ( func main() { cdc := hub.MakeCodec() - config := sdk.GetConfig() + config := types.GetConfig() config.SetBech32PrefixForAccount(types.Bech32PrefixAccAddr, types.Bech32PrefixAccPub) config.SetBech32PrefixForValidator(types.Bech32PrefixValAddr, types.Bech32PrefixValPub) config.SetBech32PrefixForConsensusNode(types.Bech32PrefixConsAddr, types.Bech32PrefixConsPub) diff --git a/app/export.go b/export.go similarity index 99% rename from app/export.go rename to export.go index bc9b622e..be64aec2 100644 --- a/app/export.go +++ b/export.go @@ -1,4 +1,4 @@ -package app +package hub import ( "encoding/json" diff --git a/go.mod b/go.mod index a8dedefa..1cf8052f 100644 --- a/go.mod +++ b/go.mod @@ -7,8 +7,7 @@ require ( github.com/gorilla/mux v1.7.4 github.com/spf13/cobra v1.0.0 github.com/spf13/viper v1.7.0 - github.com/stretchr/testify v1.6.1 - github.com/tendermint/go-amino v0.15.1 github.com/tendermint/tendermint v0.32.12 github.com/tendermint/tm-db v0.2.0 + gopkg.in/yaml.v2 v2.2.7 ) diff --git a/go.sum b/go.sum index 78ba6c00..e7dd17ba 100644 --- a/go.sum +++ b/go.sum @@ -269,9 +269,8 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 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 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stumble/gorocksdb v0.0.3/go.mod h1:v6IHdFBXk5DJ1K4FZ0xi+eY737quiiBxYtSWXadLybY= github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= @@ -282,9 +281,8 @@ github.com/tendermint/btcd v0.1.1/go.mod h1:DC6/m53jtQzr/NFmMNEu0rxf18/ktVoVtMrn github.com/tendermint/crypto v0.0.0-20180820045704-3764759f34a5 h1:u8i49c+BxloX3XQ55cvzFNXplizZP/q00i+IlttUjAU= github.com/tendermint/crypto v0.0.0-20180820045704-3764759f34a5/go.mod h1:z4YtwM70uOnk8h0pjJYlj3zdYwi9l03By6iAIF5j/Pk= github.com/tendermint/go-amino v0.14.1/go.mod h1:i/UKE5Uocn+argJJBb12qTZsCDBcAYMbR92AaJVmKso= +github.com/tendermint/go-amino v0.15.0 h1:TC4e66P59W7ML9+bxio17CPKnxW3nKIRAYskntMAoRk= github.com/tendermint/go-amino v0.15.0/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME= -github.com/tendermint/go-amino v0.15.1 h1:D2uk35eT4iTsvJd9jWIetzthE5C0/k2QmMFkCN+4JgQ= -github.com/tendermint/go-amino v0.15.1/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME= github.com/tendermint/iavl v0.12.4 h1:hd1woxUGISKkfUWBA4mmmTwOua6PQZTJM/F0FDrmMV8= github.com/tendermint/iavl v0.12.4/go.mod h1:8LHakzt8/0G3/I8FUU0ReNx98S/EP6eyPJkAUvEXT/o= github.com/tendermint/tendermint v0.32.1/go.mod h1:jmPDAKuNkev9793/ivn/fTBnfpA9mGBww8MPRNPNxnU= @@ -298,6 +296,7 @@ github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGr github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= +github.com/zondax/hid v0.9.0 h1:eiT3P6vNxAEVxXMw66eZUAAnU2zD33JBkfG/EnfAKl8= github.com/zondax/hid v0.9.0/go.mod h1:l5wttcP0jwtdLjqjMMWFVEE7d1zO0jvSPA9OPZxWpEM= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= @@ -449,8 +448,6 @@ gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.7 h1:VUgggvou5XRW9mHwD/yXxIYSMtY0zoKQf/v226p2nyo= gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -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-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/simapp/app.go b/simapp/app.go deleted file mode 100644 index de63a4fe..00000000 --- a/simapp/app.go +++ /dev/null @@ -1,296 +0,0 @@ -package simapp - -import ( - "encoding/json" - "io" - "os" - - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/crisis" - "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/genaccounts" - "github.com/cosmos/cosmos-sdk/x/genutil" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/mint" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/params/client" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/cosmos/cosmos-sdk/x/supply" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/common" - "github.com/tendermint/tendermint/libs/log" - db "github.com/tendermint/tm-db" - - "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/deposit" - "github.com/sentinel-official/hub/x/vpn" -) - -const ( - appName = "SimApp" -) - -var ( - DefaultCLIHome = os.ExpandEnv("$HOME/.simapp") - DefaultNodeHome = os.ExpandEnv("$HOME/.simapp") - - ModuleBasics = module.NewBasicManager( - genaccounts.AppModuleBasic{}, - genutil.AppModuleBasic{}, - auth.AppModuleBasic{}, - bank.AppModuleBasic{}, - staking.AppModuleBasic{}, - mint.AppModuleBasic{}, - distribution.AppModuleBasic{}, - gov.NewAppModuleBasic(client.ProposalHandler, distribution.ProposalHandler), - params.AppModuleBasic{}, - crisis.AppModuleBasic{}, - slashing.AppModuleBasic{}, - supply.AppModuleBasic{}, - deposit.AppModuleBasic{}, - vpn.AppModuleBasic{}, - ) - - moduleAccountPermissions = map[string][]string{ - auth.FeeCollectorName: nil, - distribution.ModuleName: nil, - mint.ModuleName: {supply.Minter}, - staking.BondedPoolName: {supply.Burner, supply.Staking}, - staking.NotBondedPoolName: {supply.Burner, supply.Staking}, - gov.ModuleName: {supply.Burner}, - deposit.ModuleName: nil, - } -) - -func MakeCodec() *codec.Codec { - var cdc = codec.New() - - sdk.RegisterCodec(cdc) - types.RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - codec.RegisterEvidences(cdc) - ModuleBasics.RegisterCodec(cdc) - - return cdc -} - -func SetBech32AddressPrefixes(config *sdk.Config) { - config.SetBech32PrefixForAccount(types.Bech32PrefixAccAddr, types.Bech32PrefixAccPub) - config.SetBech32PrefixForValidator(types.Bech32PrefixValAddr, types.Bech32PrefixValPub) - config.SetBech32PrefixForConsensusNode(types.Bech32PrefixConsAddr, types.Bech32PrefixConsPub) -} - -type SimApp struct { - *baseapp.BaseApp - cdc *codec.Codec - - invCheckPeriod uint - - keys map[string]*sdk.KVStoreKey - transientKeys map[string]*sdk.TransientStoreKey - - accountKeeper auth.AccountKeeper - bankKeeper bank.Keeper - supplyKeeper supply.Keeper - stakingKeeper staking.Keeper - slashingKeeper slashing.Keeper - mintKeeper mint.Keeper - distributionKeeper distribution.Keeper - govKeeper gov.Keeper - crisisKeeper crisis.Keeper - paramsKeeper params.Keeper - depositKeeper deposit.Keeper - vpnKeeper vpn.Keeper - - mm *module.Manager -} - -// nolint:funlen -func NewSimApp(logger log.Logger, db db.DB, - traceStore io.Writer, loadLatest bool, invCheckPeriod uint, - baseAppOptions ...func(*baseapp.BaseApp)) *SimApp { - cdc := MakeCodec() - - bApp := baseapp.NewBaseApp(appName, logger, db, auth.DefaultTxDecoder(cdc), baseAppOptions...) - bApp.SetCommitMultiStoreTracer(traceStore) - bApp.SetAppVersion(version.Version) - - keys := sdk.NewKVStoreKeys( - baseapp.MainStoreKey, auth.StoreKey, staking.StoreKey, - supply.StoreKey, mint.StoreKey, distribution.StoreKey, slashing.StoreKey, - gov.StoreKey, params.StoreKey, deposit.StoreKey, - vpn.StoreKeyNode, vpn.StoreKeySubscription, vpn.StoreKeySession, - ) - - transientKeys := sdk.NewTransientStoreKeys(staking.TStoreKey, params.TStoreKey) - - var app = &SimApp{ - BaseApp: bApp, - cdc: cdc, - invCheckPeriod: invCheckPeriod, - keys: keys, - transientKeys: transientKeys, - } - - app.paramsKeeper = params.NewKeeper(app.cdc, - keys[params.StoreKey], - transientKeys[params.TStoreKey], - params.DefaultCodespace) - authSubspace := app.paramsKeeper.Subspace(auth.DefaultParamspace) - bankSubspace := app.paramsKeeper.Subspace(bank.DefaultParamspace) - stakingSubspace := app.paramsKeeper.Subspace(staking.DefaultParamspace) - mintSubspace := app.paramsKeeper.Subspace(mint.DefaultParamspace) - distributionSubspace := app.paramsKeeper.Subspace(distribution.DefaultParamspace) - slashingSubspace := app.paramsKeeper.Subspace(slashing.DefaultParamspace) - govSubspace := app.paramsKeeper.Subspace(gov.DefaultParamspace) - crisisSubspace := app.paramsKeeper.Subspace(crisis.DefaultParamspace) - - app.accountKeeper = auth.NewAccountKeeper(app.cdc, - keys[auth.StoreKey], - authSubspace, - auth.ProtoBaseAccount) - app.bankKeeper = bank.NewBaseKeeper(app.accountKeeper, - bankSubspace, - bank.DefaultCodespace, - app.ModuleAccountAddrs()) - app.supplyKeeper = supply.NewKeeper(app.cdc, - keys[supply.StoreKey], - app.accountKeeper, - app.bankKeeper, - moduleAccountPermissions) - stakingKeeper := staking.NewKeeper(app.cdc, - keys[staking.StoreKey], - transientKeys[staking.TStoreKey], - app.supplyKeeper, - stakingSubspace, - staking.DefaultCodespace) - app.mintKeeper = mint.NewKeeper(app.cdc, - keys[mint.StoreKey], - mintSubspace, - &stakingKeeper, - app.supplyKeeper, - auth.FeeCollectorName) - app.distributionKeeper = distribution.NewKeeper(app.cdc, - keys[distribution.StoreKey], - distributionSubspace, - &stakingKeeper, - app.supplyKeeper, - distribution.DefaultCodespace, - auth.FeeCollectorName, - app.ModuleAccountAddrs()) - app.slashingKeeper = slashing.NewKeeper(app.cdc, - keys[slashing.StoreKey], - &stakingKeeper, - slashingSubspace, - slashing.DefaultCodespace) - app.crisisKeeper = crisis.NewKeeper(crisisSubspace, - invCheckPeriod, - app.supplyKeeper, - auth.FeeCollectorName) - - govRouter := gov.NewRouter() - govRouter.AddRoute(gov.RouterKey, gov.ProposalHandler). - AddRoute(params.RouterKey, params.NewParamChangeProposalHandler(app.paramsKeeper)). - AddRoute(distribution.RouterKey, distribution.NewCommunityPoolSpendProposalHandler(app.distributionKeeper)) - - app.govKeeper = gov.NewKeeper(app.cdc, - keys[gov.StoreKey], - app.paramsKeeper, - govSubspace, - app.supplyKeeper, - &stakingKeeper, - gov.DefaultCodespace, - govRouter) - - app.stakingKeeper = *stakingKeeper.SetHooks( - staking.NewMultiStakingHooks(app.distributionKeeper.Hooks(), app.slashingKeeper.Hooks())) - - app.depositKeeper = deposit.NewKeeper(app.cdc, - keys[deposit.StoreKey], - app.supplyKeeper) - app.vpnKeeper = vpn.NewKeeper(app.cdc, - keys[vpn.StoreKeyNode], - keys[vpn.StoreKeySubscription], - keys[vpn.StoreKeySession], - app.paramsKeeper.Subspace(vpn.DefaultParamspace), - app.depositKeeper) - - app.mm = module.NewManager( - genaccounts.NewAppModule(app.accountKeeper), - genutil.NewAppModule(app.accountKeeper, app.stakingKeeper, app.BaseApp.DeliverTx), - auth.NewAppModule(app.accountKeeper), - bank.NewAppModule(app.bankKeeper, app.accountKeeper), - crisis.NewAppModule(&app.crisisKeeper), - supply.NewAppModule(app.supplyKeeper, app.accountKeeper), - distribution.NewAppModule(app.distributionKeeper, app.supplyKeeper), - gov.NewAppModule(app.govKeeper, app.supplyKeeper), - mint.NewAppModule(app.mintKeeper), - slashing.NewAppModule(app.slashingKeeper, app.stakingKeeper), - staking.NewAppModule(app.stakingKeeper, app.distributionKeeper, app.accountKeeper, app.supplyKeeper), - deposit.NewAppModule(app.depositKeeper), - vpn.NewAppModule(app.vpnKeeper), - ) - - app.mm.SetOrderBeginBlockers(mint.ModuleName, distribution.ModuleName, slashing.ModuleName) - app.mm.SetOrderEndBlockers(crisis.ModuleName, gov.ModuleName, staking.ModuleName, vpn.ModuleName) - app.mm.SetOrderInitGenesis( - genaccounts.ModuleName, distribution.ModuleName, staking.ModuleName, - auth.ModuleName, bank.ModuleName, slashing.ModuleName, gov.ModuleName, - mint.ModuleName, supply.ModuleName, crisis.ModuleName, genutil.ModuleName, - deposit.ModuleName, vpn.ModuleName, - ) - - app.mm.RegisterInvariants(&app.crisisKeeper) - app.mm.RegisterRoutes(app.Router(), app.QueryRouter()) - app.MountKVStores(keys) - app.MountTransientStores(transientKeys) - - app.SetInitChainer(app.InitChainer) - app.SetBeginBlocker(app.BeginBlocker) - app.SetAnteHandler( - auth.NewAnteHandler(app.accountKeeper, app.supplyKeeper, auth.DefaultSigVerificationGasConsumer)) - app.SetEndBlocker(app.EndBlocker) - - if loadLatest { - if err := app.LoadLatestVersion(app.keys[baseapp.MainStoreKey]); err != nil { - common.Exit(err.Error()) - } - } - - return app -} - -func (app *SimApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - return app.mm.BeginBlock(ctx, req) -} - -func (app *SimApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - return app.mm.EndBlock(ctx, req) -} - -func (app *SimApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { - var state map[string]json.RawMessage - app.cdc.MustUnmarshalJSON(req.AppStateBytes, &state) - - return app.mm.InitGenesis(ctx, state) -} - -func (app *SimApp) LoadHeight(height int64) error { - return app.LoadVersion(height, app.keys[baseapp.MainStoreKey]) -} - -func (app *SimApp) ModuleAccountAddrs() map[string]bool { - moduleAccounts := make(map[string]bool) - for acc := range moduleAccountPermissions { - moduleAccounts[supply.NewModuleAddress(acc).String()] = true - } - - return moduleAccounts -} diff --git a/simapp/export.go b/simapp/export.go deleted file mode 100644 index 85c2e857..00000000 --- a/simapp/export.go +++ /dev/null @@ -1,134 +0,0 @@ -package simapp - -import ( - "encoding/json" - "log" - - abci "github.com/tendermint/tendermint/abci/types" - tmtypes "github.com/tendermint/tendermint/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/staking" -) - -func (app *SimApp) ExportAppStateAndValidators( - forZeroHeight bool, jailWhiteList []string, -) (appState json.RawMessage, validators []tmtypes.GenesisValidator, err error) { - ctx := app.NewContext(true, abci.Header{Height: app.LastBlockHeight()}) - - if forZeroHeight { - app.prepForZeroHeightGenesis(ctx, jailWhiteList) - } - - genState := app.mm.ExportGenesis(ctx) - appState, err = codec.MarshalJSONIndent(app.cdc, genState) - if err != nil { - return nil, nil, err - } - - validators = staking.WriteValidators(ctx, app.stakingKeeper) - return appState, validators, nil -} - -// nolint:funlen -func (app *SimApp) prepForZeroHeightGenesis( - ctx sdk.Context, jailWhiteList []string) { - applyWhiteList := false - if len(jailWhiteList) > 0 { - applyWhiteList = true - } - - whiteListMap := make(map[string]bool) - for _, addr := range jailWhiteList { - _, err := sdk.ValAddressFromBech32(addr) - if err != nil { - log.Fatal(err) - } - - whiteListMap[addr] = true - } - - app.crisisKeeper.AssertInvariants(ctx) - - app.stakingKeeper.IterateValidators(ctx, func(_ int64, val staking.ValidatorI) (stop bool) { - _, _ = app.distributionKeeper.WithdrawValidatorCommission(ctx, val.GetOperator()) - return false - }) - - delegations := app.stakingKeeper.GetAllDelegations(ctx) - for _, delegation := range delegations { - _, _ = app.distributionKeeper.WithdrawDelegationRewards(ctx, - delegation.DelegatorAddress, delegation.ValidatorAddress) - } - - app.distributionKeeper.DeleteAllValidatorSlashEvents(ctx) - app.distributionKeeper.DeleteAllValidatorHistoricalRewards(ctx) - - height := ctx.BlockHeight() - ctx = ctx.WithBlockHeight(0) - - app.stakingKeeper.IterateValidators(ctx, func(_ int64, val staking.ValidatorI) (stop bool) { - scraps := app.distributionKeeper.GetValidatorOutstandingRewards(ctx, val.GetOperator()) - feePool := app.distributionKeeper.GetFeePool(ctx) - feePool.CommunityPool = feePool.CommunityPool.Add(scraps) - app.distributionKeeper.SetFeePool(ctx, feePool) - - app.distributionKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()) - return false - }) - - for _, del := range delegations { - app.distributionKeeper.Hooks().BeforeDelegationCreated(ctx, del.DelegatorAddress, del.ValidatorAddress) - app.distributionKeeper.Hooks().AfterDelegationModified(ctx, del.DelegatorAddress, del.ValidatorAddress) - } - - ctx = ctx.WithBlockHeight(height) - - app.stakingKeeper.IterateRedelegations(ctx, func(_ int64, red staking.Redelegation) (stop bool) { - for i := range red.Entries { - red.Entries[i].CreationHeight = 0 - } - app.stakingKeeper.SetRedelegation(ctx, red) - return false - }) - - app.stakingKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd staking.UnbondingDelegation) (stop bool) { - for i := range ubd.Entries { - ubd.Entries[i].CreationHeight = 0 - } - app.stakingKeeper.SetUnbondingDelegation(ctx, ubd) - return false - }) - - store := ctx.KVStore(app.keys[staking.StoreKey]) - iter := sdk.KVStoreReversePrefixIterator(store, staking.ValidatorsKey) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - addr := sdk.ValAddress(iter.Key()[1:]) - validator, found := app.stakingKeeper.GetValidator(ctx, addr) - if !found { - panic("expected validator, not found") - } - - validator.UnbondingHeight = 0 - if applyWhiteList && !whiteListMap[addr.String()] { - validator.Jailed = true - } - - app.stakingKeeper.SetValidator(ctx, validator) - } - - _ = app.stakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) - - app.slashingKeeper.IterateValidatorSigningInfos( - ctx, - func(addr sdk.ConsAddress, info slashing.ValidatorSigningInfo) (stop bool) { - info.StartHeight = 0 - app.slashingKeeper.SetValidatorSigningInfo(ctx, addr, info) - return false - }, - ) -} diff --git a/simapp/genesis.go b/simapp/genesis.go deleted file mode 100644 index 3ab49a26..00000000 --- a/simapp/genesis.go +++ /dev/null @@ -1,11 +0,0 @@ -package simapp - -import ( - "encoding/json" -) - -type GenesisState map[string]json.RawMessage - -func NewDefaultGenesisState() GenesisState { - return ModuleBasics.DefaultGenesis() -} diff --git a/simapp/params.go b/simapp/params.go deleted file mode 100644 index 91df1a62..00000000 --- a/simapp/params.go +++ /dev/null @@ -1,15 +0,0 @@ -package simapp - -const ( - StakePerAccount = "stake_per_account" - InitiallyBondedValidators = "initially_bonded_validators" - - OpWeightMsgRegisterNode = "op_weight_msg_register_node" - OpWeightMsgUpdateNodeInfo = "op_weight_msg_update_node_info" - OpWeightMsgUpdateNodeStatus = "op_weight_msg_update_node_status" - OpWeightMsgDeregisterNode = "op_weight_msg_deregister_node" - OpWeightMsgStartSubscription = "op_weight_msg_start_sub_scription" - OpWeightMsgEndSubscription = "op_weight_msg_end_sub_scription" - OpWeightMsgUpdateSessionInfo = "op_weight_msg_update_session_info" - OpWeightVpnModuleEndBlock = "op_weight_vpn_module_end_block" -) diff --git a/simapp/sim_test.go b/simapp/sim_test.go deleted file mode 100644 index 7c0e7fc4..00000000 --- a/simapp/sim_test.go +++ /dev/null @@ -1,665 +0,0 @@ -package simapp - -import ( - "encoding/json" - "flag" - "fmt" - "io" - "io/ioutil" - "math/rand" - "os" - "testing" - "time" - - "github.com/stretchr/testify/require" - - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - dbm "github.com/tendermint/tm-db" - - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/simulation" - - "github.com/sentinel-official/hub/x/vpn" - vpnsim "github.com/sentinel-official/hub/x/vpn/simulation" -) - -func init() { - flag.StringVar(&genesisFile, "Genesis", "", "custom simulation genesis file; cannot be used with params file") - flag.StringVar(¶msFile, "Params", "", "custom simulation params file which overrides any random params; cannot be used with genesis") - flag.StringVar(&exportParamsPath, "ExportParamsPath", "", "custom file path to save the exported params JSON") - flag.IntVar(&exportParamsHeight, "ExportParamsHeight", 0, "height to which export the randomly generated params") - flag.StringVar(&exportStatePath, "ExportStatePath", "", "custom file path to save the exported app state JSON") - flag.StringVar(&exportStatsPath, "ExportStatsPath", "", "custom file path to save the exported simulation statistics JSON") - flag.Int64Var(&seed, "Seed", 42, "simulation random seed") - flag.IntVar(&initialBlockHeight, "InitialBlockHeight", 1, "initial block to start the simulation") - flag.IntVar(&numBlocks, "NumBlocks", 500, "number of new blocks to simulate from the initial block height") - flag.IntVar(&blockSize, "BlockSize", 200, "operations per block") - flag.BoolVar(&enabled, "Enabled", false, "enable the simulation") - flag.BoolVar(&verbose, "Verbose", false, "verbose log output") - flag.BoolVar(&lean, "Lean", false, "lean simulation log output") - flag.BoolVar(&commit, "Commit", false, "have the simulation commit") - flag.IntVar(&period, "Period", 1, "run slow invariants only once every period assertions") - flag.BoolVar(&onOperation, "SimulateEveryOperation", false, "run slow invariants every operation") - flag.BoolVar(&allInvariants, "PrintAllInvariants", false, "print all invariants if a broken invariant is found") - flag.Int64Var(&genesisTime, "GenesisTime", 0, "override genesis UNIX time instead of using a random UNIX time") -} - -func getSimulateFromSeedInput(tb testing.TB, w io.Writer, app *SimApp) ( - testing.TB, io.Writer, *baseapp.BaseApp, simulation.AppStateFn, int64, - simulation.WeightedOperations, sdk.Invariants, int, int, int, int, string, - bool, bool, bool, bool, bool, map[string]bool) { - exportParams := exportParamsPath != "" - - return tb, w, app.BaseApp, appStateFn, seed, - testAndRunTxs(app), invariants(app), - initialBlockHeight, numBlocks, exportParamsHeight, blockSize, - exportStatsPath, exportParams, commit, lean, onOperation, allInvariants, app.ModuleAccountAddrs() -} - -func appStateFn( - r *rand.Rand, accs []simulation.Account, -) (appState json.RawMessage, simAccs []simulation.Account, chainID string, genesisTimestamp time.Time) { - cdc := MakeCodec() - - if genesisTime == 0 { - genesisTimestamp = simulation.RandTimestamp(r) - } else { - genesisTimestamp = time.Unix(genesisTime, 0) - } - - switch { - case paramsFile != "" && genesisFile != "": - panic("cannot provide both a genesis file and a params file") - - case genesisFile != "": - appState, simAccs, chainID = AppStateFromGenesisFileFn(r, accs, genesisTimestamp) - - case paramsFile != "": - appParams := make(simulation.AppParams) - bz, err := ioutil.ReadFile(paramsFile) - if err != nil { - panic(err) - } - - cdc.MustUnmarshalJSON(bz, &appParams) - appState, simAccs, chainID = appStateRandomizedFn(r, accs, genesisTimestamp, appParams) - - default: - appParams := make(simulation.AppParams) - appState, simAccs, chainID = appStateRandomizedFn(r, accs, genesisTimestamp, appParams) - } - - return appState, simAccs, chainID, genesisTimestamp -} - -func appStateRandomizedFn( - r *rand.Rand, accs []simulation.Account, genesisTimestamp time.Time, appParams simulation.AppParams, -) (json.RawMessage, []simulation.Account, string) { - cdc := MakeCodec() - genesisState := NewDefaultGenesisState() - - var ( - amount int64 - numInitiallyBonded int64 - ) - - appParams.GetOrGenerate(cdc, StakePerAccount, &amount, r, - func(r *rand.Rand) { amount = int64(r.Intn(1e12)) }) - appParams.GetOrGenerate(cdc, InitiallyBondedValidators, &amount, r, - func(r *rand.Rand) { numInitiallyBonded = int64(r.Intn(250)) }) - - numAccs := int64(len(accs)) - if numInitiallyBonded > numAccs { - numInitiallyBonded = numAccs - } - - fmt.Printf( - `Selected randomly generated parameters for simulated genesis: -{ - stake_per_account: "%v", - initially_bonded_validators: "%v" -} -`, amount, numInitiallyBonded, - ) - - GenGenesisAccounts(cdc, r, accs, genesisTimestamp, amount, numInitiallyBonded, genesisState) - GenAuthGenesisState(cdc, r, appParams, genesisState) - GenBankGenesisState(cdc, r, appParams, genesisState) - GenSupplyGenesisState(cdc, amount, numInitiallyBonded, int64(len(accs)), genesisState) - GenGovGenesisState(cdc, r, appParams, genesisState) - GenMintGenesisState(cdc, r, appParams, genesisState) - GenDistrGenesisState(cdc, r, appParams, genesisState) - stakingGen := GenStakingGenesisState(cdc, r, accs, amount, numAccs, numInitiallyBonded, appParams, genesisState) - GenSlashingGenesisState(cdc, r, stakingGen, appParams, genesisState) - GenVpnGenesisState(cdc, r, accs, appParams, genesisState) - - appState, err := MakeCodec().MarshalJSON(genesisState) - if err != nil { - panic(err) - } - - return appState, accs, "simulation" -} - -func testAndRunTxs(app *SimApp) []simulation.WeightedOperation { - cdc := MakeCodec() - ap := make(simulation.AppParams) - - if paramsFile != "" { - bz, err := ioutil.ReadFile(paramsFile) - if err != nil { - panic(err) - } - - cdc.MustUnmarshalJSON(bz, &ap) - } - - return []simulation.WeightedOperation{ - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgRegisterNode, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - vpnsim.SimulateMsgRegisterNode(app.vpnKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgUpdateNodeInfo, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - vpnsim.SimulateMsgUpdateNodeInfo(app.vpnKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgDeregisterNode, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - vpnsim.SimulateMsgDeregisterNode(app.vpnKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgStartSubscription, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - vpnsim.SimulateMsgStartSubscription(app.vpnKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgEndSubscription, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - vpnsim.SimulateMsgEndSubscription(app.vpnKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightMsgUpdateSessionInfo, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - vpnsim.SimulateMsgUpdateSessionInfo(app.vpnKeeper), - }, - { - func(_ *rand.Rand) int { - var v int - ap.GetOrGenerate(cdc, OpWeightVpnModuleEndBlock, &v, nil, - func(_ *rand.Rand) { - v = 100 - }) - return v - }(nil), - vpnsim.SimulateEndBlock(app.vpnKeeper), - }, - } -} - -func invariants(app *SimApp) []sdk.Invariant { - if period == 1 { - return app.crisisKeeper.Invariants() - } - return simulation.PeriodicInvariants(app.crisisKeeper.Invariants(), period, 0) -} - -func fauxMerkleModeOpt(bapp *baseapp.BaseApp) { - bapp.SetFauxMerkleMode() -} - -// /usr/local/go/bin/go test -benchmem -run=^$ github.com/cosmos/cosmos-sdk/simapp -bench ^BenchmarkFullAppSimulation$ -Commit=true -cpuprofile cpu.out -func BenchmarkFullAppSimulation(b *testing.B) { - logger := log.NewNopLogger() - - var db dbm.DB - dir, _ := ioutil.TempDir("", "goleveldb-app-sim") - db, _ = sdk.NewLevelDB("Simulation", dir) - defer func() { - db.Close() - os.RemoveAll(dir) - }() - app := NewSimApp(logger, db, nil, true, 0) - - _, params, simErr := simulation.SimulateFromSeed(getSimulateFromSeedInput(b, os.Stdout, app)) - - if exportStatePath != "" { - fmt.Println("Exporting app state...") - appState, _, err := app.ExportAppStateAndValidators(false, nil) - if err != nil { - fmt.Println(err) - b.Fail() - } - err = ioutil.WriteFile(exportStatePath, []byte(appState), 0644) - if err != nil { - fmt.Println(err) - b.Fail() - } - } - - if exportParamsPath != "" { - fmt.Println("Exporting simulation params...") - paramsBz, err := json.MarshalIndent(params, "", " ") - if err != nil { - fmt.Println(err) - b.Fail() - } - - err = ioutil.WriteFile(exportParamsPath, paramsBz, 0644) - if err != nil { - fmt.Println(err) - b.Fail() - } - } - - if simErr != nil { - fmt.Println(simErr) - b.FailNow() - } - - if commit { - fmt.Println("\nGoLevelDB Stats") - fmt.Println(db.Stats()["leveldb.stats"]) - fmt.Println("GoLevelDB cached block size", db.Stats()["leveldb.cachedblock"]) - } -} - -func TestFullAppSimulation(t *testing.T) { - if !enabled { - t.Skip("Skipping application simulation") - } - - config := sdk.GetConfig() - SetBech32AddressPrefixes(config) - config.Seal() - - var logger log.Logger - - if verbose { - logger = log.TestingLogger() - } else { - logger = log.NewNopLogger() - } - - var db dbm.DB - dir, _ := ioutil.TempDir("", "goleveldb-app-sim") - db, _ = sdk.NewLevelDB("Simulation", dir) - - defer func() { - db.Close() - os.RemoveAll(dir) - }() - - app := NewSimApp(logger, db, nil, true, 0, fauxMerkleModeOpt) - require.Equal(t, "SimApp", app.Name()) - - _, params, simErr := simulation.SimulateFromSeed(getSimulateFromSeedInput(t, os.Stdout, app)) - - if exportStatePath != "" { - fmt.Println("Exporting app state...") - appState, _, err := app.ExportAppStateAndValidators(false, nil) - require.NoError(t, err) - - err = ioutil.WriteFile(exportStatePath, []byte(appState), 0644) - require.NoError(t, err) - } - - if exportParamsPath != "" { - fmt.Println("Exporting simulation params...") - fmt.Println(params) - paramsBz, err := json.MarshalIndent(params, "", " ") - require.NoError(t, err) - - err = ioutil.WriteFile(exportParamsPath, paramsBz, 0644) - require.NoError(t, err) - } - - require.NoError(t, simErr) - - if commit { - fmt.Println("\nGoLevelDB Stats") - fmt.Println(db.Stats()["leveldb.stats"]) - fmt.Println("GoLevelDB cached block size", db.Stats()["leveldb.cachedblock"]) - } -} - -func TestAppImportExport(t *testing.T) { - if !enabled { - t.Skip("Skipping application import/export simulation") - } - - var logger log.Logger - if verbose { - logger = log.TestingLogger() - } else { - logger = log.NewNopLogger() - } - - var db dbm.DB - dir, _ := ioutil.TempDir("", "goleveldb-app-sim") - db, _ = sdk.NewLevelDB("Simulation", dir) - - defer func() { - db.Close() - os.RemoveAll(dir) - }() - - app := NewSimApp(logger, db, nil, true, 0, fauxMerkleModeOpt) - require.Equal(t, "SimApp", app.Name()) - - _, simParams, simErr := simulation.SimulateFromSeed(getSimulateFromSeedInput(t, os.Stdout, app)) - - if exportStatePath != "" { - fmt.Println("Exporting app state...") - appState, _, err := app.ExportAppStateAndValidators(false, nil) - require.NoError(t, err) - - err = ioutil.WriteFile(exportStatePath, []byte(appState), 0644) - require.NoError(t, err) - } - - if exportParamsPath != "" { - fmt.Println("Exporting simulation params...") - simParamsBz, err := json.MarshalIndent(simParams, "", " ") - require.NoError(t, err) - - err = ioutil.WriteFile(exportParamsPath, simParamsBz, 0644) - require.NoError(t, err) - } - - require.NoError(t, simErr) - - if commit { - fmt.Println("\nGoLevelDB Stats") - fmt.Println(db.Stats()["leveldb.stats"]) - fmt.Println("GoLevelDB cached block size", db.Stats()["leveldb.cachedblock"]) - } - - fmt.Printf("Exporting genesis...\n") - - appState, _, err := app.ExportAppStateAndValidators(false, []string{}) - require.NoError(t, err) - fmt.Printf("Importing genesis...\n") - - newDir, _ := ioutil.TempDir("", "goleveldb-app-sim-2") - newDB, _ := sdk.NewLevelDB("Simulation-2", dir) - - defer func() { - newDB.Close() - _ = os.RemoveAll(newDir) - }() - - newApp := NewSimApp(log.NewNopLogger(), newDB, nil, true, 0, fauxMerkleModeOpt) - require.Equal(t, "SimApp", newApp.Name()) - - var genesisState GenesisState - err = app.cdc.UnmarshalJSON(appState, &genesisState) - if err != nil { - panic(err) - } - - ctxB := newApp.NewContext(true, abci.Header{Height: app.LastBlockHeight()}) - newApp.mm.InitGenesis(ctxB, genesisState) - - fmt.Printf("Comparing stores...\n") - ctxA := app.NewContext(true, abci.Header{Height: app.LastBlockHeight()}) - - type StoreKeysPrefixes struct { - A sdk.StoreKey - B sdk.StoreKey - Prefixes [][]byte - } - - storeKeysPrefixes := []StoreKeysPrefixes{ - {app.keys[baseapp.MainStoreKey], newApp.keys[baseapp.MainStoreKey], [][]byte{}}, - {app.keys[auth.StoreKey], newApp.keys[auth.StoreKey], [][]byte{}}, - - {app.keys[params.StoreKey], newApp.keys[params.StoreKey], [][]byte{}}, - {app.keys[gov.StoreKey], newApp.keys[gov.StoreKey], [][]byte{}}, - {app.keys[vpn.StoreKeyNode], newApp.keys[vpn.StoreKeyNode], [][]byte{}}, - {app.keys[vpn.StoreKeySession], newApp.keys[vpn.StoreKeySession], [][]byte{}}, - {app.keys[vpn.StoreKeySubscription], newApp.keys[vpn.StoreKeySubscription], [][]byte{}}, - } - - for _, storeKeysPrefix := range storeKeysPrefixes { - storeKeyA := storeKeysPrefix.A - storeKeyB := storeKeysPrefix.B - prefixes := storeKeysPrefix.Prefixes - storeA := ctxA.KVStore(storeKeyA) - storeB := ctxB.KVStore(storeKeyB) - kvA, kvB, count, equal := sdk.DiffKVStores(storeA, storeB, prefixes) - fmt.Printf("Compared %d key/value pairs between %s and %s\n", count, storeKeyA, storeKeyB) - require.True(t, equal, GetSimulationLog(storeKeyA.Name(), app.cdc, newApp.cdc, kvA, kvB)) - } -} - -func TestAppSimulationAfterImport(t *testing.T) { - if !enabled { - t.Skip("Skipping application simulation after import") - } - - var logger log.Logger - if verbose { - logger = log.TestingLogger() - } else { - logger = log.NewNopLogger() - } - - dir, _ := ioutil.TempDir("", "goleveldb-app-sim") - db, _ := sdk.NewLevelDB("Simulation", dir) - - defer func() { - db.Close() - os.RemoveAll(dir) - }() - - app := NewSimApp(logger, db, nil, true, 0, fauxMerkleModeOpt) - require.Equal(t, "SimApp", app.Name()) - - stopEarly, params, simErr := simulation.SimulateFromSeed(getSimulateFromSeedInput(t, os.Stdout, app)) - - if exportStatePath != "" { - fmt.Println("Exporting app state...") - appState, _, err := app.ExportAppStateAndValidators(false, nil) - require.NoError(t, err) - - err = ioutil.WriteFile(exportStatePath, []byte(appState), 0644) - require.NoError(t, err) - } - - if exportParamsPath != "" { - fmt.Println("Exporting simulation params...") - paramsBz, err := json.MarshalIndent(params, "", " ") - require.NoError(t, err) - - err = ioutil.WriteFile(exportParamsPath, paramsBz, 0644) - require.NoError(t, err) - } - - require.NoError(t, simErr) - - if commit { - fmt.Println("\nGoLevelDB Stats") - fmt.Println(db.Stats()["leveldb.stats"]) - fmt.Println("GoLevelDB cached block size", db.Stats()["leveldb.cachedblock"]) - } - - if stopEarly { - fmt.Printf("We can't export or import a zero-validator genesis, exiting test...\n") - return - } - - fmt.Printf("Exporting genesis...\n") - - appState, _, err := app.ExportAppStateAndValidators(true, []string{}) - if err != nil { - panic(err) - } - - fmt.Printf("Importing genesis...\n") - - newDir, _ := ioutil.TempDir("", "goleveldb-app-sim-2") - newDB, _ := sdk.NewLevelDB("Simulation-2", dir) - - defer func() { - newDB.Close() - _ = os.RemoveAll(newDir) - }() - - newApp := NewSimApp(log.NewNopLogger(), newDB, nil, true, 0, fauxMerkleModeOpt) - require.Equal(t, "SimApp", newApp.Name()) - newApp.InitChain(abci.RequestInitChain{ - AppStateBytes: appState, - }) - - _, _, err = simulation.SimulateFromSeed(getSimulateFromSeedInput(t, os.Stdout, newApp)) - require.Nil(t, err) -} - -func TestAppStateDeterminism(t *testing.T) { - if !enabled { - t.Skip("Skipping application simulation") - } - - numSeeds := 3 - numTimesToRunPerSeed := 5 - appHashList := make([]json.RawMessage, numTimesToRunPerSeed) - - for i := 0; i < numSeeds; i++ { - seed := rand.Int63() - - for j := 0; j < numTimesToRunPerSeed; j++ { - logger := log.NewNopLogger() - db := dbm.NewMemDB() - app := NewSimApp(logger, db, nil, true, 0) - - fmt.Printf( - "Running non-determinism simulation; seed: %d/%d (%d), attempt: %d/%d\n", - i+1, numSeeds, seed, j+1, numTimesToRunPerSeed, - ) - - _, _, err := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, appStateFn, seed, testAndRunTxs(app), - []sdk.Invariant{}, 1, numBlocks, exportParamsHeight, - blockSize, "", false, commit, lean, - false, false, app.ModuleAccountAddrs(), - ) - require.NoError(t, err) - - appHash := app.LastCommitID().Hash - appHashList[j] = appHash - } - - for k := 1; k < numTimesToRunPerSeed; k++ { - require.Equal(t, appHashList[0], appHashList[k], "appHash list: %v", appHashList) - } - } -} - -func BenchmarkInvariants(b *testing.B) { - logger := log.NewNopLogger() - dir, _ := ioutil.TempDir("", "goleveldb-app-invariant-bench") - db, _ := sdk.NewLevelDB("simulation", dir) - - defer func() { - db.Close() - os.RemoveAll(dir) - }() - - app := NewSimApp(logger, db, nil, true, 0) - exportParams := exportParamsPath != "" - - _, params, simErr := simulation.SimulateFromSeed( - b, ioutil.Discard, app.BaseApp, appStateFn, seed, testAndRunTxs(app), - []sdk.Invariant{}, initialBlockHeight, numBlocks, exportParamsHeight, blockSize, - exportStatsPath, exportParams, commit, lean, onOperation, false, app.ModuleAccountAddrs(), - ) - - if exportStatePath != "" { - fmt.Println("Exporting app state...") - appState, _, err := app.ExportAppStateAndValidators(false, nil) - if err != nil { - fmt.Println(err) - b.Fail() - } - err = ioutil.WriteFile(exportStatePath, []byte(appState), 0644) - if err != nil { - fmt.Println(err) - b.Fail() - } - } - - if exportParamsPath != "" { - fmt.Println("Exporting simulation params...") - paramsBz, err := json.MarshalIndent(params, "", " ") - if err != nil { - fmt.Println(err) - b.Fail() - } - - err = ioutil.WriteFile(exportParamsPath, paramsBz, 0644) - if err != nil { - fmt.Println(err) - b.Fail() - } - } - - if simErr != nil { - fmt.Println(simErr) - b.FailNow() - } - - ctx := app.NewContext(true, abci.Header{Height: app.LastBlockHeight() + 1}) - - for _, cr := range app.crisisKeeper.Routes() { - b.Run(fmt.Sprintf("%s/%s", cr.ModuleName, cr.Route), func(b *testing.B) { - if res, stop := cr.Invar(ctx); stop { - fmt.Printf("broken invariant at block %d of %d\n%s", ctx.BlockHeight()-1, numBlocks, res) - b.FailNow() - } - }) - } -} diff --git a/simapp/utils.go b/simapp/utils.go deleted file mode 100644 index daee2db2..00000000 --- a/simapp/utils.go +++ /dev/null @@ -1,765 +0,0 @@ -// nolint -package simapp - -import ( - "bytes" - "encoding/binary" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "math/rand" - "time" - - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/secp256k1" - cmn "github.com/tendermint/tendermint/libs/common" - "github.com/tendermint/tendermint/libs/log" - tmtypes "github.com/tendermint/tendermint/types" - dbm "github.com/tendermint/tm-db" - - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/genaccounts" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/mint" - "github.com/cosmos/cosmos-sdk/x/simulation" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/cosmos/cosmos-sdk/x/supply" - - "github.com/sentinel-official/hub/x/vpn" - - vpnsim "github.com/sentinel-official/hub/x/vpn/simulation" -) - -var ( - genesisFile string - paramsFile string - exportParamsPath string - exportParamsHeight int - exportStatePath string - exportStatsPath string - seed int64 - initialBlockHeight int - numBlocks int - blockSize int - enabled bool - verbose bool - lean bool - commit bool - period int - onOperation bool - allInvariants bool - genesisTime int64 -) - -func NewSimAppUNSAFE(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, - invCheckPeriod uint, baseAppOptions ...func(*baseapp.BaseApp), -) (gapp *SimApp, keyMain, keyStaking *sdk.KVStoreKey, stakingKeeper staking.Keeper) { - - gapp = NewSimApp(logger, db, traceStore, loadLatest, invCheckPeriod, baseAppOptions...) - return gapp, gapp.keys[baseapp.MainStoreKey], gapp.keys[staking.StoreKey], gapp.stakingKeeper -} - -func AppStateFromGenesisFileFn( - r *rand.Rand, _ []simulation.Account, _ time.Time, -) (json.RawMessage, []simulation.Account, string) { - - var genesis tmtypes.GenesisDoc - cdc := MakeCodec() - - bytes, err := ioutil.ReadFile(genesisFile) - if err != nil { - panic(err) - } - - cdc.MustUnmarshalJSON(bytes, &genesis) - - var appState GenesisState - cdc.MustUnmarshalJSON(genesis.AppState, &appState) - - accounts := genaccounts.GetGenesisStateFromAppState(cdc, appState) - - var newAccs []simulation.Account - for _, acc := range accounts { - privkeySeed := make([]byte, 15) - r.Read(privkeySeed) - - privKey := secp256k1.GenPrivKeySecp256k1(privkeySeed) - newAccs = append(newAccs, simulation.Account{privKey, privKey.PubKey(), acc.Address}) - } - - return genesis.AppState, newAccs, genesis.ChainID -} - -func GenAuthGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - authGenesis := auth.NewGenesisState( - auth.NewParams( - func(r *rand.Rand) uint64 { - var v uint64 - ap.GetOrGenerate(cdc, simulation.MaxMemoChars, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.MaxMemoChars](r).(uint64) - }) - return v - }(r), - func(r *rand.Rand) uint64 { - var v uint64 - ap.GetOrGenerate(cdc, simulation.TxSigLimit, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.TxSigLimit](r).(uint64) - }) - return v - }(r), - func(r *rand.Rand) uint64 { - var v uint64 - ap.GetOrGenerate(cdc, simulation.TxSizeCostPerByte, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.TxSizeCostPerByte](r).(uint64) - }) - return v - }(r), - func(r *rand.Rand) uint64 { - var v uint64 - ap.GetOrGenerate(cdc, simulation.SigVerifyCostED25519, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.SigVerifyCostED25519](r).(uint64) - }) - return v - }(r), - func(r *rand.Rand) uint64 { - var v uint64 - ap.GetOrGenerate(cdc, simulation.SigVerifyCostSECP256K1, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.SigVerifyCostSECP256K1](r).(uint64) - }) - return v - }(r), - ), - ) - - fmt.Printf("Selected randomly generated auth parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, authGenesis.Params)) - genesisState[auth.ModuleName] = cdc.MustMarshalJSON(authGenesis) -} - -func GenBankGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - bankGenesis := bank.NewGenesisState( - func(r *rand.Rand) bool { - var v bool - ap.GetOrGenerate(cdc, simulation.SendEnabled, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.SendEnabled](r).(bool) - }) - return v - }(r), - ) - - fmt.Printf("Selected randomly generated bank parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, bankGenesis)) - genesisState[bank.ModuleName] = cdc.MustMarshalJSON(bankGenesis) -} - -func GenSupplyGenesisState(cdc *codec.Codec, amount, numInitiallyBonded, numAccs int64, genesisState map[string]json.RawMessage) { - totalSupply := sdk.NewInt(amount * (numAccs + numInitiallyBonded)) - supplyGenesis := supply.NewGenesisState( - sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, totalSupply)), - ) - - fmt.Printf("Generated supply parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, supplyGenesis)) - genesisState[supply.ModuleName] = cdc.MustMarshalJSON(supplyGenesis) -} - -func GenGenesisAccounts( - cdc *codec.Codec, r *rand.Rand, accs []simulation.Account, - genesisTimestamp time.Time, amount, numInitiallyBonded int64, - genesisState map[string]json.RawMessage, -) { - - var genesisAccounts []genaccounts.GenesisAccount - - // randomly generate some genesis accounts - for i, acc := range accs { - coins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(amount))} - bacc := auth.NewBaseAccountWithAddress(acc.Address) - bacc.SetCoins(coins) - - var gacc genaccounts.GenesisAccount - - if int64(i) > numInitiallyBonded && r.Intn(100) < 50 { - var ( - vacc auth.VestingAccount - endTime int64 - ) - - startTime := genesisTimestamp.Unix() - - if r.Intn(100) < 50 { - endTime = int64(simulation.RandIntBetween(r, int(startTime), int(startTime+(60*60*24*30)))) - } else { - endTime = int64(simulation.RandIntBetween(r, int(startTime), int(startTime+(60*60*12)))) - } - - if startTime == endTime { - endTime++ - } - - if r.Intn(100) < 50 { - vacc = auth.NewContinuousVestingAccount(&bacc, startTime, endTime) - } else { - vacc = auth.NewDelayedVestingAccount(&bacc, endTime) - } - - var err error - gacc, err = genaccounts.NewGenesisAccountI(vacc) - if err != nil { - panic(err) - } - } else { - gacc = genaccounts.NewGenesisAccount(&bacc) - } - - genesisAccounts = append(genesisAccounts, gacc) - } - - genesisState[genaccounts.ModuleName] = cdc.MustMarshalJSON(genesisAccounts) -} - -func GenGovGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - var vp time.Duration - ap.GetOrGenerate(cdc, simulation.VotingParamsVotingPeriod, &vp, r, - func(r *rand.Rand) { - vp = simulation.ModuleParamSimulator[simulation.VotingParamsVotingPeriod](r).(time.Duration) - }) - - govGenesis := gov.NewGenesisState( - uint64(r.Intn(100)), - gov.NewDepositParams( - func(r *rand.Rand) sdk.Coins { - var v sdk.Coins - ap.GetOrGenerate(cdc, simulation.DepositParamsMinDeposit, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.DepositParamsMinDeposit](r).(sdk.Coins) - }) - return v - }(r), - vp, - ), - gov.NewVotingParams(vp), - gov.NewTallyParams( - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.TallyParamsQuorum, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.TallyParamsQuorum](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.TallyParamsThreshold, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.TallyParamsThreshold](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.TallyParamsVeto, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.TallyParamsVeto](r).(sdk.Dec) - }) - return v - }(r), - ), - ) - - fmt.Printf("Selected randomly generated governance parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, govGenesis)) - genesisState[gov.ModuleName] = cdc.MustMarshalJSON(govGenesis) -} - -func GenMintGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - mintGenesis := mint.NewGenesisState( - mint.InitialMinter( - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.Inflation, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.Inflation](r).(sdk.Dec) - }) - return v - }(r), - ), - mint.NewParams( - sdk.DefaultBondDenom, - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.InflationRateChange, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.InflationRateChange](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.InflationMax, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.InflationMax](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.InflationMin, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.InflationMin](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.GoalBonded, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.GoalBonded](r).(sdk.Dec) - }) - return v - }(r), - uint64(60*60*8766/5), - ), - ) - - fmt.Printf("Selected randomly generated minting parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, mintGenesis.Params)) - genesisState[mint.ModuleName] = cdc.MustMarshalJSON(mintGenesis) -} - -func GenDistrGenesisState(cdc *codec.Codec, r *rand.Rand, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - distrGenesis := distribution.GenesisState{ - FeePool: distribution.InitialFeePool(), - CommunityTax: func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.CommunityTax, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.CommunityTax](r).(sdk.Dec) - }) - return v - }(r), - BaseProposerReward: func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.BaseProposerReward, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.BaseProposerReward](r).(sdk.Dec) - }) - return v - }(r), - BonusProposerReward: func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.BonusProposerReward, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.BonusProposerReward](r).(sdk.Dec) - }) - return v - }(r), - } - - fmt.Printf("Selected randomly generated distribution parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, distrGenesis)) - genesisState[distribution.ModuleName] = cdc.MustMarshalJSON(distrGenesis) -} - -func GenVpnGenesisState(cdc *codec.Codec, r *rand.Rand, accs []simulation.Account, ap simulation.AppParams, genesisState map[string]json.RawMessage) { - var ( - nodes []vpn.Node - subscriptions []vpn.Subscription - sessions []vpn.Session - ) - - // Random Nodes - for i := 0; i < int(40); i++ { - node := vpnsim.GenerateRandomNode(r) - node.Owner = simulation.RandomAcc(r, accs).Address - nodes = append(nodes, node) - - subscription := vpnsim.GenerateRandomSubscription(r, nodes[i]) - subscription.Client = simulation.RandomAcc(r, accs).Address - subscriptions = append(subscriptions, subscription) - - session := vpnsim.GenerateRandomSession(r, subscriptions[i].ID) - sessions = append(sessions, session) - } - - vpnGenesis := vpn.GenesisState{ - Params: vpn.NewParams( - func(r *rand.Rand) uint64 { - var v uint64 - ap.GetOrGenerate(cdc, vpnsim.FreeNodesCount, &v, r, - func(r *rand.Rand) { - v = uint64(simulation.RandIntBetween(r, 10, 1000)) - }) - return v - }(r), - func(r *rand.Rand) sdk.Coin { - var v sdk.Coin - ap.GetOrGenerate(cdc, vpnsim.Deposit, &v, r, - func(r *rand.Rand) { - v = sdk.NewInt64Coin(sdk.DefaultBondDenom, int64(simulation.RandIntBetween(r, 1, 1e3))) - }) - return v - }(r), - func(r *rand.Rand) int64 { - var v int64 - ap.GetOrGenerate(cdc, vpnsim.SessionInactiveInterval, &v, r, - func(r *rand.Rand) { - v = int64(simulation.RandIntBetween(r, 10, 1000)) - }) - return v - }(r), - ), - Nodes: nodes, - Subscriptions: subscriptions, - Sessions: sessions, - } - fmt.Printf("Selected randomly generated slashing parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, vpnGenesis.Params)) - genesisState[vpn.ModuleName] = cdc.MustMarshalJSON(vpnGenesis) -} - -func GenSlashingGenesisState( - cdc *codec.Codec, r *rand.Rand, stakingGen staking.GenesisState, - ap simulation.AppParams, genesisState map[string]json.RawMessage, -) { - slashingGenesis := slashing.NewGenesisState( - slashing.NewParams( - stakingGen.Params.UnbondingTime, - func(r *rand.Rand) int64 { - var v int64 - ap.GetOrGenerate(cdc, simulation.SignedBlocksWindow, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.SignedBlocksWindow](r).(int64) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.MinSignedPerWindow, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.MinSignedPerWindow](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) time.Duration { - var v time.Duration - ap.GetOrGenerate(cdc, simulation.DowntimeJailDuration, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.DowntimeJailDuration](r).(time.Duration) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.SlashFractionDoubleSign, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.SlashFractionDoubleSign](r).(sdk.Dec) - }) - return v - }(r), - func(r *rand.Rand) sdk.Dec { - var v sdk.Dec - ap.GetOrGenerate(cdc, simulation.SlashFractionDowntime, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.SlashFractionDowntime](r).(sdk.Dec) - }) - return v - }(r), - ), - nil, - nil, - ) - - fmt.Printf("Selected randomly generated slashing parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, slashingGenesis.Params)) - genesisState[slashing.ModuleName] = cdc.MustMarshalJSON(slashingGenesis) -} - -func GenStakingGenesisState( - cdc *codec.Codec, r *rand.Rand, accs []simulation.Account, amount, numAccs, numInitiallyBonded int64, - ap simulation.AppParams, genesisState map[string]json.RawMessage, -) staking.GenesisState { - - stakingGenesis := staking.NewGenesisState( - staking.NewParams( - func(r *rand.Rand) time.Duration { - var v time.Duration - ap.GetOrGenerate(cdc, simulation.UnbondingTime, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.UnbondingTime](r).(time.Duration) - }) - return v - }(r), - func(r *rand.Rand) uint16 { - var v uint16 - ap.GetOrGenerate(cdc, simulation.MaxValidators, &v, r, - func(r *rand.Rand) { - v = simulation.ModuleParamSimulator[simulation.MaxValidators](r).(uint16) - }) - return v - }(r), - 7, - sdk.DefaultBondDenom, - ), - nil, - nil, - ) - - var ( - validators []staking.Validator - delegations []staking.Delegation - ) - - valAddrs := make([]sdk.ValAddress, numInitiallyBonded) - for i := 0; i < int(numInitiallyBonded); i++ { - valAddr := sdk.ValAddress(accs[i].Address) - valAddrs[i] = valAddr - - validator := staking.NewValidator(valAddr, accs[i].PubKey, staking.Description{}) - validator.Tokens = sdk.NewInt(amount) - validator.DelegatorShares = sdk.NewDec(amount) - delegation := staking.NewDelegation(accs[i].Address, valAddr, sdk.NewDec(amount)) - validators = append(validators, validator) - delegations = append(delegations, delegation) - } - - stakingGenesis.Validators = validators - stakingGenesis.Delegations = delegations - - fmt.Printf("Selected randomly generated staking parameters:\n%s\n", codec.MustMarshalJSONIndent(cdc, stakingGenesis.Params)) - genesisState[staking.ModuleName] = cdc.MustMarshalJSON(stakingGenesis) - - return stakingGenesis -} - -func GetSimulationLog(storeName string, cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) (log string) { - log = fmt.Sprintf("store A %X => %X\nstore B %X => %X\n", kvA.Key, kvA.Value, kvB.Key, kvB.Value) - - if len(kvA.Value) == 0 && len(kvB.Value) == 0 { - return - } - - switch storeName { - case auth.StoreKey: - return DecodeAccountStore(cdcA, cdcB, kvA, kvB) - case mint.StoreKey: - return DecodeMintStore(cdcA, cdcB, kvA, kvB) - case staking.StoreKey: - return DecodeStakingStore(cdcA, cdcB, kvA, kvB) - case slashing.StoreKey: - return DecodeSlashingStore(cdcA, cdcB, kvA, kvB) - case gov.StoreKey: - return DecodeGovStore(cdcA, cdcB, kvA, kvB) - case distribution.StoreKey: - return DecodeDistributionStore(cdcA, cdcB, kvA, kvB) - case supply.StoreKey: - return DecodeSupplyStore(cdcA, cdcB, kvA, kvB) - default: - return - } -} - -// DecodeAccountStore unmarshals the KVPair's Value to the corresponding auth type -func DecodeAccountStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { - switch { - case bytes.Equal(kvA.Key[:1], auth.AddressStoreKeyPrefix): - var accA, accB auth.Account - cdcA.MustUnmarshalBinaryBare(kvA.Value, &accA) - cdcB.MustUnmarshalBinaryBare(kvB.Value, &accB) - return fmt.Sprintf("%v\n%v", accA, accB) - case bytes.Equal(kvA.Key, auth.GlobalAccountNumberKey): - var globalAccNumberA, globalAccNumberB uint64 - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &globalAccNumberA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &globalAccNumberB) - return fmt.Sprintf("GlobalAccNumberA: %d\nGlobalAccNumberB: %d", globalAccNumberA, globalAccNumberB) - default: - panic(fmt.Sprintf("invalid account key %X", kvA.Key)) - } -} - -func DecodeMintStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { - switch { - case bytes.Equal(kvA.Key, mint.MinterKey): - var minterA, minterB mint.Minter - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &minterA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &minterB) - return fmt.Sprintf("%v\n%v", minterA, minterB) - default: - panic(fmt.Sprintf("invalid mint key %X", kvA.Key)) - } -} - -func DecodeDistributionStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { - switch { - case bytes.Equal(kvA.Key[:1], distribution.FeePoolKey): - var feePoolA, feePoolB distribution.FeePool - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &feePoolA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &feePoolB) - return fmt.Sprintf("%v\n%v", feePoolA, feePoolB) - - case bytes.Equal(kvA.Key[:1], distribution.ProposerKey): - return fmt.Sprintf("%v\n%v", sdk.ConsAddress(kvA.Value), sdk.ConsAddress(kvB.Value)) - - case bytes.Equal(kvA.Key[:1], distribution.ValidatorOutstandingRewardsPrefix): - var rewardsA, rewardsB distribution.ValidatorOutstandingRewards - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) - return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - - case bytes.Equal(kvA.Key[:1], distribution.DelegatorWithdrawAddrPrefix): - return fmt.Sprintf("%v\n%v", sdk.AccAddress(kvA.Value), sdk.AccAddress(kvB.Value)) - - case bytes.Equal(kvA.Key[:1], distribution.DelegatorStartingInfoPrefix): - var infoA, infoB distribution.DelegatorStartingInfo - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &infoA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &infoB) - return fmt.Sprintf("%v\n%v", infoA, infoB) - - case bytes.Equal(kvA.Key[:1], distribution.ValidatorHistoricalRewardsPrefix): - var rewardsA, rewardsB distribution.ValidatorHistoricalRewards - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) - return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - - case bytes.Equal(kvA.Key[:1], distribution.ValidatorCurrentRewardsPrefix): - var rewardsA, rewardsB distribution.ValidatorCurrentRewards - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &rewardsA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &rewardsB) - return fmt.Sprintf("%v\n%v", rewardsA, rewardsB) - - case bytes.Equal(kvA.Key[:1], distribution.ValidatorAccumulatedCommissionPrefix): - var commissionA, commissionB distribution.ValidatorAccumulatedCommission - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &commissionA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &commissionB) - return fmt.Sprintf("%v\n%v", commissionA, commissionB) - - case bytes.Equal(kvA.Key[:1], distribution.ValidatorSlashEventPrefix): - var eventA, eventB distribution.ValidatorSlashEvent - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &eventA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &eventB) - return fmt.Sprintf("%v\n%v", eventA, eventB) - - default: - panic(fmt.Sprintf("invalid distribution key prefix %X", kvA.Key[:1])) - } -} - -func DecodeStakingStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { - switch { - case bytes.Equal(kvA.Key[:1], staking.LastTotalPowerKey): - var powerA, powerB sdk.Int - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &powerA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &powerB) - return fmt.Sprintf("%v\n%v", powerA, powerB) - - case bytes.Equal(kvA.Key[:1], staking.ValidatorsKey): - var validatorA, validatorB staking.Validator - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &validatorA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &validatorB) - return fmt.Sprintf("%v\n%v", validatorA, validatorB) - - case bytes.Equal(kvA.Key[:1], staking.LastValidatorPowerKey), - bytes.Equal(kvA.Key[:1], staking.ValidatorsByConsAddrKey), - bytes.Equal(kvA.Key[:1], staking.ValidatorsByPowerIndexKey): - return fmt.Sprintf("%v\n%v", sdk.ValAddress(kvA.Value), sdk.ValAddress(kvB.Value)) - - case bytes.Equal(kvA.Key[:1], staking.DelegationKey): - var delegationA, delegationB staking.Delegation - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &delegationA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &delegationB) - return fmt.Sprintf("%v\n%v", delegationA, delegationB) - - case bytes.Equal(kvA.Key[:1], staking.UnbondingDelegationKey), - bytes.Equal(kvA.Key[:1], staking.UnbondingDelegationByValIndexKey): - var ubdA, ubdB staking.UnbondingDelegation - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &ubdA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &ubdB) - return fmt.Sprintf("%v\n%v", ubdA, ubdB) - - case bytes.Equal(kvA.Key[:1], staking.RedelegationKey), - bytes.Equal(kvA.Key[:1], staking.RedelegationByValSrcIndexKey): - var redA, redB staking.Redelegation - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &redA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &redB) - return fmt.Sprintf("%v\n%v", redA, redB) - - default: - panic(fmt.Sprintf("invalid staking key prefix %X", kvA.Key[:1])) - } -} - -func DecodeSlashingStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { - switch { - case bytes.Equal(kvA.Key[:1], slashing.ValidatorSigningInfoKey): - var infoA, infoB slashing.ValidatorSigningInfo - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &infoA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &infoB) - return fmt.Sprintf("%v\n%v", infoA, infoB) - - case bytes.Equal(kvA.Key[:1], slashing.ValidatorMissedBlockBitArrayKey): - var missedA, missedB bool - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &missedA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &missedB) - return fmt.Sprintf("missedA: %v\nmissedB: %v", missedA, missedB) - - case bytes.Equal(kvA.Key[:1], slashing.AddrPubkeyRelationKey): - var pubKeyA, pubKeyB crypto.PubKey - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &pubKeyA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &pubKeyB) - bechPKA := sdk.MustBech32ifyAccPub(pubKeyA) - bechPKB := sdk.MustBech32ifyAccPub(pubKeyB) - return fmt.Sprintf("PubKeyA: %s\nPubKeyB: %s", bechPKA, bechPKB) - - default: - panic(fmt.Sprintf("invalid slashing key prefix %X", kvA.Key[:1])) - } -} - -func DecodeGovStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { - switch { - case bytes.Equal(kvA.Key[:1], gov.ProposalsKeyPrefix): - var proposalA, proposalB gov.Proposal - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &proposalA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &proposalB) - return fmt.Sprintf("%v\n%v", proposalA, proposalB) - - case bytes.Equal(kvA.Key[:1], gov.ActiveProposalQueuePrefix), - bytes.Equal(kvA.Key[:1], gov.InactiveProposalQueuePrefix), - bytes.Equal(kvA.Key[:1], gov.ProposalIDKey): - proposalIDA := binary.LittleEndian.Uint64(kvA.Value) - proposalIDB := binary.LittleEndian.Uint64(kvB.Value) - return fmt.Sprintf("proposalIDA: %d\nProposalIDB: %d", proposalIDA, proposalIDB) - - case bytes.Equal(kvA.Key[:1], gov.DepositsKeyPrefix): - var depositA, depositB gov.Deposit - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &depositA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &depositB) - return fmt.Sprintf("%v\n%v", depositA, depositB) - - case bytes.Equal(kvA.Key[:1], gov.VotesKeyPrefix): - var voteA, voteB gov.Vote - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &voteA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &voteB) - return fmt.Sprintf("%v\n%v", voteA, voteB) - - default: - panic(fmt.Sprintf("invalid governance key prefix %X", kvA.Key[:1])) - } -} - -func DecodeSupplyStore(cdcA, cdcB *codec.Codec, kvA, kvB cmn.KVPair) string { - switch { - case bytes.Equal(kvA.Key[:1], supply.SupplyKey): - var supplyA, supplyB supply.Supply - cdcA.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &supplyA) - cdcB.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &supplyB) - return fmt.Sprintf("%v\n%v", supplyB, supplyB) - default: - panic(fmt.Sprintf("invalid supply key %X", kvA.Key)) - } -} diff --git a/types/address.go b/types/address.go index 15b6a6b0..b01f765d 100644 --- a/types/address.go +++ b/types/address.go @@ -1,5 +1,16 @@ package types +import ( + "bytes" + "encoding/json" + "fmt" + "strings" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/tendermint/tendermint/libs/bech32" + "gopkg.in/yaml.v2" +) + const ( // Bech32PrefixAccAddr defines the Bech32 prefix of an account's address Bech32MainPrefix = "sent" @@ -13,6 +24,11 @@ const ( // PrefixOperator is the prefix for operator keys PrefixOperator = "oper" + // PrefixProvider is the prefix for provider keys + PrefixProvider = "prov" + // PrefixNode is the prefix for node keys + PrefixNode = "node" + // Bech32PrefixAccAddr defines the Bech32 prefix of an account's address Bech32PrefixAccAddr = Bech32MainPrefix // Bech32PrefixAccPub defines the Bech32 prefix of an account's public key @@ -25,4 +41,231 @@ const ( Bech32PrefixConsAddr = Bech32MainPrefix + PrefixValidator + PrefixConsensus // Bech32PrefixConsPub defines the Bech32 prefix of a consensus node public key Bech32PrefixConsPub = Bech32MainPrefix + PrefixValidator + PrefixConsensus + PrefixPublic + + // Bech32PrefixProvAddr defines the Bech32 prefix of a providers's address + Bech32PrefixProvAddr = Bech32MainPrefix + PrefixProvider + // Bech32PrefixNodeAddr defines the Bech32 prefix of a node's address + Bech32PrefixNodeAddr = Bech32MainPrefix + PrefixNode +) + +var ( + _ sdk.Address = ProvAddress{} + _ yaml.Marshaler = ProvAddress{} + + _ sdk.Address = NodeAddress{} + _ yaml.Marshaler = NodeAddress{} ) + +type ProvAddress []byte + +func (p ProvAddress) Equals(address sdk.Address) bool { + if p.Empty() && address == nil { + return true + } + + return bytes.Equal(p.Bytes(), address.Bytes()) +} + +func (p ProvAddress) Empty() bool { + return bytes.Equal(p.Bytes(), ProvAddress{}.Bytes()) +} + +func (p ProvAddress) Bytes() []byte { + return p +} + +func (p ProvAddress) String() string { + if p.Empty() { + return "" + } + + s, err := bech32.ConvertAndEncode(GetConfig().GetBech32ProviderAddrPrefix(), p.Bytes()) + if err != nil { + panic(err) + } + + return s +} + +func (p ProvAddress) Format(f fmt.State, c rune) { + switch c { + case 's': + _, _ = f.Write([]byte(p.String())) + case 'p': + _, _ = f.Write([]byte(fmt.Sprintf("%p", p))) + default: + _, _ = f.Write([]byte(fmt.Sprintf("%X", p.Bytes()))) + } +} + +func (p ProvAddress) Marshal() ([]byte, error) { + return p, nil +} + +func (p ProvAddress) MarshalJSON() ([]byte, error) { + return json.Marshal(p.String()) +} + +func (p ProvAddress) MarshalYAML() (interface{}, error) { + return p.String(), nil +} + +func (p *ProvAddress) Unmarshal(data []byte) error { + *p = data + return nil +} + +func (p *ProvAddress) UnmarshalJSON(data []byte) error { + var s string + if err := json.Unmarshal(data, &s); err != nil { + return err + } + + address, err := ProvAddressFromBech32(s) + if err != nil { + return err + } + + *p = address + return nil +} + +func (p *ProvAddress) UnmarshalYAML(data []byte) error { + var s string + if err := yaml.Unmarshal(data, &s); err != nil { + return err + } + + address, err := ProvAddressFromBech32(s) + if err != nil { + return err + } + + *p = address + return nil +} + +func ProvAddressFromBech32(s string) (ProvAddress, error) { + s = strings.TrimSpace(s) + if len(s) == 0 { + return ProvAddress{}, nil + } + + bz, err := sdk.GetFromBech32(s, GetConfig().GetBech32ProviderAddrPrefix()) + if err != nil { + return nil, err + } + + if err = sdk.VerifyAddressFormat(bz); err != nil { + return nil, err + } + + return bz, nil +} + +type NodeAddress []byte + +func (n NodeAddress) Equals(address sdk.Address) bool { + if n.Empty() && address == nil { + return true + } + + return bytes.Equal(n.Bytes(), address.Bytes()) +} + +func (n NodeAddress) Empty() bool { + return bytes.Equal(n.Bytes(), NodeAddress{}.Bytes()) +} + +func (n NodeAddress) Bytes() []byte { + return n +} + +func (n NodeAddress) String() string { + if n.Empty() { + return "" + } + + s, err := bech32.ConvertAndEncode(GetConfig().GetBech32NodeAddrPrefix(), n.Bytes()) + if err != nil { + panic(err) + } + + return s +} + +func (n NodeAddress) Format(f fmt.State, c rune) { + switch c { + case 's': + _, _ = f.Write([]byte(n.String())) + case 'p': + _, _ = f.Write([]byte(fmt.Sprintf("%p", n))) + default: + _, _ = f.Write([]byte(fmt.Sprintf("%X", n.Bytes()))) + } +} + +func (n NodeAddress) Marshal() ([]byte, error) { + return n, nil +} + +func (n NodeAddress) MarshalJSON() ([]byte, error) { + return json.Marshal(n.String()) +} + +func (n NodeAddress) MarshalYAML() (interface{}, error) { + return n.String(), nil +} + +func (n *NodeAddress) Unmarshal(data []byte) error { + *n = data + return nil +} + +func (n *NodeAddress) UnmarshalJSON(data []byte) error { + var s string + if err := json.Unmarshal(data, &s); err != nil { + return err + } + + address, err := NodeAddressFromBech32(s) + if err != nil { + return err + } + + *n = address + return nil +} + +func (n *NodeAddress) UnmarshalYAML(data []byte) error { + var s string + if err := yaml.Unmarshal(data, &s); err != nil { + return err + } + + address, err := NodeAddressFromBech32(s) + if err != nil { + return err + } + + *n = address + return nil +} + +func NodeAddressFromBech32(s string) (NodeAddress, error) { + s = strings.TrimSpace(s) + if len(s) == 0 { + return NodeAddress{}, nil + } + + bz, err := sdk.GetFromBech32(s, GetConfig().GetBech32NodeAddrPrefix()) + if err != nil { + return nil, err + } + + if err = sdk.VerifyAddressFormat(bz); err != nil { + return nil, err + } + + return bz, nil +} diff --git a/types/bandwidth.go b/types/bandwidth.go index a93f9d18..4bab1f58 100644 --- a/types/bandwidth.go +++ b/types/bandwidth.go @@ -1,7 +1,6 @@ package types import ( - "encoding/json" "fmt" "math/big" @@ -9,10 +8,9 @@ import ( ) var ( - KB = sdk.NewInt(1000) - MB = KB.MulRaw(1000) - MB500 = MB.MulRaw(500) - GB = MB.MulRaw(1000) + Kilobyte = sdk.NewInt(1000) + Megabyte = sdk.NewInt(1000).Mul(Kilobyte) + Gigabyte = sdk.NewInt(1000).Mul(Megabyte) ) type Bandwidth struct { @@ -28,108 +26,65 @@ func NewBandwidth(upload, download sdk.Int) Bandwidth { } func (b Bandwidth) String() string { - return fmt.Sprintf("%d upload, %d download", b.Upload.Int64(), b.Download.Int64()) + return fmt.Sprintf("%s↑, %s↓ bytes", b.Upload, b.Download) } -func (b Bandwidth) CeilTo(precision sdk.Int) Bandwidth { - _b := Bandwidth{ - Upload: precision.Sub(sdk.NewIntFromBigInt( - big.NewInt(0).Rem(b.Upload.BigInt(), precision.BigInt()))), - Download: precision.Sub(sdk.NewIntFromBigInt( - big.NewInt(0).Rem(b.Download.BigInt(), precision.BigInt()))), - } - - if _b.Upload.Equal(precision) { - _b.Upload = sdk.NewInt(0) - } - - if _b.Download.Equal(precision) { - _b.Download = sdk.NewInt(0) - } - - return b.Add(_b) +func (b Bandwidth) IsAnyZero() bool { + return b.Upload.IsZero() || b.Download.IsZero() } -func (b Bandwidth) Sum() sdk.Int { - return b.Upload.Add(b.Download) +func (b Bandwidth) IsAllZero() bool { + return b.Upload.IsZero() && b.Download.IsZero() } -func (b Bandwidth) Add(bandwidth Bandwidth) Bandwidth { - b.Upload = b.Upload.Add(bandwidth.Upload) - b.Download = b.Download.Add(bandwidth.Download) - - return b +func (b Bandwidth) IsAnyNegative() bool { + return b.Upload.IsNegative() || b.Download.IsNegative() } -func (b Bandwidth) Sub(bandwidth Bandwidth) Bandwidth { - b.Upload = b.Upload.Sub(bandwidth.Upload) - b.Download = b.Download.Sub(bandwidth.Download) - - return b +func (b Bandwidth) IsValid() bool { + return !b.IsAnyNegative() && !b.IsAnyZero() } -func (b Bandwidth) AllLT(bandwidth Bandwidth) bool { - return b.Upload.LT(bandwidth.Upload) && - b.Download.LT(bandwidth.Download) +func (b Bandwidth) Sum() sdk.Int { + return b.Upload.Add(b.Download) } -func (b Bandwidth) AnyLT(bandwidth Bandwidth) bool { - return b.Upload.LT(bandwidth.Upload) || - b.Download.LT(bandwidth.Download) -} +func (b Bandwidth) Add(v Bandwidth) Bandwidth { + b.Upload = b.Upload.Add(v.Upload) + b.Download = b.Download.Add(v.Download) -func (b Bandwidth) AllEqual(bandwidth Bandwidth) bool { - return b.Upload.Equal(bandwidth.Upload) && - b.Download.Equal(bandwidth.Download) + return b } -func (b Bandwidth) AllLTE(bandwidth Bandwidth) bool { - return b.AllLT(bandwidth) || b.AllEqual(bandwidth) +func (b Bandwidth) IsAllLTE(v Bandwidth) bool { + return b.Upload.LTE(v.Upload) && b.Download.LTE(v.Download) } -func (b Bandwidth) AnyZero() bool { - return b.Upload.IsZero() || - b.Download.IsZero() +func (b Bandwidth) IsAnyGT(v Bandwidth) bool { + return b.Upload.GT(v.Upload) || b.Download.GT(v.Download) } -func (b Bandwidth) AllPositive() bool { - return b.Upload.IsPositive() && - b.Download.IsPositive() -} +func (b Bandwidth) CeilTo(precision sdk.Int) Bandwidth { + v := NewBandwidth( + precision.Sub(sdk.NewIntFromBigInt( + big.NewInt(0).Rem(b.Upload.BigInt(), precision.BigInt()))), + precision.Sub(sdk.NewIntFromBigInt( + big.NewInt(0).Rem(b.Download.BigInt(), precision.BigInt()))), + ) -func (b Bandwidth) AnyNegative() bool { - return b.Upload.IsNegative() || - b.Download.IsNegative() -} + if v.Upload.Equal(precision) { + v.Upload = sdk.NewInt(0) + } + if v.Download.Equal(precision) { + v.Download = sdk.NewInt(0) + } -func (b Bandwidth) AnyNil() bool { - return b.Upload == sdk.Int{} || - b.Download == sdk.Int{} + return b.Add(v) } func NewBandwidthFromInt64(upload, download int64) Bandwidth { - return NewBandwidth(sdk.NewInt(upload), sdk.NewInt(download)) -} - -type BandwidthSignatureData struct { - ID SubscriptionID `json:"id"` - Index uint64 `json:"index"` - Bandwidth Bandwidth `json:"bandwidth"` -} - -func NewBandwidthSignatureData(id SubscriptionID, index uint64, bandwidth Bandwidth) BandwidthSignatureData { - return BandwidthSignatureData{ - ID: id, - Index: index, - Bandwidth: bandwidth, - } -} - -func (b BandwidthSignatureData) Bytes() []byte { - bz, err := json.Marshal(b) - if err != nil { - panic(err) + return Bandwidth{ + Upload: sdk.NewInt(upload), + Download: sdk.NewInt(download), } - - return bz } diff --git a/types/codec.go b/types/codec.go deleted file mode 100644 index a9c9a049..00000000 --- a/types/codec.go +++ /dev/null @@ -1,12 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" -) - -func RegisterCodec(cdc *codec.Codec) { - cdc.RegisterInterface((*ID)(nil), nil) - cdc.RegisterConcrete(NodeID{}, "types/nodeID", nil) - cdc.RegisterConcrete(SessionID{}, "types/sessionID", nil) - cdc.RegisterConcrete(SubscriptionID{}, "types/subscriptionID", nil) -} diff --git a/types/config.go b/types/config.go new file mode 100644 index 00000000..9ec3caf9 --- /dev/null +++ b/types/config.go @@ -0,0 +1,63 @@ +package types + +import ( + "sync" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type Config struct { + *sdk.Config + prefixes map[string]string + sealed bool + mtx sync.Mutex +} + +var ( + config = &Config{ + Config: sdk.GetConfig(), + prefixes: map[string]string{ + "provider_addr": Bech32PrefixProvAddr, + "node_addr": Bech32PrefixNodeAddr, + }, + } +) + +func GetConfig() *Config { + return config +} + +func (c *Config) assert() { + c.mtx.Lock() + defer c.mtx.Unlock() + + if c.sealed { + panic("config is sealed") + } +} + +func (c *Config) Seal() { + c.mtx.Lock() + defer c.mtx.Unlock() + + c.Config.Seal() + c.sealed = true +} + +func (c *Config) SetBech32PrefixForProvider(prefix string) { + c.assert() + config.prefixes["provider_addr"] = prefix +} + +func (c *Config) SetBech32PrefixForNode(prefix string) { + c.assert() + config.prefixes["node_addr"] = prefix +} + +func (c *Config) GetBech32ProviderAddrPrefix() string { + return c.prefixes["provider_addr"] +} + +func (c *Config) GetBech32NodeAddrPrefix() string { + return c.prefixes["node_addr"] +} diff --git a/types/errors.go b/types/errors.go index a5558415..d56c9f06 100644 --- a/types/errors.go +++ b/types/errors.go @@ -1,9 +1,11 @@ package types const ( - ErrCodeMarshal = 101 - ErrCodeUnmarshal = 102 + ErrorCodeMarshal = iota + 101 + ErrorCodeUnmarshal +) - ErrMsgMarshal = "Error occurred while marshalling the data" // nolint:misspell - ErrMsgUnmarshal = "Error occurred while unmarshalling the data" +const ( + ErrorMsgMarshal = "error occurred while marshalling the data" + ErrorMsgUnmarshal = "error occurred while unmarshalling the data" ) diff --git a/types/id.go b/types/id.go deleted file mode 100644 index a393d226..00000000 --- a/types/id.go +++ /dev/null @@ -1,261 +0,0 @@ -package types - -import ( - "encoding/binary" - "encoding/json" - "fmt" - "sort" - "strconv" - "strings" - - "github.com/cosmos/cosmos-sdk/types" -) - -const ( - NodeIDPrefix = "node" - SessionIDPrefix = "sess" - SubscriptionIDPrefix = "subs" -) - -type ID interface { - String() string - Uint64() uint64 - Bytes() []byte - Prefix() string - IsEqual(ID) bool - MarshalJSON() ([]byte, error) -} - -var ( - _ ID = NodeID{} - _ ID = SessionID{} - _ ID = SubscriptionID{} -) - -type NodeID []byte - -func NewNodeID(i uint64) NodeID { - return types.Uint64ToBigEndian(i) -} - -func NewNodeIDFromString(s string) (NodeID, error) { - if len(s) < 5 { - return nil, fmt.Errorf("invalid node is length") - } - - i, err := strconv.ParseUint(s[4:], 16, 64) - if err != nil { - return nil, err - } - - return NewNodeID(i), nil -} - -func (id NodeID) String() string { - return fmt.Sprintf("%s%x", NodeIDPrefix, id.Uint64()) -} - -func (id NodeID) Uint64() uint64 { - return binary.BigEndian.Uint64(id) -} - -func (id NodeID) Bytes() []byte { - return id -} - -func (id NodeID) Prefix() string { - return NodeIDPrefix -} - -func (id NodeID) IsEqual(_id ID) bool { - return id.String() == _id.String() -} - -func (id NodeID) MarshalJSON() ([]byte, error) { - return json.Marshal(id.String()) -} - -func (id *NodeID) UnmarshalJSON(bytes []byte) error { - var s string - if err := json.Unmarshal(bytes, &s); err != nil { - return err - } - - _id, err := NewNodeIDFromString(s) - if err != nil { - return err - } - - *id = _id - - return nil -} - -type SessionID []byte - -func NewSessionID(i uint64) SessionID { - return types.Uint64ToBigEndian(i) -} - -func NewSessionIDFromString(s string) (SessionID, error) { - if len(s) < 5 { - return nil, fmt.Errorf("invalid session id length") - } - - i, err := strconv.ParseUint(s[4:], 16, 64) - if err != nil { - panic(err) - } - - return NewSessionID(i), nil -} - -func (id SessionID) String() string { - return fmt.Sprintf("%s%x", SessionIDPrefix, id.Uint64()) -} - -func (id SessionID) Uint64() uint64 { - return binary.BigEndian.Uint64(id) -} - -func (id SessionID) Bytes() []byte { - return id -} - -func (id SessionID) Prefix() string { - return SessionIDPrefix -} - -func (id SessionID) IsEqual(_id ID) bool { - return id.String() == _id.String() -} - -func (id SessionID) MarshalJSON() ([]byte, error) { - return json.Marshal(id.String()) -} - -func (id *SessionID) UnmarshalJSON(b []byte) error { - var s string - if err := json.Unmarshal(b, &s); err != nil { - return err - } - - _id, err := NewSessionIDFromString(s) - if err != nil { - return err - } - - *id = _id - - return nil -} - -type SubscriptionID []byte - -func NewSubscriptionID(i uint64) SubscriptionID { - return types.Uint64ToBigEndian(i) -} - -func NewSubscriptionIDFromString(s string) (SubscriptionID, error) { - if len(s) < 5 { - return nil, fmt.Errorf("invalid subscription id length") - } - - i, err := strconv.ParseUint(s[4:], 16, 64) - if err != nil { - return nil, err - } - - return NewSubscriptionID(i), nil -} - -func (id SubscriptionID) String() string { - return fmt.Sprintf("%s%x", SubscriptionIDPrefix, id.Uint64()) -} - -func (id SubscriptionID) Uint64() uint64 { - return binary.BigEndian.Uint64(id) -} - -func (id SubscriptionID) Bytes() []byte { - return id -} - -func (id SubscriptionID) Prefix() string { - return SubscriptionIDPrefix -} - -func (id SubscriptionID) IsEqual(_id ID) bool { - return id.String() == _id.String() -} - -func (id SubscriptionID) MarshalJSON() ([]byte, error) { - return json.Marshal(id.String()) -} - -func (id *SubscriptionID) UnmarshalJSON(bytes []byte) error { - var s string - if err := json.Unmarshal(bytes, &s); err != nil { - return err - } - - _id, err := NewSubscriptionIDFromString(s) - if err != nil { - return err - } - - *id = _id - - return nil -} - -var _ sort.Interface = (*IDs)(nil) - -type IDs []ID - -func (ids IDs) Append(id ID) IDs { - return append(ids, id) -} - -func (ids IDs) Len() int { - return len(ids) -} - -func (ids IDs) Less(x, y int) bool { - i := strings.Compare(ids[x].Prefix(), ids[y].Prefix()) - if i < 0 { - return true - } else if i == 0 { - return ids[x].Uint64() < ids[y].Uint64() - } - - return false -} - -func (ids IDs) Swap(x, y int) { - ids[x], ids[y] = ids[y], ids[x] -} - -func (ids IDs) Sort() IDs { - sort.Slice(ids, ids.Less) - return ids -} - -func (ids IDs) Delete(x int) IDs { - ids[x] = ids[ids.Len()-1] - return ids[:ids.Len()-1] -} - -func (ids IDs) Search(id ID) int { - i := id.Uint64() - index := sort.Search(len(ids), func(x int) bool { - return ids[x].Prefix() > id.Prefix() || ids[x].Uint64() >= i - }) - - if (index == ids.Len()) || - (index < ids.Len() && ids[index].String() != id.String()) { - return ids.Len() - } - - return index -} diff --git a/types/status.go b/types/status.go new file mode 100644 index 00000000..35a2557c --- /dev/null +++ b/types/status.go @@ -0,0 +1,39 @@ +package types + +const ( + StatusUnknown = iota + 0x00 + StatusActive + StatusInactive +) + +type Status byte + +func StatusFromString(s string) Status { + switch s { + case "Active": + return StatusActive + case "Inactive": + return StatusInactive + default: + return StatusUnknown + } +} + +func (s Status) IsValid() bool { + return s == StatusActive || s == StatusInactive +} + +func (s Status) Equal(v Status) bool { + return s == v +} + +func (s Status) String() string { + switch s { + case StatusActive: + return "Active" + case StatusInactive: + return "Inactive" + default: + return "Unknown" + } +} diff --git a/x/deposit/alias.go b/x/deposit/alias.go deleted file mode 100644 index 381a1da1..00000000 --- a/x/deposit/alias.go +++ /dev/null @@ -1,48 +0,0 @@ -// nolint -// autogenerated code using github.com/rigelrozanski/multitool -// aliases generated for the following subdirectories: -// ALIASGEN: github.com/sentinel-official/hub/x/deposit/types/ -// ALIASGEN: github.com/sentinel-official/hub/x/deposit/keeper/ -// ALIASGEN: github.com/sentinel-official/hub/x/deposit/querier/ -package deposit - -import ( - "github.com/sentinel-official/hub/x/deposit/keeper" - "github.com/sentinel-official/hub/x/deposit/querier" - "github.com/sentinel-official/hub/x/deposit/types" -) - -const ( - Codespace = types.Codespace - ModuleName = types.ModuleName - StoreKey = types.StoreKey - RouterKey = types.RouterKey - QuerierRoute = types.QuerierRoute - QueryDepositOfAddress = types.QueryDepositOfAddress - QueryAllDeposits = types.QueryAllDeposits -) - -var ( - // functions aliases - ErrorMarshal = types.ErrorMarshal - ErrorUnmarshal = types.ErrorUnmarshal - ErrorInvalidQueryType = types.ErrorInvalidQueryType - ErrorInsufficientDepositFunds = types.ErrorInsufficientDepositFunds - NewGenesisState = types.NewGenesisState - DefaultGenesisState = types.DefaultGenesisState - DepositKey = types.DepositKey - NewQueryDepositOfAddressParams = types.NewQueryDepositOfAddressParams - NewKeeper = keeper.NewKeeper - NewQuerier = querier.NewQuerier - - // variable aliases - ModuleCdc = types.ModuleCdc - DepositKeyPrefix = types.DepositKeyPrefix -) - -type ( - Deposit = types.Deposit - GenesisState = types.GenesisState - QueryDepositOfAddressPrams = types.QueryDepositOfAddressPrams - Keeper = keeper.Keeper -) diff --git a/x/deposit/client/cli/cli.go b/x/deposit/client/cli/cli.go deleted file mode 100644 index 39d3f1d0..00000000 --- a/x/deposit/client/cli/cli.go +++ /dev/null @@ -1,10 +0,0 @@ -package cli - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/spf13/cobra" -) - -func GetQueryCmd(cdc *codec.Codec) *cobra.Command { - return QueryDepositsCmd(cdc) -} diff --git a/x/deposit/client/cli/falgs.go b/x/deposit/client/cli/falgs.go deleted file mode 100644 index 6d4579c2..00000000 --- a/x/deposit/client/cli/falgs.go +++ /dev/null @@ -1,3 +0,0 @@ -package cli - -const flagAddress = "address" diff --git a/x/deposit/client/cli/query_deposits.go b/x/deposit/client/cli/query_deposits.go deleted file mode 100644 index 9ca59736..00000000 --- a/x/deposit/client/cli/query_deposits.go +++ /dev/null @@ -1,50 +0,0 @@ -package cli - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/sentinel-official/hub/x/deposit/client/common" -) - -func QueryDepositsCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "deposits", - Short: "Query deposits", - RunE: func(cmd *cobra.Command, args []string) error { - ctx := context.NewCLIContext().WithCodec(cdc) - - address := viper.GetString(flagAddress) - - if address != "" { - deposit, err := common.QueryDepositOfAddress(ctx, address) - if err != nil { - return err - } - - fmt.Println(deposit) - return nil - } - - deposits, err := common.QueryAllDeposits(ctx) - if err != nil { - return err - } - - for _, deposit := range deposits { - fmt.Println(deposit) - } - - return nil - }, - } - - cmd.Flags().String(flagAddress, "", "Account address") - - return client.GetCommands(cmd)[0] -} diff --git a/x/deposit/client/common/query.go b/x/deposit/client/common/query.go deleted file mode 100644 index 64518205..00000000 --- a/x/deposit/client/common/query.go +++ /dev/null @@ -1,58 +0,0 @@ -package common - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/sentinel-official/hub/x/deposit/types" -) - -func QueryDepositOfAddress(ctx context.CLIContext, s string) (*types.Deposit, error) { - address, err := sdk.AccAddressFromBech32(s) - if err != nil { - return nil, err - } - - params := types.NewQueryDepositOfAddressParams(address) - - bytes, err := ctx.Codec.MarshalJSON(params) - if err != nil { - return nil, err - } - - path := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryDepositOfAddress) - res, _, err := ctx.QueryWithData(path, bytes) - if err != nil { - return nil, err - } - if res == nil { - return nil, fmt.Errorf("no deposit found") - } - - var d types.Deposit - if err = ctx.Codec.UnmarshalJSON(res, &d); err != nil { - return nil, err - } - - return &d, nil -} - -func QueryAllDeposits(ctx context.CLIContext) ([]types.Deposit, error) { - path := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryAllDeposits) - res, _, err := ctx.QueryWithData(path, nil) - if err != nil { - return nil, err - } - if string(res) == "[]" || string(res) == "null" { - return nil, fmt.Errorf("no deposits found") - } - - var d []types.Deposit - if err = ctx.Codec.UnmarshalJSON(res, &d); err != nil { - return nil, err - } - - return d, nil -} diff --git a/x/deposit/client/rest/rest.go b/x/deposit/client/rest/rest.go deleted file mode 100644 index 4b397c69..00000000 --- a/x/deposit/client/rest/rest.go +++ /dev/null @@ -1,17 +0,0 @@ -package rest - -import ( - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/gorilla/mux" -) - -func RegisterRoutes(ctx context.CLIContext, r *mux.Router) { - registerQueryRoutes(ctx, r) -} - -func registerQueryRoutes(ctx context.CLIContext, r *mux.Router) { - r.HandleFunc("/deposits", getAllDeposits(ctx)). - Methods("GET") - r.HandleFunc("/deposits/{address}", getDepositOfAddressHandlerFunc(ctx)). - Methods("GET") -} diff --git a/x/deposit/genesis.go b/x/deposit/genesis.go deleted file mode 100644 index e208db86..00000000 --- a/x/deposit/genesis.go +++ /dev/null @@ -1,39 +0,0 @@ -package deposit - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/sentinel-official/hub/x/deposit/types" -) - -func InitGenesis(ctx sdk.Context, k Keeper, data types.GenesisState) { - for _, deposit := range data { - k.SetDeposit(ctx, deposit) - } -} - -func ExportGenesis(ctx sdk.Context, k Keeper) types.GenesisState { - deposits := k.GetAllDeposits(ctx) - - return types.NewGenesisState(deposits) -} - -func ValidateGenesis(data types.GenesisState) error { - addressMap := make(map[string]bool, len(data)) - for _, deposit := range data { - if err := deposit.IsValid(); err != nil { - return fmt.Errorf("%s for the %s", err.Error(), deposit) - } - - addressStr := deposit.Address.String() - if addressMap[addressStr] { - return fmt.Errorf("duplicate address for the %s", deposit) - } - - addressMap[addressStr] = true - } - - return nil -} diff --git a/x/deposit/keeper/deposit_test.go b/x/deposit/keeper/deposit_test.go deleted file mode 100644 index 64779238..00000000 --- a/x/deposit/keeper/deposit_test.go +++ /dev/null @@ -1,351 +0,0 @@ -package keeper - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/sentinel-official/hub/x/deposit/types" -) - -func TestKeeper_SetDeposit(t *testing.T) { - ctx, dk, _ := CreateTestInput(t, false) - - deposit, found := dk.GetDeposit(ctx, types.Deposit{}.Address) - require.Equal(t, false, found) - require.Equal(t, types.Deposit{}, deposit) - dk.SetDeposit(ctx, types.Deposit{}) - deposit, found = dk.GetDeposit(ctx, types.Deposit{}.Address) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{}, deposit) - - dk.SetDeposit(ctx, types.Deposit{Coins: sdk.Coins(nil)}) - deposit, found = dk.GetDeposit(ctx, types.Deposit{Coins: sdk.Coins(nil)}.Address) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{Coins: sdk.Coins(nil)}, deposit) - - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, false, found) - require.Equal(t, types.Deposit{}, deposit) - dk.SetDeposit(ctx, types.Deposit{types.TestAddress1, sdk.Coins{sdk.Coin{"stake", sdk.NewInt(-10)}}}) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins{sdk.Coin{"stake", sdk.NewInt(-10)}}}, deposit) - - dk.SetDeposit(ctx, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 0)}}) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 0)}}, deposit) - - dk.SetDeposit(ctx, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}) - deposit, found = dk.GetDeposit(ctx, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}.Address) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}, deposit) -} - -func TestKeeper_GetDeposit(t *testing.T) { - TestKeeper_SetDeposit(t) -} - -func TestKeeper_GetAllDeposits(t *testing.T) { - ctx, dk, _ := CreateTestInput(t, false) - - deposits := dk.GetAllDeposits(ctx) - require.Len(t, deposits, 0) - require.Equal(t, []types.Deposit(nil), deposits) - - dk.SetDeposit(ctx, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}) - deposits = dk.GetAllDeposits(ctx) - require.Len(t, deposits, 1) - require.Equal(t, []types.Deposit{{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}}, deposits) - - depositPos2 := types.Deposit{Address: types.TestAddress2, Coins: sdk.Coins{sdk.NewInt64Coin("stake", 10)}} - dk.SetDeposit(ctx, depositPos2) - deposits = dk.GetAllDeposits(ctx) - require.Len(t, deposits, 2) -} - -func TestKeeper_Add(t *testing.T) { - ctx, dk, bk := CreateTestInput(t, false) - - err := dk.Add(ctx, types.TestAddress1, sdk.Coins{}) - require.Nil(t, err) - deposit, found := dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins(nil)}, deposit) - - err = dk.Add(ctx, types.TestAddress1, sdk.Coins(nil)) - require.Nil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins(nil)}, deposit) - - err = dk.Add(ctx, types.TestAddress1, sdk.Coins{sdk.Coin{"stake", sdk.NewInt(-10)}}) - require.NotNil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins(nil)}, deposit) - - err = dk.Add(ctx, types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 0)}) - require.NotNil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins(nil)}, deposit) - - err = dk.Add(ctx, types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - require.NotNil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins(nil)}, deposit) - - coins, err := bk.AddCoins(ctx, types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - require.Nil(t, err) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 10)}, coins) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 10)}, bk.GetCoins(ctx, types.TestAddress1)) - - err = dk.Add(ctx, types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - require.Nil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}, deposit) - require.Equal(t, sdk.Coins(nil), bk.GetCoins(ctx, types.TestAddress1)) - - err = dk.Add(ctx, types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - require.NotNil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}, deposit) - require.Equal(t, sdk.Coins(nil), bk.GetCoins(ctx, types.TestAddress1)) - - coinsPos2 := sdk.Coins{sdk.NewInt64Coin("stake", 10)}.Add(sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - depositPos2 := types.Deposit{Address: types.TestAddress1, Coins: coinsPos2} - - coins, err = bk.AddCoins(ctx, types.TestAddress1, coinsPos2) - require.Nil(t, err) - require.Equal(t, coinsPos2, bk.GetCoins(ctx, types.TestAddress1)) - - err = dk.Add(ctx, types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - require.Nil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, depositPos2, deposit) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 10)}, bk.GetCoins(ctx, types.TestAddress1)) - - coinsPos3 := coinsPos2.Add(sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - depositPos3 := types.Deposit{Address: types.TestAddress1, Coins: coinsPos3} - - err = dk.Add(ctx, types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - require.Nil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, depositPos3, deposit) - require.Equal(t, sdk.Coins(nil), bk.GetCoins(ctx, types.TestAddress1)) -} - -func TestKeeper_Subtract(t *testing.T) { - ctx, dk, bk := CreateTestInput(t, false) - - deposit, found := dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, false, found) - require.Equal(t, types.Deposit{}, deposit) - - err := dk.Subtract(ctx, types.TestAddress1, sdk.Coins{}) - require.NotNil(t, err) - err = dk.Subtract(ctx, types.TestAddress1, sdk.Coins(nil)) - require.NotNil(t, err) - err = dk.Subtract(ctx, types.TestAddress1, sdk.Coins{sdk.Coin{"stake", sdk.NewInt(-10)}}) - require.NotNil(t, err) - err = dk.Subtract(ctx, types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 0)}) - require.NotNil(t, err) - err = dk.Subtract(ctx, types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - require.NotNil(t, err) - - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, false, found) - require.Equal(t, types.Deposit{}, deposit) - dk.SetDeposit(ctx, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}, deposit) - - err = dk.Subtract(ctx, types.TestAddress1, sdk.Coins{}) - require.Nil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}, deposit) - - err = dk.Subtract(ctx, types.TestAddress1, sdk.Coins(nil)) - require.Nil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}, deposit) - - err = dk.Subtract(ctx, types.TestAddress1, sdk.Coins{sdk.Coin{"stake", sdk.NewInt(-10)}}) - require.NotNil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}, deposit) - - err = dk.Subtract(ctx, types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 0)}) - require.NotNil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}, deposit) - - err = dk.Subtract(ctx, types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - require.NotNil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 10)}, deposit.Coins) - coins := bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins(nil), coins) -} - -func TestKeeper_SendFromDepositToAccount(t *testing.T) { - ctx, dk, bk := CreateTestInput(t, false) - - deposit, found := dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, false, found) - require.Equal(t, types.Deposit{}, deposit) - - err := dk.SendCoinsFromDepositToAccount(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins{}) - require.NotNil(t, err) - err = dk.SendCoinsFromDepositToAccount(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins(nil)) - require.NotNil(t, err) - err = dk.SendCoinsFromDepositToAccount(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins{sdk.Coin{"stake", sdk.NewInt(-10)}}) - require.NotNil(t, err) - err = dk.SendCoinsFromDepositToAccount(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins{sdk.NewInt64Coin("stake", 0)}) - require.NotNil(t, err) - err = dk.SendCoinsFromDepositToAccount(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - require.NotNil(t, err) - - dk.SetDeposit(ctx, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}) - err = dk.SendCoinsFromDepositToAccount(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins{}) - require.Nil(t, err) - coins := bk.GetCoins(ctx, types.TestAddress2) - require.Equal(t, sdk.Coins(nil), coins) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}, deposit) - - err = dk.SendCoinsFromDepositToAccount(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins(nil)) - require.Nil(t, err) - coins = bk.GetCoins(ctx, types.TestAddress2) - require.Equal(t, sdk.Coins(nil), coins) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}, deposit) - - err = dk.SendCoinsFromDepositToAccount(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins{sdk.Coin{"stake", sdk.NewInt(-10)}}) - require.NotNil(t, err) - coins = bk.GetCoins(ctx, types.TestAddress2) - require.Equal(t, sdk.Coins(nil), coins) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}, deposit) - - err = dk.SendCoinsFromDepositToAccount(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins{sdk.NewInt64Coin("stake", 0)}) - require.NotNil(t, err) - coins = bk.GetCoins(ctx, types.TestAddress2) - require.Equal(t, sdk.Coins(nil), coins) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}, deposit) - - err = dk.SendCoinsFromDepositToAccount(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - require.NotNil(t, err) - coins = bk.GetCoins(ctx, types.TestAddress2) - require.Equal(t, sdk.Coins(nil), coins) - coins = bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins{}, coins) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 10)}, deposit.Coins) -} - -func TestKeeper_ReceiveFromAccountToDeposit(t *testing.T) { - ctx, dk, bk := CreateTestInput(t, false) - - deposit, found := dk.GetDeposit(ctx, types.TestAddress2) - require.Equal(t, false, found) - coins := bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins{}, coins) - - err := dk.SendCoinsFromAccountToDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins{}) - require.Nil(t, err) - err = dk.SendCoinsFromAccountToDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins(nil)) - require.Nil(t, err) - err = dk.SendCoinsFromAccountToDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins{sdk.Coin{"stake", sdk.NewInt(-10)}}) - require.NotNil(t, err) - err = dk.SendCoinsFromAccountToDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins{sdk.NewInt64Coin("stake", 0)}) - require.NotNil(t, err) - err = dk.SendCoinsFromAccountToDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - require.NotNil(t, err) - - deposit, found = dk.GetDeposit(ctx, types.TestAddress2) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - coins, err = bk.AddCoins(ctx, types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - require.Nil(t, err) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 10)}, coins) - - err = dk.SendCoinsFromAccountToDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins{}) - require.Nil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress2) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - coins = bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 10)}, coins) - - err = dk.SendCoinsFromAccountToDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins(nil)) - require.Nil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress2) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - coins = bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 10)}, coins) - - err = dk.SendCoinsFromAccountToDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins{sdk.Coin{"stake", sdk.NewInt(-10)}}) - require.NotNil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress2) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - coins = bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 10)}, coins) - - err = dk.SendCoinsFromAccountToDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins{sdk.NewInt64Coin("stake", 0)}) - require.NotNil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress2) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - coins = bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 10)}, coins) - - err = dk.SendCoinsFromAccountToDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - require.Nil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress2) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 10)}, deposit.Coins) - coins = bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins(nil), coins) - - err = dk.SendCoinsFromAccountToDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - require.NotNil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress2) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 10)}, deposit.Coins) - coins = bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins(nil), coins) - - coins, err = bk.AddCoins(ctx, types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}.Add(sdk.Coins{sdk.NewInt64Coin("stake", 10)})) - require.Nil(t, err) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 10)}.Add(sdk.Coins{sdk.NewInt64Coin("stake", 10)}), coins) - err = dk.SendCoinsFromAccountToDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.Coins{sdk.NewInt64Coin("stake", 10)}) - require.Nil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress2) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 10)}.Add(sdk.Coins{sdk.NewInt64Coin("stake", 10)}), deposit.Coins) - coins = bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 10)}, coins) -} diff --git a/x/deposit/keeper/keeper.go b/x/deposit/keeper/keeper.go deleted file mode 100644 index dd3a680d..00000000 --- a/x/deposit/keeper/keeper.go +++ /dev/null @@ -1,21 +0,0 @@ -package keeper - -import ( - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/supply" -) - -type Keeper struct { - key sdk.StoreKey - cdc *codec.Codec - supply supply.Keeper -} - -func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, sk supply.Keeper) Keeper { - return Keeper{ - key: key, - cdc: cdc, - supply: sk, - } -} diff --git a/x/deposit/keeper/test_common.go b/x/deposit/keeper/test_common.go deleted file mode 100644 index b09869d0..00000000 --- a/x/deposit/keeper/test_common.go +++ /dev/null @@ -1,64 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/supply" - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - db "github.com/tendermint/tm-db" - - "github.com/sentinel-official/hub/x/deposit/types" -) - -func CreateTestInput(t *testing.T, isCheckTx bool) (sdk.Context, Keeper, bank.Keeper) { - keyParams := sdk.NewKVStoreKey(params.StoreKey) - keyAccount := sdk.NewKVStoreKey(auth.StoreKey) - keySupply := sdk.NewKVStoreKey(supply.StoreKey) - keyDeposits := sdk.NewKVStoreKey(types.StoreKey) - tkeyParams := sdk.NewTransientStoreKey(params.TStoreKey) - - mdb := db.NewMemDB() - ms := store.NewCommitMultiStore(mdb) - ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, mdb) - ms.MountStoreWithDB(keyAccount, sdk.StoreTypeIAVL, mdb) - ms.MountStoreWithDB(keySupply, sdk.StoreTypeIAVL, mdb) - ms.MountStoreWithDB(keyDeposits, sdk.StoreTypeIAVL, mdb) - ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, mdb) - require.Nil(t, ms.LoadLatestVersion()) - - depositAccount := supply.NewEmptyModuleAccount(types.ModuleName) - blacklist := make(map[string]bool) - blacklist[depositAccount.String()] = true - accountPermissions := map[string][]string{ - types.ModuleName: nil, - } - - cdc := MakeTestCodec() - ctx := sdk.NewContext(ms, abci.Header{ChainID: "chain-id"}, isCheckTx, log.NewNopLogger()) - - pk := params.NewKeeper(cdc, keyParams, tkeyParams, params.DefaultCodespace) - ak := auth.NewAccountKeeper(cdc, keyAccount, pk.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) - bk := bank.NewBaseKeeper(ak, pk.Subspace(bank.DefaultParamspace), bank.DefaultCodespace, blacklist) - sk := supply.NewKeeper(cdc, keySupply, ak, bk, accountPermissions) - dk := NewKeeper(cdc, keyDeposits, sk) - - sk.SetModuleAccount(ctx, depositAccount) - - return ctx, dk, bk -} - -func MakeTestCodec() *codec.Codec { - var cdc = codec.New() - codec.RegisterCrypto(cdc) - auth.RegisterCodec(cdc) - supply.RegisterCodec(cdc) - return cdc -} diff --git a/x/deposit/module.go b/x/deposit/module.go deleted file mode 100644 index 2c2c235e..00000000 --- a/x/deposit/module.go +++ /dev/null @@ -1,102 +0,0 @@ -package deposit - -import ( - "encoding/json" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/gorilla/mux" - "github.com/spf13/cobra" - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/sentinel-official/hub/x/deposit/client/cli" - "github.com/sentinel-official/hub/x/deposit/client/rest" -) - -var ( - _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModule = AppModule{} -) - -type AppModuleBasic struct{} - -func (a AppModuleBasic) Name() string { - return ModuleName -} - -func (a AppModuleBasic) RegisterCodec(*codec.Codec) {} - -func (a AppModuleBasic) DefaultGenesis() json.RawMessage { - return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) -} - -func (a AppModuleBasic) ValidateGenesis(data json.RawMessage) error { - var state GenesisState - if err := ModuleCdc.UnmarshalJSON(data, &state); err != nil { - return err - } - - return ValidateGenesis(state) -} - -func (a AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, r *mux.Router) { - rest.RegisterRoutes(ctx, r) -} - -func (a AppModuleBasic) GetTxCmd(_ *codec.Codec) *cobra.Command { - return &cobra.Command{} -} - -func (a AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { - return cli.GetQueryCmd(cdc) -} - -type AppModule struct { - AppModuleBasic - keeper Keeper -} - -func NewAppModule(k Keeper) AppModule { - return AppModule{ - keeper: k, - } -} - -func (a AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { - var state GenesisState - ModuleCdc.MustUnmarshalJSON(data, &state) - InitGenesis(ctx, a.keeper, state) - - return nil -} - -func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { - state := ExportGenesis(ctx, a.keeper) - return ModuleCdc.MustMarshalJSON(state) -} - -func (a AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -func (a AppModule) Route() string { - return RouterKey -} - -func (a AppModule) NewHandler() sdk.Handler { - return nil -} - -func (a AppModule) QuerierRoute() string { - return QuerierRoute -} - -func (a AppModule) NewQuerierHandler() sdk.Querier { - return NewQuerier(a.keeper) -} - -func (a AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - -func (a AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return nil -} diff --git a/x/deposit/querier/deposit_test.go b/x/deposit/querier/deposit_test.go deleted file mode 100644 index 4ad48ab3..00000000 --- a/x/deposit/querier/deposit_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package querier - -import ( - "fmt" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/sentinel-official/hub/x/deposit/keeper" - "github.com/sentinel-official/hub/x/deposit/types" -) - -func Test_queryDepositOfAddress(t *testing.T) { - ctx, dk, _ := keeper.CreateTestInput(t, false) - cdc := keeper.MakeTestCodec() - req := abci.RequestQuery{ - Path: fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryDepositOfAddress), - Data: []byte{}, - } - - res, err := queryDepositOfAddress(ctx, req, dk) - require.NotNil(t, err) - require.Equal(t, []byte(nil), res) - require.Len(t, res, 0) - - req.Data = cdc.MustMarshalJSON(types.NewQueryDepositOfAddressParams([]byte(""))) - - res, err = queryDepositOfAddress(ctx, req, dk) - require.Nil(t, err) - require.Equal(t, []byte(nil), res) - require.Len(t, res, 0) - - var deposit types.Deposit - require.NotNil(t, cdc.UnmarshalJSON(res, &deposit)) - require.NotEqual(t, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}, deposit) - dk.SetDeposit(ctx, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}) - - req.Data = cdc.MustMarshalJSON(types.NewQueryDepositOfAddressParams([]byte(""))) - - res, err = queryDepositOfAddress(ctx, req, dk) - require.Nil(t, err) - require.Equal(t, []byte(nil), res) - require.Len(t, res, 0) - - require.NotNil(t, cdc.UnmarshalJSON(res, &deposit)) - require.NotEqual(t, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}, deposit) - - req.Data = cdc.MustMarshalJSON(types.NewQueryDepositOfAddressParams(types.TestAddress1)) - require.Nil(t, err) - - res, err = queryDepositOfAddress(ctx, req, dk) - require.Nil(t, err) - require.NotEqual(t, []byte(nil), res) - - cdc.MustUnmarshalJSON(res, &deposit) - require.Nil(t, err) - require.Equal(t, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}, deposit) - - req.Data = cdc.MustMarshalJSON(types.NewQueryDepositOfAddressParams(types.TestAddress2)) - require.Nil(t, err) - - res, err = queryDepositOfAddress(ctx, req, dk) - require.Nil(t, err) - require.Equal(t, []byte(nil), res) - require.NotNil(t, cdc.UnmarshalJSON(res, &deposit)) -} - -func Test_queryAllDeposits(t *testing.T) { - ctx, dk, _ := keeper.CreateTestInput(t, false) - cdc := keeper.MakeTestCodec() - - res, err := queryAllDeposits(ctx, dk) - require.Nil(t, err) - require.Equal(t, []byte("null"), res) - - var deposits []types.Deposit - cdc.MustUnmarshalJSON(res, &deposits) - require.NotEqual(t, []types.Deposit{{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}}, deposits) - - dk.SetDeposit(ctx, types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}) - - res, err = queryAllDeposits(ctx, dk) - require.Nil(t, err) - require.NotEqual(t, []byte(nil), res) - - cdc.MustUnmarshalJSON(res, &deposits) - require.Equal(t, []types.Deposit{{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}}}, deposits) - - deposit := types.Deposit{types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 10)}} - deposit.Address = types.TestAddress2 - dk.SetDeposit(ctx, deposit) - - res, err = queryAllDeposits(ctx, dk) - require.Nil(t, err) - require.NotEqual(t, []byte(nil), res) - - cdc.MustUnmarshalJSON(res, &deposits) - require.Nil(t, err) - require.Len(t, deposits, 2) -} diff --git a/x/deposit/querier/querier.go b/x/deposit/querier/querier.go deleted file mode 100644 index e829c963..00000000 --- a/x/deposit/querier/querier.go +++ /dev/null @@ -1,22 +0,0 @@ -package querier - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/sentinel-official/hub/x/deposit/keeper" - "github.com/sentinel-official/hub/x/deposit/types" -) - -func NewQuerier(k keeper.Keeper) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, sdk.Error) { - switch path[0] { - case types.QueryDepositOfAddress: - return queryDepositOfAddress(ctx, req, k) - case types.QueryAllDeposits: - return queryAllDeposits(ctx, k) - default: - return nil, types.ErrorInvalidQueryType(path[0]) - } - } -} diff --git a/x/deposit/types/deposit.go b/x/deposit/types/deposit.go deleted file mode 100644 index 8a17bc51..00000000 --- a/x/deposit/types/deposit.go +++ /dev/null @@ -1,29 +0,0 @@ -package types - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type Deposit struct { - Address sdk.AccAddress `json:"address"` - Coins sdk.Coins `json:"coins"` -} - -func (d Deposit) String() string { - return fmt.Sprintf(`Deposit - Address: %s - Coins: %s`, d.Address, d.Coins) -} - -func (d Deposit) IsValid() error { - if d.Address == nil || d.Address.Empty() { - return fmt.Errorf("invalid address") - } - if !d.Coins.IsValid() { - return fmt.Errorf("invalid coins") - } - - return nil -} diff --git a/x/deposit/types/errors.go b/x/deposit/types/errors.go deleted file mode 100644 index 47cb8e14..00000000 --- a/x/deposit/types/errors.go +++ /dev/null @@ -1,41 +0,0 @@ -package types - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - hub "github.com/sentinel-official/hub/types" -) - -const ( - Codespace = sdk.CodespaceType("deposit") - - errCodeInvalidQueryType = 101 - errCodeInsufficientDepositFunds = 102 - errCodeDepositDoesNotExist = 103 - - errMsgInvalidQueryType = "invalid query type: %s" - errMsgInsufficientDepositFunds = "insufficient deposit funds: %s < %s" - errMsgDepositDoesNotExist = "deposit does not exist" -) - -func ErrorMarshal() sdk.Error { - return sdk.NewError(Codespace, hub.ErrCodeMarshal, hub.ErrMsgMarshal) -} - -func ErrorUnmarshal() sdk.Error { - return sdk.NewError(Codespace, hub.ErrCodeUnmarshal, hub.ErrMsgUnmarshal) -} - -func ErrorInvalidQueryType(queryType string) sdk.Error { - return sdk.NewError(Codespace, errCodeInvalidQueryType, fmt.Sprintf(errMsgInvalidQueryType, queryType)) -} - -func ErrorInsufficientDepositFunds(x, y sdk.Coins) sdk.Error { - return sdk.NewError(Codespace, errCodeInsufficientDepositFunds, fmt.Sprintf(errMsgInsufficientDepositFunds, x, y)) -} - -func ErrorDepositDoesNotExist() sdk.Error { - return sdk.NewError(Codespace, errCodeDepositDoesNotExist, errMsgDepositDoesNotExist) -} diff --git a/x/deposit/types/querier.go b/x/deposit/types/querier.go deleted file mode 100644 index fc307f7d..00000000 --- a/x/deposit/types/querier.go +++ /dev/null @@ -1,20 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - QueryDepositOfAddress = "deposit_of_address" - QueryAllDeposits = "all_deposits" -) - -type QueryDepositOfAddressPrams struct { - Address sdk.AccAddress -} - -func NewQueryDepositOfAddressParams(address sdk.AccAddress) QueryDepositOfAddressPrams { - return QueryDepositOfAddressPrams{ - Address: address, - } -} diff --git a/x/deposit/types/test_common.go b/x/deposit/types/test_common.go deleted file mode 100644 index b8e9ac05..00000000 --- a/x/deposit/types/test_common.go +++ /dev/null @@ -1,16 +0,0 @@ -// nolint -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/tendermint/tendermint/crypto/ed25519" -) - -var ( - TestPrivKey1 = ed25519.GenPrivKey() - TestPrivKey2 = ed25519.GenPrivKey() - TestPubKey1 = TestPrivKey1.PubKey() - TestPubKey2 = TestPrivKey2.PubKey() - TestAddress1 = sdk.AccAddress(TestPubKey1.Address()) - TestAddress2 = sdk.AccAddress(TestPubKey2.Address()) -) diff --git a/x/dvpn/alias.go b/x/dvpn/alias.go new file mode 100644 index 00000000..7875f6f9 --- /dev/null +++ b/x/dvpn/alias.go @@ -0,0 +1,42 @@ +// nolint +// autogenerated code using github.com/rigelrozanski/multitool +// aliases generated for the following subdirectories: +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/types +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/keeper +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/querier +package dvpn + +import ( + "github.com/sentinel-official/hub/x/dvpn/keeper" + "github.com/sentinel-official/hub/x/dvpn/querier" + "github.com/sentinel-official/hub/x/dvpn/types" +) + +const ( + Codespace = types.Codespace + ModuleName = types.ModuleName + RouterKey = types.RouterKey + QuerierRoute = types.QuerierRoute + StoreKey = types.StoreKey +) + +var ( + // functions aliases + RegisterCodec = types.RegisterCodec + ErrorMarshal = types.ErrorMarshal + ErrorUnmarshal = types.ErrorUnmarshal + ErrorUnknownMsgType = types.ErrorUnknownMsgType + ErrorUnknownQueryType = types.ErrorUnknownQueryType + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + NewKeeper = keeper.NewKeeper + NewQuerier = querier.NewQuerier + + // variable aliases + ModuleCdc = types.ModuleCdc +) + +type ( + GenesisState = types.GenesisState + Keeper = keeper.Keeper +) diff --git a/x/dvpn/client/cli/cli.go b/x/dvpn/client/cli/cli.go new file mode 100644 index 00000000..36406f82 --- /dev/null +++ b/x/dvpn/client/cli/cli.go @@ -0,0 +1,43 @@ +package cli + +import ( + "github.com/cosmos/cosmos-sdk/codec" + "github.com/spf13/cobra" + + deposit "github.com/sentinel-official/hub/x/dvpn/deposit/client/cli" + node "github.com/sentinel-official/hub/x/dvpn/node/client/cli" + plan "github.com/sentinel-official/hub/x/dvpn/plan/client/cli" + provider "github.com/sentinel-official/hub/x/dvpn/provider/client/cli" + session "github.com/sentinel-official/hub/x/dvpn/session/client/cli" + subscription "github.com/sentinel-official/hub/x/dvpn/subscription/client/cli" +) + +func GetQueryCmd(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "dvpn", + Short: "Querying commands for the dVPN module", + } + + cmd.AddCommand(deposit.GetQueryCommands(cdc)...) + cmd.AddCommand(provider.GetQueryCommands(cdc)...) + cmd.AddCommand(node.GetQueryCommands(cdc)...) + cmd.AddCommand(plan.GetQueryCommands(cdc)...) + cmd.AddCommand(subscription.GetQueryCommands(cdc)...) + + return cmd +} + +func GetTxCmd(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "dvpn", + Short: "dVPN transactions subcommands", + } + + cmd.AddCommand(provider.GetTxCommands(cdc)...) + cmd.AddCommand(node.GetTxCommands(cdc)...) + cmd.AddCommand(plan.GetTxCommands(cdc)...) + cmd.AddCommand(subscription.GetTxCommands(cdc)...) + cmd.AddCommand(session.GetTxCommands(cdc)...) + + return cmd +} diff --git a/x/dvpn/client/rest/rest.go b/x/dvpn/client/rest/rest.go new file mode 100644 index 00000000..346eb3bb --- /dev/null +++ b/x/dvpn/client/rest/rest.go @@ -0,0 +1,22 @@ +package rest + +import ( + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/gorilla/mux" + + deposit "github.com/sentinel-official/hub/x/dvpn/deposit/client/rest" + node "github.com/sentinel-official/hub/x/dvpn/node/client/rest" + plan "github.com/sentinel-official/hub/x/dvpn/plan/client/rest" + provider "github.com/sentinel-official/hub/x/dvpn/provider/client/rest" + session "github.com/sentinel-official/hub/x/dvpn/session/client/rest" + subscription "github.com/sentinel-official/hub/x/dvpn/subscription/client/rest" +) + +func RegisterRoutes(context context.CLIContext, router *mux.Router) { + deposit.RegisterRoutes(context, router) + provider.RegisterRoutes(context, router) + node.RegisterRoutes(context, router) + plan.RegisterRoutes(context, router) + subscription.RegisterRoutes(context, router) + session.RegisterRoutes(context, router) +} diff --git a/x/dvpn/deposit/alias.go b/x/dvpn/deposit/alias.go new file mode 100644 index 00000000..832e61fb --- /dev/null +++ b/x/dvpn/deposit/alias.go @@ -0,0 +1,51 @@ +// nolint +// autogenerated code using github.com/rigelrozanski/multitool +// aliases generated for the following subdirectories: +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/deposit/types +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/deposit/keeper +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/deposit/querier +package deposit + +import ( + "github.com/sentinel-official/hub/x/dvpn/deposit/keeper" + "github.com/sentinel-official/hub/x/dvpn/deposit/querier" + "github.com/sentinel-official/hub/x/dvpn/deposit/types" +) + +const ( + Codespace = types.Codespace + ModuleName = types.ModuleName + QuerierRoute = types.QuerierRoute + QueryDeposit = types.QueryDeposit + QueryDeposits = types.QueryDeposits +) + +var ( + // functions aliases + RegisterCodec = types.RegisterCodec + ErrorMarshal = types.ErrorMarshal + ErrorUnmarshal = types.ErrorUnmarshal + ErrorUnknownQueryType = types.ErrorUnknownQueryType + ErrorInsufficientDepositFunds = types.ErrorInsufficientDepositFunds + ErrorDepositDoesNotExist = types.ErrorDepositDoesNotExist + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + DepositKey = types.DepositKey + NewQueryDepositParams = types.NewQueryDepositParams + NewKeeper = keeper.NewKeeper + Querier = querier.Querier + + // variable aliases + ModuleCdc = types.ModuleCdc + RouterKey = types.RouterKey + StoreKey = types.StoreKey + DepositKeyPrefix = types.DepositKeyPrefix +) + +type ( + Deposit = types.Deposit + Deposits = types.Deposits + GenesisState = types.GenesisState + QueryDepositParams = types.QueryDepositParams + Keeper = keeper.Keeper +) diff --git a/x/dvpn/deposit/client/cli/cli.go b/x/dvpn/deposit/client/cli/cli.go new file mode 100644 index 00000000..7ed686ad --- /dev/null +++ b/x/dvpn/deposit/client/cli/cli.go @@ -0,0 +1,14 @@ +package cli + +import ( + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/spf13/cobra" +) + +func GetQueryCommands(cdc *codec.Codec) []*cobra.Command { + return client.GetCommands( + queryDepositCmd(cdc), + queryDepositsCmd(cdc), + ) +} diff --git a/x/dvpn/deposit/client/cli/query.go b/x/dvpn/deposit/client/cli/query.go new file mode 100644 index 00000000..5246d7ab --- /dev/null +++ b/x/dvpn/deposit/client/cli/query.go @@ -0,0 +1,57 @@ +package cli + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/spf13/cobra" + + "github.com/sentinel-official/hub/x/dvpn/deposit/client/common" +) + +func queryDepositCmd(cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "deposit", + Short: "Query a deposit", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.NewCLIContext().WithCodec(cdc) + + address, err := sdk.AccAddressFromBech32(args[0]) + if err != nil { + return err + } + + deposit, err := common.QueryDeposit(ctx, address) + if err != nil { + return err + } + + fmt.Println(deposit) + return nil + }, + } +} + +func queryDepositsCmd(cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "deposits", + Short: "Query deposits", + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.NewCLIContext().WithCodec(cdc) + + deposits, err := common.QueryDeposits(ctx) + if err != nil { + return err + } + + for _, deposit := range deposits { + fmt.Println(deposit) + } + + return nil + }, + } +} diff --git a/x/dvpn/deposit/client/common/query.go b/x/dvpn/deposit/client/common/query.go new file mode 100644 index 00000000..95a8716c --- /dev/null +++ b/x/dvpn/deposit/client/common/query.go @@ -0,0 +1,52 @@ +package common + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/client/context" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/sentinel-official/hub/x/dvpn/deposit/types" +) + +func QueryDeposit(ctx context.CLIContext, address sdk.AccAddress) (*types.Deposit, error) { + params := types.NewQueryDepositParams(address) + bytes, err := ctx.Codec.MarshalJSON(params) + if err != nil { + return nil, err + } + + path := fmt.Sprintf("custom/%s/%s/%s", types.StoreKey, types.QuerierRoute, types.QueryDeposit) + res, _, err := ctx.QueryWithData(path, bytes) + if err != nil { + return nil, err + } + if res == nil { + return nil, fmt.Errorf("no deposit found") + } + + var deposit types.Deposit + if err = ctx.Codec.UnmarshalJSON(res, &deposit); err != nil { + return nil, err + } + + return &deposit, nil +} + +func QueryDeposits(ctx context.CLIContext) (types.Deposits, error) { + path := fmt.Sprintf("custom/%s/%s/%s", types.StoreKey, types.QuerierRoute, types.QueryDeposits) + res, _, err := ctx.QueryWithData(path, nil) + if err != nil { + return nil, err + } + if res == nil { + return nil, fmt.Errorf("no deposits found") + } + + var deposits types.Deposits + if err = ctx.Codec.UnmarshalJSON(res, &deposits); err != nil { + return nil, err + } + + return deposits, nil +} diff --git a/x/deposit/client/rest/query_deposits.go b/x/dvpn/deposit/client/rest/query.go similarity index 55% rename from x/deposit/client/rest/query_deposits.go rename to x/dvpn/deposit/client/rest/query.go index 2060ae59..6a9bb147 100644 --- a/x/deposit/client/rest/query_deposits.go +++ b/x/dvpn/deposit/client/rest/query.go @@ -4,17 +4,24 @@ import ( "net/http" "github.com/cosmos/cosmos-sdk/client/context" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/gorilla/mux" - "github.com/sentinel-official/hub/x/deposit/client/common" + "github.com/sentinel-official/hub/x/dvpn/deposit/client/common" ) -func getDepositOfAddressHandlerFunc(ctx context.CLIContext) http.HandlerFunc { +func getDepositHandlerFunc(ctx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) - deposit, err := common.QueryDepositOfAddress(ctx, vars["address"]) + address, err := sdk.AccAddressFromBech32(vars["address"]) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } + + deposit, err := common.QueryDeposit(ctx, address) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return @@ -24,9 +31,9 @@ func getDepositOfAddressHandlerFunc(ctx context.CLIContext) http.HandlerFunc { } } -func getAllDeposits(ctx context.CLIContext) http.HandlerFunc { +func getDeposits(ctx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - deposits, err := common.QueryAllDeposits(ctx) + deposits, err := common.QueryDeposits(ctx) if err != nil { rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) return diff --git a/x/dvpn/deposit/client/rest/rest.go b/x/dvpn/deposit/client/rest/rest.go new file mode 100644 index 00000000..fbf1623e --- /dev/null +++ b/x/dvpn/deposit/client/rest/rest.go @@ -0,0 +1,17 @@ +package rest + +import ( + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/gorilla/mux" +) + +func registerQueryRoutes(ctx context.CLIContext, router *mux.Router) { + router.HandleFunc("/deposits", getDeposits(ctx)). + Methods("GET") + router.HandleFunc("/deposits/{address}", getDepositHandlerFunc(ctx)). + Methods("GET") +} + +func RegisterRoutes(ctx context.CLIContext, router *mux.Router) { + registerQueryRoutes(ctx, router) +} diff --git a/x/dvpn/deposit/expected/keeper.go b/x/dvpn/deposit/expected/keeper.go new file mode 100644 index 00000000..e6bde120 --- /dev/null +++ b/x/dvpn/deposit/expected/keeper.go @@ -0,0 +1,10 @@ +package expected + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type SupplyKeeper interface { + SendCoinsFromAccountToModule(ctx sdk.Context, address sdk.AccAddress, name string, coins sdk.Coins) sdk.Error + SendCoinsFromModuleToAccount(ctx sdk.Context, name string, address sdk.AccAddress, coins sdk.Coins) sdk.Error +} diff --git a/x/dvpn/deposit/genesis.go b/x/dvpn/deposit/genesis.go new file mode 100644 index 00000000..6be65eb6 --- /dev/null +++ b/x/dvpn/deposit/genesis.go @@ -0,0 +1,21 @@ +package deposit + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/sentinel-official/hub/x/dvpn/deposit/types" +) + +func InitGenesis(ctx sdk.Context, k Keeper, state types.GenesisState) { + for _, deposit := range state { + k.SetDeposit(ctx, deposit) + } +} + +func ExportGenesis(ctx sdk.Context, k Keeper) types.GenesisState { + return k.GetDeposits(ctx) +} + +func ValidateGenesis(state types.GenesisState) error { + return nil +} diff --git a/x/deposit/keeper/deposit.go b/x/dvpn/deposit/keeper/deposit.go similarity index 78% rename from x/deposit/keeper/deposit.go rename to x/dvpn/deposit/keeper/deposit.go index 00494bda..f47f27b9 100644 --- a/x/deposit/keeper/deposit.go +++ b/x/dvpn/deposit/keeper/deposit.go @@ -3,19 +3,19 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/sentinel-official/hub/x/deposit/types" + "github.com/sentinel-official/hub/x/dvpn/deposit/types" ) func (k Keeper) SetDeposit(ctx sdk.Context, deposit types.Deposit) { key := types.DepositKey(deposit.Address) value := k.cdc.MustMarshalBinaryLengthPrefixed(deposit) - store := ctx.KVStore(k.key) + store := k.Store(ctx) store.Set(key, value) } func (k Keeper) GetDeposit(ctx sdk.Context, address sdk.AccAddress) (deposit types.Deposit, found bool) { - store := ctx.KVStore(k.key) + store := k.Store(ctx) key := types.DepositKey(address) value := store.Get(key) @@ -27,22 +27,22 @@ func (k Keeper) GetDeposit(ctx sdk.Context, address sdk.AccAddress) (deposit typ return deposit, true } -func (k Keeper) GetAllDeposits(ctx sdk.Context) (deposits []types.Deposit) { - store := ctx.KVStore(k.key) +func (k Keeper) GetDeposits(ctx sdk.Context) (items types.Deposits) { + store := k.Store(ctx) iter := sdk.KVStorePrefixIterator(store, types.DepositKeyPrefix) defer iter.Close() for ; iter.Valid(); iter.Next() { - var deposit types.Deposit - k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &deposit) - deposits = append(deposits, deposit) + var item types.Deposit + k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &item) + items = append(items, item) } - return deposits + return items } -func (k Keeper) Add(ctx sdk.Context, address sdk.AccAddress, coins sdk.Coins) (err sdk.Error) { +func (k Keeper) Add(ctx sdk.Context, address sdk.AccAddress, coins sdk.Coins) sdk.Error { if err := k.supply.SendCoinsFromAccountToModule(ctx, address, types.ModuleName, coins); err != nil { return err } @@ -57,14 +57,14 @@ func (k Keeper) Add(ctx sdk.Context, address sdk.AccAddress, coins sdk.Coins) (e deposit.Coins = deposit.Coins.Add(coins) if deposit.Coins.IsAnyNegative() { - return types.ErrorInsufficientDepositFunds(deposit.Coins, coins) + return types.ErrorInsufficientDepositFunds() } k.SetDeposit(ctx, deposit) return nil } -func (k Keeper) Subtract(ctx sdk.Context, address sdk.AccAddress, coins sdk.Coins) (err sdk.Error) { +func (k Keeper) Subtract(ctx sdk.Context, address sdk.AccAddress, coins sdk.Coins) sdk.Error { deposit, found := k.GetDeposit(ctx, address) if !found { return types.ErrorDepositDoesNotExist() @@ -72,7 +72,7 @@ func (k Keeper) Subtract(ctx sdk.Context, address sdk.AccAddress, coins sdk.Coin deposit.Coins, _ = deposit.Coins.SafeSub(coins) if deposit.Coins.IsAnyNegative() { - return types.ErrorInsufficientDepositFunds(deposit.Coins, coins) + return types.ErrorInsufficientDepositFunds() } if err := k.supply.SendCoinsFromModuleToAccount(ctx, types.ModuleName, address, coins); err != nil { @@ -91,7 +91,7 @@ func (k Keeper) SendCoinsFromDepositToAccount(ctx sdk.Context, from, to sdk.AccA deposit.Coins, _ = deposit.Coins.SafeSub(coins) if deposit.Coins.IsAnyNegative() { - return types.ErrorInsufficientDepositFunds(deposit.Coins, coins) + return types.ErrorInsufficientDepositFunds() } if err := k.supply.SendCoinsFromModuleToAccount(ctx, types.ModuleName, to, coins); err != nil { @@ -117,15 +117,15 @@ func (k Keeper) SendCoinsFromAccountToDeposit(ctx sdk.Context, from, to sdk.AccA deposit.Coins = deposit.Coins.Add(coins) if deposit.Coins.IsAnyNegative() { - return types.ErrorInsufficientDepositFunds(deposit.Coins, coins) + return types.ErrorInsufficientDepositFunds() } k.SetDeposit(ctx, deposit) return nil } -func (k Keeper) IterateDeposits(ctx sdk.Context, fn func(index int64, deposit types.Deposit) (stop bool)) { - store := ctx.KVStore(k.key) +func (k Keeper) IterateDeposits(ctx sdk.Context, fn func(index int64, item types.Deposit) (stop bool)) { + store := k.Store(ctx) iterator := sdk.KVStorePrefixIterator(store, types.DepositKeyPrefix) defer iterator.Close() diff --git a/x/dvpn/deposit/keeper/keeper.go b/x/dvpn/deposit/keeper/keeper.go new file mode 100644 index 00000000..f9a547f5 --- /dev/null +++ b/x/dvpn/deposit/keeper/keeper.go @@ -0,0 +1,34 @@ +package keeper + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store/prefix" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/sentinel-official/hub/x/dvpn/deposit/expected" + "github.com/sentinel-official/hub/x/dvpn/deposit/types" +) + +type Keeper struct { + key sdk.StoreKey + cdc *codec.Codec + supply expected.SupplyKeeper +} + +func NewKeeper(cdc *codec.Codec, key sdk.StoreKey) Keeper { + return Keeper{ + key: key, + cdc: cdc, + } +} + +func (k *Keeper) WithSupplyKeeper(keeper expected.SupplyKeeper) { + k.supply = keeper +} + +func (k Keeper) Store(ctx sdk.Context) sdk.KVStore { + child := fmt.Sprintf("%s/", types.ModuleName) + return prefix.NewStore(ctx.KVStore(k.key), []byte(child)) +} diff --git a/x/deposit/querier/deposit.go b/x/dvpn/deposit/querier/deposit.go similarity index 55% rename from x/deposit/querier/deposit.go rename to x/dvpn/deposit/querier/deposit.go index af2f86cd..5e65d2ec 100644 --- a/x/deposit/querier/deposit.go +++ b/x/dvpn/deposit/querier/deposit.go @@ -4,12 +4,12 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" - "github.com/sentinel-official/hub/x/deposit/keeper" - "github.com/sentinel-official/hub/x/deposit/types" + "github.com/sentinel-official/hub/x/dvpn/deposit/keeper" + "github.com/sentinel-official/hub/x/dvpn/deposit/types" ) -func queryDepositOfAddress(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { - var params types.QueryDepositOfAddressPrams +func queryDeposit(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + var params types.QueryDepositParams if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { return nil, types.ErrorUnmarshal() } @@ -27,10 +27,8 @@ func queryDepositOfAddress(ctx sdk.Context, req abci.RequestQuery, k keeper.Keep return res, nil } -func queryAllDeposits(ctx sdk.Context, k keeper.Keeper) ([]byte, sdk.Error) { - deposits := k.GetAllDeposits(ctx) - - res, err := types.ModuleCdc.MarshalJSON(deposits) +func queryDeposits(ctx sdk.Context, _ abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + res, err := types.ModuleCdc.MarshalJSON(k.GetDeposits(ctx)) if err != nil { return nil, types.ErrorMarshal() } diff --git a/x/dvpn/deposit/querier/querier.go b/x/dvpn/deposit/querier/querier.go new file mode 100644 index 00000000..0c04ec50 --- /dev/null +++ b/x/dvpn/deposit/querier/querier.go @@ -0,0 +1,20 @@ +package querier + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/sentinel-official/hub/x/dvpn/deposit/keeper" + "github.com/sentinel-official/hub/x/dvpn/deposit/types" +) + +func Querier(ctx sdk.Context, path []string, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + switch path[0] { + case types.QueryDeposit: + return queryDeposit(ctx, req, k) + case types.QueryDeposits: + return queryDeposits(ctx, req, k) + default: + return nil, types.ErrorUnknownQueryType(path[0]) + } +} diff --git a/x/deposit/types/codec.go b/x/dvpn/deposit/types/codec.go similarity index 74% rename from x/deposit/types/codec.go rename to x/dvpn/deposit/types/codec.go index 947677dd..ddb40457 100644 --- a/x/deposit/types/codec.go +++ b/x/dvpn/deposit/types/codec.go @@ -11,5 +11,8 @@ var ( func init() { ModuleCdc = codec.New() codec.RegisterCrypto(ModuleCdc) + RegisterCodec(ModuleCdc) ModuleCdc.Seal() } + +func RegisterCodec(_ *codec.Codec) {} diff --git a/x/dvpn/deposit/types/deposit.go b/x/dvpn/deposit/types/deposit.go new file mode 100644 index 00000000..c5999cf2 --- /dev/null +++ b/x/dvpn/deposit/types/deposit.go @@ -0,0 +1,21 @@ +package types + +import ( + "fmt" + "strings" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type Deposit struct { + Address sdk.AccAddress `json:"address"` + Coins sdk.Coins `json:"coins"` +} + +func (d Deposit) String() string { + return fmt.Sprintf(strings.TrimSpace(` +Address: %s +Coins: %s`), d.Address, d.Coins) +} + +type Deposits []Deposit diff --git a/x/dvpn/deposit/types/errors.go b/x/dvpn/deposit/types/errors.go new file mode 100644 index 00000000..f8eb3d3f --- /dev/null +++ b/x/dvpn/deposit/types/errors.go @@ -0,0 +1,45 @@ +package types + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +const ( + Codespace = sdk.CodespaceType(ModuleName) +) + +const ( + errorCodeUnknownQueryType = iota + 101 + errorCodeInsufficientDepositFunds + errorCodeDepositDoesNotExist +) + +const ( + errorMsgUnknownQueryType = "unknown query type: %s" + errorMsgInsufficientDepositFunds = "insufficient deposit funds" + errorMsgDepositDoesNotExist = "deposit does not exist" +) + +func ErrorMarshal() sdk.Error { + return sdk.NewError(Codespace, hub.ErrorCodeMarshal, hub.ErrorMsgMarshal) +} + +func ErrorUnmarshal() sdk.Error { + return sdk.NewError(Codespace, hub.ErrorCodeUnmarshal, hub.ErrorMsgUnmarshal) +} + +func ErrorUnknownQueryType(v string) sdk.Error { + return sdk.NewError(Codespace, errorCodeUnknownQueryType, fmt.Sprintf(errorMsgUnknownQueryType, v)) +} + +func ErrorInsufficientDepositFunds() sdk.Error { + return sdk.NewError(Codespace, errorCodeInsufficientDepositFunds, errorMsgInsufficientDepositFunds) +} + +func ErrorDepositDoesNotExist() sdk.Error { + return sdk.NewError(Codespace, errorCodeDepositDoesNotExist, errorMsgDepositDoesNotExist) +} diff --git a/x/dvpn/deposit/types/events.go b/x/dvpn/deposit/types/events.go new file mode 100644 index 00000000..ab1254f4 --- /dev/null +++ b/x/dvpn/deposit/types/events.go @@ -0,0 +1 @@ +package types diff --git a/x/deposit/types/genesis.go b/x/dvpn/deposit/types/genesis.go similarity index 55% rename from x/deposit/types/genesis.go rename to x/dvpn/deposit/types/genesis.go index 2b6e72df..e5444eed 100644 --- a/x/deposit/types/genesis.go +++ b/x/dvpn/deposit/types/genesis.go @@ -1,8 +1,8 @@ package types -type GenesisState []Deposit +type GenesisState = Deposits -func NewGenesisState(deposits []Deposit) GenesisState { +func NewGenesisState(deposits Deposits) GenesisState { return deposits } diff --git a/x/deposit/types/keys.go b/x/dvpn/deposit/types/keys.go similarity index 73% rename from x/deposit/types/keys.go rename to x/dvpn/deposit/types/keys.go index 3a60e8ab..c8d3cd0c 100644 --- a/x/deposit/types/keys.go +++ b/x/dvpn/deposit/types/keys.go @@ -6,13 +6,16 @@ import ( const ( ModuleName = "deposit" - StoreKey = ModuleName - RouterKey = ModuleName QuerierRoute = ModuleName ) var ( - DepositKeyPrefix = []byte{0x01} + RouterKey = ModuleName + StoreKey = ModuleName +) + +var ( + DepositKeyPrefix = []byte{0x00} ) func DepositKey(address sdk.AccAddress) []byte { diff --git a/x/dvpn/deposit/types/querier.go b/x/dvpn/deposit/types/querier.go new file mode 100644 index 00000000..3fe3a71b --- /dev/null +++ b/x/dvpn/deposit/types/querier.go @@ -0,0 +1,20 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +const ( + QueryDeposit = "deposit" + QueryDeposits = "deposits" +) + +type QueryDepositParams struct { + Address sdk.AccAddress +} + +func NewQueryDepositParams(address sdk.AccAddress) QueryDepositParams { + return QueryDepositParams{ + Address: address, + } +} diff --git a/x/dvpn/genesis.go b/x/dvpn/genesis.go new file mode 100644 index 00000000..0e9e48e1 --- /dev/null +++ b/x/dvpn/genesis.go @@ -0,0 +1,57 @@ +package dvpn + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/sentinel-official/hub/x/dvpn/deposit" + "github.com/sentinel-official/hub/x/dvpn/keeper" + "github.com/sentinel-official/hub/x/dvpn/node" + "github.com/sentinel-official/hub/x/dvpn/plan" + "github.com/sentinel-official/hub/x/dvpn/provider" + "github.com/sentinel-official/hub/x/dvpn/session" + "github.com/sentinel-official/hub/x/dvpn/subscription" + "github.com/sentinel-official/hub/x/dvpn/types" +) + +func InitGenesis(ctx sdk.Context, k keeper.Keeper, state types.GenesisState) { + deposit.InitGenesis(ctx, k.Deposit, state.Deposits) + provider.InitGenesis(ctx, k.Provider, state.Providers) + node.InitGenesis(ctx, k.Node, state.Nodes) + plan.InitGenesis(ctx, k.Plan, state.Plans) + subscription.InitGenesis(ctx, k.Subscription, state.Subscriptions) + session.InitGenesis(ctx, k.Session, state.Sessions) +} + +func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { + return types.GenesisState{ + Deposits: deposit.ExportGenesis(ctx, k.Deposit), + Providers: provider.ExportGenesis(ctx, k.Provider), + Nodes: node.ExportGenesis(ctx, k.Node), + Plans: plan.ExportGenesis(ctx, k.Plan), + Subscriptions: subscription.ExportGenesis(ctx, k.Subscription), + Sessions: session.ExportGenesis(ctx, k.Session), + } +} + +func ValidateGenesis(state types.GenesisState) error { + if err := deposit.ValidateGenesis(state.Deposits); err != nil { + return err + } + if err := provider.ValidateGenesis(state.Providers); err != nil { + return err + } + if err := node.ValidateGenesis(state.Nodes); err != nil { + return err + } + if err := plan.ValidateGenesis(state.Plans); err != nil { + return err + } + if err := subscription.ValidateGenesis(state.Subscriptions); err != nil { + return err + } + if err := session.ValidateGenesis(state.Sessions); err != nil { + return err + } + + return nil +} diff --git a/x/dvpn/handler.go b/x/dvpn/handler.go new file mode 100644 index 00000000..9c1d8e42 --- /dev/null +++ b/x/dvpn/handler.go @@ -0,0 +1,57 @@ +package dvpn + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/sentinel-official/hub/x/dvpn/keeper" + "github.com/sentinel-official/hub/x/dvpn/node" + "github.com/sentinel-official/hub/x/dvpn/plan" + "github.com/sentinel-official/hub/x/dvpn/provider" + "github.com/sentinel-official/hub/x/dvpn/session" + "github.com/sentinel-official/hub/x/dvpn/subscription" + "github.com/sentinel-official/hub/x/dvpn/types" +) + +func BeginBlock(ctx sdk.Context, k keeper.Keeper) { + ctx, write := ctx.CacheContext() + defer write() + + node.BeginBlock(ctx, k.Node) +} + +func NewHandler(k keeper.Keeper) sdk.Handler { + return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { + switch msg := msg.(type) { + case provider.MsgRegisterProvider: + return provider.HandleRegisterProvider(ctx, k.Provider, msg) + case provider.MsgUpdateProvider: + return provider.HandleUpdateProvider(ctx, k.Provider, msg) + case node.MsgRegisterNode: + return node.HandleRegisterNode(ctx, k.Node, msg) + case node.MsgUpdateNode: + return node.HandleUpdateNode(ctx, k.Node, msg) + case node.MsgSetNodeStatus: + return node.HandleSetNodeStatus(ctx, k.Node, msg) + case plan.MsgAddPlan: + return plan.HandleAddPlan(ctx, k.Plan, msg) + case plan.MsgSetPlanStatus: + return plan.HandleSetPlanStatus(ctx, k.Plan, msg) + case plan.MsgAddNodeForPlan: + return plan.HandleAddNodeForPlan(ctx, k.Plan, msg) + case plan.MsgRemoveNodeForPlan: + return plan.HandleRemoveNodeForPlan(ctx, k.Plan, msg) + case subscription.MsgStartSubscription: + return subscription.HandleStartSubscription(ctx, k.Subscription, msg) + case subscription.MsgAddMemberForSubscription: + return subscription.HandleAddMemberForSubscription(ctx, k.Subscription, msg) + case subscription.MsgRemoveMemberForSubscription: + return subscription.HandleRemoveMemberForSubscription(ctx, k.Subscription, msg) + case subscription.MsgEndSubscription: + return subscription.HandleEndSubscription(ctx, k.Subscription, msg) + case session.MsgUpdateSession: + return session.HandleUpdateSession(ctx, k.Session, msg) + default: + return types.ErrorUnknownMsgType(msg.Type()).Result() + } + } +} diff --git a/x/dvpn/keeper/keeper.go b/x/dvpn/keeper/keeper.go new file mode 100644 index 00000000..ca4b4223 --- /dev/null +++ b/x/dvpn/keeper/keeper.go @@ -0,0 +1,65 @@ +package keeper + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/bank" + "github.com/cosmos/cosmos-sdk/x/params" + "github.com/cosmos/cosmos-sdk/x/supply" + + "github.com/sentinel-official/hub/x/dvpn/deposit" + "github.com/sentinel-official/hub/x/dvpn/node" + "github.com/sentinel-official/hub/x/dvpn/plan" + "github.com/sentinel-official/hub/x/dvpn/provider" + "github.com/sentinel-official/hub/x/dvpn/session" + "github.com/sentinel-official/hub/x/dvpn/subscription" + "github.com/sentinel-official/hub/x/dvpn/types" +) + +type Keeper struct { + Deposit deposit.Keeper + Provider provider.Keeper + Node node.Keeper + Plan plan.Keeper + Subscription subscription.Keeper + Session session.Keeper +} + +func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, paramsKeeper params.Keeper, bankKeeper bank.Keeper, supplyKeeper supply.Keeper) Keeper { + nodeParams := paramsKeeper.Subspace(fmt.Sprintf("%s/%s", types.ModuleName, node.ParamsSubspace)) + sessionParams := paramsKeeper.Subspace(fmt.Sprintf("%s/%s", types.ModuleName, session.ParamsSubspace)) + + depositKeeper := deposit.NewKeeper(cdc, key) + providerKeeper := provider.NewKeeper(cdc, key) + nodeKeeper := node.NewKeeper(cdc, key, nodeParams) + planKeeper := plan.NewKeeper(cdc, key) + subscriptionKeeper := subscription.NewKeeper(cdc, key) + sessionKeeper := session.NewKeeper(cdc, key, sessionParams) + + depositKeeper.WithSupplyKeeper(supplyKeeper) + + nodeKeeper.WithProviderKeeper(&providerKeeper) + nodeKeeper.WithPlanKeeper(&planKeeper) + + planKeeper.WithProviderKeeper(&providerKeeper) + planKeeper.WithNodeKeeper(&nodeKeeper) + + subscriptionKeeper.WithDepositKeeper(&depositKeeper) + subscriptionKeeper.WithBankKeeper(bankKeeper) + subscriptionKeeper.WithNodeKeeper(&nodeKeeper) + subscriptionKeeper.WithPlanKeeper(&planKeeper) + + sessionKeeper.WithPlanKeeper(&planKeeper) + sessionKeeper.WithSubscriptionKeeper(&subscriptionKeeper) + + return Keeper{ + Deposit: depositKeeper, + Provider: providerKeeper, + Node: nodeKeeper, + Plan: planKeeper, + Subscription: subscriptionKeeper, + Session: sessionKeeper, + } +} diff --git a/x/vpn/module.go b/x/dvpn/module.go similarity index 55% rename from x/vpn/module.go rename to x/dvpn/module.go index bb2eac5f..641bb431 100644 --- a/x/vpn/module.go +++ b/x/dvpn/module.go @@ -1,4 +1,4 @@ -package vpn +package dvpn import ( "encoding/json" @@ -11,8 +11,11 @@ import ( "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" - "github.com/sentinel-official/hub/x/vpn/client/cli" - "github.com/sentinel-official/hub/x/vpn/client/rest" + "github.com/sentinel-official/hub/x/dvpn/client/cli" + "github.com/sentinel-official/hub/x/dvpn/client/rest" + "github.com/sentinel-official/hub/x/dvpn/keeper" + "github.com/sentinel-official/hub/x/dvpn/querier" + "github.com/sentinel-official/hub/x/dvpn/types" ) var ( @@ -23,28 +26,26 @@ var ( type AppModuleBasic struct{} func (a AppModuleBasic) Name() string { - return ModuleName + return types.ModuleName } func (a AppModuleBasic) RegisterCodec(cdc *codec.Codec) { - RegisterCodec(cdc) + types.RegisterCodec(cdc) } func (a AppModuleBasic) DefaultGenesis() json.RawMessage { - return ModuleCdc.MustMarshalJSON(DefaultGenesisState()) + return types.ModuleCdc.MustMarshalJSON(types.DefaultGenesisState()) } func (a AppModuleBasic) ValidateGenesis(data json.RawMessage) error { - var state GenesisState - if err := ModuleCdc.UnmarshalJSON(data, &state); err != nil { - return err - } + var state types.GenesisState + types.ModuleCdc.MustUnmarshalJSON(data, &state) return ValidateGenesis(state) } -func (a AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, r *mux.Router) { - rest.RegisterRoutes(ctx, r) +func (a AppModuleBasic) RegisterRESTRoutes(context context.CLIContext, router *mux.Router) { + rest.RegisterRoutes(context, router) } func (a AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { @@ -57,49 +58,49 @@ func (a AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { type AppModule struct { AppModuleBasic - keeper Keeper + k keeper.Keeper } -func NewAppModule(k Keeper) AppModule { +func NewAppModule(k keeper.Keeper) AppModule { return AppModule{ - keeper: k, + k: k, } } func (a AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { - var state GenesisState - ModuleCdc.MustUnmarshalJSON(data, &state) - InitGenesis(ctx, a.keeper, state) + var state types.GenesisState + types.ModuleCdc.MustUnmarshalJSON(data, &state) + InitGenesis(ctx, a.k, state) return nil } func (a AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { - state := ExportGenesis(ctx, a.keeper) - return ModuleCdc.MustMarshalJSON(state) + return types.ModuleCdc.MustMarshalJSON(ExportGenesis(ctx, a.k)) } func (a AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} func (a AppModule) Route() string { - return RouterKey + return types.RouterKey } func (a AppModule) NewHandler() sdk.Handler { - return NewHandler(a.keeper) + return NewHandler(a.k) } func (a AppModule) QuerierRoute() string { - return QuerierRoute + return types.QuerierRoute } func (a AppModule) NewQuerierHandler() sdk.Querier { - return NewQuerier(a.keeper) + return querier.NewQuerier(a.k) } -func (a AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} +func (a AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { + BeginBlock(ctx, a.k) +} -func (a AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - EndBlock(ctx, a.keeper) +func (a AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return nil } diff --git a/x/dvpn/node/alias.go b/x/dvpn/node/alias.go new file mode 100644 index 00000000..4be4c754 --- /dev/null +++ b/x/dvpn/node/alias.go @@ -0,0 +1,86 @@ +// nolint +// autogenerated code using github.com/rigelrozanski/multitool +// aliases generated for the following subdirectories: +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/node/types +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/node/keeper +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/node/querier +package node + +import ( + "github.com/sentinel-official/hub/x/dvpn/node/keeper" + "github.com/sentinel-official/hub/x/dvpn/node/querier" + "github.com/sentinel-official/hub/x/dvpn/node/types" +) + +const ( + Codespace = types.Codespace + EventTypeSetNode = types.EventTypeSetNode + EventTypeUpdateNode = types.EventTypeUpdateNode + EventTypeSetNodeStatus = types.EventTypeSetNodeStatus + AttributeKeyProvider = types.AttributeKeyProvider + AttributeKeyAddress = types.AttributeKeyAddress + AttributeKeyStatus = types.AttributeKeyStatus + ModuleName = types.ModuleName + ParamsSubspace = types.ParamsSubspace + QuerierRoute = types.QuerierRoute + CategoryUnknown = types.CategoryUnknown + DefaultInactiveDuration = types.DefaultInactiveDuration + QueryNode = types.QueryNode + QueryNodes = types.QueryNodes + QueryNodesForProvider = types.QueryNodesForProvider +) + +var ( + // functions aliases + RegisterCodec = types.RegisterCodec + ErrorMarshal = types.ErrorMarshal + ErrorUnmarshal = types.ErrorUnmarshal + ErrorUnknownMsgType = types.ErrorUnknownMsgType + ErrorUnknownQueryType = types.ErrorUnknownQueryType + ErrorInvalidField = types.ErrorInvalidField + ErrorProviderDoesNotExist = types.ErrorProviderDoesNotExist + ErrorDuplicateNode = types.ErrorDuplicateNode + ErrorNodeDoesNotExist = types.ErrorNodeDoesNotExist + ErrorCanNotUpdate = types.ErrorCanNotUpdate + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + NodeKey = types.NodeKey + NodeForProviderByProviderKey = types.NodeForProviderByProviderKey + NodeForProviderKey = types.NodeForProviderKey + ActiveNodeAtByTimeKey = types.ActiveNodeAtByTimeKey + ActiveNodeAtKey = types.ActiveNodeAtKey + NewMsgRegisterNode = types.NewMsgRegisterNode + NewMsgUpdateNode = types.NewMsgUpdateNode + NewMsgSetNodeStatus = types.NewMsgSetNodeStatus + NodeCategoryFromString = types.NodeCategoryFromString + NewParams = types.NewParams + DefaultParams = types.DefaultParams + ParamsKeyTable = types.ParamsKeyTable + NewQueryNodeParams = types.NewQueryNodeParams + NewQueryNodesForProviderParams = types.NewQueryNodesForProviderParams + NewKeeper = keeper.NewKeeper + Querier = querier.Querier + + // variable aliases + ModuleCdc = types.ModuleCdc + RouterKey = types.RouterKey + StoreKey = types.StoreKey + NodeKeyPrefix = types.NodeKeyPrefix + NodeForProviderKeyPrefix = types.NodeForProviderKeyPrefix + ActiveNodeAtKeyPrefix = types.ActiveNodeAtKeyPrefix + KeyInactiveDuration = types.KeyInactiveDuration +) + +type ( + GenesisState = types.GenesisState + MsgRegisterNode = types.MsgRegisterNode + MsgUpdateNode = types.MsgUpdateNode + MsgSetNodeStatus = types.MsgSetNodeStatus + NodeCategory = types.NodeCategory + Node = types.Node + Nodes = types.Nodes + Params = types.Params + QueryNodeParams = types.QueryNodeParams + QueryNodesForProviderParams = types.QueryNodesForProviderParams + Keeper = keeper.Keeper +) diff --git a/x/dvpn/node/client/cli/cli.go b/x/dvpn/node/client/cli/cli.go new file mode 100644 index 00000000..5f1a237d --- /dev/null +++ b/x/dvpn/node/client/cli/cli.go @@ -0,0 +1,29 @@ +package cli + +import ( + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/spf13/cobra" +) + +func GetQueryCommands(cdc *codec.Codec) []*cobra.Command { + return client.GetCommands( + queryNodeCmd(cdc), + queryNodesCmd(cdc), + ) +} + +func GetTxCommands(cdc *codec.Codec) []*cobra.Command { + cmd := &cobra.Command{ + Use: "node", + Short: "Node module sub-commands", + } + + cmd.AddCommand(client.PostCommands( + txRegisterNodeCmd(cdc), + txUpdateNodeCmd(cdc), + txSetNodeStatusCmd(cdc), + )...) + + return []*cobra.Command{cmd} +} diff --git a/x/dvpn/node/client/cli/flags.go b/x/dvpn/node/client/cli/flags.go new file mode 100644 index 00000000..35bb036f --- /dev/null +++ b/x/dvpn/node/client/cli/flags.go @@ -0,0 +1,12 @@ +package cli + +const ( + flagProvider = "provider" + flagPlan = "plan" + flagPrice = "price" + flagRemoteURL = "remote-url" + flagVersion = "version" + flagUploadSpeed = "upload-speed" + flagDownloadSpeed = "download-speed" + flagCategory = "category" +) diff --git a/x/dvpn/node/client/cli/query.go b/x/dvpn/node/client/cli/query.go new file mode 100644 index 00000000..410fa6a1 --- /dev/null +++ b/x/dvpn/node/client/cli/query.go @@ -0,0 +1,92 @@ +package cli + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/spf13/cobra" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/node/client/common" + "github.com/sentinel-official/hub/x/dvpn/node/types" +) + +func queryNodeCmd(cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "node", + Short: "Query a node", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.NewCLIContext().WithCodec(cdc) + + address, err := hub.NodeAddressFromBech32(args[0]) + if err != nil { + return err + } + + node, err := common.QueryNode(ctx, address) + if err != nil { + return err + } + + fmt.Println(node) + return nil + }, + } +} + +func queryNodesCmd(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "nodes", + Short: "Query nodes", + RunE: func(cmd *cobra.Command, args []string) (err error) { + ctx := context.NewCLIContext().WithCodec(cdc) + + provider, err := cmd.Flags().GetString(flagProvider) + if err != nil { + return err + } + + plan, err := cmd.Flags().GetUint64(flagPlan) + if err != nil { + return err + } + + var nodes types.Nodes + + if len(provider) > 0 { + address, err := hub.ProvAddressFromBech32(provider) + if err != nil { + return err + } + + nodes, err = common.QueryNodesForProvider(ctx, address) + if err != nil { + return err + } + } else if plan > 0 { + nodes, err = common.QueryNodesForPlan(ctx, plan) + if err != nil { + return err + } + } else { + nodes, err = common.QueryNodes(ctx) + if err != nil { + return err + } + } + + for _, node := range nodes { + fmt.Println(node) + } + + return nil + }, + } + + cmd.Flags().String(flagProvider, "", "Provider address") + cmd.Flags().Uint64(flagPlan, 0, "Subscription plan ID") + + return cmd +} diff --git a/x/dvpn/node/client/cli/tx.go b/x/dvpn/node/client/cli/tx.go new file mode 100644 index 00000000..e016aedc --- /dev/null +++ b/x/dvpn/node/client/cli/tx.go @@ -0,0 +1,182 @@ +package cli + +import ( + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/client/utils" + "github.com/spf13/cobra" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/node/types" +) + +func txRegisterNodeCmd(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "register", + Short: "Register a node", + RunE: func(cmd *cobra.Command, args []string) error { + txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + ctx := context.NewCLIContext().WithCodec(cdc) + + s, err := cmd.Flags().GetString(flagProvider) + if err != nil { + return err + } + + provider, err := hub.ProvAddressFromBech32(s) + if err != nil { + return err + } + + s, err = cmd.Flags().GetString(flagPrice) + if err != nil { + return err + } + + price, err := sdk.ParseCoins(s) + if err != nil { + return err + } + + upload, err := cmd.Flags().GetInt64(flagUploadSpeed) + if err != nil { + return err + } + + download, err := cmd.Flags().GetInt64(flagDownloadSpeed) + if err != nil { + return err + } + + remoteURL, err := cmd.Flags().GetString(flagRemoteURL) + if err != nil { + return err + } + + version, err := cmd.Flags().GetString(flagVersion) + if err != nil { + return err + } + + s, err = cmd.Flags().GetString(flagCategory) + if err != nil { + return err + } + + msg := types.NewMsgRegisterNode(ctx.FromAddress, provider, price, + hub.NewBandwidthFromInt64(upload, download), remoteURL, version, types.NodeCategoryFromString(s)) + return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) + }, + } + + cmd.Flags().String(flagProvider, "", "Node provider address") + cmd.Flags().String(flagPrice, "", "Node price per Gigabyte") + cmd.Flags().String(flagRemoteURL, "", "Node remove URL") + cmd.Flags().String(flagVersion, "", "Node version") + cmd.Flags().Int64(flagUploadSpeed, 0, "Node upload speed") + cmd.Flags().Int64(flagDownloadSpeed, 0, "Node download speed") + cmd.Flags().String(flagCategory, "", "Node category") + + _ = cmd.MarkFlagRequired(flagRemoteURL) + _ = cmd.MarkFlagRequired(flagVersion) + _ = cmd.MarkFlagRequired(flagUploadSpeed) + _ = cmd.MarkFlagRequired(flagDownloadSpeed) + _ = cmd.MarkFlagRequired(flagCategory) + + return cmd +} + +func txUpdateNodeCmd(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "update", + Short: "Update a node", + RunE: func(cmd *cobra.Command, args []string) error { + txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + ctx := context.NewCLIContext().WithCodec(cdc) + + s, err := cmd.Flags().GetString(flagProvider) + if err != nil { + return err + } + + var provider hub.ProvAddress + if len(s) > 0 { + provider, err = hub.ProvAddressFromBech32(s) + if err != nil { + return err + } + } + + s, err = cmd.Flags().GetString(flagPrice) + if err != nil { + return err + } + + var price sdk.Coins + if len(s) > 0 { + price, err = sdk.ParseCoins(s) + if err != nil { + return err + } + } + + upload, err := cmd.Flags().GetInt64(flagUploadSpeed) + if err != nil { + return err + } + + download, err := cmd.Flags().GetInt64(flagDownloadSpeed) + if err != nil { + return err + } + + s, err = cmd.Flags().GetString(flagCategory) + if err != nil { + return err + } + + remoteURL, err := cmd.Flags().GetString(flagRemoteURL) + if err != nil { + return err + } + + version, err := cmd.Flags().GetString(flagVersion) + if err != nil { + return err + } + + msg := types.NewMsgUpdateNode(ctx.FromAddress.Bytes(), provider, price, + hub.NewBandwidthFromInt64(upload, download), remoteURL, version, types.NodeCategoryFromString(s)) + return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) + }, + } + + cmd.Flags().String(flagProvider, "", "Node provider address") + cmd.Flags().String(flagPrice, "", "Node price per Gigabyte") + cmd.Flags().String(flagRemoteURL, "", "Node remove URL") + cmd.Flags().String(flagVersion, "", "Node version") + cmd.Flags().Int64(flagUploadSpeed, 0, "Node upload speed") + cmd.Flags().Int64(flagDownloadSpeed, 0, "Node download speed") + cmd.Flags().String(flagCategory, "", "Node category") + + return cmd +} + +func txSetNodeStatusCmd(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "status-set", + Short: "Set a node status", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + ctx := context.NewCLIContext().WithCodec(cdc) + + msg := types.NewMsgSetNodeStatus(ctx.FromAddress.Bytes(), hub.StatusFromString(args[0])) + return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) + }, + } + + return cmd +} diff --git a/x/dvpn/node/client/common/query.go b/x/dvpn/node/client/common/query.go new file mode 100644 index 00000000..8edd0d16 --- /dev/null +++ b/x/dvpn/node/client/common/query.go @@ -0,0 +1,101 @@ +package common + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/client/context" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/node/types" + plan "github.com/sentinel-official/hub/x/dvpn/plan/types" +) + +func QueryNode(ctx context.CLIContext, address hub.NodeAddress) (*types.Node, error) { + params := types.NewQueryNodeParams(address) + bytes, err := ctx.Codec.MarshalJSON(params) + if err != nil { + return nil, err + } + + path := fmt.Sprintf("custom/%s/%s/%s", types.StoreKey, types.QuerierRoute, types.QueryNode) + res, _, err := ctx.QueryWithData(path, bytes) + if err != nil { + return nil, err + } + if res == nil { + return nil, fmt.Errorf("no node found") + } + + var node types.Node + if err := ctx.Codec.UnmarshalJSON(res, &node); err != nil { + return nil, err + } + + return &node, nil +} + +func QueryNodes(ctx context.CLIContext) (types.Nodes, error) { + path := fmt.Sprintf("custom/%s/%s/%s", types.StoreKey, types.QuerierRoute, types.QueryNodes) + res, _, err := ctx.QueryWithData(path, nil) + if err != nil { + return nil, err + } + if res == nil { + return nil, fmt.Errorf("no nodes found") + } + + var nodes types.Nodes + if err := ctx.Codec.UnmarshalJSON(res, &nodes); err != nil { + return nil, err + } + + return nodes, nil +} + +func QueryNodesForProvider(ctx context.CLIContext, address hub.ProvAddress) (types.Nodes, error) { + params := types.NewQueryNodesForProviderParams(address) + bytes, err := ctx.Codec.MarshalJSON(params) + if err != nil { + return nil, err + } + + path := fmt.Sprintf("custom/%s/%s/%s", types.StoreKey, types.QuerierRoute, types.QueryNodesForProvider) + res, _, err := ctx.QueryWithData(path, bytes) + if err != nil { + return nil, err + } + if res == nil { + return nil, fmt.Errorf("no nodes found") + } + + var nodes types.Nodes + if err := ctx.Codec.UnmarshalJSON(res, &nodes); err != nil { + return nil, err + } + + return nodes, nil +} + +func QueryNodesForPlan(ctx context.CLIContext, id uint64) (types.Nodes, error) { + params := plan.NewQueryNodesForPlanParams(id) + bytes, err := ctx.Codec.MarshalJSON(params) + if err != nil { + return nil, err + } + + path := fmt.Sprintf("custom/%s/%s/%s", plan.StoreKey, plan.QuerierRoute, plan.QueryNodesForPlan) + res, _, err := ctx.QueryWithData(path, bytes) + if err != nil { + return nil, err + } + if res == nil { + return nil, fmt.Errorf("no nodes found") + } + + var nodes types.Nodes + if err := ctx.Codec.UnmarshalJSON(res, &nodes); err != nil { + return nil, err + } + + return nodes, nil +} diff --git a/x/dvpn/node/client/rest/query.go b/x/dvpn/node/client/rest/query.go new file mode 100644 index 00000000..8966750b --- /dev/null +++ b/x/dvpn/node/client/rest/query.go @@ -0,0 +1,19 @@ +package rest + +import ( + "net/http" + + "github.com/cosmos/cosmos-sdk/client/context" +) + +func queryNodeHandlerFunc(ctx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + } +} + +func queryNodesHandlerFunc(ctx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + } +} diff --git a/x/dvpn/node/client/rest/rest.go b/x/dvpn/node/client/rest/rest.go new file mode 100644 index 00000000..00d68b25 --- /dev/null +++ b/x/dvpn/node/client/rest/rest.go @@ -0,0 +1,23 @@ +package rest + +import ( + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/gorilla/mux" +) + +func registerQueryRoutes(ctx context.CLIContext, router *mux.Router) { + router.HandleFunc("/nodes", queryNodesHandlerFunc(ctx)). + Methods("GET") + router.HandleFunc("/nodes/{address}", queryNodeHandlerFunc(ctx)). + Methods("GET") +} + +func registerTxRoutes(ctx context.CLIContext, router *mux.Router) { + router.HandleFunc("/nodes", txRegisterNodeHandlerFunc(ctx)). + Methods("POST") +} + +func RegisterRoutes(ctx context.CLIContext, router *mux.Router) { + registerQueryRoutes(ctx, router) + registerTxRoutes(ctx, router) +} diff --git a/x/dvpn/node/client/rest/tx.go b/x/dvpn/node/client/rest/tx.go new file mode 100644 index 00000000..715bcefb --- /dev/null +++ b/x/dvpn/node/client/rest/tx.go @@ -0,0 +1,13 @@ +package rest + +import ( + "net/http" + + "github.com/cosmos/cosmos-sdk/client/context" +) + +func txRegisterNodeHandlerFunc(ctx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + } +} diff --git a/x/dvpn/node/expected/keeper.go b/x/dvpn/node/expected/keeper.go new file mode 100644 index 00000000..4aecec83 --- /dev/null +++ b/x/dvpn/node/expected/keeper.go @@ -0,0 +1,17 @@ +package expected + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" + plan "github.com/sentinel-official/hub/x/dvpn/plan/types" +) + +type ProviderKeeper interface { + HasProvider(ctx sdk.Context, address hub.ProvAddress) bool +} + +type PlanKeeper interface { + GetPlansForProvider(ctx sdk.Context, address hub.ProvAddress) plan.Plans + DeleteNodeForPlan(ctx sdk.Context, id uint64, address hub.NodeAddress) +} diff --git a/x/dvpn/node/genesis.go b/x/dvpn/node/genesis.go new file mode 100644 index 00000000..4c0b614a --- /dev/null +++ b/x/dvpn/node/genesis.go @@ -0,0 +1,27 @@ +package node + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/sentinel-official/hub/x/dvpn/node/keeper" + "github.com/sentinel-official/hub/x/dvpn/node/types" +) + +func InitGenesis(ctx sdk.Context, k keeper.Keeper, state types.GenesisState) { + k.SetParams(ctx, state.Params) + for _, node := range state.Nodes { + k.SetNode(ctx, node) + k.SetNodeForProvider(ctx, node.Provider, node.Address) + } +} + +func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { + return types.NewGenesisState( + k.GetNodes(ctx), + k.GetParams(ctx), + ) +} + +func ValidateGenesis(state types.GenesisState) error { + return nil +} diff --git a/x/dvpn/node/handler.go b/x/dvpn/node/handler.go new file mode 100644 index 00000000..5b4891d1 --- /dev/null +++ b/x/dvpn/node/handler.go @@ -0,0 +1,133 @@ +package node + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/node/keeper" + "github.com/sentinel-official/hub/x/dvpn/node/types" +) + +func BeginBlock(ctx sdk.Context, k keeper.Keeper) { + end := ctx.BlockTime().Add(-1 * k.InactiveDuration(ctx)) + k.IterateActiveNodes(ctx, end, func(_ int, node types.Node) (stop bool) { + k.DeleteActiveNodeAt(ctx, node.StatusAt, node.Address) + + node.Status = hub.StatusInactive + node.StatusAt = ctx.BlockTime() + k.SetNode(ctx, node) + + return false + }) +} + +func HandleRegisterNode(ctx sdk.Context, k keeper.Keeper, msg types.MsgRegisterNode) sdk.Result { + if !k.HasProvider(ctx, msg.Provider) { + return types.ErrorProviderDoesNotExist().Result() + } + + if k.HasNode(ctx, msg.From.Bytes()) { + return types.ErrorDuplicateNode().Result() + } + + node := types.Node{ + Address: msg.From.Bytes(), + Provider: msg.Provider, + Price: msg.Price, + InternetSpeed: msg.InternetSpeed, + RemoteURL: msg.RemoteURL, + Version: msg.Version, + Category: msg.Category, + Status: hub.StatusInactive, + StatusAt: ctx.BlockTime(), + } + + k.SetNode(ctx, node) + if node.Provider != nil { + k.SetNodeForProvider(ctx, node.Provider, node.Address) + } + + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeSetNode, + sdk.NewAttribute(types.AttributeKeyProvider, node.Provider.String()), + sdk.NewAttribute(types.AttributeKeyAddress, node.Address.String()), + )) + + return sdk.Result{Events: ctx.EventManager().Events()} +} + +func HandleUpdateNode(ctx sdk.Context, k keeper.Keeper, msg types.MsgUpdateNode) sdk.Result { + node, found := k.GetNode(ctx, msg.From) + if !found { + return types.ErrorNodeDoesNotExist().Result() + } + if node.Provider.Equals(msg.Provider) { + return types.ErrorCanNotUpdate().Result() + } + + if msg.Provider != nil || msg.Price != nil { + k.DeleteNodeForProvider(ctx, node.Provider, node.Address) + + plans := k.GetPlansForProvider(ctx, node.Provider) + for _, plan := range plans { + k.DeleteNodeForPlan(ctx, plan.ID, node.Address) + } + } + + if msg.Provider != nil { + if !k.HasProvider(ctx, msg.Provider) { + return types.ErrorProviderDoesNotExist().Result() + } + + node.Provider = msg.Provider + node.Price = nil + + k.SetNodeForProvider(ctx, node.Provider, node.Address) + } + if msg.Price != nil { + node.Provider = nil + node.Price = msg.Price + } + if !msg.InternetSpeed.IsAnyZero() { + node.InternetSpeed = msg.InternetSpeed + } + if len(msg.RemoteURL) > 0 { + node.RemoteURL = msg.RemoteURL + } + if len(msg.Version) > 0 { + node.Version = msg.Version + } + if msg.Category.IsValid() { + node.Category = msg.Category + } + + k.SetNode(ctx, node) + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeUpdateNode, + sdk.NewAttribute(types.AttributeKeyAddress, node.Address.String()), + )) + + return sdk.Result{Events: ctx.EventManager().Events()} +} + +func HandleSetNodeStatus(ctx sdk.Context, k keeper.Keeper, msg types.MsgSetNodeStatus) sdk.Result { + node, found := k.GetNode(ctx, msg.From) + if !found { + return types.ErrorNodeDoesNotExist().Result() + } + + k.DeleteActiveNodeAt(ctx, node.StatusAt, node.Address) + k.SetActiveNodeAt(ctx, ctx.BlockTime(), node.Address) + + node.Status = msg.Status + node.StatusAt = ctx.BlockTime() + + k.SetNode(ctx, node) + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeSetNodeStatus, + sdk.NewAttribute(types.AttributeKeyAddress, node.Address.String()), + sdk.NewAttribute(types.AttributeKeyStatus, node.Status.String()), + )) + + return sdk.Result{Events: ctx.EventManager().Events()} +} diff --git a/x/dvpn/node/keeper/alias.go b/x/dvpn/node/keeper/alias.go new file mode 100644 index 00000000..464afb1d --- /dev/null +++ b/x/dvpn/node/keeper/alias.go @@ -0,0 +1,20 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" + plan "github.com/sentinel-official/hub/x/dvpn/plan/types" +) + +func (k Keeper) HasProvider(ctx sdk.Context, address hub.ProvAddress) bool { + return address == nil || k.provider.HasProvider(ctx, address) +} + +func (k Keeper) GetPlansForProvider(ctx sdk.Context, address hub.ProvAddress) plan.Plans { + return k.plan.GetPlansForProvider(ctx, address) +} + +func (k Keeper) DeleteNodeForPlan(ctx sdk.Context, id uint64, address hub.NodeAddress) { + k.plan.DeleteNodeForPlan(ctx, id, address) +} diff --git a/x/dvpn/node/keeper/keeper.go b/x/dvpn/node/keeper/keeper.go new file mode 100644 index 00000000..5b15d07c --- /dev/null +++ b/x/dvpn/node/keeper/keeper.go @@ -0,0 +1,42 @@ +package keeper + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store/prefix" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/params" + + "github.com/sentinel-official/hub/x/dvpn/node/expected" + "github.com/sentinel-official/hub/x/dvpn/node/types" +) + +type Keeper struct { + cdc *codec.Codec + key sdk.StoreKey + params params.Subspace + provider expected.ProviderKeeper + plan expected.PlanKeeper +} + +func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, params params.Subspace) Keeper { + return Keeper{ + cdc: cdc, + key: key, + params: params.WithKeyTable(types.ParamsKeyTable()), + } +} + +func (k *Keeper) WithProviderKeeper(keeper expected.ProviderKeeper) { + k.provider = keeper +} + +func (k *Keeper) WithPlanKeeper(keeper expected.PlanKeeper) { + k.plan = keeper +} + +func (k Keeper) Store(ctx sdk.Context) sdk.KVStore { + child := fmt.Sprintf("%s/", types.ModuleName) + return prefix.NewStore(ctx.KVStore(k.key), []byte(child)) +} diff --git a/x/dvpn/node/keeper/node.go b/x/dvpn/node/keeper/node.go new file mode 100644 index 00000000..13093dd9 --- /dev/null +++ b/x/dvpn/node/keeper/node.go @@ -0,0 +1,135 @@ +package keeper + +import ( + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/node/types" +) + +func (k Keeper) SetNode(ctx sdk.Context, node types.Node) { + key := types.NodeKey(node.Address) + value := k.cdc.MustMarshalBinaryLengthPrefixed(node) + + store := k.Store(ctx) + store.Set(key, value) +} + +func (k Keeper) HasNode(ctx sdk.Context, address hub.NodeAddress) bool { + store := k.Store(ctx) + + key := types.NodeKey(address) + return store.Has(key) +} + +func (k Keeper) GetNode(ctx sdk.Context, address hub.NodeAddress) (node types.Node, found bool) { + store := k.Store(ctx) + + key := types.NodeKey(address) + value := store.Get(key) + if value == nil { + return node, false + } + + k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &node) + return node, true +} + +func (k Keeper) SetNodeForProvider(ctx sdk.Context, p hub.ProvAddress, n hub.NodeAddress) { + key := types.NodeForProviderKey(p, n) + value := k.cdc.MustMarshalBinaryLengthPrefixed(n) + + store := k.Store(ctx) + store.Set(key, value) +} + +func (k Keeper) DeleteNodeForProvider(ctx sdk.Context, p hub.ProvAddress, n hub.NodeAddress) { + store := k.Store(ctx) + + key := types.NodeForProviderKey(p, n) + store.Delete(key) +} + +func (k Keeper) GetNodes(ctx sdk.Context) (items types.Nodes) { + store := k.Store(ctx) + + iter := sdk.KVStorePrefixIterator(store, types.NodeKeyPrefix) + defer iter.Close() + + for ; iter.Valid(); iter.Next() { + var item types.Node + k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &item) + items = append(items, item) + } + + return items +} + +func (k Keeper) GetNodesForProvider(ctx sdk.Context, address hub.ProvAddress) (items types.Nodes) { + store := k.Store(ctx) + + iter := sdk.KVStorePrefixIterator(store, types.NodeForProviderByProviderKey(address)) + defer iter.Close() + + for ; iter.Valid(); iter.Next() { + var address hub.NodeAddress + k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &address) + + item, _ := k.GetNode(ctx, address) + items = append(items, item) + } + + return items +} + +func (k Keeper) IterateNodes(ctx sdk.Context, f func(index int, item types.Node) (stop bool)) { + store := k.Store(ctx) + + iter := sdk.KVStorePrefixIterator(store, types.NodeKeyPrefix) + defer iter.Close() + + for i := 0; iter.Valid(); iter.Next() { + var node types.Node + k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &node) + + if stop := f(i, node); stop { + break + } + i++ + } +} + +func (k Keeper) SetActiveNodeAt(ctx sdk.Context, at time.Time, address hub.NodeAddress) { + key := types.ActiveNodeAtKey(at, address) + value := k.cdc.MustMarshalBinaryLengthPrefixed(address) + + store := k.Store(ctx) + store.Set(key, value) +} + +func (k Keeper) DeleteActiveNodeAt(ctx sdk.Context, at time.Time, address hub.NodeAddress) { + key := types.ActiveNodeAtKey(at, address) + + store := k.Store(ctx) + store.Delete(key) +} + +func (k Keeper) IterateActiveNodes(ctx sdk.Context, end time.Time, f func(index int, item types.Node) (stop bool)) { + store := k.Store(ctx) + + iter := store.Iterator(types.ActiveNodeAtKeyPrefix, sdk.PrefixEndBytes(types.ActiveNodeAtByTimeKey(end))) + defer iter.Close() + + for i := 0; iter.Valid(); iter.Next() { + var address hub.NodeAddress + k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &address) + + node, _ := k.GetNode(ctx, address) + if stop := f(i, node); stop { + break + } + i++ + } +} diff --git a/x/dvpn/node/keeper/params.go b/x/dvpn/node/keeper/params.go new file mode 100644 index 00000000..6d2575c0 --- /dev/null +++ b/x/dvpn/node/keeper/params.go @@ -0,0 +1,24 @@ +package keeper + +import ( + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/sentinel-official/hub/x/dvpn/node/types" +) + +func (k Keeper) InactiveDuration(ctx sdk.Context) (duration time.Duration) { + k.params.Get(ctx, types.KeyInactiveDuration, &duration) + return +} + +func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { + k.params.SetParamSet(ctx, ¶ms) +} + +func (k Keeper) GetParams(ctx sdk.Context) types.Params { + return types.NewParams( + k.InactiveDuration(ctx), + ) +} diff --git a/x/vpn/querier/node.go b/x/dvpn/node/querier/node.go similarity index 55% rename from x/vpn/querier/node.go rename to x/dvpn/node/querier/node.go index d08ecec9..b1d2f727 100644 --- a/x/vpn/querier/node.go +++ b/x/dvpn/node/querier/node.go @@ -4,23 +4,22 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" - "github.com/sentinel-official/hub/x/vpn/keeper" - "github.com/sentinel-official/hub/x/vpn/types" + "github.com/sentinel-official/hub/x/dvpn/node/keeper" + "github.com/sentinel-official/hub/x/dvpn/node/types" ) func queryNode(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { var params types.QueryNodeParams - if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { return nil, types.ErrorUnmarshal() } - node, found := k.GetNode(ctx, params.ID) + provider, found := k.GetNode(ctx, params.Address) if !found { return nil, nil } - res, err := types.ModuleCdc.MarshalJSON(node) + res, err := types.ModuleCdc.MarshalJSON(provider) if err != nil { return nil, types.ErrorMarshal() } @@ -28,15 +27,8 @@ func queryNode(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, return res, nil } -func queryNodesOfAddress(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { - var params types.QueryNodesOfAddressPrams - if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, types.ErrorUnmarshal() - } - - nodes := k.GetNodesOfAddress(ctx, params.Address) - - res, err := types.ModuleCdc.MarshalJSON(nodes) +func queryNodes(ctx sdk.Context, _ abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + res, err := types.ModuleCdc.MarshalJSON(k.GetNodes(ctx)) if err != nil { return nil, types.ErrorMarshal() } @@ -44,10 +36,13 @@ func queryNodesOfAddress(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper return res, nil } -func queryAllNodes(ctx sdk.Context, k keeper.Keeper) ([]byte, sdk.Error) { - nodes := k.GetAllNodes(ctx) +func queryNodesForProvider(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + var params types.QueryNodesForProviderParams + if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { + return nil, types.ErrorUnmarshal() + } - res, err := types.ModuleCdc.MarshalJSON(nodes) + res, err := types.ModuleCdc.MarshalJSON(k.GetNodesForProvider(ctx, params.Address)) if err != nil { return nil, types.ErrorMarshal() } diff --git a/x/dvpn/node/querier/querier.go b/x/dvpn/node/querier/querier.go new file mode 100644 index 00000000..861901d2 --- /dev/null +++ b/x/dvpn/node/querier/querier.go @@ -0,0 +1,22 @@ +package querier + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/sentinel-official/hub/x/dvpn/node/keeper" + "github.com/sentinel-official/hub/x/dvpn/node/types" +) + +func Querier(ctx sdk.Context, path []string, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + switch path[0] { + case types.QueryNode: + return queryNode(ctx, req, k) + case types.QueryNodes: + return queryNodes(ctx, req, k) + case types.QueryNodesForProvider: + return queryNodesForProvider(ctx, req, k) + default: + return nil, types.ErrorUnknownQueryType(path[0]) + } +} diff --git a/x/dvpn/node/types/codec.go b/x/dvpn/node/types/codec.go new file mode 100644 index 00000000..0d6849dd --- /dev/null +++ b/x/dvpn/node/types/codec.go @@ -0,0 +1,22 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec" +) + +var ( + ModuleCdc *codec.Codec +) + +func init() { + ModuleCdc = codec.New() + codec.RegisterCrypto(ModuleCdc) + RegisterCodec(ModuleCdc) + ModuleCdc.Seal() +} + +func RegisterCodec(cdc *codec.Codec) { + cdc.RegisterConcrete(MsgRegisterNode{}, "sentinel/MsgRegisterNode", nil) + cdc.RegisterConcrete(MsgUpdateNode{}, "sentinel/MsgUpdateNode", nil) + cdc.RegisterConcrete(MsgSetNodeStatus{}, "sentinel/MsgSetNodeStatus", nil) +} diff --git a/x/dvpn/node/types/errors.go b/x/dvpn/node/types/errors.go new file mode 100644 index 00000000..44ab8eab --- /dev/null +++ b/x/dvpn/node/types/errors.go @@ -0,0 +1,69 @@ +package types + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +const ( + Codespace = sdk.CodespaceType(ModuleName) +) + +const ( + errorCodeUnknownMsgType = iota + 101 + errorCodeUnknownQueryType + errorCodeInvalidField + errorCodeProviderDoesNotExist + errorCodeDuplicateNode + errorCodeNodeDoesNotExist + errorCodeCanNotUpdate +) + +const ( + errorMsgUnknownMsgType = "unknown message type: %s" + errorMsgUnknownQueryType = "unknown query type: %s" + errorMsgInvalidField = "invalid field: %s" + errorMsgProviderDoesNotExist = "provider does not exist" + errorMsgDuplicateNode = "duplicate node" + errorMsgNodeDoesNotExist = "node does not exist" + errorMsgCanNotUpdate = "can not update" +) + +func ErrorMarshal() sdk.Error { + return sdk.NewError(Codespace, hub.ErrorCodeMarshal, hub.ErrorMsgMarshal) +} + +func ErrorUnmarshal() sdk.Error { + return sdk.NewError(Codespace, hub.ErrorCodeUnmarshal, hub.ErrorMsgUnmarshal) +} + +func ErrorUnknownMsgType(v string) sdk.Error { + return sdk.NewError(Codespace, errorCodeUnknownMsgType, fmt.Sprintf(errorMsgUnknownMsgType, v)) +} + +func ErrorUnknownQueryType(v string) sdk.Error { + return sdk.NewError(Codespace, errorCodeUnknownQueryType, fmt.Sprintf(errorMsgUnknownQueryType, v)) +} + +func ErrorInvalidField(v string) sdk.Error { + return sdk.NewError(Codespace, errorCodeInvalidField, fmt.Sprintf(errorMsgInvalidField, v)) +} + +func ErrorProviderDoesNotExist() sdk.Error { + return sdk.NewError(Codespace, errorCodeProviderDoesNotExist, errorMsgProviderDoesNotExist) +} + +func ErrorDuplicateNode() sdk.Error { + return sdk.NewError(Codespace, errorCodeDuplicateNode, errorMsgDuplicateNode) +} + +func ErrorNodeDoesNotExist() sdk.Error { + return sdk.NewError(Codespace, errorCodeNodeDoesNotExist, errorMsgNodeDoesNotExist) +} + +func ErrorCanNotUpdate() sdk.Error { + return sdk.NewError(Codespace, errorCodeCanNotUpdate, errorMsgCanNotUpdate) +} diff --git a/x/dvpn/node/types/events.go b/x/dvpn/node/types/events.go new file mode 100644 index 00000000..27be5226 --- /dev/null +++ b/x/dvpn/node/types/events.go @@ -0,0 +1,13 @@ +package types + +const ( + EventTypeSetNode = "set_node" + EventTypeUpdateNode = "update_node" + EventTypeSetNodeStatus = "set_node_status" +) + +const ( + AttributeKeyProvider = "provider" + AttributeKeyAddress = "address" + AttributeKeyStatus = "status" +) diff --git a/x/dvpn/node/types/genesis.go b/x/dvpn/node/types/genesis.go new file mode 100644 index 00000000..b7770e33 --- /dev/null +++ b/x/dvpn/node/types/genesis.go @@ -0,0 +1,20 @@ +package types + +type GenesisState struct { + Nodes Nodes `json:"_"` + Params Params `json:"params"` +} + +func NewGenesisState(nodes Nodes, params Params) GenesisState { + return GenesisState{ + Nodes: nodes, + Params: params, + } +} + +func DefaultGenesisState() GenesisState { + return GenesisState{ + Nodes: nil, + Params: DefaultParams(), + } +} diff --git a/x/dvpn/node/types/keys.go b/x/dvpn/node/types/keys.go new file mode 100644 index 00000000..5474d985 --- /dev/null +++ b/x/dvpn/node/types/keys.go @@ -0,0 +1,46 @@ +package types + +import ( + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +const ( + ModuleName = "node" + ParamsSubspace = ModuleName + QuerierRoute = ModuleName +) + +var ( + RouterKey = ModuleName + StoreKey = ModuleName +) + +var ( + NodeKeyPrefix = []byte{0x00} + NodeForProviderKeyPrefix = []byte{0x01} + ActiveNodeAtKeyPrefix = []byte{0x02} +) + +func NodeKey(address hub.NodeAddress) []byte { + return append(NodeKeyPrefix, address.Bytes()...) +} + +func NodeForProviderByProviderKey(address hub.ProvAddress) []byte { + return append(NodeForProviderKeyPrefix, address.Bytes()...) +} + +func NodeForProviderKey(p hub.ProvAddress, n hub.NodeAddress) []byte { + return append(NodeForProviderByProviderKey(p), n.Bytes()...) +} + +func ActiveNodeAtByTimeKey(at time.Time) []byte { + return append(ActiveNodeAtKeyPrefix, sdk.FormatTimeBytes(at)...) +} + +func ActiveNodeAtKey(at time.Time, address hub.NodeAddress) []byte { + return append(ActiveNodeAtByTimeKey(at), address.Bytes()...) +} diff --git a/x/dvpn/node/types/msg.go b/x/dvpn/node/types/msg.go new file mode 100644 index 00000000..5f4a08f9 --- /dev/null +++ b/x/dvpn/node/types/msg.go @@ -0,0 +1,239 @@ +package types + +import ( + "encoding/json" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +var ( + _ sdk.Msg = (*MsgRegisterNode)(nil) + _ sdk.Msg = (*MsgUpdateNode)(nil) + _ sdk.Msg = (*MsgSetNodeStatus)(nil) +) + +// MsgRegisterNode is for registering a dVPN node. +type MsgRegisterNode struct { + From sdk.AccAddress `json:"from"` + Provider hub.ProvAddress `json:"provider,omitempty"` + Price sdk.Coins `json:"price,omitempty"` + InternetSpeed hub.Bandwidth `json:"internet_speed"` + RemoteURL string `json:"remote_url"` + Version string `json:"version"` + Category NodeCategory `json:"category"` +} + +func NewMsgRegisterNode(from sdk.AccAddress, provider hub.ProvAddress, price sdk.Coins, + speed hub.Bandwidth, remoteURL, version string, category NodeCategory) MsgRegisterNode { + return MsgRegisterNode{ + From: from, + Provider: provider, + Price: price, + InternetSpeed: speed, + RemoteURL: remoteURL, + Version: version, + Category: category, + } +} + +func (m MsgRegisterNode) Route() string { + return RouterKey +} + +func (m MsgRegisterNode) Type() string { + return "register_node" +} + +func (m MsgRegisterNode) ValidateBasic() sdk.Error { + if m.From == nil || m.From.Empty() { + return ErrorInvalidField("from") + } + + // Provider and Price both shouldn't nil at the same time + if (m.Provider != nil && m.Price != nil) || + (m.Provider == nil && m.Price == nil) { + return ErrorInvalidField("provider and price") + } + + // Provider can be nil. If not, it shouldn't be empty + if m.Provider != nil && m.Provider.Empty() { + return ErrorInvalidField("provider") + } + + // Price can be nil. If not, it should be valid + if m.Price != nil && !m.Price.IsValid() { + return ErrorInvalidField("price") + } + + // InternetSpeed shouldn't be negative and zero + if !m.InternetSpeed.IsValid() { + return ErrorInvalidField("internet_speed") + } + + // RemoteURL can't be empty and length should be (0, 64] + if len(m.RemoteURL) == 0 || len(m.RemoteURL) > 64 { + return ErrorInvalidField("remote_url") + } + + // Version can't be empty and length should be (0, 64] + if len(m.Version) == 0 || len(m.Version) > 64 { + return ErrorInvalidField("version") + } + + // Category should be valid + if !m.Category.IsValid() { + return ErrorInvalidField("category") + } + + return nil +} + +func (m MsgRegisterNode) GetSignBytes() []byte { + bytes, err := json.Marshal(m) + if err != nil { + panic(err) + } + + return bytes +} + +func (m MsgRegisterNode) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{m.From} +} + +// MsgUpdateNode is for updating the information of a dVPN node. +type MsgUpdateNode struct { + From hub.NodeAddress `json:"from"` + Provider hub.ProvAddress `json:"provider,omitempty"` + Price sdk.Coins `json:"price,omitempty"` + InternetSpeed hub.Bandwidth `json:"internet_speed,omitempty"` + RemoteURL string `json:"remote_url,omitempty"` + Version string `json:"version,omitempty"` + Category NodeCategory `json:"category,omitempty"` +} + +func NewMsgUpdateNode(from hub.NodeAddress, provider hub.ProvAddress, price sdk.Coins, + speed hub.Bandwidth, remoteURL, version string, category NodeCategory) MsgUpdateNode { + return MsgUpdateNode{ + From: from, + Provider: provider, + Price: price, + InternetSpeed: speed, + RemoteURL: remoteURL, + Version: version, + Category: category, + } +} + +func (m MsgUpdateNode) Route() string { + return RouterKey +} + +func (m MsgUpdateNode) Type() string { + return "update_node" +} + +func (m MsgUpdateNode) ValidateBasic() sdk.Error { + if m.From == nil || m.From.Empty() { + return ErrorInvalidField("from") + } + + // Provider and Price both shouldn't nil at the same time + if m.Provider != nil && m.Price != nil { + return ErrorInvalidField("provider and price") + } + + // Provider can be nil. If not, it shouldn't be empty + if m.Provider != nil && m.Provider.Empty() { + return ErrorInvalidField("provider") + } + + // Price can be nil. If not, it should be valid + if m.Price != nil && !m.Price.IsValid() { + return ErrorInvalidField("price") + } + + // InternetSpeed can be zero. If not, it shouldn't be negative and zero + if !m.InternetSpeed.IsAllZero() && !m.InternetSpeed.IsValid() { + return ErrorInvalidField("internet_speed") + } + + // RemoteURL length should be [0, 64] + if len(m.RemoteURL) > 64 { + return ErrorInvalidField("remote_url") + } + + // Version length should be [0, 64] + if len(m.Version) > 64 { + return ErrorInvalidField("version") + } + + // Category can be Unknown. If not, should be valid + if m.Category != CategoryUnknown && !m.Category.IsValid() { + return ErrorInvalidField("category") + } + + return nil +} + +func (m MsgUpdateNode) GetSignBytes() []byte { + bytes, err := json.Marshal(m) + if err != nil { + panic(err) + } + + return bytes +} + +func (m MsgUpdateNode) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{m.From.Bytes()} +} + +// MsgSetNodeStatus is for updating the status of a dVPN node. +type MsgSetNodeStatus struct { + From hub.NodeAddress `json:"from"` + Status hub.Status `json:"status"` +} + +func NewMsgSetNodeStatus(from hub.NodeAddress, status hub.Status) MsgSetNodeStatus { + return MsgSetNodeStatus{ + From: from, + Status: status, + } +} + +func (m MsgSetNodeStatus) Route() string { + return RouterKey +} + +func (m MsgSetNodeStatus) Type() string { + return "set_node_status" +} + +func (m MsgSetNodeStatus) ValidateBasic() sdk.Error { + if m.From == nil || m.From.Empty() { + return ErrorInvalidField("from") + } + + // Status should be valid + if !m.Status.IsValid() { + return ErrorInvalidField("status") + } + + return nil +} + +func (m MsgSetNodeStatus) GetSignBytes() []byte { + bytes, err := json.Marshal(m) + if err != nil { + panic(err) + } + + return bytes +} + +func (m MsgSetNodeStatus) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{m.From.Bytes()} +} diff --git a/x/dvpn/node/types/node.go b/x/dvpn/node/types/node.go new file mode 100644 index 00000000..55aafa6f --- /dev/null +++ b/x/dvpn/node/types/node.go @@ -0,0 +1,113 @@ +package types + +import ( + "fmt" + "strings" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +const ( + CategoryUnknown = iota + 0x00 + CategoryOpenVPN + CategoryWireGuard +) + +type NodeCategory byte + +func NodeCategoryFromString(s string) NodeCategory { + switch s { + case "OpenVPN": + return CategoryOpenVPN + case "WireGuard": + return CategoryWireGuard + default: + return CategoryUnknown + } +} + +func (n NodeCategory) Equal(v NodeCategory) bool { + return n == v +} + +func (n NodeCategory) String() string { + switch n { + case CategoryOpenVPN: + return "OpenVPN" + case CategoryWireGuard: + return "WireGuard" + default: + return "Unknown" + } +} + +func (n NodeCategory) IsValid() bool { + return n == CategoryOpenVPN || + n == CategoryWireGuard +} + +type Node struct { + Address hub.NodeAddress `json:"address"` + Provider hub.ProvAddress `json:"provider,omitempty"` + Price sdk.Coins `json:"price,omitempty"` + InternetSpeed hub.Bandwidth `json:"internet_speed"` + RemoteURL string `json:"remote_url"` + Version string `json:"version"` + Category NodeCategory `json:"category"` + Status hub.Status `json:"status"` + StatusAt time.Time `json:"status_at"` +} + +func (n Node) String() string { + if n.Provider == nil { + return strings.TrimSpace(fmt.Sprintf(` +Address: %s +Price: %s +Internet speed: %s +Remote URL: %s +Version: %s +Category: %s +Status: %s +Status at: %s +`, n.Address, n.Price, n.InternetSpeed, n.RemoteURL, n.Version, n.Category, n.Status, n.StatusAt)) + } + + return strings.TrimSpace(fmt.Sprintf(` +Address: %s +Provider: %s +Internet speed: %s +Remote URL: %s +Version: %s +Category: %s +Status: %s +Status at: %s +`, n.Address, n.Provider, n.InternetSpeed, n.RemoteURL, n.Version, n.Category, n.Status, n.StatusAt)) +} + +func (n Node) PriceForDenom(s string) (sdk.Coin, bool) { + for _, coin := range n.Price { + if coin.Denom == s { + return coin, true + } + } + + return sdk.Coin{}, false +} + +func (n Node) BandwidthForCoin(coin sdk.Coin) (hub.Bandwidth, error) { + price, found := n.PriceForDenom(coin.Denom) + if !found { + return hub.Bandwidth{}, fmt.Errorf("price does not exist") + } + + bytes := coin.Amount. + Mul(hub.Gigabyte.QuoRaw(2)). + Quo(price.Amount) + + return hub.NewBandwidth(bytes, bytes), nil +} + +type Nodes []Node diff --git a/x/dvpn/node/types/params.go b/x/dvpn/node/types/params.go new file mode 100644 index 00000000..ee2ccfb5 --- /dev/null +++ b/x/dvpn/node/types/params.go @@ -0,0 +1,51 @@ +package types + +import ( + "fmt" + "strings" + "time" + + "github.com/cosmos/cosmos-sdk/x/params" +) + +const ( + DefaultInactiveDuration = 30 * time.Minute +) + +var ( + KeyInactiveDuration = []byte("InactiveDuration") +) + +var _ params.ParamSet = (*Params)(nil) + +type Params struct { + InactiveDuration time.Duration `json:"inactive_duration"` +} + +func (p Params) String() string { + return fmt.Sprintf(strings.TrimSpace(` +Inactive duration: %s +`), p.InactiveDuration) +} + +func (p *Params) ParamSetPairs() params.ParamSetPairs { + return params.ParamSetPairs{ + {Key: KeyInactiveDuration, Value: &p.InactiveDuration}, + } +} + +func NewParams(inactiveDuration time.Duration) Params { + return Params{ + InactiveDuration: inactiveDuration, + } +} + +func DefaultParams() Params { + return Params{ + InactiveDuration: DefaultInactiveDuration, + } +} + +func ParamsKeyTable() params.KeyTable { + return params.NewKeyTable().RegisterParamSet(&Params{}) +} diff --git a/x/dvpn/node/types/querier.go b/x/dvpn/node/types/querier.go new file mode 100644 index 00000000..4f950ffc --- /dev/null +++ b/x/dvpn/node/types/querier.go @@ -0,0 +1,31 @@ +package types + +import ( + hub "github.com/sentinel-official/hub/types" +) + +const ( + QueryNode = "query_node" + QueryNodes = "query_nodes" + QueryNodesForProvider = "query_nodes_for_provider" +) + +type QueryNodeParams struct { + Address hub.NodeAddress `json:"address"` +} + +func NewQueryNodeParams(address hub.NodeAddress) QueryNodeParams { + return QueryNodeParams{ + Address: address, + } +} + +type QueryNodesForProviderParams struct { + Address hub.ProvAddress `json:"address"` +} + +func NewQueryNodesForProviderParams(address hub.ProvAddress) QueryNodesForProviderParams { + return QueryNodesForProviderParams{ + Address: address, + } +} diff --git a/x/dvpn/plan/alias.go b/x/dvpn/plan/alias.go new file mode 100644 index 00000000..c806fbec --- /dev/null +++ b/x/dvpn/plan/alias.go @@ -0,0 +1,87 @@ +// nolint +// autogenerated code using github.com/rigelrozanski/multitool +// aliases generated for the following subdirectories: +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/plan/types +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/plan/keeper +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/plan/querier +package plan + +import ( + "github.com/sentinel-official/hub/x/dvpn/plan/keeper" + "github.com/sentinel-official/hub/x/dvpn/plan/querier" + "github.com/sentinel-official/hub/x/dvpn/plan/types" +) + +const ( + Codespace = types.Codespace + EventTypeSetPlan = types.EventTypeSetPlan + EventTypeSetPlansCount = types.EventTypeSetPlansCount + EventTypeSetPlanStatus = types.EventTypeSetPlanStatus + EventTypeAddNodeForPlan = types.EventTypeAddNodeForPlan + EventTypeRemoveNodeForPlan = types.EventTypeRemoveNodeForPlan + AttributeKeyAddress = types.AttributeKeyAddress + AttributeKeyID = types.AttributeKeyID + AttributeKeyCount = types.AttributeKeyCount + AttributeKeyStatus = types.AttributeKeyStatus + ModuleName = types.ModuleName + QuerierRoute = types.QuerierRoute + QueryPlan = types.QueryPlan + QueryPlans = types.QueryPlans + QueryPlansForProvider = types.QueryPlansForProvider + QueryNodesForPlan = types.QueryNodesForPlan +) + +var ( + // functions aliases + RegisterCodec = types.RegisterCodec + ErrorMarshal = types.ErrorMarshal + ErrorUnmarshal = types.ErrorUnmarshal + ErrorUnknownMsgType = types.ErrorUnknownMsgType + ErrorUnknownQueryType = types.ErrorUnknownQueryType + ErrorInvalidField = types.ErrorInvalidField + ErrorProviderDoesNotExist = types.ErrorProviderDoesNotExist + ErrorPlanDoesNotExist = types.ErrorPlanDoesNotExist + ErrorNodeDoesNotExist = types.ErrorNodeDoesNotExist + ErrorUnauthorized = types.ErrorUnauthorized + ErrorDuplicateNode = types.ErrorDuplicateNode + ErrorNodeWasNotAdded = types.ErrorNodeWasNotAdded + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + PlanKey = types.PlanKey + PlanForProviderKeyPrefix = types.PlanForProviderKeyPrefix + PlanForProviderKey = types.PlanForProviderKey + NodeForPlanKeyPrefix = types.NodeForPlanKeyPrefix + NodeForPlanKey = types.NodeForPlanKey + NewMsgAddPlan = types.NewMsgAddPlan + NewMsgSetPlanStatus = types.NewMsgSetPlanStatus + NewMsgAddNodeForPlan = types.NewMsgAddNodeForPlan + NewMsgRemoveNodeForPlan = types.NewMsgRemoveNodeForPlan + NewQueryPlanParams = types.NewQueryPlanParams + NewQueryPlansForProviderParams = types.NewQueryPlansForProviderParams + NewQueryNodesForPlanParams = types.NewQueryNodesForPlanParams + NewKeeper = keeper.NewKeeper + Querier = querier.Querier + + // variable aliases + ModuleCdc = types.ModuleCdc + RouterKey = types.RouterKey + StoreKey = types.StoreKey + PlansCountKey = types.PlansCountKey + PlanKeyPrefix = types.PlanKeyPrefix +) + +type ( + GenesisPlan = types.GenesisPlan + GenesisPlans = types.GenesisPlans + GenesisState = types.GenesisState + MsgAddPlan = types.MsgAddPlan + MsgSetPlanStatus = types.MsgSetPlanStatus + MsgAddNodeForPlan = types.MsgAddNodeForPlan + MsgRemoveNodeForPlan = types.MsgRemoveNodeForPlan + Plan = types.Plan + Plans = types.Plans + QueryPlanParams = types.QueryPlanParams + QueryPlansForProviderParams = types.QueryPlansForProviderParams + QueryNodesForPlanParams = types.QueryNodesForPlanParams + Keeper = keeper.Keeper +) diff --git a/x/dvpn/plan/client/cli/cli.go b/x/dvpn/plan/client/cli/cli.go new file mode 100644 index 00000000..e4355435 --- /dev/null +++ b/x/dvpn/plan/client/cli/cli.go @@ -0,0 +1,30 @@ +package cli + +import ( + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/spf13/cobra" +) + +func GetQueryCommands(cdc *codec.Codec) []*cobra.Command { + return client.GetCommands( + queryPlanCmd(cdc), + queryPlansCmd(cdc), + ) +} + +func GetTxCommands(cdc *codec.Codec) []*cobra.Command { + cmd := &cobra.Command{ + Use: "plan", + Short: "plan module sub-commands", + } + + cmd.AddCommand(client.PostCommands( + txAddPlanCmd(cdc), + txSetPlanStatusCmd(cdc), + txAddNodeForPlanCmd(cdc), + txRemoveNodeForPlanCmd(cdc), + )...) + + return []*cobra.Command{cmd} +} diff --git a/x/dvpn/plan/client/cli/flags.go b/x/dvpn/plan/client/cli/flags.go new file mode 100644 index 00000000..53122469 --- /dev/null +++ b/x/dvpn/plan/client/cli/flags.go @@ -0,0 +1,10 @@ +package cli + +const ( + flagProvider = "provider" + flagPrice = "price" + flagValidity = "validity" + flagUpload = "upload" + flagDownload = "download" + flagDuration = "duration" +) diff --git a/x/dvpn/plan/client/cli/query.go b/x/dvpn/plan/client/cli/query.go new file mode 100644 index 00000000..29d71119 --- /dev/null +++ b/x/dvpn/plan/client/cli/query.go @@ -0,0 +1,82 @@ +package cli + +import ( + "fmt" + "strconv" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/spf13/cobra" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/plan/client/common" + "github.com/sentinel-official/hub/x/dvpn/plan/types" +) + +func queryPlanCmd(cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "plan", + Short: "Query a plan", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.NewCLIContext().WithCodec(cdc) + + id, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return err + } + + plan, err := common.QueryPlan(ctx, id) + if err != nil { + return err + } + + fmt.Println(plan) + return nil + }, + } +} + +func queryPlansCmd(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "plans", + Short: "Query plans", + RunE: func(cmd *cobra.Command, args []string) (err error) { + ctx := context.NewCLIContext().WithCodec(cdc) + + provider, err := cmd.Flags().GetString(flagProvider) + if err != nil { + return err + } + + var plans types.Plans + + if len(provider) > 0 { + address, err := hub.ProvAddressFromBech32(provider) + if err != nil { + return err + } + + plans, err = common.QueryPlansForProvider(ctx, address) + if err != nil { + return err + } + } else { + plans, err = common.QueryPlans(ctx) + if err != nil { + return err + } + } + + for _, plan := range plans { + fmt.Println(plan) + } + + return nil + }, + } + + cmd.Flags().String(flagProvider, "", "Provider address") + + return cmd +} diff --git a/x/dvpn/plan/client/cli/tx.go b/x/dvpn/plan/client/cli/tx.go new file mode 100644 index 00000000..247c7499 --- /dev/null +++ b/x/dvpn/plan/client/cli/tx.go @@ -0,0 +1,161 @@ +package cli + +import ( + "strconv" + "time" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/client/utils" + "github.com/spf13/cobra" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/plan/types" +) + +func txAddPlanCmd(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "add", + Short: "Add a plan", + RunE: func(cmd *cobra.Command, args []string) error { + txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + ctx := context.NewCLIContext().WithCodec(cdc) + + s, err := cmd.Flags().GetString(flagPrice) + if err != nil { + return err + } + + price, err := sdk.ParseCoins(s) + if err != nil { + return err + } + + s, err = cmd.Flags().GetString(flagValidity) + if err != nil { + return err + } + + validity, err := time.ParseDuration(s) + if err != nil { + return err + } + + upload, err := cmd.Flags().GetInt64(flagUpload) + if err != nil { + return err + } + + download, err := cmd.Flags().GetInt64(flagDownload) + if err != nil { + return err + } + + s, err = cmd.Flags().GetString(flagDuration) + if err != nil { + return err + } + + duration, err := time.ParseDuration(s) + if err != nil { + return err + } + + msg := types.NewMsgAddPlan(ctx.FromAddress.Bytes(), price, validity, + hub.NewBandwidthFromInt64(upload, download), duration) + return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) + }, + } + + cmd.Flags().String(flagPrice, "", "Plan price") + cmd.Flags().String(flagValidity, "", "Plan validity") + cmd.Flags().Int64(flagUpload, 0, "Plan upload bandwidth") + cmd.Flags().Int64(flagDownload, 0, "Plan download bandwidth") + cmd.Flags().String(flagDuration, "", "Plan duration") + + _ = cmd.MarkFlagRequired(flagPrice) + _ = cmd.MarkFlagRequired(flagValidity) + _ = cmd.MarkFlagRequired(flagUpload) + _ = cmd.MarkFlagRequired(flagDownload) + _ = cmd.MarkFlagRequired(flagDuration) + + return cmd +} + +func txSetPlanStatusCmd(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "status-set", + Short: "Set a plan status", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + ctx := context.NewCLIContext().WithCodec(cdc) + + id, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return err + } + + msg := types.NewMsgSetPlanStatus(ctx.FromAddress.Bytes(), id, hub.StatusFromString(args[1])) + return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) + }, + } + + return cmd +} + +func txAddNodeForPlanCmd(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "node-add", + Short: "Add a node for a plan", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + ctx := context.NewCLIContext().WithCodec(cdc) + + id, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return err + } + + node, err := hub.NodeAddressFromBech32(args[1]) + if err != nil { + return err + } + + msg := types.NewMsgAddNodeForPlan(ctx.FromAddress.Bytes(), id, node) + return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) + }, + } + + return cmd +} + +func txRemoveNodeForPlanCmd(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "node-remove", + Short: "Remove a node for a plan", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + ctx := context.NewCLIContext().WithCodec(cdc) + + id, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return err + } + + node, err := hub.NodeAddressFromBech32(args[1]) + if err != nil { + return err + } + + msg := types.NewMsgRemoveNodeForPlan(ctx.FromAddress.Bytes(), id, node) + return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) + }, + } + + return cmd +} diff --git a/x/dvpn/plan/client/common/query.go b/x/dvpn/plan/client/common/query.go new file mode 100644 index 00000000..7b8e4968 --- /dev/null +++ b/x/dvpn/plan/client/common/query.go @@ -0,0 +1,76 @@ +package common + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/client/context" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/plan/types" +) + +func QueryPlan(ctx context.CLIContext, id uint64) (*types.Plan, error) { + params := types.NewQueryPlanParams(id) + bytes, err := ctx.Codec.MarshalJSON(params) + if err != nil { + return nil, err + } + + path := fmt.Sprintf("custom/%s/%s/%s", types.StoreKey, types.QuerierRoute, types.QueryPlan) + res, _, err := ctx.QueryWithData(path, bytes) + if err != nil { + return nil, err + } + if res == nil { + return nil, fmt.Errorf("no plan found") + } + + var plan types.Plan + if err := ctx.Codec.UnmarshalJSON(res, &plan); err != nil { + return nil, err + } + + return &plan, nil +} + +func QueryPlans(ctx context.CLIContext) (types.Plans, error) { + path := fmt.Sprintf("custom/%s/%s/%s", types.StoreKey, types.QuerierRoute, types.QueryPlans) + res, _, err := ctx.QueryWithData(path, nil) + if err != nil { + return nil, err + } + if res == nil { + return nil, fmt.Errorf("no plans found") + } + + var plans types.Plans + if err := ctx.Codec.UnmarshalJSON(res, &plans); err != nil { + return nil, err + } + + return plans, nil +} + +func QueryPlansForProvider(ctx context.CLIContext, address hub.ProvAddress) (types.Plans, error) { + params := types.NewQueryPlansForProviderParams(address) + bytes, err := ctx.Codec.MarshalJSON(params) + if err != nil { + return nil, err + } + + path := fmt.Sprintf("custom/%s/%s/%s", types.StoreKey, types.QuerierRoute, types.QueryPlansForProvider) + res, _, err := ctx.QueryWithData(path, bytes) + if err != nil { + return nil, err + } + if res == nil { + return nil, fmt.Errorf("no plans found") + } + + var plans types.Plans + if err := ctx.Codec.UnmarshalJSON(res, &plans); err != nil { + return nil, err + } + + return plans, nil +} diff --git a/x/dvpn/plan/client/rest/query.go b/x/dvpn/plan/client/rest/query.go new file mode 100644 index 00000000..696d7d68 --- /dev/null +++ b/x/dvpn/plan/client/rest/query.go @@ -0,0 +1,25 @@ +package rest + +import ( + "net/http" + + "github.com/cosmos/cosmos-sdk/client/context" +) + +func queryPlanHandlerFunc(ctx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + } +} + +func queryPlansHandlerFunc(ctx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + } +} + +func queryPlansForProviderHandlerFunc(ctx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + } +} diff --git a/x/dvpn/plan/client/rest/rest.go b/x/dvpn/plan/client/rest/rest.go new file mode 100644 index 00000000..1d28f84b --- /dev/null +++ b/x/dvpn/plan/client/rest/rest.go @@ -0,0 +1,29 @@ +package rest + +import ( + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/gorilla/mux" +) + +func registerQueryRoutes(ctx context.CLIContext, router *mux.Router) { + router.HandleFunc("/plans", queryPlansHandlerFunc(ctx)). + Methods("GET") + router.HandleFunc("/plans/{address}", queryPlansForProviderHandlerFunc(ctx)). + Methods("GET") + router.HandleFunc("/plans/{address}/{id}", queryPlanHandlerFunc(ctx)). + Methods("GET") +} + +func registerTxRoutes(ctx context.CLIContext, router *mux.Router) { + router.HandleFunc("/plans", txAddPlanHandlerFunc(ctx)). + Methods("POST") + router.HandleFunc("/plans/{address}/{id}/status", txSetPlanStatusHandlerFunc(ctx)). + Methods("PUT") + router.HandleFunc("/plans/{address}/{id}/nodes", txAddNodeHandlerFunc(ctx)). + Methods("POST") +} + +func RegisterRoutes(ctx context.CLIContext, router *mux.Router) { + registerQueryRoutes(ctx, router) + registerTxRoutes(ctx, router) +} diff --git a/x/dvpn/plan/client/rest/tx.go b/x/dvpn/plan/client/rest/tx.go new file mode 100644 index 00000000..89e014d2 --- /dev/null +++ b/x/dvpn/plan/client/rest/tx.go @@ -0,0 +1,25 @@ +package rest + +import ( + "net/http" + + "github.com/cosmos/cosmos-sdk/client/context" +) + +func txAddPlanHandlerFunc(ctx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + } +} + +func txSetPlanStatusHandlerFunc(ctx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + } +} + +func txAddNodeHandlerFunc(ctx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + } +} diff --git a/x/dvpn/plan/expected/keeper.go b/x/dvpn/plan/expected/keeper.go new file mode 100644 index 00000000..3a20d4eb --- /dev/null +++ b/x/dvpn/plan/expected/keeper.go @@ -0,0 +1,16 @@ +package expected + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" + node "github.com/sentinel-official/hub/x/dvpn/node/types" +) + +type ProviderKeeper interface { + HasProvider(ctx sdk.Context, address hub.ProvAddress) bool +} + +type NodeKeeper interface { + GetNode(ctx sdk.Context, address hub.NodeAddress) (node.Node, bool) +} diff --git a/x/dvpn/plan/genesis.go b/x/dvpn/plan/genesis.go new file mode 100644 index 00000000..5366fda3 --- /dev/null +++ b/x/dvpn/plan/genesis.go @@ -0,0 +1,46 @@ +package plan + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/sentinel-official/hub/x/dvpn/plan/keeper" + "github.com/sentinel-official/hub/x/dvpn/plan/types" +) + +func InitGenesis(ctx sdk.Context, k keeper.Keeper, state types.GenesisState) { + for _, item := range state { + k.SetPlan(ctx, item.Plan) + k.SetPlanForProvider(ctx, item.Plan.Provider, item.Plan.ID) + + for _, node := range item.Nodes { + k.SetNodeForPlan(ctx, item.Plan.ID, node) + } + + k.SetPlansCount(ctx, k.GetPlansCount(ctx)+1) + } +} + +func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { + _plans := k.GetPlans(ctx) + + plans := make(types.GenesisPlans, 0, len(_plans)) + for _, item := range _plans { + plan := types.GenesisPlan{ + Plan: item, + Nodes: nil, + } + + nodes := k.GetNodesForPlan(ctx, item.ID) + for _, node := range nodes { + plan.Nodes = append(plan.Nodes, node.Address) + } + + plans = append(plans, plan) + } + + return types.NewGenesisState(plans) +} + +func ValidateGenesis(state types.GenesisState) error { + return nil +} diff --git a/x/dvpn/plan/handler.go b/x/dvpn/plan/handler.go new file mode 100644 index 00000000..12243771 --- /dev/null +++ b/x/dvpn/plan/handler.go @@ -0,0 +1,121 @@ +package plan + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/plan/keeper" + "github.com/sentinel-official/hub/x/dvpn/plan/types" +) + +func HandleAddPlan(ctx sdk.Context, k keeper.Keeper, msg types.MsgAddPlan) sdk.Result { + if !k.HasProvider(ctx, msg.From) { + return types.ErrorProviderDoesNotExist().Result() + } + + count := k.GetPlansCount(ctx) + plan := types.Plan{ + ID: count + 1, + Provider: msg.From, + Price: msg.Price, + Validity: msg.Validity, + Bandwidth: msg.Bandwidth, + Duration: msg.Duration, + Status: hub.StatusInactive, + StatusAt: ctx.BlockTime(), + } + + k.SetPlan(ctx, plan) + k.SetPlanForProvider(ctx, plan.Provider, plan.ID) + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeSetPlan, + sdk.NewAttribute(types.AttributeKeyID, fmt.Sprintf("%d", plan.ID)), + sdk.NewAttribute(types.AttributeKeyAddress, plan.Provider.String()), + )) + + k.SetPlansCount(ctx, count+1) + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeSetPlansCount, + sdk.NewAttribute(types.AttributeKeyCount, fmt.Sprintf("%d", count+1)), + )) + + return sdk.Result{Events: ctx.EventManager().Events()} +} + +func HandleSetPlanStatus(ctx sdk.Context, k keeper.Keeper, msg types.MsgSetPlanStatus) sdk.Result { + plan, found := k.GetPlan(ctx, msg.ID) + if !found { + return types.ErrorPlanDoesNotExist().Result() + } + if !msg.From.Equals(plan.Provider) { + return types.ErrorUnauthorized().Result() + } + + plan.Status = msg.Status + plan.StatusAt = ctx.BlockTime() + + k.SetPlan(ctx, plan) + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeSetPlanStatus, + sdk.NewAttribute(types.AttributeKeyID, fmt.Sprintf("%d", plan.ID)), + sdk.NewAttribute(types.AttributeKeyStatus, plan.Status.String()), + )) + + return sdk.Result{Events: ctx.EventManager().Events()} +} + +func HandleAddNodeForPlan(ctx sdk.Context, k keeper.Keeper, msg types.MsgAddNodeForPlan) sdk.Result { + plan, found := k.GetPlan(ctx, msg.ID) + if !found { + return types.ErrorPlanDoesNotExist().Result() + } + if !msg.From.Equals(plan.Provider) { + return types.ErrorUnauthorized().Result() + } + + node, found := k.GetNode(ctx, msg.Address) + if !found { + return types.ErrorNodeDoesNotExist().Result() + } + if !msg.From.Equals(node.Provider) { + return types.ErrorUnauthorized().Result() + } + + if k.HasNodeForPlan(ctx, plan.ID, node.Address) { + return types.ErrorDuplicateNode().Result() + } + + k.SetNodeForPlan(ctx, plan.ID, node.Address) + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeAddNodeForPlan, + sdk.NewAttribute(types.AttributeKeyID, fmt.Sprintf("%d", plan.ID)), + sdk.NewAttribute(types.AttributeKeyAddress, node.Address.String()), + )) + + return sdk.Result{Events: ctx.EventManager().Events()} +} + +func HandleRemoveNodeForPlan(ctx sdk.Context, k keeper.Keeper, msg types.MsgRemoveNodeForPlan) sdk.Result { + plan, found := k.GetPlan(ctx, msg.ID) + if !found { + return types.ErrorPlanDoesNotExist().Result() + } + if !msg.From.Equals(plan.Provider) { + return types.ErrorUnauthorized().Result() + } + + if !k.HasNodeForPlan(ctx, plan.ID, msg.Address) { + return types.ErrorNodeWasNotAdded().Result() + } + + k.DeleteNodeForPlan(ctx, plan.ID, msg.Address) + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeRemoveNodeForPlan, + sdk.NewAttribute(types.AttributeKeyID, fmt.Sprintf("%d", plan.ID)), + sdk.NewAttribute(types.AttributeKeyAddress, msg.Address.String()), + )) + + return sdk.Result{Events: ctx.EventManager().Events()} +} diff --git a/x/dvpn/plan/keeper/alias.go b/x/dvpn/plan/keeper/alias.go new file mode 100644 index 00000000..f123f5e1 --- /dev/null +++ b/x/dvpn/plan/keeper/alias.go @@ -0,0 +1,16 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" + node "github.com/sentinel-official/hub/x/dvpn/node/types" +) + +func (k Keeper) HasProvider(ctx sdk.Context, address hub.ProvAddress) bool { + return k.provider.HasProvider(ctx, address) +} + +func (k Keeper) GetNode(ctx sdk.Context, address hub.NodeAddress) (node.Node, bool) { + return k.node.GetNode(ctx, address) +} diff --git a/x/dvpn/plan/keeper/keeper.go b/x/dvpn/plan/keeper/keeper.go new file mode 100644 index 00000000..1bcf95a0 --- /dev/null +++ b/x/dvpn/plan/keeper/keeper.go @@ -0,0 +1,39 @@ +package keeper + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store/prefix" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/sentinel-official/hub/x/dvpn/plan/expected" + "github.com/sentinel-official/hub/x/dvpn/plan/types" +) + +type Keeper struct { + cdc *codec.Codec + key sdk.StoreKey + provider expected.ProviderKeeper + node expected.NodeKeeper +} + +func NewKeeper(cdc *codec.Codec, key sdk.StoreKey) Keeper { + return Keeper{ + cdc: cdc, + key: key, + } +} + +func (k *Keeper) WithProviderKeeper(keeper expected.ProviderKeeper) { + k.provider = keeper +} + +func (k *Keeper) WithNodeKeeper(keeper expected.NodeKeeper) { + k.node = keeper +} + +func (k Keeper) Store(ctx sdk.Context) sdk.KVStore { + child := fmt.Sprintf("%s/", types.ModuleName) + return prefix.NewStore(ctx.KVStore(k.key), []byte(child)) +} diff --git a/x/dvpn/plan/keeper/plan.go b/x/dvpn/plan/keeper/plan.go new file mode 100644 index 00000000..e3b8e55a --- /dev/null +++ b/x/dvpn/plan/keeper/plan.go @@ -0,0 +1,130 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" + node "github.com/sentinel-official/hub/x/dvpn/node/types" + "github.com/sentinel-official/hub/x/dvpn/plan/types" +) + +func (k Keeper) SetPlansCount(ctx sdk.Context, count uint64) { + key := types.PlansCountKey + value := k.cdc.MustMarshalBinaryLengthPrefixed(count) + + store := k.Store(ctx) + store.Set(key, value) +} + +func (k Keeper) GetPlansCount(ctx sdk.Context) (count uint64) { + store := k.Store(ctx) + + key := types.PlansCountKey + value := store.Get(key) + if value == nil { + return 0 + } + + k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &count) + return count +} + +func (k Keeper) SetPlan(ctx sdk.Context, plan types.Plan) { + key := types.PlanKey(plan.ID) + value := k.cdc.MustMarshalBinaryLengthPrefixed(plan) + + store := k.Store(ctx) + store.Set(key, value) +} + +func (k Keeper) GetPlan(ctx sdk.Context, id uint64) (plan types.Plan, found bool) { + store := k.Store(ctx) + + key := types.PlanKey(id) + value := store.Get(key) + if value == nil { + return plan, false + } + + k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &plan) + return plan, true +} + +func (k Keeper) GetPlans(ctx sdk.Context) (items types.Plans) { + store := k.Store(ctx) + + iter := sdk.KVStorePrefixIterator(store, types.PlanKeyPrefix) + defer iter.Close() + + for ; iter.Valid(); iter.Next() { + var item types.Plan + k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &item) + items = append(items, item) + } + + return items +} + +func (k Keeper) SetPlanForProvider(ctx sdk.Context, address hub.ProvAddress, id uint64) { + key := types.PlanForProviderKey(address, id) + value := k.cdc.MustMarshalBinaryLengthPrefixed(id) + + store := k.Store(ctx) + store.Set(key, value) +} + +func (k Keeper) GetPlansForProvider(ctx sdk.Context, address hub.ProvAddress) (items types.Plans) { + store := k.Store(ctx) + + iter := sdk.KVStorePrefixIterator(store, types.PlanForProviderKeyPrefix(address)) + defer iter.Close() + + for ; iter.Valid(); iter.Next() { + var id uint64 + k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &id) + + item, _ := k.GetPlan(ctx, id) + items = append(items, item) + } + + return items +} + +func (k Keeper) SetNodeForPlan(ctx sdk.Context, id uint64, address hub.NodeAddress) { + key := types.NodeForPlanKey(id, address) + value := k.cdc.MustMarshalBinaryLengthPrefixed(address) + + store := k.Store(ctx) + store.Set(key, value) +} + +func (k Keeper) HasNodeForPlan(ctx sdk.Context, id uint64, address hub.NodeAddress) bool { + store := k.Store(ctx) + + key := types.NodeForPlanKey(id, address) + return store.Has(key) +} + +func (k Keeper) DeleteNodeForPlan(ctx sdk.Context, id uint64, address hub.NodeAddress) { + store := k.Store(ctx) + + key := types.NodeForPlanKey(id, address) + store.Delete(key) +} + +func (k Keeper) GetNodesForPlan(ctx sdk.Context, id uint64) (items node.Nodes) { + store := k.Store(ctx) + + iter := sdk.KVStorePrefixIterator(store, types.NodeForPlanKeyPrefix(id)) + defer iter.Close() + + for ; iter.Valid(); iter.Next() { + var address hub.NodeAddress + k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &address) + + item, _ := k.GetNode(ctx, address) + items = append(items, item) + } + + return items +} diff --git a/x/dvpn/plan/querier/plan.go b/x/dvpn/plan/querier/plan.go new file mode 100644 index 00000000..1f5f978a --- /dev/null +++ b/x/dvpn/plan/querier/plan.go @@ -0,0 +1,65 @@ +package querier + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/sentinel-official/hub/x/dvpn/plan/keeper" + "github.com/sentinel-official/hub/x/dvpn/plan/types" +) + +func queryPlan(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + var params types.QueryPlanParams + if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { + return nil, types.ErrorUnmarshal() + } + + plan, found := k.GetPlan(ctx, params.ID) + if !found { + return nil, nil + } + + res, err := types.ModuleCdc.MarshalJSON(plan) + if err != nil { + return nil, types.ErrorMarshal() + } + + return res, nil +} + +func queryPlans(ctx sdk.Context, _ abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + res, err := types.ModuleCdc.MarshalJSON(k.GetPlans(ctx)) + if err != nil { + return nil, types.ErrorMarshal() + } + + return res, nil +} + +func queryPlansForProvider(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + var params types.QueryPlansForProviderParams + if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { + return nil, types.ErrorUnmarshal() + } + + res, err := types.ModuleCdc.MarshalJSON(k.GetPlansForProvider(ctx, params.Address)) + if err != nil { + return nil, types.ErrorMarshal() + } + + return res, nil +} + +func queryNodesForPlan(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + var params types.QueryNodesForPlanParams + if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { + return nil, types.ErrorUnmarshal() + } + + res, err := types.ModuleCdc.MarshalJSON(k.GetNodesForPlan(ctx, params.ID)) + if err != nil { + return nil, types.ErrorMarshal() + } + + return res, nil +} diff --git a/x/dvpn/plan/querier/querier.go b/x/dvpn/plan/querier/querier.go new file mode 100644 index 00000000..147ffb11 --- /dev/null +++ b/x/dvpn/plan/querier/querier.go @@ -0,0 +1,24 @@ +package querier + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/sentinel-official/hub/x/dvpn/plan/keeper" + "github.com/sentinel-official/hub/x/dvpn/plan/types" +) + +func Querier(ctx sdk.Context, path []string, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + switch path[0] { + case types.QueryPlan: + return queryPlan(ctx, req, k) + case types.QueryPlans: + return queryPlans(ctx, req, k) + case types.QueryPlansForProvider: + return queryPlansForProvider(ctx, req, k) + case types.QueryNodesForPlan: + return queryNodesForPlan(ctx, req, k) + default: + return nil, types.ErrorUnknownQueryType(path[0]) + } +} diff --git a/x/dvpn/plan/types/codec.go b/x/dvpn/plan/types/codec.go new file mode 100644 index 00000000..41e88ce5 --- /dev/null +++ b/x/dvpn/plan/types/codec.go @@ -0,0 +1,23 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec" +) + +var ( + ModuleCdc *codec.Codec +) + +func init() { + ModuleCdc = codec.New() + codec.RegisterCrypto(ModuleCdc) + RegisterCodec(ModuleCdc) + ModuleCdc.Seal() +} + +func RegisterCodec(cdc *codec.Codec) { + cdc.RegisterConcrete(MsgAddPlan{}, "sentinel/MsgAddPlan", nil) + cdc.RegisterConcrete(MsgSetPlanStatus{}, "sentinel/MsgSetPlanStatus", nil) + cdc.RegisterConcrete(MsgAddNodeForPlan{}, "sentinel/MsgAddNodeForPlan", nil) + cdc.RegisterConcrete(MsgRemoveNodeForPlan{}, "sentinel/MsgRemoveNodeForPlan", nil) +} diff --git a/x/dvpn/plan/types/errors.go b/x/dvpn/plan/types/errors.go new file mode 100644 index 00000000..928898b8 --- /dev/null +++ b/x/dvpn/plan/types/errors.go @@ -0,0 +1,81 @@ +package types + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +const ( + Codespace = sdk.CodespaceType(ModuleName) +) + +const ( + errorCodeUnknownMsgType = iota + 101 + errorCodeUnknownQueryType + errorCodeInvalidField + errorCodeProviderDoesNotExist + errorCodePlanDoesNotExist + errorCodeNodeDoesNotExist + errorCodeUnauthorized + errorCodeDuplicateNode + errorCodeNodeWasNotAdded +) + +const ( + errorMsgUnknownMsgType = "unknown message type: %s" + errorMsgUnknownQueryType = "unknown query type: %s" + errorMsgInvalidField = "invalid field: %s" + errorMsgProviderDoesNotExist = "provider does not exist" + errorMsgPlanDoesNotExist = "plan does not exist" + errorMsgNodeDoesNotExist = "node does not exist" + errorMsgUnauthorized = "unauthorized" + errorMsgDuplicateNode = "duplicate node" + errorMsgNodeWasNotAdded = "node was not added" +) + +func ErrorMarshal() sdk.Error { + return sdk.NewError(Codespace, hub.ErrorCodeMarshal, hub.ErrorMsgMarshal) +} + +func ErrorUnmarshal() sdk.Error { + return sdk.NewError(Codespace, hub.ErrorCodeUnmarshal, hub.ErrorMsgUnmarshal) +} + +func ErrorUnknownMsgType(v string) sdk.Error { + return sdk.NewError(Codespace, errorCodeUnknownMsgType, fmt.Sprintf(errorMsgUnknownMsgType, v)) +} + +func ErrorUnknownQueryType(v string) sdk.Error { + return sdk.NewError(Codespace, errorCodeUnknownQueryType, fmt.Sprintf(errorMsgUnknownQueryType, v)) +} + +func ErrorInvalidField(v string) sdk.Error { + return sdk.NewError(Codespace, errorCodeInvalidField, fmt.Sprintf(errorMsgInvalidField, v)) +} + +func ErrorProviderDoesNotExist() sdk.Error { + return sdk.NewError(Codespace, errorCodeProviderDoesNotExist, errorMsgProviderDoesNotExist) +} + +func ErrorPlanDoesNotExist() sdk.Error { + return sdk.NewError(Codespace, errorCodePlanDoesNotExist, errorMsgPlanDoesNotExist) +} + +func ErrorNodeDoesNotExist() sdk.Error { + return sdk.NewError(Codespace, errorCodeNodeDoesNotExist, errorMsgNodeDoesNotExist) +} + +func ErrorUnauthorized() sdk.Error { + return sdk.NewError(Codespace, errorCodeUnauthorized, errorMsgUnauthorized) +} + +func ErrorDuplicateNode() sdk.Error { + return sdk.NewError(Codespace, errorCodeDuplicateNode, errorMsgDuplicateNode) +} + +func ErrorNodeWasNotAdded() sdk.Error { + return sdk.NewError(Codespace, errorCodeNodeWasNotAdded, errorMsgNodeWasNotAdded) +} diff --git a/x/dvpn/plan/types/events.go b/x/dvpn/plan/types/events.go new file mode 100644 index 00000000..ae9447f4 --- /dev/null +++ b/x/dvpn/plan/types/events.go @@ -0,0 +1,16 @@ +package types + +const ( + EventTypeSetPlan = "set_plan" + EventTypeSetPlansCount = "set_plans_count" + EventTypeSetPlanStatus = "set_plan_status" + EventTypeAddNodeForPlan = "add_node_for_plan" + EventTypeRemoveNodeForPlan = "remove_node_for_plan" +) + +const ( + AttributeKeyAddress = "address" + AttributeKeyID = "id" + AttributeKeyCount = "count" + AttributeKeyStatus = "status" +) diff --git a/x/dvpn/plan/types/genesis.go b/x/dvpn/plan/types/genesis.go new file mode 100644 index 00000000..894954c1 --- /dev/null +++ b/x/dvpn/plan/types/genesis.go @@ -0,0 +1,22 @@ +package types + +import ( + hub "github.com/sentinel-official/hub/types" +) + +type GenesisPlan struct { + Plan Plan `json:"_"` + Nodes []hub.NodeAddress `json:"nodes"` +} + +type GenesisPlans []GenesisPlan + +type GenesisState = GenesisPlans + +func NewGenesisState(plans GenesisPlans) GenesisState { + return plans +} + +func DefaultGenesisState() GenesisState { + return GenesisState{} +} diff --git a/x/dvpn/plan/types/keys.go b/x/dvpn/plan/types/keys.go new file mode 100644 index 00000000..275d089e --- /dev/null +++ b/x/dvpn/plan/types/keys.go @@ -0,0 +1,42 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +const ( + ModuleName = "plan" + QuerierRoute = ModuleName +) + +var ( + RouterKey = ModuleName + StoreKey = ModuleName +) + +var ( + PlansCountKey = []byte{0x00} + PlanKeyPrefix = []byte{0x01} +) + +func PlanKey(i uint64) []byte { + return append(PlanKeyPrefix, sdk.Uint64ToBigEndian(i)...) +} + +func PlanForProviderKeyPrefix(address hub.ProvAddress) []byte { + return append([]byte{0x02}, address.Bytes()...) +} + +func PlanForProviderKey(address hub.ProvAddress, id uint64) []byte { + return append(PlanForProviderKeyPrefix(address), sdk.Uint64ToBigEndian(id)...) +} + +func NodeForPlanKeyPrefix(id uint64) []byte { + return append([]byte{0x03}, sdk.Uint64ToBigEndian(id)...) +} + +func NodeForPlanKey(id uint64, address hub.NodeAddress) []byte { + return append(NodeForPlanKeyPrefix(id), address.Bytes()...) +} diff --git a/x/dvpn/plan/types/msg.go b/x/dvpn/plan/types/msg.go new file mode 100644 index 00000000..25ca453b --- /dev/null +++ b/x/dvpn/plan/types/msg.go @@ -0,0 +1,248 @@ +package types + +import ( + "encoding/json" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +var ( + _ sdk.Msg = (*MsgAddPlan)(nil) + _ sdk.Msg = (*MsgSetPlanStatus)(nil) + _ sdk.Msg = (*MsgAddNodeForPlan)(nil) + _ sdk.Msg = (*MsgRemoveNodeForPlan)(nil) +) + +// MsgAddPlan is adding a subscription plan. +type MsgAddPlan struct { + From hub.ProvAddress `json:"from"` + Price sdk.Coins `json:"price"` + Validity time.Duration `json:"validity"` + Bandwidth hub.Bandwidth `json:"bandwidth"` + Duration time.Duration `json:"duration"` +} + +func NewMsgAddPlan(from hub.ProvAddress, price sdk.Coins, validity time.Duration, + bandwidth hub.Bandwidth, duration time.Duration) MsgAddPlan { + return MsgAddPlan{ + From: from, + Price: price, + Validity: validity, + Bandwidth: bandwidth, + Duration: duration, + } +} + +func (m MsgAddPlan) Route() string { + return RouterKey +} + +func (m MsgAddPlan) Type() string { + return "add_plan" +} + +func (m MsgAddPlan) ValidateBasic() sdk.Error { + if m.From == nil || m.From.Empty() { + return ErrorInvalidField("from") + } + + // Price can be nil. If not, it should be valid + if m.Price != nil && !m.Price.IsValid() { + return ErrorInvalidField("price") + } + + // Validity shouldn't be negative and zero + if m.Validity <= 0 { + return ErrorInvalidField("validity") + } + + // Bandwidth shouldn't be negative and zero + if !m.Bandwidth.IsValid() { + return ErrorInvalidField("bandwidth") + } + + // Duration shouldn't be negative and zero + if m.Duration <= 0 { + return ErrorInvalidField("duration") + } + + return nil +} + +func (m MsgAddPlan) GetSignBytes() []byte { + bytes, err := json.Marshal(m) + if err != nil { + panic(err) + } + + return bytes +} + +func (m MsgAddPlan) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{m.From.Bytes()} +} + +// MsgSetPlanStatus is for updating the status of a plan. +type MsgSetPlanStatus struct { + From hub.ProvAddress `json:"from"` + ID uint64 `json:"id"` + Status hub.Status `json:"status"` +} + +func NewMsgSetPlanStatus(from hub.ProvAddress, id uint64, status hub.Status) MsgSetPlanStatus { + return MsgSetPlanStatus{ + From: from, + ID: id, + Status: status, + } +} + +func (m MsgSetPlanStatus) Route() string { + return RouterKey +} + +func (m MsgSetPlanStatus) Type() string { + return "set_plan_status" +} + +func (m MsgSetPlanStatus) ValidateBasic() sdk.Error { + if m.From == nil || m.From.Empty() { + return ErrorInvalidField("from") + } + + // ID shouldn't be zero + if m.ID == 0 { + return ErrorInvalidField("id") + } + + // Status should be valid + if !m.Status.IsValid() { + return ErrorInvalidField("status") + } + + return nil +} + +func (m MsgSetPlanStatus) GetSignBytes() []byte { + bytes, err := json.Marshal(m) + if err != nil { + panic(err) + } + + return bytes +} + +func (m MsgSetPlanStatus) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{m.From.Bytes()} +} + +// MsgAddNodeForPlan is for adding a node for a plan. +type MsgAddNodeForPlan struct { + From hub.ProvAddress `json:"from"` + ID uint64 `json:"id"` + Address hub.NodeAddress `json:"address"` +} + +func NewMsgAddNodeForPlan(from hub.ProvAddress, id uint64, address hub.NodeAddress) MsgAddNodeForPlan { + return MsgAddNodeForPlan{ + From: from, + ID: id, + Address: address, + } +} + +func (m MsgAddNodeForPlan) Route() string { + return RouterKey +} + +func (m MsgAddNodeForPlan) Type() string { + return "add_node_for_plan" +} + +func (m MsgAddNodeForPlan) ValidateBasic() sdk.Error { + if m.From == nil || m.From.Empty() { + return ErrorInvalidField("from") + } + + // ID shouldn't be zero + if m.ID == 0 { + return ErrorInvalidField("id") + } + + // Address shouldn't be nil or empty + if m.Address == nil || m.Address.Empty() { + return ErrorInvalidField("address") + } + + return nil +} + +func (m MsgAddNodeForPlan) GetSignBytes() []byte { + bytes, err := json.Marshal(m) + if err != nil { + panic(err) + } + + return bytes +} + +func (m MsgAddNodeForPlan) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{m.From.Bytes()} +} + +// MsgRemoveNodeForPlan is for removing a node for a plan. +type MsgRemoveNodeForPlan struct { + From hub.ProvAddress `json:"from"` + ID uint64 `json:"id"` + Address hub.NodeAddress `json:"address"` +} + +func NewMsgRemoveNodeForPlan(from hub.ProvAddress, id uint64, address hub.NodeAddress) MsgRemoveNodeForPlan { + return MsgRemoveNodeForPlan{ + From: from, + ID: id, + Address: address, + } +} + +func (m MsgRemoveNodeForPlan) Route() string { + return RouterKey +} + +func (m MsgRemoveNodeForPlan) Type() string { + return "remove_node_for_plan" +} + +func (m MsgRemoveNodeForPlan) ValidateBasic() sdk.Error { + if m.From == nil || m.From.Empty() { + return ErrorInvalidField("from") + } + + // ID shouldn't be zero + if m.ID == 0 { + return ErrorInvalidField("id") + } + + // Address shouldn't be nil or empty + if m.Address == nil || m.Address.Empty() { + return ErrorInvalidField("address") + } + + return nil +} + +func (m MsgRemoveNodeForPlan) GetSignBytes() []byte { + bytes, err := json.Marshal(m) + if err != nil { + panic(err) + } + + return bytes +} + +func (m MsgRemoveNodeForPlan) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{m.From.Bytes()} +} diff --git a/x/dvpn/plan/types/plan.go b/x/dvpn/plan/types/plan.go new file mode 100644 index 00000000..06c1809a --- /dev/null +++ b/x/dvpn/plan/types/plan.go @@ -0,0 +1,47 @@ +package types + +import ( + "fmt" + "strings" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +type Plan struct { + ID uint64 `json:"id"` + Provider hub.ProvAddress `json:"provider"` + Price sdk.Coins `json:"price"` + Validity time.Duration `json:"validity"` + Bandwidth hub.Bandwidth `json:"bandwidth"` + Duration time.Duration `json:"duration"` + Status hub.Status `json:"status"` + StatusAt time.Time `json:"status_at"` +} + +func (p Plan) String() string { + return strings.TrimSpace(fmt.Sprintf(` +ID: %d +Provider: %s +Price: %s +Validity: %s +Bandwidth: %s +Duration: %s +Status: %s +Status at: %s +`, p.ID, p.Provider, p.Price, p.Validity, p.Bandwidth, p.Duration, p.Status, p.StatusAt)) +} + +func (p Plan) PriceForDenom(s string) (sdk.Coin, bool) { + for _, coin := range p.Price { + if coin.Denom == s { + return coin, true + } + } + + return sdk.Coin{}, false +} + +type Plans []Plan diff --git a/x/dvpn/plan/types/querier.go b/x/dvpn/plan/types/querier.go new file mode 100644 index 00000000..14c7dbc7 --- /dev/null +++ b/x/dvpn/plan/types/querier.go @@ -0,0 +1,42 @@ +package types + +import ( + hub "github.com/sentinel-official/hub/types" +) + +const ( + QueryPlan = "query_plan" + QueryPlans = "query_plans" + QueryPlansForProvider = "query_plans_for_provider" + QueryNodesForPlan = "query_nodes_for_plan" +) + +type QueryPlanParams struct { + ID uint64 `json:"id"` +} + +func NewQueryPlanParams(id uint64) QueryPlanParams { + return QueryPlanParams{ + ID: id, + } +} + +type QueryPlansForProviderParams struct { + Address hub.ProvAddress `json:"address"` +} + +func NewQueryPlansForProviderParams(address hub.ProvAddress) QueryPlansForProviderParams { + return QueryPlansForProviderParams{ + Address: address, + } +} + +type QueryNodesForPlanParams struct { + ID uint64 `json:"id"` +} + +func NewQueryNodesForPlanParams(id uint64) QueryNodesForPlanParams { + return QueryNodesForPlanParams{ + ID: id, + } +} diff --git a/x/dvpn/provider/alias.go b/x/dvpn/provider/alias.go new file mode 100644 index 00000000..06952399 --- /dev/null +++ b/x/dvpn/provider/alias.go @@ -0,0 +1,60 @@ +// nolint +// autogenerated code using github.com/rigelrozanski/multitool +// aliases generated for the following subdirectories: +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/provider/types +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/provider/keeper +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/provider/querier +package provider + +import ( + "github.com/sentinel-official/hub/x/dvpn/provider/keeper" + "github.com/sentinel-official/hub/x/dvpn/provider/querier" + "github.com/sentinel-official/hub/x/dvpn/provider/types" +) + +const ( + Codespace = types.Codespace + EventTypeSetProvider = types.EventTypeSetProvider + EventTypeUpdateProvider = types.EventTypeUpdateProvider + AttributeKeyAddress = types.AttributeKeyAddress + ModuleName = types.ModuleName + QuerierRoute = types.QuerierRoute + QueryProvider = types.QueryProvider + QueryProviders = types.QueryProviders +) + +var ( + // functions aliases + RegisterCodec = types.RegisterCodec + ErrorMarshal = types.ErrorMarshal + ErrorUnmarshal = types.ErrorUnmarshal + ErrorUnknownMsgType = types.ErrorUnknownMsgType + ErrorUnknownQueryType = types.ErrorUnknownQueryType + ErrorInvalidField = types.ErrorInvalidField + ErrorDuplicateProvider = types.ErrorDuplicateProvider + ErrorProviderDoesNotExist = types.ErrorProviderDoesNotExist + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + ProviderKey = types.ProviderKey + NewMsgRegisterProvider = types.NewMsgRegisterProvider + NewMsgUpdateProvider = types.NewMsgUpdateProvider + NewQueryProviderParams = types.NewQueryProviderParams + NewKeeper = keeper.NewKeeper + Querier = querier.Querier + + // variable aliases + ModuleCdc = types.ModuleCdc + RouterKey = types.RouterKey + StoreKey = types.StoreKey + ProviderKeyPrefix = types.ProviderKeyPrefix +) + +type ( + GenesisState = types.GenesisState + MsgRegisterProvider = types.MsgRegisterProvider + MsgUpdateProvider = types.MsgUpdateProvider + Provider = types.Provider + Providers = types.Providers + QueryProviderParams = types.QueryProviderParams + Keeper = keeper.Keeper +) diff --git a/x/dvpn/provider/client/cli/cli.go b/x/dvpn/provider/client/cli/cli.go new file mode 100644 index 00000000..0d374445 --- /dev/null +++ b/x/dvpn/provider/client/cli/cli.go @@ -0,0 +1,28 @@ +package cli + +import ( + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/spf13/cobra" +) + +func GetQueryCommands(cdc *codec.Codec) []*cobra.Command { + return client.GetCommands( + queryProviderCmd(cdc), + queryProvidersCmd(cdc), + ) +} + +func GetTxCommands(cdc *codec.Codec) []*cobra.Command { + cmd := &cobra.Command{ + Use: "provider", + Short: "Provider module sub-commands", + } + + cmd.AddCommand(client.PostCommands( + txRegisterProviderCmd(cdc), + txUpdateProviderCmd(cdc), + )...) + + return []*cobra.Command{cmd} +} diff --git a/x/dvpn/provider/client/cli/flags.go b/x/dvpn/provider/client/cli/flags.go new file mode 100644 index 00000000..74f1d710 --- /dev/null +++ b/x/dvpn/provider/client/cli/flags.go @@ -0,0 +1,8 @@ +package cli + +const ( + flagName = "name" + flagIdentity = "identity" + flagWebsite = "website" + flagDescription = "description" +) diff --git a/x/dvpn/provider/client/cli/query.go b/x/dvpn/provider/client/cli/query.go new file mode 100644 index 00000000..20638bd3 --- /dev/null +++ b/x/dvpn/provider/client/cli/query.go @@ -0,0 +1,57 @@ +package cli + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/spf13/cobra" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/provider/client/common" +) + +func queryProviderCmd(cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "provider", + Short: "Query a provider", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.NewCLIContext().WithCodec(cdc) + + address, err := hub.ProvAddressFromBech32(args[0]) + if err != nil { + return err + } + + provider, err := common.QueryProvider(ctx, address) + if err != nil { + return err + } + + fmt.Println(provider) + return nil + }, + } +} + +func queryProvidersCmd(cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "providers", + Short: "Query providers", + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.NewCLIContext().WithCodec(cdc) + + providers, err := common.QueryProviders(ctx) + if err != nil { + return err + } + + for _, provider := range providers { + fmt.Println(provider) + } + + return nil + }, + } +} diff --git a/x/dvpn/provider/client/cli/tx.go b/x/dvpn/provider/client/cli/tx.go new file mode 100644 index 00000000..8c0d8988 --- /dev/null +++ b/x/dvpn/provider/client/cli/tx.go @@ -0,0 +1,96 @@ +package cli + +import ( + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/client/utils" + "github.com/spf13/cobra" + + "github.com/sentinel-official/hub/x/dvpn/provider/types" +) + +func txRegisterProviderCmd(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "register", + Short: "Register a provider", + RunE: func(cmd *cobra.Command, args []string) error { + txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + ctx := context.NewCLIContext().WithCodec(cdc) + + name, err := cmd.Flags().GetString(flagName) + if err != nil { + return err + } + + identity, err := cmd.Flags().GetString(flagIdentity) + if err != nil { + return err + } + + website, err := cmd.Flags().GetString(flagWebsite) + if err != nil { + return err + } + + description, err := cmd.Flags().GetString(flagDescription) + if err != nil { + return err + } + + msg := types.NewMsgRegisterProvider(ctx.FromAddress, name, identity, website, description) + return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) + }, + } + + cmd.Flags().String(flagName, "", "Provider name") + cmd.Flags().String(flagIdentity, "", "Provider identity") + cmd.Flags().String(flagWebsite, "", "Provider website") + cmd.Flags().String(flagDescription, "", "Provider description") + + _ = cmd.MarkFlagRequired(flagName) + + return cmd +} + +func txUpdateProviderCmd(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "update", + Short: "Update a provider", + RunE: func(cmd *cobra.Command, args []string) error { + txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + ctx := context.NewCLIContext().WithCodec(cdc) + + name, err := cmd.Flags().GetString(flagName) + if err != nil { + return err + } + + identity, err := cmd.Flags().GetString(flagIdentity) + if err != nil { + return err + } + + website, err := cmd.Flags().GetString(flagWebsite) + if err != nil { + return err + } + + description, err := cmd.Flags().GetString(flagDescription) + if err != nil { + return err + } + + msg := types.NewMsgUpdateProvider(ctx.FromAddress.Bytes(), name, identity, website, description) + return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) + }, + } + + cmd.Flags().String(flagName, "", "Provider name") + cmd.Flags().String(flagIdentity, "", "Provider identity") + cmd.Flags().String(flagWebsite, "", "Provider website") + cmd.Flags().String(flagDescription, "", "Provider description") + + return cmd +} diff --git a/x/dvpn/provider/client/common/query.go b/x/dvpn/provider/client/common/query.go new file mode 100644 index 00000000..d65221fc --- /dev/null +++ b/x/dvpn/provider/client/common/query.go @@ -0,0 +1,52 @@ +package common + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/client/context" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/provider/types" +) + +func QueryProvider(ctx context.CLIContext, address hub.ProvAddress) (*types.Provider, error) { + params := types.NewQueryProviderParams(address) + bytes, err := ctx.Codec.MarshalJSON(params) + if err != nil { + return nil, err + } + + path := fmt.Sprintf("custom/%s/%s/%s", types.StoreKey, types.QuerierRoute, types.QueryProvider) + res, _, err := ctx.QueryWithData(path, bytes) + if err != nil { + return nil, err + } + if res == nil { + return nil, fmt.Errorf("no provider found") + } + + var provider types.Provider + if err := ctx.Codec.UnmarshalJSON(res, &provider); err != nil { + return nil, err + } + + return &provider, nil +} + +func QueryProviders(ctx context.CLIContext) (types.Providers, error) { + path := fmt.Sprintf("custom/%s/%s/%s", types.StoreKey, types.QuerierRoute, types.QueryProviders) + res, _, err := ctx.QueryWithData(path, nil) + if err != nil { + return nil, err + } + if res == nil { + return nil, fmt.Errorf("no providers found") + } + + var providers types.Providers + if err := ctx.Codec.UnmarshalJSON(res, &providers); err != nil { + return nil, err + } + + return providers, nil +} diff --git a/x/dvpn/provider/client/rest/query.go b/x/dvpn/provider/client/rest/query.go new file mode 100644 index 00000000..bed3cb05 --- /dev/null +++ b/x/dvpn/provider/client/rest/query.go @@ -0,0 +1,19 @@ +package rest + +import ( + "net/http" + + "github.com/cosmos/cosmos-sdk/client/context" +) + +func queryProviderHandlerFunc(ctx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + } +} + +func queryProvidersHandlerFunc(ctx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + } +} diff --git a/x/dvpn/provider/client/rest/rest.go b/x/dvpn/provider/client/rest/rest.go new file mode 100644 index 00000000..bb53a162 --- /dev/null +++ b/x/dvpn/provider/client/rest/rest.go @@ -0,0 +1,23 @@ +package rest + +import ( + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/gorilla/mux" +) + +func registerQueryRoutes(ctx context.CLIContext, router *mux.Router) { + router.HandleFunc("/providers", queryProvidersHandlerFunc(ctx)). + Methods("GET") + router.HandleFunc("/providers/{address}", queryProviderHandlerFunc(ctx)). + Methods("GET") +} + +func registerTxRoutes(ctx context.CLIContext, router *mux.Router) { + router.HandleFunc("/providers", txRegisterProviderHandlerFunc(ctx)). + Methods("POST") +} + +func RegisterRoutes(ctx context.CLIContext, router *mux.Router) { + registerQueryRoutes(ctx, router) + registerTxRoutes(ctx, router) +} diff --git a/x/dvpn/provider/client/rest/tx.go b/x/dvpn/provider/client/rest/tx.go new file mode 100644 index 00000000..f0d0081e --- /dev/null +++ b/x/dvpn/provider/client/rest/tx.go @@ -0,0 +1,13 @@ +package rest + +import ( + "net/http" + + "github.com/cosmos/cosmos-sdk/client/context" +) + +func txRegisterProviderHandlerFunc(ctx context.CLIContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + + } +} diff --git a/x/dvpn/provider/genesis.go b/x/dvpn/provider/genesis.go new file mode 100644 index 00000000..9fcb8615 --- /dev/null +++ b/x/dvpn/provider/genesis.go @@ -0,0 +1,22 @@ +package provider + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/sentinel-official/hub/x/dvpn/provider/keeper" + "github.com/sentinel-official/hub/x/dvpn/provider/types" +) + +func InitGenesis(ctx sdk.Context, k keeper.Keeper, state types.GenesisState) { + for _, provider := range state { + k.SetProvider(ctx, provider) + } +} + +func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { + return k.GetProviders(ctx) +} + +func ValidateGenesis(state types.GenesisState) error { + return nil +} diff --git a/x/dvpn/provider/handler.go b/x/dvpn/provider/handler.go new file mode 100644 index 00000000..123edfb4 --- /dev/null +++ b/x/dvpn/provider/handler.go @@ -0,0 +1,59 @@ +package provider + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/sentinel-official/hub/x/dvpn/provider/keeper" + "github.com/sentinel-official/hub/x/dvpn/provider/types" +) + +func HandleRegisterProvider(ctx sdk.Context, k keeper.Keeper, msg types.MsgRegisterProvider) sdk.Result { + _, found := k.GetProvider(ctx, msg.From.Bytes()) + if found { + return types.ErrorDuplicateProvider().Result() + } + + provider := types.Provider{ + Address: msg.From.Bytes(), + Name: msg.Name, + Identity: msg.Identity, + Website: msg.Website, + Description: msg.Description, + } + + k.SetProvider(ctx, provider) + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeSetProvider, + sdk.NewAttribute(types.AttributeKeyAddress, provider.Address.String()), + )) + + return sdk.Result{Events: ctx.EventManager().Events()} +} + +func HandleUpdateProvider(ctx sdk.Context, k keeper.Keeper, msg types.MsgUpdateProvider) sdk.Result { + provider, found := k.GetProvider(ctx, msg.From) + if !found { + return types.ErrorProviderDoesNotExist().Result() + } + + if len(msg.Name) > 0 { + provider.Name = msg.Name + } + if len(msg.Identity) > 0 { + provider.Identity = msg.Identity + } + if len(msg.Website) > 0 { + provider.Website = msg.Website + } + if len(msg.Description) > 0 { + provider.Description = msg.Description + } + + k.SetProvider(ctx, provider) + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeUpdateProvider, + sdk.NewAttribute(types.AttributeKeyAddress, provider.Address.String()), + )) + + return sdk.Result{Events: ctx.EventManager().Events()} +} diff --git a/x/dvpn/provider/keeper/keeper.go b/x/dvpn/provider/keeper/keeper.go new file mode 100644 index 00000000..fcd46ee1 --- /dev/null +++ b/x/dvpn/provider/keeper/keeper.go @@ -0,0 +1,28 @@ +package keeper + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store/prefix" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/sentinel-official/hub/x/dvpn/provider/types" +) + +type Keeper struct { + cdc *codec.Codec + key sdk.StoreKey +} + +func NewKeeper(cdc *codec.Codec, key sdk.StoreKey) Keeper { + return Keeper{ + cdc: cdc, + key: key, + } +} + +func (k Keeper) Store(ctx sdk.Context) sdk.KVStore { + child := fmt.Sprintf("%s/", types.ModuleName) + return prefix.NewStore(ctx.KVStore(k.key), []byte(child)) +} diff --git a/x/dvpn/provider/keeper/provider.go b/x/dvpn/provider/keeper/provider.go new file mode 100644 index 00000000..f98157ca --- /dev/null +++ b/x/dvpn/provider/keeper/provider.go @@ -0,0 +1,68 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/provider/types" +) + +func (k Keeper) SetProvider(ctx sdk.Context, provider types.Provider) { + key := types.ProviderKey(provider.Address) + value := k.cdc.MustMarshalBinaryLengthPrefixed(provider) + + store := k.Store(ctx) + store.Set(key, value) +} + +func (k Keeper) HasProvider(ctx sdk.Context, address hub.ProvAddress) bool { + store := k.Store(ctx) + + key := types.ProviderKey(address) + return store.Has(key) +} + +func (k Keeper) GetProvider(ctx sdk.Context, address hub.ProvAddress) (provider types.Provider, found bool) { + store := k.Store(ctx) + + key := types.ProviderKey(address) + value := store.Get(key) + if value == nil { + return provider, false + } + + k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &provider) + return provider, true +} + +func (k Keeper) GetProviders(ctx sdk.Context) (items types.Providers) { + store := k.Store(ctx) + + iter := sdk.KVStorePrefixIterator(store, types.ProviderKeyPrefix) + defer iter.Close() + + for ; iter.Valid(); iter.Next() { + var item types.Provider + k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &item) + items = append(items, item) + } + + return items +} + +func (k Keeper) IterateProviders(ctx sdk.Context, f func(index int, item types.Provider) (stop bool)) { + store := k.Store(ctx) + + iter := sdk.KVStorePrefixIterator(store, types.ProviderKeyPrefix) + defer iter.Close() + + for i := 0; iter.Valid(); iter.Next() { + var provider types.Provider + k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &provider) + + if stop := f(i, provider); stop { + break + } + i++ + } +} diff --git a/x/dvpn/provider/querier/provider.go b/x/dvpn/provider/querier/provider.go new file mode 100644 index 00000000..e2b5f255 --- /dev/null +++ b/x/dvpn/provider/querier/provider.go @@ -0,0 +1,37 @@ +package querier + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/sentinel-official/hub/x/dvpn/provider/keeper" + "github.com/sentinel-official/hub/x/dvpn/provider/types" +) + +func queryProvider(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + var params types.QueryProviderParams + if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { + return nil, types.ErrorUnmarshal() + } + + provider, found := k.GetProvider(ctx, params.Address) + if !found { + return nil, nil + } + + res, err := types.ModuleCdc.MarshalJSON(provider) + if err != nil { + return nil, types.ErrorMarshal() + } + + return res, nil +} + +func queryProviders(ctx sdk.Context, _ abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + res, err := types.ModuleCdc.MarshalJSON(k.GetProviders(ctx)) + if err != nil { + return nil, types.ErrorMarshal() + } + + return res, nil +} diff --git a/x/dvpn/provider/querier/querier.go b/x/dvpn/provider/querier/querier.go new file mode 100644 index 00000000..ec4179ba --- /dev/null +++ b/x/dvpn/provider/querier/querier.go @@ -0,0 +1,20 @@ +package querier + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/sentinel-official/hub/x/dvpn/provider/keeper" + "github.com/sentinel-official/hub/x/dvpn/provider/types" +) + +func Querier(ctx sdk.Context, path []string, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + switch path[0] { + case types.QueryProvider: + return queryProvider(ctx, req, k) + case types.QueryProviders: + return queryProviders(ctx, req, k) + default: + return nil, types.ErrorUnknownQueryType(path[0]) + } +} diff --git a/x/dvpn/provider/types/codec.go b/x/dvpn/provider/types/codec.go new file mode 100644 index 00000000..2e53421c --- /dev/null +++ b/x/dvpn/provider/types/codec.go @@ -0,0 +1,21 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec" +) + +var ( + ModuleCdc *codec.Codec +) + +func init() { + ModuleCdc = codec.New() + codec.RegisterCrypto(ModuleCdc) + RegisterCodec(ModuleCdc) + ModuleCdc.Seal() +} + +func RegisterCodec(cdc *codec.Codec) { + cdc.RegisterConcrete(MsgRegisterProvider{}, "sentinel/MsgRegisterProvider", nil) + cdc.RegisterConcrete(MsgUpdateProvider{}, "sentinel/MsgUpdateProvider", nil) +} diff --git a/x/dvpn/provider/types/errors.go b/x/dvpn/provider/types/errors.go new file mode 100644 index 00000000..bd22427e --- /dev/null +++ b/x/dvpn/provider/types/errors.go @@ -0,0 +1,57 @@ +package types + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +const ( + Codespace = sdk.CodespaceType(ModuleName) +) + +const ( + errorCodeUnknownMsgType = iota + 101 + errorCodeUnknownQueryType + errorCodeInvalidField + errorCodeDuplicateProvider + errorCodeProviderDoesNotExist +) + +const ( + errorMsgUnknownMsgType = "unknown message type: %s" + errorMsgUnknownQueryType = "unknown query type: %s" + errorMsgInvalidField = "invalid field: %s" + errorMsgDuplicateProvider = "duplicate provider" + errorMsgProviderDoesNotExist = "provider does not exist" +) + +func ErrorMarshal() sdk.Error { + return sdk.NewError(Codespace, hub.ErrorCodeMarshal, hub.ErrorMsgMarshal) +} + +func ErrorUnmarshal() sdk.Error { + return sdk.NewError(Codespace, hub.ErrorCodeUnmarshal, hub.ErrorMsgUnmarshal) +} + +func ErrorUnknownMsgType(v string) sdk.Error { + return sdk.NewError(Codespace, errorCodeUnknownMsgType, fmt.Sprintf(errorMsgUnknownMsgType, v)) +} + +func ErrorUnknownQueryType(v string) sdk.Error { + return sdk.NewError(Codespace, errorCodeUnknownQueryType, fmt.Sprintf(errorMsgUnknownQueryType, v)) +} + +func ErrorInvalidField(v string) sdk.Error { + return sdk.NewError(Codespace, errorCodeInvalidField, fmt.Sprintf(errorMsgInvalidField, v)) +} + +func ErrorDuplicateProvider() sdk.Error { + return sdk.NewError(Codespace, errorCodeDuplicateProvider, errorMsgDuplicateProvider) +} + +func ErrorProviderDoesNotExist() sdk.Error { + return sdk.NewError(Codespace, errorCodeProviderDoesNotExist, errorMsgProviderDoesNotExist) +} diff --git a/x/dvpn/provider/types/events.go b/x/dvpn/provider/types/events.go new file mode 100644 index 00000000..6bb6a659 --- /dev/null +++ b/x/dvpn/provider/types/events.go @@ -0,0 +1,10 @@ +package types + +const ( + EventTypeSetProvider = "set_provider" + EventTypeUpdateProvider = "update_provider" +) + +const ( + AttributeKeyAddress = "address" +) diff --git a/x/dvpn/provider/types/genesis.go b/x/dvpn/provider/types/genesis.go new file mode 100644 index 00000000..4872b6f9 --- /dev/null +++ b/x/dvpn/provider/types/genesis.go @@ -0,0 +1,11 @@ +package types + +type GenesisState = Providers + +func NewGenesisState(providers Providers) GenesisState { + return providers +} + +func DefaultGenesisState() GenesisState { + return GenesisState{} +} diff --git a/x/dvpn/provider/types/keys.go b/x/dvpn/provider/types/keys.go new file mode 100644 index 00000000..40510ae6 --- /dev/null +++ b/x/dvpn/provider/types/keys.go @@ -0,0 +1,23 @@ +package types + +import ( + hub "github.com/sentinel-official/hub/types" +) + +const ( + ModuleName = "provider" + QuerierRoute = ModuleName +) + +var ( + RouterKey = ModuleName + StoreKey = ModuleName +) + +var ( + ProviderKeyPrefix = []byte{0x00} +) + +func ProviderKey(address hub.ProvAddress) []byte { + return append(ProviderKeyPrefix, address.Bytes()...) +} diff --git a/x/dvpn/provider/types/msg.go b/x/dvpn/provider/types/msg.go new file mode 100644 index 00000000..212e6ffc --- /dev/null +++ b/x/dvpn/provider/types/msg.go @@ -0,0 +1,150 @@ +package types + +import ( + "encoding/json" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +var ( + _ sdk.Msg = (*MsgRegisterProvider)(nil) + _ sdk.Msg = (*MsgUpdateProvider)(nil) +) + +// MsgRegisterProvider is for registering a provider. +type MsgRegisterProvider struct { + From sdk.AccAddress `json:"from"` + Name string `json:"name"` + Identity string `json:"identity"` + Website string `json:"website"` + Description string `json:"description"` +} + +func NewMsgRegisterProvider(from sdk.AccAddress, name, identity, website, description string) MsgRegisterProvider { + return MsgRegisterProvider{ + From: from, + Name: name, + Identity: identity, + Website: website, + Description: description, + } +} + +func (m MsgRegisterProvider) Route() string { + return RouterKey +} + +func (m MsgRegisterProvider) Type() string { + return "register_provider" +} + +func (m MsgRegisterProvider) ValidateBasic() sdk.Error { + if m.From == nil || m.From.Empty() { + return ErrorInvalidField("from") + } + + // Name can't be empty and length should be [1, 64] + if len(m.Name) == 0 || len(m.Name) > 64 { + return ErrorInvalidField("name") + } + + // Identity length should be [0, 64] + if len(m.Identity) > 64 { + return ErrorInvalidField("identity") + } + + // Website length should be [0, 64] + if len(m.Website) > 64 { + return ErrorInvalidField("website") + } + + // Description length should be [0, 256] + if len(m.Description) > 256 { + return ErrorInvalidField("description") + } + + return nil +} + +func (m MsgRegisterProvider) GetSignBytes() []byte { + bytes, err := json.Marshal(m) + if err != nil { + panic(err) + } + + return bytes +} + +func (m MsgRegisterProvider) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{m.From} +} + +// MsgUpdateProvider is for updating a provider. +type MsgUpdateProvider struct { + From hub.ProvAddress `json:"from"` + Name string `json:"name,omitempty"` + Identity string `json:"identity,omitempty"` + Website string `json:"website,omitempty"` + Description string `json:"description,omitempty"` +} + +func NewMsgUpdateProvider(from hub.ProvAddress, name, identity, website, description string) MsgUpdateProvider { + return MsgUpdateProvider{ + From: from, + Name: name, + Identity: identity, + Website: website, + Description: description, + } +} + +func (m MsgUpdateProvider) Route() string { + return RouterKey +} + +func (m MsgUpdateProvider) Type() string { + return "update_provider" +} + +func (m MsgUpdateProvider) ValidateBasic() sdk.Error { + if m.From == nil || m.From.Empty() { + return ErrorInvalidField("from") + } + + // Name length should be [0, 64] + if len(m.Name) > 64 { + return ErrorInvalidField("name") + } + + // Identity length should be [0, 64] + if len(m.Identity) > 64 { + return ErrorInvalidField("identity") + } + + // Website length should be [0, 64] + if len(m.Website) > 64 { + return ErrorInvalidField("website") + } + + // Description length should be [0, 256] + if len(m.Description) > 256 { + return ErrorInvalidField("description") + } + + return nil +} + +func (m MsgUpdateProvider) GetSignBytes() []byte { + bytes, err := json.Marshal(m) + if err != nil { + panic(err) + } + + return bytes +} + +func (m MsgUpdateProvider) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{m.From.Bytes()} +} diff --git a/x/dvpn/provider/types/provider.go b/x/dvpn/provider/types/provider.go new file mode 100644 index 00000000..0fd02388 --- /dev/null +++ b/x/dvpn/provider/types/provider.go @@ -0,0 +1,28 @@ +package types + +import ( + "fmt" + "strings" + + hub "github.com/sentinel-official/hub/types" +) + +type Provider struct { + Address hub.ProvAddress `json:"address"` + Name string `json:"name"` + Identity string `json:"identity"` + Website string `json:"website"` + Description string `json:"description"` +} + +func (p Provider) String() string { + return strings.TrimSpace(fmt.Sprintf(` +Address: %s +Name: %s +Identity: %s +Website: %s +Description: %s +`, p.Address, p.Identity, p.Name, p.Website, p.Description)) +} + +type Providers []Provider diff --git a/x/dvpn/provider/types/querier.go b/x/dvpn/provider/types/querier.go new file mode 100644 index 00000000..7283ffe1 --- /dev/null +++ b/x/dvpn/provider/types/querier.go @@ -0,0 +1,20 @@ +package types + +import ( + hub "github.com/sentinel-official/hub/types" +) + +const ( + QueryProvider = "query_provider" + QueryProviders = "query_providers" +) + +type QueryProviderParams struct { + Address hub.ProvAddress `json:"address"` +} + +func NewQueryProviderParams(address hub.ProvAddress) QueryProviderParams { + return QueryProviderParams{ + Address: address, + } +} diff --git a/x/dvpn/querier/querier.go b/x/dvpn/querier/querier.go new file mode 100644 index 00000000..825d68cc --- /dev/null +++ b/x/dvpn/querier/querier.go @@ -0,0 +1,33 @@ +package querier + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/sentinel-official/hub/x/dvpn/deposit" + "github.com/sentinel-official/hub/x/dvpn/keeper" + "github.com/sentinel-official/hub/x/dvpn/node" + "github.com/sentinel-official/hub/x/dvpn/plan" + "github.com/sentinel-official/hub/x/dvpn/provider" + "github.com/sentinel-official/hub/x/dvpn/subscription" + "github.com/sentinel-official/hub/x/dvpn/types" +) + +func NewQuerier(k keeper.Keeper) sdk.Querier { + return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, sdk.Error) { + switch path[0] { + case deposit.ModuleName: + return deposit.Querier(ctx, path[1:], req, k.Deposit) + case provider.ModuleName: + return provider.Querier(ctx, path[1:], req, k.Provider) + case node.ModuleName: + return node.Querier(ctx, path[1:], req, k.Node) + case plan.ModuleName: + return plan.Querier(ctx, path[1:], req, k.Plan) + case subscription.ModuleName: + return subscription.Querier(ctx, path[1:], req, k.Subscription) + default: + return nil, types.ErrorUnknownQueryType(path[0]) + } + } +} diff --git a/x/dvpn/session/alias.go b/x/dvpn/session/alias.go new file mode 100644 index 00000000..241d97c9 --- /dev/null +++ b/x/dvpn/session/alias.go @@ -0,0 +1,83 @@ +// nolint +// autogenerated code using github.com/rigelrozanski/multitool +// aliases generated for the following subdirectories: +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/session/types +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/session/keeper +package session + +import ( + "github.com/sentinel-official/hub/x/dvpn/session/keeper" + "github.com/sentinel-official/hub/x/dvpn/session/types" +) + +const ( + Codespace = types.Codespace + EventTypeSetSessionsCount = types.EventTypeSetSessionsCount + EventTypeSetActiveSession = types.EventTypeSetActiveSession + EventTypeUpdateSession = types.EventTypeUpdateSession + AttributeKeyCount = types.AttributeKeyCount + AttributeKeyID = types.AttributeKeyID + AttributeKeySubscription = types.AttributeKeySubscription + AttributeKeyNode = types.AttributeKeyNode + AttributeKeyAddress = types.AttributeKeyAddress + ModuleName = types.ModuleName + ParamsSubspace = types.ParamsSubspace + QuerierRoute = types.QuerierRoute + DefaultInactiveDuration = types.DefaultInactiveDuration + QuerySession = types.QuerySession + QuerySessions = types.QuerySessions + QuerySessionsForSubscription = types.QuerySessionsForSubscription + QuerySessionsForNode = types.QuerySessionsForNode + QuerySessionsForAddress = types.QuerySessionsForAddress +) + +var ( + // functions aliases + RegisterCodec = types.RegisterCodec + ErrorMarshal = types.ErrorMarshal + ErrorUnmarshal = types.ErrorUnmarshal + ErrorUnknownMsgType = types.ErrorUnknownMsgType + ErrorUnknownQueryType = types.ErrorUnknownQueryType + ErrorInvalidField = types.ErrorInvalidField + ErrorSubscriptionDoesNotExit = types.ErrorSubscriptionDoesNotExit + ErrorInvalidSubscriptionStatus = types.ErrorInvalidSubscriptionStatus + ErrorUnauthorized = types.ErrorUnauthorized + ErrorAddressWasNotAdded = types.ErrorAddressWasNotAdded + ErrorInvalidDuration = types.ErrorInvalidDuration + ErrorInvalidBandwidth = types.ErrorInvalidBandwidth + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + SessionKey = types.SessionKey + ActiveSessionKey = types.ActiveSessionKey + NewMsgUpdateSession = types.NewMsgUpdateSession + NewParams = types.NewParams + DefaultParams = types.DefaultParams + ParamsKeyTable = types.ParamsKeyTable + NewQuerySessionParams = types.NewQuerySessionParams + NewQuerySessionsForSubscriptionParams = types.NewQuerySessionsForSubscriptionParams + NewQuerySessionsForNodeParams = types.NewQuerySessionsForNodeParams + NewQuerySessionsForAddressParams = types.NewQuerySessionsForAddressParams + NewKeeper = keeper.NewKeeper + + // variable aliases + ModuleCdc = types.ModuleCdc + RouterKey = types.RouterKey + StoreKey = types.StoreKey + SessionsCountKey = types.SessionsCountKey + SessionKeyPrefix = types.SessionKeyPrefix + ActiveSessionKeyPrefix = types.ActiveSessionKeyPrefix + KeyInactiveDuration = types.KeyInactiveDuration +) + +type ( + GenesisState = types.GenesisState + MsgUpdateSession = types.MsgUpdateSession + Params = types.Params + QuerySessionParams = types.QuerySessionParams + QuerySessionsForSubscriptionParams = types.QuerySessionsForSubscriptionParams + QuerySessionsForNodeParams = types.QuerySessionsForNodeParams + QuerySessionsForAddressParams = types.QuerySessionsForAddressParams + Session = types.Session + Sessions = types.Sessions + Keeper = keeper.Keeper +) diff --git a/x/dvpn/session/client/cli/cli.go b/x/dvpn/session/client/cli/cli.go new file mode 100644 index 00000000..c52ae6cf --- /dev/null +++ b/x/dvpn/session/client/cli/cli.go @@ -0,0 +1,24 @@ +package cli + +import ( + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/spf13/cobra" +) + +func GetQueryCommands(cdc *codec.Codec) []*cobra.Command { + return nil +} + +func GetTxCommands(cdc *codec.Codec) []*cobra.Command { + cmd := &cobra.Command{ + Use: "session", + Short: "Session module sub-commands", + } + + cmd.AddCommand(client.PostCommands( + txUpdateSession(cdc), + )...) + + return []*cobra.Command{cmd} +} diff --git a/x/dvpn/session/client/cli/flags.go b/x/dvpn/session/client/cli/flags.go new file mode 100644 index 00000000..7f1e458c --- /dev/null +++ b/x/dvpn/session/client/cli/flags.go @@ -0,0 +1 @@ +package cli diff --git a/x/dvpn/session/client/cli/query.go b/x/dvpn/session/client/cli/query.go new file mode 100644 index 00000000..7f1e458c --- /dev/null +++ b/x/dvpn/session/client/cli/query.go @@ -0,0 +1 @@ +package cli diff --git a/x/dvpn/session/client/cli/tx.go b/x/dvpn/session/client/cli/tx.go new file mode 100644 index 00000000..a4bf83cb --- /dev/null +++ b/x/dvpn/session/client/cli/tx.go @@ -0,0 +1,57 @@ +package cli + +import ( + "strconv" + "time" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/client/utils" + "github.com/spf13/cobra" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/session/types" +) + +func txUpdateSession(cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "update", + Short: "Update a session", + Args: cobra.ExactArgs(5), + RunE: func(cmd *cobra.Command, args []string) error { + txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + ctx := context.NewCLIContext().WithCodec(cdc) + + subscription, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return err + } + + address, err := sdk.AccAddressFromBech32(args[1]) + if err != nil { + return err + } + + duration, err := time.ParseDuration(args[2]) + if err != nil { + return err + } + + upload, err := strconv.ParseInt(args[3], 10, 64) + if err != nil { + return err + } + + download, err := strconv.ParseInt(args[4], 10, 64) + if err != nil { + return err + } + + msg := types.NewMsgUpdateSession(ctx.FromAddress.Bytes(), + subscription, address, duration, hub.NewBandwidthFromInt64(upload, download)) + return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) + }, + } +} diff --git a/x/dvpn/session/client/common/query.go b/x/dvpn/session/client/common/query.go new file mode 100644 index 00000000..805d0c79 --- /dev/null +++ b/x/dvpn/session/client/common/query.go @@ -0,0 +1 @@ +package common diff --git a/x/dvpn/session/client/rest/query.go b/x/dvpn/session/client/rest/query.go new file mode 100644 index 00000000..0062e0ca --- /dev/null +++ b/x/dvpn/session/client/rest/query.go @@ -0,0 +1 @@ +package rest diff --git a/x/dvpn/session/client/rest/rest.go b/x/dvpn/session/client/rest/rest.go new file mode 100644 index 00000000..5700977e --- /dev/null +++ b/x/dvpn/session/client/rest/rest.go @@ -0,0 +1,19 @@ +package rest + +import ( + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/gorilla/mux" +) + +func registerQueryRoutes(ctx context.CLIContext, router *mux.Router) { + +} + +func registerTxRoutes(ctx context.CLIContext, router *mux.Router) { + +} + +func RegisterRoutes(ctx context.CLIContext, router *mux.Router) { + registerQueryRoutes(ctx, router) + registerTxRoutes(ctx, router) +} diff --git a/x/dvpn/session/client/rest/tx.go b/x/dvpn/session/client/rest/tx.go new file mode 100644 index 00000000..0062e0ca --- /dev/null +++ b/x/dvpn/session/client/rest/tx.go @@ -0,0 +1 @@ +package rest diff --git a/x/dvpn/session/expected/keeper.go b/x/dvpn/session/expected/keeper.go new file mode 100644 index 00000000..a0df492a --- /dev/null +++ b/x/dvpn/session/expected/keeper.go @@ -0,0 +1,20 @@ +package expected + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" + subscription "github.com/sentinel-official/hub/x/dvpn/subscription/types" +) + +type PlanKeeper interface { + HasNodeForPlan(ctx sdk.Context, id uint64, address hub.NodeAddress) bool +} + +type SubscriptionKeeper interface { + SetSubscription(ctx sdk.Context, subscription subscription.Subscription) + GetSubscription(ctx sdk.Context, id uint64) (subscription.Subscription, bool) + + HasSubscriptionForNode(ctx sdk.Context, address hub.NodeAddress, id uint64) bool + HasSubscriptionForAddress(ctx sdk.Context, address sdk.AccAddress, id uint64) bool +} diff --git a/x/dvpn/session/genesis.go b/x/dvpn/session/genesis.go new file mode 100644 index 00000000..7949af05 --- /dev/null +++ b/x/dvpn/session/genesis.go @@ -0,0 +1,32 @@ +package session + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/session/keeper" + "github.com/sentinel-official/hub/x/dvpn/session/types" +) + +func InitGenesis(ctx sdk.Context, k keeper.Keeper, state types.GenesisState) { + k.SetParams(ctx, state.Params) + for _, session := range state.Sessions { + k.SetSession(ctx, session) + if session.Status.Equal(hub.StatusActive) { + k.SetActiveSession(ctx, session.Subscription, session.Node, session.Address, session.ID) + } + + k.SetSessionsCount(ctx, k.GetSessionsCount(ctx)+1) + } +} + +func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { + return types.NewGenesisState( + k.GetSessions(ctx), + k.GetParams(ctx), + ) +} + +func ValidateGenesis(state types.GenesisState) error { + return nil +} diff --git a/x/dvpn/session/handler.go b/x/dvpn/session/handler.go new file mode 100644 index 00000000..18c9f8a6 --- /dev/null +++ b/x/dvpn/session/handler.go @@ -0,0 +1,84 @@ +package session + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/session/keeper" + "github.com/sentinel-official/hub/x/dvpn/session/types" +) + +func isAuthorized(ctx sdk.Context, k keeper.Keeper, p, s uint64, n hub.NodeAddress) bool { + return p == 0 && k.HasSubscriptionForNode(ctx, n, s) || + k.HasNodeForPlan(ctx, p, n) +} + +func HandleUpdateSession(ctx sdk.Context, k keeper.Keeper, msg types.MsgUpdateSession) sdk.Result { + subscription, found := k.GetSubscription(ctx, msg.Subscription) + if !found { + return types.ErrorSubscriptionDoesNotExit().Result() + } + if !subscription.Status.Equal(hub.StatusActive) { + return types.ErrorInvalidSubscriptionStatus().Result() + } + if !isAuthorized(ctx, k, subscription.Plan, subscription.ID, msg.From) { + return types.ErrorUnauthorized().Result() + } + if !k.HasSubscriptionForAddress(ctx, msg.Address, subscription.ID) { + return types.ErrorAddressWasNotAdded().Result() + } + + subscription.Duration = subscription.Duration + msg.Duration + if subscription.Duration > subscription.TotalDuration { + return types.ErrorInvalidDuration().Result() + } + + subscription.Bandwidth = subscription.Bandwidth.Add(msg.Bandwidth) + if subscription.Bandwidth.IsAnyGT(subscription.TotalBandwidth) { + return types.ErrorInvalidBandwidth().Result() + } + + session, found := k.GetActiveSession(ctx, subscription.ID, msg.From, msg.Address) + if !found { + count := k.GetSessionsCount(ctx) + session = types.Session{ + ID: count + 1, + Subscription: subscription.ID, + Node: msg.From, + Address: msg.Address, + Duration: 0, + Bandwidth: hub.NewBandwidthFromInt64(0, 0), + Status: hub.StatusActive, + StatusAt: ctx.BlockTime(), + } + + k.SetSessionsCount(ctx, count+1) + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeSetSessionsCount, + sdk.NewAttribute(types.AttributeKeyCount, fmt.Sprintf("%d", count+1)), + )) + + k.SetActiveSession(ctx, session.Subscription, session.Node, session.Address, session.ID) + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeSetActiveSession, + sdk.NewAttribute(types.AttributeKeySubscription, fmt.Sprintf("%d", session.Subscription)), + sdk.NewAttribute(types.AttributeKeyNode, session.Node.String()), + sdk.NewAttribute(types.AttributeKeyAddress, session.Address.String()), + sdk.NewAttribute(types.AttributeKeyID, fmt.Sprintf("%d", session.ID)), + )) + } + + session.Duration = session.Duration + msg.Duration + session.Bandwidth = session.Bandwidth.Add(msg.Bandwidth) + + k.SetSession(ctx, session) + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeUpdateSession, + sdk.NewAttribute(types.AttributeKeyID, fmt.Sprintf("%d", session.ID)), + )) + + k.SetSubscription(ctx, subscription) + return sdk.Result{Events: ctx.EventManager().Events()} +} diff --git a/x/dvpn/session/keeper/alias.go b/x/dvpn/session/keeper/alias.go new file mode 100644 index 00000000..2327a8b1 --- /dev/null +++ b/x/dvpn/session/keeper/alias.go @@ -0,0 +1,28 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" + subscription "github.com/sentinel-official/hub/x/dvpn/subscription/types" +) + +func (k Keeper) HasNodeForPlan(ctx sdk.Context, id uint64, address hub.NodeAddress) bool { + return k.plan.HasNodeForPlan(ctx, id, address) +} + +func (k Keeper) SetSubscription(ctx sdk.Context, subscription subscription.Subscription) { + k.subscription.SetSubscription(ctx, subscription) +} + +func (k Keeper) GetSubscription(ctx sdk.Context, id uint64) (subscription.Subscription, bool) { + return k.subscription.GetSubscription(ctx, id) +} + +func (k Keeper) HasSubscriptionForNode(ctx sdk.Context, address hub.NodeAddress, id uint64) bool { + return k.subscription.HasSubscriptionForNode(ctx, address, id) +} + +func (k Keeper) HasSubscriptionForAddress(ctx sdk.Context, address sdk.AccAddress, id uint64) bool { + return k.subscription.HasSubscriptionForAddress(ctx, address, id) +} diff --git a/x/dvpn/session/keeper/keeper.go b/x/dvpn/session/keeper/keeper.go new file mode 100644 index 00000000..a1114480 --- /dev/null +++ b/x/dvpn/session/keeper/keeper.go @@ -0,0 +1,39 @@ +package keeper + +import ( + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store/prefix" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/params" + + "github.com/sentinel-official/hub/x/dvpn/session/expected" + "github.com/sentinel-official/hub/x/dvpn/session/types" +) + +type Keeper struct { + cdc *codec.Codec + key sdk.StoreKey + params params.Subspace + plan expected.PlanKeeper + subscription expected.SubscriptionKeeper +} + +func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, params params.Subspace) Keeper { + return Keeper{ + cdc: cdc, + key: key, + params: params.WithKeyTable(types.ParamsKeyTable()), + } +} + +func (k *Keeper) WithPlanKeeper(keeper expected.PlanKeeper) { + k.plan = keeper +} + +func (k *Keeper) WithSubscriptionKeeper(keeper expected.SubscriptionKeeper) { + k.subscription = keeper +} + +func (k Keeper) Store(ctx sdk.Context) sdk.KVStore { + return prefix.NewStore(ctx.KVStore(k.key), []byte("session/")) +} diff --git a/x/dvpn/session/keeper/params.go b/x/dvpn/session/keeper/params.go new file mode 100644 index 00000000..87011a21 --- /dev/null +++ b/x/dvpn/session/keeper/params.go @@ -0,0 +1,24 @@ +package keeper + +import ( + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/sentinel-official/hub/x/dvpn/session/types" +) + +func (k Keeper) InactiveDuration(ctx sdk.Context) (duration time.Duration) { + k.params.Get(ctx, types.KeyInactiveDuration, &duration) + return +} + +func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { + k.params.SetParamSet(ctx, ¶ms) +} + +func (k Keeper) GetParams(ctx sdk.Context) types.Params { + return types.NewParams( + k.InactiveDuration(ctx), + ) +} diff --git a/x/dvpn/session/keeper/session.go b/x/dvpn/session/keeper/session.go new file mode 100644 index 00000000..f50f04f3 --- /dev/null +++ b/x/dvpn/session/keeper/session.go @@ -0,0 +1,105 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/session/types" +) + +func (k Keeper) SetSessionsCount(ctx sdk.Context, count uint64) { + key := types.SessionsCountKey + value := k.cdc.MustMarshalBinaryLengthPrefixed(count) + + store := k.Store(ctx) + store.Set(key, value) +} + +func (k Keeper) GetSessionsCount(ctx sdk.Context) (count uint64) { + store := k.Store(ctx) + + key := types.SessionsCountKey + value := store.Get(key) + if value == nil { + return 0 + } + + k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &count) + return count +} + +func (k Keeper) SetSession(ctx sdk.Context, session types.Session) { + key := types.SessionKey(session.ID) + value := k.cdc.MustMarshalBinaryLengthPrefixed(session) + + store := k.Store(ctx) + store.Set(key, value) +} + +func (k Keeper) GetSession(ctx sdk.Context, id uint64) (session types.Session, found bool) { + store := k.Store(ctx) + + key := types.SessionKey(id) + value := store.Get(key) + if value == nil { + return session, false + } + + k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &session) + return session, true +} + +func (k Keeper) GetSessions(ctx sdk.Context) (items types.Sessions) { + store := k.Store(ctx) + + iter := sdk.KVStorePrefixIterator(store, types.SessionKeyPrefix) + defer iter.Close() + + for ; iter.Valid(); iter.Next() { + var item types.Session + k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &item) + items = append(items, item) + } + + return items +} + +func (k Keeper) IterateSessions(ctx sdk.Context, f func(index int, item types.Session) (stop bool)) { + store := k.Store(ctx) + + iter := sdk.KVStorePrefixIterator(store, types.SessionKeyPrefix) + defer iter.Close() + + for i := 0; iter.Valid(); iter.Next() { + var session types.Session + k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &session) + + if stop := f(i, session); stop { + break + } + i++ + } +} + +func (k Keeper) SetActiveSession(ctx sdk.Context, s uint64, n hub.NodeAddress, a sdk.AccAddress, id uint64) { + key := types.ActiveSessionKey(s, n, a) + value := k.cdc.MustMarshalBinaryLengthPrefixed(id) + + store := k.Store(ctx) + store.Set(key, value) +} + +func (k Keeper) GetActiveSession(ctx sdk.Context, s uint64, n hub.NodeAddress, a sdk.AccAddress) (session types.Session, found bool) { + store := k.Store(ctx) + + key := types.ActiveSessionKey(s, n, a) + value := store.Get(key) + if value == nil { + return session, false + } + + var id uint64 + k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &id) + + return k.GetSession(ctx, id) +} diff --git a/x/dvpn/session/querier/querier.go b/x/dvpn/session/querier/querier.go new file mode 100644 index 00000000..f8d6aa6e --- /dev/null +++ b/x/dvpn/session/querier/querier.go @@ -0,0 +1 @@ +package querier diff --git a/x/dvpn/session/querier/session.go b/x/dvpn/session/querier/session.go new file mode 100644 index 00000000..f8d6aa6e --- /dev/null +++ b/x/dvpn/session/querier/session.go @@ -0,0 +1 @@ +package querier diff --git a/x/dvpn/session/types/codec.go b/x/dvpn/session/types/codec.go new file mode 100644 index 00000000..adb3f0e6 --- /dev/null +++ b/x/dvpn/session/types/codec.go @@ -0,0 +1,20 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec" +) + +var ( + ModuleCdc *codec.Codec +) + +func init() { + ModuleCdc = codec.New() + codec.RegisterCrypto(ModuleCdc) + RegisterCodec(ModuleCdc) + ModuleCdc.Seal() +} + +func RegisterCodec(cdc *codec.Codec) { + cdc.RegisterConcrete(MsgUpdateSession{}, "sentinel/MsgUpdateSession", nil) +} diff --git a/x/dvpn/session/types/errors.go b/x/dvpn/session/types/errors.go new file mode 100644 index 00000000..891a40d1 --- /dev/null +++ b/x/dvpn/session/types/errors.go @@ -0,0 +1,81 @@ +package types + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +const ( + Codespace = sdk.CodespaceType("session") +) + +const ( + errorCodeUnknownMsgType = iota + 101 + errorCodeUnknownQueryType + errorCodeInvalidField + errorCodeSubscriptionDoesNotExit + errorCodeInvalidSubscriptionStatus + errorCodeUnauthorized + errorCodeAddressWasNotAdded + errorCodeInvalidDuration + errorCodeInvalidBandwidth +) + +const ( + errorMsgUnknownMsgType = "unknown message type: %s" + errorMsgUnknownQueryType = "unknown query type: %s" + errorMsgInvalidField = "invalid field: %s" + errorMsgSubscriptionDoesNotExit = "subscription does not exist" + errorMsgInvalidSubscriptionStatus = "invalid subscription status" + errorMsgUnauthorized = "unauthorized" + errorMsgAddressWasNotAdded = "address was not added" + errorMsgInvalidDuration = "invalid duration" + errorMsgInvalidBandwidth = "invalid bandwidth" +) + +func ErrorMarshal() sdk.Error { + return sdk.NewError(Codespace, hub.ErrorCodeMarshal, hub.ErrorMsgMarshal) +} + +func ErrorUnmarshal() sdk.Error { + return sdk.NewError(Codespace, hub.ErrorCodeUnmarshal, hub.ErrorMsgUnmarshal) +} + +func ErrorUnknownMsgType(v string) sdk.Error { + return sdk.NewError(Codespace, errorCodeUnknownMsgType, fmt.Sprintf(errorMsgUnknownMsgType, v)) +} + +func ErrorUnknownQueryType(v string) sdk.Error { + return sdk.NewError(Codespace, errorCodeUnknownQueryType, fmt.Sprintf(errorMsgUnknownQueryType, v)) +} + +func ErrorInvalidField(v string) sdk.Error { + return sdk.NewError(Codespace, errorCodeInvalidField, fmt.Sprintf(errorMsgInvalidField, v)) +} + +func ErrorSubscriptionDoesNotExit() sdk.Error { + return sdk.NewError(Codespace, errorCodeSubscriptionDoesNotExit, errorMsgSubscriptionDoesNotExit) +} + +func ErrorInvalidSubscriptionStatus() sdk.Error { + return sdk.NewError(Codespace, errorCodeInvalidSubscriptionStatus, errorMsgInvalidSubscriptionStatus) +} + +func ErrorUnauthorized() sdk.Error { + return sdk.NewError(Codespace, errorCodeUnauthorized, errorMsgUnauthorized) +} + +func ErrorAddressWasNotAdded() sdk.Error { + return sdk.NewError(Codespace, errorCodeAddressWasNotAdded, errorMsgAddressWasNotAdded) +} + +func ErrorInvalidDuration() sdk.Error { + return sdk.NewError(Codespace, errorCodeInvalidDuration, errorMsgInvalidDuration) +} + +func ErrorInvalidBandwidth() sdk.Error { + return sdk.NewError(Codespace, errorCodeInvalidBandwidth, errorMsgInvalidBandwidth) +} diff --git a/x/dvpn/session/types/events.go b/x/dvpn/session/types/events.go new file mode 100644 index 00000000..27919510 --- /dev/null +++ b/x/dvpn/session/types/events.go @@ -0,0 +1,15 @@ +package types + +const ( + EventTypeSetSessionsCount = "sessions_count" + EventTypeSetActiveSession = "set_active_session" + EventTypeUpdateSession = "update_session" +) + +const ( + AttributeKeyCount = "count" + AttributeKeyID = "id" + AttributeKeySubscription = "subscription" + AttributeKeyNode = "node" + AttributeKeyAddress = "address" +) diff --git a/x/dvpn/session/types/genesis.go b/x/dvpn/session/types/genesis.go new file mode 100644 index 00000000..4e5188e8 --- /dev/null +++ b/x/dvpn/session/types/genesis.go @@ -0,0 +1,20 @@ +package types + +type GenesisState struct { + Sessions Sessions `json:"_"` + Params Params `json:"params"` +} + +func NewGenesisState(sessions Sessions, params Params) GenesisState { + return GenesisState{ + Sessions: sessions, + Params: params, + } +} + +func DefaultGenesisState() GenesisState { + return GenesisState{ + Sessions: nil, + Params: DefaultParams(), + } +} diff --git a/x/dvpn/session/types/keys.go b/x/dvpn/session/types/keys.go new file mode 100644 index 00000000..333a54ae --- /dev/null +++ b/x/dvpn/session/types/keys.go @@ -0,0 +1,34 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +const ( + ModuleName = "session" + ParamsSubspace = ModuleName + QuerierRoute = ModuleName +) + +var ( + RouterKey = ModuleName + StoreKey = ModuleName +) + +var ( + SessionsCountKey = []byte{0x00} + SessionKeyPrefix = []byte{0x01} + ActiveSessionKeyPrefix = []byte{0x02} +) + +func SessionKey(id uint64) []byte { + return append(SessionKeyPrefix, sdk.Uint64ToBigEndian(id)...) +} + +func ActiveSessionKey(s uint64, n hub.NodeAddress, a sdk.AccAddress) []byte { + return append(ActiveSessionKeyPrefix, + append(sdk.Uint64ToBigEndian(s), + append(n.Bytes(), a.Bytes()...)...)...) +} diff --git a/x/dvpn/session/types/msg.go b/x/dvpn/session/types/msg.go new file mode 100644 index 00000000..5af6c78a --- /dev/null +++ b/x/dvpn/session/types/msg.go @@ -0,0 +1,83 @@ +package types + +import ( + "encoding/json" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +var ( + _ sdk.Msg = (*MsgUpdateSession)(nil) +) + +// MsgUpdateSession is for updating the session of a plan. +type MsgUpdateSession struct { + From hub.NodeAddress `json:"from"` + Subscription uint64 `json:"subscription"` + Address sdk.AccAddress `json:"address"` + Duration time.Duration `json:"duration"` + Bandwidth hub.Bandwidth `json:"bandwidth"` +} + +func NewMsgUpdateSession(from hub.NodeAddress, subscription uint64, + address sdk.AccAddress, duration time.Duration, bandwidth hub.Bandwidth) MsgUpdateSession { + return MsgUpdateSession{ + From: from, + Subscription: subscription, + Address: address, + Duration: duration, + Bandwidth: bandwidth, + } +} + +func (m MsgUpdateSession) Route() string { + return RouterKey +} + +func (m MsgUpdateSession) Type() string { + return "update_session" +} + +func (m MsgUpdateSession) ValidateBasic() sdk.Error { + if m.From == nil || m.From.Empty() { + return ErrorInvalidField("from") + } + + // Subscription shouldn't be zero + if m.Subscription == 0 { + return ErrorInvalidField("subscription") + } + + // Address shouldn't be nil or empty + if m.Address == nil || m.Address.Empty() { + return ErrorInvalidField("address") + } + + // Duration shouldn't be zero + if m.Duration == 0 { + return ErrorInvalidField("duration") + } + + // Bandwidth shouldn't be zero + if m.Bandwidth.IsAllZero() { + return ErrorInvalidField("bandwidth") + } + + return nil +} + +func (m MsgUpdateSession) GetSignBytes() []byte { + bytes, err := json.Marshal(m) + if err != nil { + panic(err) + } + + return bytes +} + +func (m MsgUpdateSession) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{m.From.Bytes()} +} diff --git a/x/dvpn/session/types/params.go b/x/dvpn/session/types/params.go new file mode 100644 index 00000000..ee2ccfb5 --- /dev/null +++ b/x/dvpn/session/types/params.go @@ -0,0 +1,51 @@ +package types + +import ( + "fmt" + "strings" + "time" + + "github.com/cosmos/cosmos-sdk/x/params" +) + +const ( + DefaultInactiveDuration = 30 * time.Minute +) + +var ( + KeyInactiveDuration = []byte("InactiveDuration") +) + +var _ params.ParamSet = (*Params)(nil) + +type Params struct { + InactiveDuration time.Duration `json:"inactive_duration"` +} + +func (p Params) String() string { + return fmt.Sprintf(strings.TrimSpace(` +Inactive duration: %s +`), p.InactiveDuration) +} + +func (p *Params) ParamSetPairs() params.ParamSetPairs { + return params.ParamSetPairs{ + {Key: KeyInactiveDuration, Value: &p.InactiveDuration}, + } +} + +func NewParams(inactiveDuration time.Duration) Params { + return Params{ + InactiveDuration: inactiveDuration, + } +} + +func DefaultParams() Params { + return Params{ + InactiveDuration: DefaultInactiveDuration, + } +} + +func ParamsKeyTable() params.KeyTable { + return params.NewKeyTable().RegisterParamSet(&Params{}) +} diff --git a/x/dvpn/session/types/querier.go b/x/dvpn/session/types/querier.go new file mode 100644 index 00000000..cfd397ac --- /dev/null +++ b/x/dvpn/session/types/querier.go @@ -0,0 +1,55 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +const ( + QuerySession = "query_session" + QuerySessions = "query_sessions" + QuerySessionsForSubscription = "query_sessions_for_subscription" + QuerySessionsForNode = "query_sessions_for_node" + QuerySessionsForAddress = "query_sessions_for_address" +) + +type QuerySessionParams struct { + ID uint64 `json:"id"` +} + +func NewQuerySessionParams(id uint64) QuerySessionParams { + return QuerySessionParams{ + ID: id, + } +} + +type QuerySessionsForSubscriptionParams struct { + ID uint64 `json:"id"` +} + +func NewQuerySessionsForSubscriptionParams(id uint64) QuerySessionsForSubscriptionParams { + return QuerySessionsForSubscriptionParams{ + ID: id, + } +} + +type QuerySessionsForNodeParams struct { + Address hub.NodeAddress `json:"address"` +} + +func NewQuerySessionsForNodeParams(address hub.NodeAddress) QuerySessionsForNodeParams { + return QuerySessionsForNodeParams{ + Address: address, + } +} + +type QuerySessionsForAddressParams struct { + Address sdk.AccAddress `json:"address"` +} + +func NewQuerySessionsForAddressParams(address sdk.AccAddress) QuerySessionsForAddressParams { + return QuerySessionsForAddressParams{ + Address: address, + } +} diff --git a/x/dvpn/session/types/session.go b/x/dvpn/session/types/session.go new file mode 100644 index 00000000..0309550d --- /dev/null +++ b/x/dvpn/session/types/session.go @@ -0,0 +1,37 @@ +package types + +import ( + "fmt" + "strings" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +type Session struct { + ID uint64 `json:"id"` + Subscription uint64 `json:"subscription"` + Node hub.NodeAddress `json:"node"` + Address sdk.AccAddress `json:"address"` + Duration time.Duration `json:"duration"` + Bandwidth hub.Bandwidth `json:"bandwidth"` + Status hub.Status `json:"status"` + StatusAt time.Time `json:"status_at"` +} + +func (s Session) String() string { + return fmt.Sprintf(strings.TrimSpace(` +ID: %d +Subscription: %d +Node: %s +Address: %s +Duration: %s +Bandwidth: %s +Status: %s +Status at: %s +`), s.ID, s.Subscription, s.Node, s.Address, s.Duration, s.Bandwidth, s.Status, s.StatusAt) +} + +type Sessions []Session diff --git a/x/dvpn/subscription/alias.go b/x/dvpn/subscription/alias.go new file mode 100644 index 00000000..222ae681 --- /dev/null +++ b/x/dvpn/subscription/alias.go @@ -0,0 +1,109 @@ +// nolint +// autogenerated code using github.com/rigelrozanski/multitool +// aliases generated for the following subdirectories: +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/subscription/types +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/subscription/keeper +// ALIASGEN: github.com/sentinel-official/hub/x/dvpn/subscription/querier +package subscription + +import ( + "github.com/sentinel-official/hub/x/dvpn/subscription/keeper" + "github.com/sentinel-official/hub/x/dvpn/subscription/querier" + "github.com/sentinel-official/hub/x/dvpn/subscription/types" +) + +const ( + Codespace = types.Codespace + EventTypeSetSubscription = types.EventTypeSetSubscription + EventTypeSetSubscriptionsCount = types.EventTypeSetSubscriptionsCount + EventTypeAddAddressForSubscription = types.EventTypeAddAddressForSubscription + EventTypeRemoveAddressForSubscription = types.EventTypeRemoveAddressForSubscription + EventTypeEndSubscription = types.EventTypeEndSubscription + AttributeKeyAddress = types.AttributeKeyAddress + AttributeKeyID = types.AttributeKeyID + AttributeKeyNode = types.AttributeKeyNode + AttributeKeyCount = types.AttributeKeyCount + AttributeKeyPlan = types.AttributeKeyPlan + ModuleName = types.ModuleName + QuerierRoute = types.QuerierRoute + QuerySubscription = types.QuerySubscription + QuerySubscriptions = types.QuerySubscriptions + QuerySubscriptionsForAddress = types.QuerySubscriptionsForAddress + QuerySubscriptionsForPlan = types.QuerySubscriptionsForPlan + QuerySubscriptionsForNode = types.QuerySubscriptionsForNode + QueryMembersForSubscription = types.QueryMembersForSubscription +) + +var ( + // functions aliases + RegisterCodec = types.RegisterCodec + ErrorMarshal = types.ErrorMarshal + ErrorUnmarshal = types.ErrorUnmarshal + ErrorUnknownMsgType = types.ErrorUnknownMsgType + ErrorUnknownQueryType = types.ErrorUnknownQueryType + ErrorInvalidField = types.ErrorInvalidField + ErrorPlanDoesNotExist = types.ErrorPlanDoesNotExist + ErrorNodeDoesNotExist = types.ErrorNodeDoesNotExist + ErrorUnauthorized = types.ErrorUnauthorized + ErrorInvalidPlanStatus = types.ErrorInvalidPlanStatus + ErrorPriceDoesNotExist = types.ErrorPriceDoesNotExist + ErrorInvalidNodeStatus = types.ErrorInvalidNodeStatus + ErrorSubscriptionDoesNotExist = types.ErrorSubscriptionDoesNotExist + ErrorInvalidSubscriptionStatus = types.ErrorInvalidSubscriptionStatus + ErrorDuplicateAddress = types.ErrorDuplicateAddress + ErrorAddressWasNotAdded = types.ErrorAddressWasNotAdded + ErrorCanNotSubscribe = types.ErrorCanNotSubscribe + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + SubscriptionKey = types.SubscriptionKey + SubscriptionForAddressKeyPrefix = types.SubscriptionForAddressKeyPrefix + SubscriptionForAddressKey = types.SubscriptionForAddressKey + SubscriptionForPlanKeyPrefix = types.SubscriptionForPlanKeyPrefix + SubscriptionForPlanKey = types.SubscriptionForPlanKey + SubscriptionForNodeKeyPrefix = types.SubscriptionForNodeKeyPrefix + SubscriptionForNodeKey = types.SubscriptionForNodeKey + MemberForSubscriptionKeyPrefix = types.MemberForSubscriptionKeyPrefix + MemberForSubscriptionKey = types.MemberForSubscriptionKey + NewMsgStartSubscription = types.NewMsgStartSubscription + NewMsgAddMemberForSubscription = types.NewMsgAddMemberForSubscription + NewMsgRemoveMemberForSubscription = types.NewMsgRemoveMemberForSubscription + NewMsgEndSubscription = types.NewMsgEndSubscription + NewQueryPlanParams = types.NewQueryPlanParams + NewQueryPlansForProviderParams = types.NewQueryPlansForProviderParams + NewQueryNodesForPlanParams = types.NewQueryNodesForPlanParams + NewQuerySubscriptionParams = types.NewQuerySubscriptionParams + NewQuerySubscriptionsForAddressParams = types.NewQuerySubscriptionsForAddressParams + NewQuerySubscriptionsForPlanParams = types.NewQuerySubscriptionsForPlanParams + NewQuerySubscriptionsForNodeParams = types.NewQuerySubscriptionsForNodeParams + NewQueryMembersForSubscriptionParams = types.NewQueryMembersForSubscriptionParams + NewKeeper = keeper.NewKeeper + Querier = querier.Querier + + // variable aliases + ModuleCdc = types.ModuleCdc + RouterKey = types.RouterKey + StoreKey = types.StoreKey + SubscriptionsCountKey = types.SubscriptionsCountKey + SubscriptionKeyPrefix = types.SubscriptionKeyPrefix +) + +type ( + GenesisSubscription = types.GenesisSubscription + GenesisSubscriptions = types.GenesisSubscriptions + GenesisState = types.GenesisState + MsgStartSubscription = types.MsgStartSubscription + MsgAddMemberForSubscription = types.MsgAddMemberForSubscription + MsgRemoveMemberForSubscription = types.MsgRemoveMemberForSubscription + MsgEndSubscription = types.MsgEndSubscription + QueryPlanParams = types.QueryPlanParams + QueryPlansForProviderParams = types.QueryPlansForProviderParams + QueryNodesForPlanParams = types.QueryNodesForPlanParams + QuerySubscriptionParams = types.QuerySubscriptionParams + QuerySubscriptionsForAddressParams = types.QuerySubscriptionsForAddressParams + QuerySubscriptionsForPlanParams = types.QuerySubscriptionsForPlanParams + QuerySubscriptionsForNodeParams = types.QuerySubscriptionsForNodeParams + QueryMembersForSubscriptionParams = types.QueryMembersForSubscriptionParams + Subscription = types.Subscription + Subscriptions = types.Subscriptions + Keeper = keeper.Keeper +) diff --git a/x/dvpn/subscription/client/cli/cli.go b/x/dvpn/subscription/client/cli/cli.go new file mode 100644 index 00000000..d6b2c7eb --- /dev/null +++ b/x/dvpn/subscription/client/cli/cli.go @@ -0,0 +1,31 @@ +package cli + +import ( + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + "github.com/spf13/cobra" +) + +func GetQueryCommands(cdc *codec.Codec) []*cobra.Command { + return client.GetCommands( + querySubscriptionCmd(cdc), + querySubscriptionsCmd(cdc), + ) +} + +func GetTxCommands(cdc *codec.Codec) []*cobra.Command { + cmd := &cobra.Command{ + Use: "subscription", + Short: "Subscription module sub-commands", + } + + cmd.AddCommand(client.PostCommands( + txStartPlanSubscription(cdc), + txStartNodeSubscription(cdc), + txAddAddressForSubscription(cdc), + txRemoveAddressForSubscription(cdc), + txEndSubscription(cdc), + )...) + + return []*cobra.Command{cmd} +} diff --git a/x/dvpn/subscription/client/cli/flags.go b/x/dvpn/subscription/client/cli/flags.go new file mode 100644 index 00000000..9df7019f --- /dev/null +++ b/x/dvpn/subscription/client/cli/flags.go @@ -0,0 +1,8 @@ +package cli + +const ( + flagAddress = "address" + flagNodeAddress = "node-address" + flagPlan = "plan" + flagMembersOnly = "members-only" +) diff --git a/x/dvpn/subscription/client/cli/query.go b/x/dvpn/subscription/client/cli/query.go new file mode 100644 index 00000000..3155ef76 --- /dev/null +++ b/x/dvpn/subscription/client/cli/query.go @@ -0,0 +1,132 @@ +package cli + +import ( + "fmt" + "strconv" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/spf13/cobra" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/subscription/client/common" + "github.com/sentinel-official/hub/x/dvpn/subscription/types" +) + +func querySubscriptionCmd(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "subscription", + Short: "Query a subscription", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + ctx := context.NewCLIContext().WithCodec(cdc) + + membersOnly, err := cmd.Flags().GetBool(flagMembersOnly) + if err != nil { + return err + } + + id, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return err + } + + if membersOnly { + members, err := common.QueryMembersForSubscription(ctx, id) + if err != nil { + return err + } + + for _, member := range members { + fmt.Println(member.String()) + } + + return nil + } + + subscription, err := common.QuerySubscription(ctx, id) + if err != nil { + return err + } + + fmt.Println(subscription) + return nil + }, + } + + cmd.Flags().Bool(flagMembersOnly, false, "Show members only") + + return cmd +} + +func querySubscriptionsCmd(cdc *codec.Codec) *cobra.Command { + cmd := &cobra.Command{ + Use: "subscriptions", + Short: "Query subscriptions", + RunE: func(cmd *cobra.Command, args []string) (err error) { + ctx := context.NewCLIContext().WithCodec(cdc) + + address, err := cmd.Flags().GetString(flagAddress) + if err != nil { + return err + } + + plan, err := cmd.Flags().GetUint64(flagPlan) + if err != nil { + return err + } + + nodeAddress, err := cmd.Flags().GetString(flagNodeAddress) + if err != nil { + return err + } + + var subscriptions types.Subscriptions + + if len(address) > 0 { + address, err := sdk.AccAddressFromBech32(address) + if err != nil { + return err + } + + subscriptions, err = common.QuerySubscriptionsForAddress(ctx, address) + if err != nil { + return err + } + } else if plan > 0 { + subscriptions, err = common.QuerySubscriptionsForPlan(ctx, plan) + if err != nil { + return err + } + } else if len(nodeAddress) > 0 { + address, err := hub.NodeAddressFromBech32(nodeAddress) + if err != nil { + return err + } + + subscriptions, err = common.QuerySubscriptionsForNode(ctx, address) + if err != nil { + return err + } + } else { + subscriptions, err = common.QuerySubscriptions(ctx) + if err != nil { + return err + } + } + + for _, subscription := range subscriptions { + fmt.Println(subscription) + } + + return nil + }, + } + + cmd.Flags().String(flagAddress, "", "Account address") + cmd.Flags().Uint64(flagPlan, 0, "Plan ID") + cmd.Flags().String(flagNodeAddress, "", "Node address") + + return cmd +} diff --git a/x/dvpn/subscription/client/cli/tx.go b/x/dvpn/subscription/client/cli/tx.go new file mode 100644 index 00000000..ed18754f --- /dev/null +++ b/x/dvpn/subscription/client/cli/tx.go @@ -0,0 +1,130 @@ +package cli + +import ( + "strconv" + + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/auth/client/utils" + "github.com/spf13/cobra" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/subscription/types" +) + +func txStartPlanSubscription(cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "subscribe-plan", + Short: "Subscribe to a plan", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + ctx := context.NewCLIContext().WithCodec(cdc) + + id, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return err + } + + msg := types.NewMsgStartSubscription(ctx.FromAddress, id, args[1], nil, sdk.Coin{}) + return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) + }, + } +} + +func txStartNodeSubscription(cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "subscribe-node", + Short: "Subscribe to a node", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + ctx := context.NewCLIContext().WithCodec(cdc) + + address, err := hub.NodeAddressFromBech32(args[0]) + if err != nil { + return err + } + + deposit, err := sdk.ParseCoin(args[1]) + if err != nil { + return err + } + + msg := types.NewMsgStartSubscription(ctx.FromAddress, 0, "", address, deposit) + return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) + }, + } +} + +func txAddAddressForSubscription(cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "member-add", + Short: "Add a member for a subscription", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + ctx := context.NewCLIContext().WithCodec(cdc) + + id, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return err + } + + address, err := sdk.AccAddressFromBech32(args[1]) + if err != nil { + return err + } + + msg := types.NewMsgAddMemberForSubscription(ctx.FromAddress, id, address) + return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) + }, + } +} + +func txRemoveAddressForSubscription(cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "member-remove", + Short: "Remove a member for a subscription", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + ctx := context.NewCLIContext().WithCodec(cdc) + + id, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return err + } + + address, err := sdk.AccAddressFromBech32(args[1]) + if err != nil { + return err + } + + msg := types.NewMsgRemoveMemberForSubscription(ctx.FromAddress, id, address) + return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) + }, + } +} + +func txEndSubscription(cdc *codec.Codec) *cobra.Command { + return &cobra.Command{ + Use: "end", + Short: "End a subscription", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) + ctx := context.NewCLIContext().WithCodec(cdc) + + id, err := strconv.ParseUint(args[0], 10, 64) + if err != nil { + return err + } + + msg := types.NewMsgEndSubscription(ctx.FromAddress, id) + return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) + }, + } +} diff --git a/x/dvpn/subscription/client/common/query.go b/x/dvpn/subscription/client/common/query.go new file mode 100644 index 00000000..9e8d267a --- /dev/null +++ b/x/dvpn/subscription/client/common/query.go @@ -0,0 +1,149 @@ +package common + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/client/context" + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/subscription/types" +) + +func QuerySubscription(ctx context.CLIContext, id uint64) (*types.Subscription, error) { + params := types.NewQuerySubscriptionParams(id) + bytes, err := ctx.Codec.MarshalJSON(params) + if err != nil { + return nil, err + } + + path := fmt.Sprintf("custom/%s/%s/%s", types.StoreKey, types.QuerierRoute, types.QuerySubscription) + res, _, err := ctx.QueryWithData(path, bytes) + if err != nil { + return nil, err + } + if res == nil { + return nil, fmt.Errorf("no subscription found") + } + + var subscription types.Subscription + if err := ctx.Codec.UnmarshalJSON(res, &subscription); err != nil { + return nil, err + } + + return &subscription, nil +} + +func QuerySubscriptions(ctx context.CLIContext) (types.Subscriptions, error) { + path := fmt.Sprintf("custom/%s/%s/%s", types.StoreKey, types.QuerierRoute, types.QuerySubscriptions) + res, _, err := ctx.QueryWithData(path, nil) + if err != nil { + return nil, err + } + if res == nil { + return nil, fmt.Errorf("no subscriptions found") + } + + var subscriptions types.Subscriptions + if err := ctx.Codec.UnmarshalJSON(res, &subscriptions); err != nil { + return nil, err + } + + return subscriptions, nil +} + +func QuerySubscriptionsForAddress(ctx context.CLIContext, address sdk.AccAddress) (types.Subscriptions, error) { + params := types.NewQuerySubscriptionsForAddressParams(address) + bytes, err := ctx.Codec.MarshalJSON(params) + if err != nil { + return nil, err + } + + path := fmt.Sprintf("custom/%s/%s/%s", types.StoreKey, types.QuerierRoute, types.QuerySubscriptionsForAddress) + res, _, err := ctx.QueryWithData(path, bytes) + if err != nil { + return nil, err + } + if res == nil { + return nil, fmt.Errorf("no subscriptions found") + } + + var subscriptions types.Subscriptions + if err := ctx.Codec.UnmarshalJSON(res, &subscriptions); err != nil { + return nil, err + } + + return subscriptions, nil +} + +func QuerySubscriptionsForPlan(ctx context.CLIContext, id uint64) (types.Subscriptions, error) { + params := types.NewQuerySubscriptionsForPlanParams(id) + bytes, err := ctx.Codec.MarshalJSON(params) + if err != nil { + return nil, err + } + + path := fmt.Sprintf("custom/%s/%s/%s", types.StoreKey, types.QuerierRoute, types.QuerySubscriptionsForPlan) + res, _, err := ctx.QueryWithData(path, bytes) + if err != nil { + return nil, err + } + if res == nil { + return nil, fmt.Errorf("no subscriptions found") + } + + var subscriptions types.Subscriptions + if err := ctx.Codec.UnmarshalJSON(res, &subscriptions); err != nil { + return nil, err + } + + return subscriptions, nil +} + +func QuerySubscriptionsForNode(ctx context.CLIContext, address hub.NodeAddress) (types.Subscriptions, error) { + params := types.NewQuerySubscriptionsForNodeParams(address) + bytes, err := ctx.Codec.MarshalJSON(params) + if err != nil { + return nil, err + } + + path := fmt.Sprintf("custom/%s/%s/%s", types.StoreKey, types.QuerierRoute, types.QuerySubscriptionsForNode) + res, _, err := ctx.QueryWithData(path, bytes) + if err != nil { + return nil, err + } + if res == nil { + return nil, fmt.Errorf("no subscriptions found") + } + + var subscriptions types.Subscriptions + if err := ctx.Codec.UnmarshalJSON(res, &subscriptions); err != nil { + return nil, err + } + + return subscriptions, nil +} + +func QueryMembersForSubscription(ctx context.CLIContext, id uint64) ([]sdk.AccAddress, error) { + params := types.NewQueryMembersForSubscriptionParams(id) + bytes, err := ctx.Codec.MarshalJSON(params) + if err != nil { + return nil, err + } + + path := fmt.Sprintf("custom/%s/%s/%s", types.StoreKey, types.QuerierRoute, types.QueryMembersForSubscription) + res, _, err := ctx.QueryWithData(path, bytes) + if err != nil { + return nil, err + } + if res == nil { + return nil, fmt.Errorf("no members found") + } + + var members []sdk.AccAddress + if err := ctx.Codec.UnmarshalJSON(res, &members); err != nil { + return nil, err + } + + return members, nil +} diff --git a/x/dvpn/subscription/client/rest/query.go b/x/dvpn/subscription/client/rest/query.go new file mode 100644 index 00000000..0062e0ca --- /dev/null +++ b/x/dvpn/subscription/client/rest/query.go @@ -0,0 +1 @@ +package rest diff --git a/x/dvpn/subscription/client/rest/rest.go b/x/dvpn/subscription/client/rest/rest.go new file mode 100644 index 00000000..5700977e --- /dev/null +++ b/x/dvpn/subscription/client/rest/rest.go @@ -0,0 +1,19 @@ +package rest + +import ( + "github.com/cosmos/cosmos-sdk/client/context" + "github.com/gorilla/mux" +) + +func registerQueryRoutes(ctx context.CLIContext, router *mux.Router) { + +} + +func registerTxRoutes(ctx context.CLIContext, router *mux.Router) { + +} + +func RegisterRoutes(ctx context.CLIContext, router *mux.Router) { + registerQueryRoutes(ctx, router) + registerTxRoutes(ctx, router) +} diff --git a/x/dvpn/subscription/client/rest/tx.go b/x/dvpn/subscription/client/rest/tx.go new file mode 100644 index 00000000..0062e0ca --- /dev/null +++ b/x/dvpn/subscription/client/rest/tx.go @@ -0,0 +1 @@ +package rest diff --git a/x/dvpn/subscription/expected/keeper.go b/x/dvpn/subscription/expected/keeper.go new file mode 100644 index 00000000..1983ad0d --- /dev/null +++ b/x/dvpn/subscription/expected/keeper.go @@ -0,0 +1,26 @@ +package expected + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" + node "github.com/sentinel-official/hub/x/dvpn/node/types" + plan "github.com/sentinel-official/hub/x/dvpn/plan/types" +) + +type BankKeeper interface { + SendCoins(ctx sdk.Context, from sdk.AccAddress, to sdk.AccAddress, coins sdk.Coins) sdk.Error +} + +type DepositKeeper interface { + Add(ctx sdk.Context, address sdk.AccAddress, coins sdk.Coins) sdk.Error + Subtract(ctx sdk.Context, address sdk.AccAddress, coins sdk.Coins) sdk.Error +} + +type NodeKeeper interface { + GetNode(ctx sdk.Context, address hub.NodeAddress) (node.Node, bool) +} + +type PlanKeeper interface { + GetPlan(ctx sdk.Context, id uint64) (plan.Plan, bool) +} diff --git a/x/dvpn/subscription/genesis.go b/x/dvpn/subscription/genesis.go new file mode 100644 index 00000000..d7dd28b8 --- /dev/null +++ b/x/dvpn/subscription/genesis.go @@ -0,0 +1,45 @@ +package subscription + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/sentinel-official/hub/x/dvpn/subscription/keeper" + "github.com/sentinel-official/hub/x/dvpn/subscription/types" +) + +func InitGenesis(ctx sdk.Context, k keeper.Keeper, state types.GenesisState) { + for _, item := range state { + k.SetSubscription(ctx, item.Subscription) + + for _, member := range item.Members { + k.SetSubscriptionForAddress(ctx, member, item.Subscription.ID) + k.SetMemberForSubscription(ctx, item.Subscription.ID, member) + } + + if item.Subscription.ID == 0 { + k.SetSubscriptionForNode(ctx, item.Subscription.Node, item.Subscription.ID) + } else { + k.SetSubscriptionForPlan(ctx, item.Subscription.Plan, item.Subscription.ID) + } + + k.SetSubscriptionsCount(ctx, k.GetSubscriptionsCount(ctx)+1) + } +} + +func ExportGenesis(ctx sdk.Context, k keeper.Keeper) types.GenesisState { + _subscriptions := k.GetSubscriptions(ctx) + + subscriptions := make(types.GenesisSubscriptions, 0, len(_subscriptions)) + for _, item := range _subscriptions { + subscriptions = append(subscriptions, types.GenesisSubscription{ + Subscription: item, + Members: k.GetMembersForSubscription(ctx, item.ID), + }) + } + + return types.NewGenesisState(subscriptions) +} + +func ValidateGenesis(state types.GenesisState) error { + return nil +} diff --git a/x/dvpn/subscription/handler.go b/x/dvpn/subscription/handler.go new file mode 100644 index 00000000..4e8e28d6 --- /dev/null +++ b/x/dvpn/subscription/handler.go @@ -0,0 +1,216 @@ +package subscription + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/subscription/keeper" + "github.com/sentinel-official/hub/x/dvpn/subscription/types" +) + +func startPlanSubscription(ctx sdk.Context, k keeper.Keeper, from sdk.AccAddress, id uint64, denom string) sdk.Result { + plan, found := k.GetPlan(ctx, id) + if !found { + return types.ErrorPlanDoesNotExist().Result() + } + if !plan.Status.Equal(hub.StatusActive) { + return types.ErrorInvalidPlanStatus().Result() + } + + price, found := plan.PriceForDenom(denom) + if !found { + return types.ErrorPriceDoesNotExist().Result() + } + + if err := k.SendCoin(ctx, from, plan.Provider.Bytes(), price); err != nil { + return err.Result() + } + + count := k.GetSubscriptionsCount(ctx) + subscription := types.Subscription{ + ID: count + 1, + Address: from, + + Plan: plan.ID, + Duration: 0, + TotalDuration: plan.Duration, + ExpiresAt: ctx.BlockTime().Add(plan.Validity), + + Bandwidth: hub.NewBandwidthFromInt64(0, 0), + TotalBandwidth: plan.Bandwidth, + Status: hub.StatusActive, + StatusAt: ctx.BlockTime(), + } + + k.SetSubscription(ctx, subscription) + k.SetSubscriptionForAddress(ctx, subscription.Address, subscription.ID) + k.SetSubscriptionForPlan(ctx, subscription.Plan, subscription.ID) + k.SetMemberForSubscription(ctx, subscription.ID, subscription.Address) + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeSetSubscription, + sdk.NewAttribute(types.AttributeKeyID, fmt.Sprintf("%d", subscription.ID)), + sdk.NewAttribute(types.AttributeKeyPlan, fmt.Sprintf("%d", subscription.Plan)), + sdk.NewAttribute(types.AttributeKeyAddress, subscription.Address.String()), + )) + + k.SetSubscriptionsCount(ctx, count+1) + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeSetSubscriptionsCount, + sdk.NewAttribute(types.AttributeKeyCount, fmt.Sprintf("%d", count+1)), + )) + + return sdk.Result{Events: ctx.EventManager().Events()} +} + +func startNodeSubscription(ctx sdk.Context, k keeper.Keeper, from sdk.AccAddress, address hub.NodeAddress, deposit sdk.Coin) sdk.Result { + node, found := k.GetNode(ctx, address) + if !found { + return types.ErrorNodeDoesNotExist().Result() + } + if !node.Status.Equal(hub.StatusActive) { + return types.ErrorInvalidNodeStatus().Result() + } + if node.Provider != nil { + return types.ErrorCanNotSubscribe().Result() + } + + if err := k.AddDeposit(ctx, from, deposit); err != nil { + return err.Result() + } + + price, found := node.PriceForDenom(deposit.Denom) + if !found { + return types.ErrorPriceDoesNotExist().Result() + } + + count := k.GetSubscriptionsCount(ctx) + bandwidth, _ := node.BandwidthForCoin(deposit) + + subscription := types.Subscription{ + ID: count + 1, + Address: from, + + Node: address, + Price: price, + Deposit: deposit, + + Bandwidth: hub.NewBandwidthFromInt64(0, 0), + TotalBandwidth: bandwidth, + Status: hub.StatusActive, + StatusAt: ctx.BlockTime(), + } + + k.SetSubscription(ctx, subscription) + k.SetSubscriptionForAddress(ctx, subscription.Address, subscription.ID) + k.SetSubscriptionForNode(ctx, subscription.Node, subscription.ID) + k.SetMemberForSubscription(ctx, subscription.ID, subscription.Address) + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeSetSubscription, + sdk.NewAttribute(types.AttributeKeyID, fmt.Sprintf("%d", subscription.ID)), + sdk.NewAttribute(types.AttributeKeyNode, subscription.Node.String()), + sdk.NewAttribute(types.AttributeKeyAddress, subscription.Address.String()), + )) + + k.SetSubscriptionsCount(ctx, count+1) + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeSetSubscriptionsCount, + sdk.NewAttribute(types.AttributeKeyCount, fmt.Sprintf("%d", count+1)), + )) + + return sdk.Result{Events: ctx.EventManager().Events()} +} + +func HandleStartSubscription(ctx sdk.Context, k keeper.Keeper, msg types.MsgStartSubscription) sdk.Result { + if msg.ID == 0 { + return startNodeSubscription(ctx, k, msg.From, msg.Address, msg.Deposit) + } + + return startPlanSubscription(ctx, k, msg.From, msg.ID, msg.Denom) +} + +func HandleAddMemberForSubscription(ctx sdk.Context, k keeper.Keeper, msg types.MsgAddMemberForSubscription) sdk.Result { + subscription, found := k.GetSubscription(ctx, msg.ID) + if !found { + return types.ErrorSubscriptionDoesNotExist().Result() + } + if !msg.From.Equals(subscription.Address) { + return types.ErrorUnauthorized().Result() + } + if !subscription.Status.Equal(hub.StatusActive) { + return types.ErrorInvalidSubscriptionStatus().Result() + } + + if k.HasMemberForSubscription(ctx, subscription.ID, msg.Address) { + return types.ErrorDuplicateAddress().Result() + } + + k.SetSubscriptionForAddress(ctx, msg.Address, subscription.ID) + k.SetMemberForSubscription(ctx, subscription.ID, msg.Address) + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeAddAddressForSubscription, + sdk.NewAttribute(types.AttributeKeyID, fmt.Sprintf("%d", subscription.ID)), + sdk.NewAttribute(types.AttributeKeyAddress, msg.Address.String()), + )) + + return sdk.Result{Events: ctx.EventManager().Events()} +} + +func HandleRemoveMemberForSubscription(ctx sdk.Context, k keeper.Keeper, msg types.MsgRemoveMemberForSubscription) sdk.Result { + subscription, found := k.GetSubscription(ctx, msg.ID) + if !found { + return types.ErrorSubscriptionDoesNotExist().Result() + } + if !msg.From.Equals(subscription.Address) { + return types.ErrorUnauthorized().Result() + } + if !subscription.Status.Equal(hub.StatusActive) { + return types.ErrorInvalidSubscriptionStatus().Result() + } + + if !k.HasMemberForSubscription(ctx, subscription.ID, msg.Address) { + return types.ErrorAddressWasNotAdded().Result() + } + + k.DeleteSubscriptionForAddress(ctx, msg.Address, subscription.ID) + k.DeleteMemberForSubscription(ctx, subscription.ID, msg.Address) + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeRemoveAddressForSubscription, + sdk.NewAttribute(types.AttributeKeyID, fmt.Sprintf("%d", subscription.ID)), + sdk.NewAttribute(types.AttributeKeyAddress, msg.Address.String()), + )) + + return sdk.Result{Events: ctx.EventManager().Events()} +} + +func HandleEndSubscription(ctx sdk.Context, k keeper.Keeper, msg types.MsgEndSubscription) sdk.Result { + subscription, found := k.GetSubscription(ctx, msg.ID) + if !found { + return types.ErrorSubscriptionDoesNotExist().Result() + } + if !msg.From.Equals(subscription.Address) { + return types.ErrorUnauthorized().Result() + } + if !subscription.Status.Equal(hub.StatusActive) { + return types.ErrorInvalidSubscriptionStatus().Result() + } + + if subscription.Plan == 0 { + amount := subscription.Deposit.Sub(subscription.Amount()) + if err := k.SubtractDeposit(ctx, subscription.Address, amount); err != nil { + return err.Result() + } + } + + subscription.Status = hub.StatusInactive + subscription.StatusAt = ctx.BlockTime() + + k.SetSubscription(ctx, subscription) + ctx.EventManager().EmitEvent(sdk.NewEvent( + types.EventTypeEndSubscription, + sdk.NewAttribute(types.AttributeKeyID, fmt.Sprintf("%d", subscription.ID)), + )) + + return sdk.Result{Events: ctx.EventManager().Events()} +} diff --git a/x/dvpn/subscription/keeper/alias.go b/x/dvpn/subscription/keeper/alias.go new file mode 100644 index 00000000..e758d064 --- /dev/null +++ b/x/dvpn/subscription/keeper/alias.go @@ -0,0 +1,33 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" + node "github.com/sentinel-official/hub/x/dvpn/node/types" + plan "github.com/sentinel-official/hub/x/dvpn/plan/types" +) + +func (k Keeper) SendCoin(ctx sdk.Context, from sdk.AccAddress, to sdk.AccAddress, coin sdk.Coin) sdk.Error { + return k.bank.SendCoins(ctx, from, to, sdk.NewCoins(coin)) +} + +func (k Keeper) AddDeposit(ctx sdk.Context, address sdk.AccAddress, coin sdk.Coin) sdk.Error { + return k.deposit.Add(ctx, address, sdk.Coins{coin}) +} + +func (k Keeper) SubtractDeposit(ctx sdk.Context, address sdk.AccAddress, coin sdk.Coin) sdk.Error { + if coin.IsZero() { + return nil + } + + return k.deposit.Subtract(ctx, address, sdk.Coins{coin}) +} + +func (k Keeper) GetNode(ctx sdk.Context, address hub.NodeAddress) (node.Node, bool) { + return k.node.GetNode(ctx, address) +} + +func (k Keeper) GetPlan(ctx sdk.Context, id uint64) (plan.Plan, bool) { + return k.plan.GetPlan(ctx, id) +} diff --git a/x/dvpn/subscription/keeper/keeper.go b/x/dvpn/subscription/keeper/keeper.go new file mode 100644 index 00000000..9e8c9f0a --- /dev/null +++ b/x/dvpn/subscription/keeper/keeper.go @@ -0,0 +1,49 @@ +package keeper + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/store/prefix" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/sentinel-official/hub/x/dvpn/subscription/expected" + "github.com/sentinel-official/hub/x/dvpn/subscription/types" +) + +type Keeper struct { + cdc *codec.Codec + key sdk.StoreKey + bank expected.BankKeeper + deposit expected.DepositKeeper + node expected.NodeKeeper + plan expected.PlanKeeper +} + +func NewKeeper(cdc *codec.Codec, key sdk.StoreKey) Keeper { + return Keeper{ + cdc: cdc, + key: key, + } +} + +func (k *Keeper) WithBankKeeper(keeper expected.BankKeeper) { + k.bank = keeper +} + +func (k *Keeper) WithDepositKeeper(keeper expected.DepositKeeper) { + k.deposit = keeper +} + +func (k *Keeper) WithNodeKeeper(keeper expected.NodeKeeper) { + k.node = keeper +} + +func (k *Keeper) WithPlanKeeper(keeper expected.PlanKeeper) { + k.plan = keeper +} + +func (k Keeper) Store(ctx sdk.Context) sdk.KVStore { + child := fmt.Sprintf("%s/", types.ModuleName) + return prefix.NewStore(ctx.KVStore(k.key), []byte(child)) +} diff --git a/x/dvpn/subscription/keeper/subscription.go b/x/dvpn/subscription/keeper/subscription.go new file mode 100644 index 00000000..708422aa --- /dev/null +++ b/x/dvpn/subscription/keeper/subscription.go @@ -0,0 +1,198 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" + "github.com/sentinel-official/hub/x/dvpn/subscription/types" +) + +func (k Keeper) SetSubscriptionsCount(ctx sdk.Context, count uint64) { + key := types.SubscriptionsCountKey + value := k.cdc.MustMarshalBinaryLengthPrefixed(count) + + store := k.Store(ctx) + store.Set(key, value) +} + +func (k Keeper) GetSubscriptionsCount(ctx sdk.Context) (count uint64) { + store := k.Store(ctx) + + key := types.SubscriptionsCountKey + value := store.Get(key) + if value == nil { + return 0 + } + + k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &count) + return count +} + +func (k Keeper) SetSubscription(ctx sdk.Context, subscription types.Subscription) { + key := types.SubscriptionKey(subscription.ID) + value := k.cdc.MustMarshalBinaryLengthPrefixed(subscription) + + store := k.Store(ctx) + store.Set(key, value) +} + +func (k Keeper) GetSubscription(ctx sdk.Context, id uint64) (subscription types.Subscription, found bool) { + store := k.Store(ctx) + + key := types.SubscriptionKey(id) + value := store.Get(key) + if value == nil { + return subscription, false + } + + k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &subscription) + return subscription, true +} + +func (k Keeper) GetSubscriptions(ctx sdk.Context) (items types.Subscriptions) { + store := k.Store(ctx) + + iter := sdk.KVStorePrefixIterator(store, types.SubscriptionKeyPrefix) + defer iter.Close() + + for ; iter.Valid(); iter.Next() { + var item types.Subscription + k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &item) + items = append(items, item) + } + + return items +} + +func (k Keeper) SetSubscriptionForAddress(ctx sdk.Context, address sdk.AccAddress, id uint64) { + key := types.SubscriptionForAddressKey(address, id) + value := k.cdc.MustMarshalBinaryLengthPrefixed(id) + + store := k.Store(ctx) + store.Set(key, value) +} + +func (k Keeper) HasSubscriptionForAddress(ctx sdk.Context, address sdk.AccAddress, id uint64) bool { + key := types.SubscriptionForAddressKey(address, id) + + store := k.Store(ctx) + return store.Has(key) +} + +func (k Keeper) DeleteSubscriptionForAddress(ctx sdk.Context, address sdk.AccAddress, id uint64) { + key := types.SubscriptionForAddressKey(address, id) + + store := k.Store(ctx) + store.Delete(key) +} + +func (k Keeper) GetSubscriptionsForAddress(ctx sdk.Context, address sdk.AccAddress) (items types.Subscriptions) { + store := k.Store(ctx) + + iter := sdk.KVStorePrefixIterator(store, types.SubscriptionForAddressKeyPrefix(address)) + defer iter.Close() + + for ; iter.Valid(); iter.Next() { + var id uint64 + k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &id) + + item, _ := k.GetSubscription(ctx, id) + items = append(items, item) + } + + return items +} + +func (k Keeper) SetMemberForSubscription(ctx sdk.Context, id uint64, address sdk.AccAddress) { + key := types.MemberForSubscriptionKey(id, address) + value := k.cdc.MustMarshalBinaryLengthPrefixed(address) + + store := k.Store(ctx) + store.Set(key, value) +} + +func (k Keeper) HasMemberForSubscription(ctx sdk.Context, id uint64, address sdk.AccAddress) bool { + key := types.MemberForSubscriptionKey(id, address) + + store := k.Store(ctx) + return store.Has(key) +} + +func (k Keeper) DeleteMemberForSubscription(ctx sdk.Context, id uint64, address sdk.AccAddress) { + key := types.MemberForSubscriptionKey(id, address) + + store := k.Store(ctx) + store.Delete(key) +} + +func (k Keeper) GetMembersForSubscription(ctx sdk.Context, id uint64) (items []sdk.AccAddress) { + store := k.Store(ctx) + + iter := sdk.KVStorePrefixIterator(store, types.MemberForSubscriptionKeyPrefix(id)) + defer iter.Close() + + for ; iter.Valid(); iter.Next() { + var item sdk.AccAddress + k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &item) + items = append(items, item) + } + + return items +} + +func (k Keeper) SetSubscriptionForPlan(ctx sdk.Context, plan, id uint64) { + key := types.SubscriptionForPlanKey(plan, id) + value := k.cdc.MustMarshalBinaryLengthPrefixed(id) + + store := k.Store(ctx) + store.Set(key, value) +} + +func (k Keeper) GetSubscriptionsForPlan(ctx sdk.Context, plan uint64) (items types.Subscriptions) { + store := k.Store(ctx) + + iter := sdk.KVStorePrefixIterator(store, sdk.Uint64ToBigEndian(plan)) + defer iter.Close() + + for ; iter.Valid(); iter.Next() { + var id uint64 + k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &id) + + item, _ := k.GetSubscription(ctx, id) + items = append(items, item) + } + + return items +} + +func (k Keeper) SetSubscriptionForNode(ctx sdk.Context, address hub.NodeAddress, id uint64) { + key := types.SubscriptionForNodeKey(address, id) + value := k.cdc.MustMarshalBinaryLengthPrefixed(id) + + store := k.Store(ctx) + store.Set(key, value) +} + +func (k Keeper) HasSubscriptionForNode(ctx sdk.Context, address hub.NodeAddress, id uint64) bool { + key := types.SubscriptionForNodeKey(address, id) + + store := k.Store(ctx) + return store.Has(key) +} + +func (k Keeper) GetSubscriptionsForNode(ctx sdk.Context, address hub.NodeAddress) (items types.Subscriptions) { + store := k.Store(ctx) + + iter := sdk.KVStorePrefixIterator(store, types.SubscriptionForNodeKeyPrefix(address)) + defer iter.Close() + + for ; iter.Valid(); iter.Next() { + var id uint64 + k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &id) + + item, _ := k.GetSubscription(ctx, id) + items = append(items, item) + } + + return items +} diff --git a/x/dvpn/subscription/querier/querier.go b/x/dvpn/subscription/querier/querier.go new file mode 100644 index 00000000..75cfe063 --- /dev/null +++ b/x/dvpn/subscription/querier/querier.go @@ -0,0 +1,28 @@ +package querier + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/sentinel-official/hub/x/dvpn/subscription/keeper" + "github.com/sentinel-official/hub/x/dvpn/subscription/types" +) + +func Querier(ctx sdk.Context, path []string, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + switch path[0] { + case types.QuerySubscription: + return querySubscription(ctx, req, k) + case types.QuerySubscriptions: + return querySubscriptions(ctx, req, k) + case types.QuerySubscriptionsForAddress: + return querySubscriptionsForAddress(ctx, req, k) + case types.QuerySubscriptionsForPlan: + return querySubscriptionsForPlan(ctx, req, k) + case types.QuerySubscriptionsForNode: + return querySubscriptionsForNode(ctx, req, k) + case types.QueryMembersForSubscription: + return queryMembersForSubscription(ctx, req, k) + default: + return nil, types.ErrorUnknownQueryType(path[0]) + } +} diff --git a/x/dvpn/subscription/querier/subscription.go b/x/dvpn/subscription/querier/subscription.go new file mode 100644 index 00000000..fd8caa6c --- /dev/null +++ b/x/dvpn/subscription/querier/subscription.go @@ -0,0 +1,93 @@ +package querier + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/sentinel-official/hub/x/dvpn/subscription/keeper" + "github.com/sentinel-official/hub/x/dvpn/subscription/types" +) + +func querySubscription(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + var params types.QuerySubscriptionParams + if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { + return nil, types.ErrorUnmarshal() + } + + plan, found := k.GetSubscription(ctx, params.ID) + if !found { + return nil, nil + } + + res, err := types.ModuleCdc.MarshalJSON(plan) + if err != nil { + return nil, types.ErrorMarshal() + } + + return res, nil +} + +func querySubscriptions(ctx sdk.Context, _ abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + res, err := types.ModuleCdc.MarshalJSON(k.GetSubscriptions(ctx)) + if err != nil { + return nil, types.ErrorMarshal() + } + + return res, nil +} + +func querySubscriptionsForAddress(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + var params types.QuerySubscriptionsForAddressParams + if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { + return nil, types.ErrorUnmarshal() + } + + res, err := types.ModuleCdc.MarshalJSON(k.GetSubscriptionsForAddress(ctx, params.Address)) + if err != nil { + return nil, types.ErrorMarshal() + } + + return res, nil +} + +func querySubscriptionsForPlan(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + var params types.QuerySubscriptionsForPlanParams + if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { + return nil, types.ErrorUnmarshal() + } + + res, err := types.ModuleCdc.MarshalJSON(k.GetSubscriptionsForPlan(ctx, params.ID)) + if err != nil { + return nil, types.ErrorMarshal() + } + + return res, nil +} + +func querySubscriptionsForNode(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + var params types.QuerySubscriptionsForNodeParams + if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { + return nil, types.ErrorUnmarshal() + } + + res, err := types.ModuleCdc.MarshalJSON(k.GetSubscriptionsForNode(ctx, params.Address)) + if err != nil { + return nil, types.ErrorMarshal() + } + + return res, nil +} + +func queryMembersForSubscription(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { + var params types.QueryMembersForSubscriptionParams + if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { + return nil, types.ErrorUnmarshal() + } + + res, err := types.ModuleCdc.MarshalJSON(k.GetMembersForSubscription(ctx, params.ID)) + if err != nil { + return nil, types.ErrorMarshal() + } + + return res, nil +} diff --git a/x/dvpn/subscription/types/codec.go b/x/dvpn/subscription/types/codec.go new file mode 100644 index 00000000..bad92dfb --- /dev/null +++ b/x/dvpn/subscription/types/codec.go @@ -0,0 +1,23 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec" +) + +var ( + ModuleCdc *codec.Codec +) + +func init() { + ModuleCdc = codec.New() + codec.RegisterCrypto(ModuleCdc) + RegisterCodec(ModuleCdc) + ModuleCdc.Seal() +} + +func RegisterCodec(cdc *codec.Codec) { + cdc.RegisterConcrete(MsgStartSubscription{}, "sentinel/MsgStartSubscription", nil) + cdc.RegisterConcrete(MsgAddMemberForSubscription{}, "sentinel/MsgAddMemberForSubscription", nil) + cdc.RegisterConcrete(MsgRemoveMemberForSubscription{}, "sentinel/MsgRemoveMemberForSubscription", nil) + cdc.RegisterConcrete(MsgEndSubscription{}, "sentinel/MsgEndSubscription", nil) +} diff --git a/x/dvpn/subscription/types/errors.go b/x/dvpn/subscription/types/errors.go new file mode 100644 index 00000000..e4b4e470 --- /dev/null +++ b/x/dvpn/subscription/types/errors.go @@ -0,0 +1,111 @@ +package types + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +const ( + Codespace = sdk.CodespaceType(ModuleName) +) + +const ( + errorCodeUnknownMsgType = iota + 101 + errorCodeUnknownQueryType + errorCodeInvalidField + errorCodePlanDoesNotExist + errorCodeNodeDoesNotExist + errorCodeUnauthorized + errorCodeInvalidPlanStatus + errorCodePriceDoesNotExist + errorCodeInvalidNodeStatus + errorCodeSubscriptionDoesNotExist + errorCodeInvalidSubscriptionStatus + errorCodeDuplicateAddress + errorCodeAddressWasNotAdded + errorCodeCanNotSubscribe +) + +const ( + errorMsgUnknownMsgType = "unknown message type: %s" + errorMsgUnknownQueryType = "unknown query type: %s" + errorMsgInvalidField = "invalid field: %s" + errorMsgPlanDoesNotExist = "plan does not exist" + errorMsgNodeDoesNotExist = "node does not exist" + errorMsgUnauthorized = "unauthorized" + errorMsgInvalidPlanStatus = "invalid plan status" + errorMsgPriceDoesNotExist = "price does not exist" + errorMsgInvalidNodeStatus = "invalid node status" + errorMsgSubscriptionDoesNotExist = "subscription does not exist" + errorMsgInvalidSubscriptionStatus = "invalid subscription status" + errorMsgDuplicateAddress = "duplicate address" + errorMsgAddressWasNotAdded = "address was not added" + errorMsgCanNotSubscribe = "can not subscribe" +) + +func ErrorMarshal() sdk.Error { + return sdk.NewError(Codespace, hub.ErrorCodeMarshal, hub.ErrorMsgMarshal) +} + +func ErrorUnmarshal() sdk.Error { + return sdk.NewError(Codespace, hub.ErrorCodeUnmarshal, hub.ErrorMsgUnmarshal) +} + +func ErrorUnknownMsgType(v string) sdk.Error { + return sdk.NewError(Codespace, errorCodeUnknownMsgType, fmt.Sprintf(errorMsgUnknownMsgType, v)) +} + +func ErrorUnknownQueryType(v string) sdk.Error { + return sdk.NewError(Codespace, errorCodeUnknownQueryType, fmt.Sprintf(errorMsgUnknownQueryType, v)) +} + +func ErrorInvalidField(v string) sdk.Error { + return sdk.NewError(Codespace, errorCodeInvalidField, fmt.Sprintf(errorMsgInvalidField, v)) +} + +func ErrorPlanDoesNotExist() sdk.Error { + return sdk.NewError(Codespace, errorCodePlanDoesNotExist, errorMsgPlanDoesNotExist) +} + +func ErrorNodeDoesNotExist() sdk.Error { + return sdk.NewError(Codespace, errorCodeNodeDoesNotExist, errorMsgNodeDoesNotExist) +} + +func ErrorUnauthorized() sdk.Error { + return sdk.NewError(Codespace, errorCodeUnauthorized, errorMsgUnauthorized) +} + +func ErrorInvalidPlanStatus() sdk.Error { + return sdk.NewError(Codespace, errorCodeInvalidPlanStatus, errorMsgInvalidPlanStatus) +} + +func ErrorPriceDoesNotExist() sdk.Error { + return sdk.NewError(Codespace, errorCodePriceDoesNotExist, errorMsgPriceDoesNotExist) +} + +func ErrorInvalidNodeStatus() sdk.Error { + return sdk.NewError(Codespace, errorCodeInvalidNodeStatus, errorMsgInvalidNodeStatus) +} + +func ErrorSubscriptionDoesNotExist() sdk.Error { + return sdk.NewError(Codespace, errorCodeSubscriptionDoesNotExist, errorMsgSubscriptionDoesNotExist) +} + +func ErrorInvalidSubscriptionStatus() sdk.Error { + return sdk.NewError(Codespace, errorCodeInvalidSubscriptionStatus, errorMsgInvalidSubscriptionStatus) +} + +func ErrorDuplicateAddress() sdk.Error { + return sdk.NewError(Codespace, errorCodeDuplicateAddress, errorMsgDuplicateAddress) +} + +func ErrorAddressWasNotAdded() sdk.Error { + return sdk.NewError(Codespace, errorCodeAddressWasNotAdded, errorMsgAddressWasNotAdded) +} + +func ErrorCanNotSubscribe() sdk.Error { + return sdk.NewError(Codespace, errorCodeCanNotSubscribe, errorMsgCanNotSubscribe) +} diff --git a/x/dvpn/subscription/types/events.go b/x/dvpn/subscription/types/events.go new file mode 100644 index 00000000..dcd22af7 --- /dev/null +++ b/x/dvpn/subscription/types/events.go @@ -0,0 +1,17 @@ +package types + +const ( + EventTypeSetSubscription = "set_subscription" + EventTypeSetSubscriptionsCount = "set_subscriptions_count" + EventTypeAddAddressForSubscription = "add_address_for_subscription" + EventTypeRemoveAddressForSubscription = "remove_address_for_subscription" + EventTypeEndSubscription = "end_subscription" +) + +const ( + AttributeKeyAddress = "address" + AttributeKeyID = "id" + AttributeKeyNode = "node" + AttributeKeyCount = "count" + AttributeKeyPlan = "plan" +) diff --git a/x/dvpn/subscription/types/genesis.go b/x/dvpn/subscription/types/genesis.go new file mode 100644 index 00000000..f1727839 --- /dev/null +++ b/x/dvpn/subscription/types/genesis.go @@ -0,0 +1,22 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type GenesisSubscription struct { + Subscription Subscription `json:"_"` + Members []sdk.AccAddress `json:"members"` +} + +type GenesisSubscriptions []GenesisSubscription + +type GenesisState = GenesisSubscriptions + +func NewGenesisState(subscriptions GenesisSubscriptions) GenesisState { + return subscriptions +} + +func DefaultGenesisState() GenesisState { + return GenesisState{} +} diff --git a/x/dvpn/subscription/types/keys.go b/x/dvpn/subscription/types/keys.go new file mode 100644 index 00000000..5402a549 --- /dev/null +++ b/x/dvpn/subscription/types/keys.go @@ -0,0 +1,58 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +const ( + ModuleName = "subscription" + QuerierRoute = ModuleName +) + +var ( + RouterKey = ModuleName + StoreKey = ModuleName +) + +var ( + SubscriptionsCountKey = []byte{0x00} + SubscriptionKeyPrefix = []byte{0x01} +) + +func SubscriptionKey(id uint64) []byte { + return append(SubscriptionKeyPrefix, sdk.Uint64ToBigEndian(id)...) +} + +func SubscriptionForAddressKeyPrefix(address sdk.AccAddress) []byte { + return append([]byte{0x02}, address.Bytes()...) +} + +func SubscriptionForAddressKey(address sdk.AccAddress, i uint64) []byte { + return append(SubscriptionForAddressKeyPrefix(address), sdk.Uint64ToBigEndian(i)...) +} + +func SubscriptionForPlanKeyPrefix(id uint64) []byte { + return append([]byte{0x03}, sdk.Uint64ToBigEndian(id)...) +} + +func SubscriptionForPlanKey(p, s uint64) []byte { + return append(SubscriptionForPlanKeyPrefix(p), sdk.Uint64ToBigEndian(s)...) +} + +func SubscriptionForNodeKeyPrefix(address hub.NodeAddress) []byte { + return append([]byte{0x04}, address.Bytes()...) +} + +func SubscriptionForNodeKey(address hub.NodeAddress, id uint64) []byte { + return append(SubscriptionForNodeKeyPrefix(address), sdk.Uint64ToBigEndian(id)...) +} + +func MemberForSubscriptionKeyPrefix(id uint64) []byte { + return append([]byte{0x05}, sdk.Uint64ToBigEndian(id)...) +} + +func MemberForSubscriptionKey(id uint64, address sdk.AccAddress) []byte { + return append(MemberForSubscriptionKeyPrefix(id), address.Bytes()...) +} diff --git a/x/dvpn/subscription/types/msg.go b/x/dvpn/subscription/types/msg.go new file mode 100644 index 00000000..1bae8949 --- /dev/null +++ b/x/dvpn/subscription/types/msg.go @@ -0,0 +1,251 @@ +package types + +import ( + "encoding/json" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +var ( + _ sdk.Msg = (*MsgStartSubscription)(nil) + _ sdk.Msg = (*MsgAddMemberForSubscription)(nil) + _ sdk.Msg = (*MsgRemoveMemberForSubscription)(nil) + _ sdk.Msg = (*MsgEndSubscription)(nil) +) + +// MsgStartSubscription is for starting a subscription. +type MsgStartSubscription struct { + From sdk.AccAddress `json:"from"` + + ID uint64 `json:"id,omitempty"` + Denom string `json:"denom,omitempty"` + + Address hub.NodeAddress `json:"address,omitempty"` + Deposit sdk.Coin `json:"deposit,omitempty"` +} + +func NewMsgStartSubscription(from sdk.AccAddress, id uint64, denom string, + address hub.NodeAddress, deposit sdk.Coin) MsgStartSubscription { + return MsgStartSubscription{ + From: from, + ID: id, + Denom: denom, + Address: address, + Deposit: deposit, + } +} + +func (m MsgStartSubscription) Route() string { + return RouterKey +} + +func (m MsgStartSubscription) Type() string { + return "start_subscription" +} + +func (m MsgStartSubscription) ValidateBasic() sdk.Error { + if m.From == nil || m.From.Empty() { + return ErrorInvalidField("from") + } + + if m.ID == 0 { + // Address shouldn't be nil or empty + if m.Address == nil || m.Address.Empty() { + return ErrorInvalidField("address") + } + + // Deposit should be valid + if !m.Deposit.IsValid() { + return ErrorInvalidField("deposit") + } + + return nil + } + + // Denom length should be [3, 16] + if len(m.Denom) < 3 || len(m.Denom) > 16 { + return ErrorInvalidField("denom") + } + + return nil +} + +func (m MsgStartSubscription) GetSignBytes() []byte { + bytes, err := json.Marshal(m) + if err != nil { + panic(err) + } + + return bytes +} + +func (m MsgStartSubscription) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{m.From} +} + +// MsgAddMemberForSubscription is for adding a member for a subscription. +type MsgAddMemberForSubscription struct { + From sdk.AccAddress `json:"from"` + ID uint64 `json:"id"` + Address sdk.AccAddress `json:"address"` +} + +func NewMsgAddMemberForSubscription(from sdk.AccAddress, id uint64, address sdk.AccAddress) MsgAddMemberForSubscription { + return MsgAddMemberForSubscription{ + From: from, + ID: id, + Address: address, + } +} + +func (m MsgAddMemberForSubscription) Route() string { + return RouterKey +} + +func (m MsgAddMemberForSubscription) Type() string { + return "add_member_for_subscription" +} + +func (m MsgAddMemberForSubscription) ValidateBasic() sdk.Error { + if m.From == nil || m.From.Empty() { + return ErrorInvalidField("from") + } + + // ID shouldn't be zero + if m.ID == 0 { + return ErrorInvalidField("id") + } + + // Address shouldn't be nil or empty + if m.Address == nil || m.Address.Empty() { + return ErrorInvalidField("address") + } + + // From and Address both shouldn't be same + if m.From.Equals(m.Address) { + return ErrorInvalidField("from and address") + } + + return nil +} + +func (m MsgAddMemberForSubscription) GetSignBytes() []byte { + bytes, err := json.Marshal(m) + if err != nil { + panic(err) + } + + return bytes +} + +func (m MsgAddMemberForSubscription) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{m.From} +} + +// MsgRemoveMemberForSubscription is for removing a member for a subscription. +type MsgRemoveMemberForSubscription struct { + From sdk.AccAddress `json:"from"` + ID uint64 `json:"id"` + Address sdk.AccAddress `json:"address"` +} + +func NewMsgRemoveMemberForSubscription(from sdk.AccAddress, id uint64, address sdk.AccAddress) MsgRemoveMemberForSubscription { + return MsgRemoveMemberForSubscription{ + From: from, + ID: id, + Address: address, + } +} + +func (m MsgRemoveMemberForSubscription) Route() string { + return RouterKey +} + +func (m MsgRemoveMemberForSubscription) Type() string { + return "remove_address_for_subscription" +} + +func (m MsgRemoveMemberForSubscription) ValidateBasic() sdk.Error { + if m.From == nil || m.From.Empty() { + return ErrorInvalidField("from") + } + + // ID shouldn't be zero + if m.ID == 0 { + return ErrorInvalidField("id") + } + + // Address shouldn't be nil or empty + if m.Address == nil || m.Address.Empty() { + return ErrorInvalidField("address") + } + + // From and Address both shouldn't be same + if m.From.Equals(m.Address) { + return ErrorInvalidField("from and address") + } + + return nil +} + +func (m MsgRemoveMemberForSubscription) GetSignBytes() []byte { + bytes, err := json.Marshal(m) + if err != nil { + panic(err) + } + + return bytes +} + +func (m MsgRemoveMemberForSubscription) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{m.From} +} + +// MsgEndSubscription is for ending a subscription. +type MsgEndSubscription struct { + From sdk.AccAddress `json:"from"` + ID uint64 `json:"id"` +} + +func NewMsgEndSubscription(from sdk.AccAddress, id uint64) MsgEndSubscription { + return MsgEndSubscription{ + From: from, + ID: id, + } +} + +func (m MsgEndSubscription) Route() string { + return RouterKey +} + +func (m MsgEndSubscription) Type() string { + return "end_subscription" +} + +func (m MsgEndSubscription) ValidateBasic() sdk.Error { + if m.From == nil || m.From.Empty() { + return ErrorInvalidField("from") + } + + // ID shouldn't be zero + if m.ID == 0 { + return ErrorInvalidField("id") + } + + return nil +} + +func (m MsgEndSubscription) GetSignBytes() []byte { + bytes, err := json.Marshal(m) + if err != nil { + panic(err) + } + + return bytes +} + +func (m MsgEndSubscription) GetSigners() []sdk.AccAddress { + return []sdk.AccAddress{m.From} +} diff --git a/x/dvpn/subscription/types/querier.go b/x/dvpn/subscription/types/querier.go new file mode 100644 index 00000000..3e9c36c1 --- /dev/null +++ b/x/dvpn/subscription/types/querier.go @@ -0,0 +1,96 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +const ( + QuerySubscription = "query_subscription" + QuerySubscriptions = "query_subscriptions" + QuerySubscriptionsForAddress = "query_subscriptions_for_address" + QuerySubscriptionsForPlan = "query_subscriptions_for_plan" + QuerySubscriptionsForNode = "query_subscriptions_for_node" + QueryMembersForSubscription = "query_members_for_subscription" +) + +type QueryPlanParams struct { + ID uint64 `json:"id"` +} + +func NewQueryPlanParams(id uint64) QueryPlanParams { + return QueryPlanParams{ + ID: id, + } +} + +type QueryPlansForProviderParams struct { + Address hub.ProvAddress `json:"address"` +} + +func NewQueryPlansForProviderParams(address hub.ProvAddress) QueryPlansForProviderParams { + return QueryPlansForProviderParams{ + Address: address, + } +} + +type QueryNodesForPlanParams struct { + ID uint64 `json:"id"` +} + +func NewQueryNodesForPlanParams(id uint64) QueryNodesForPlanParams { + return QueryNodesForPlanParams{ + ID: id, + } +} + +type QuerySubscriptionParams struct { + ID uint64 `json:"id"` +} + +func NewQuerySubscriptionParams(id uint64) QuerySubscriptionParams { + return QuerySubscriptionParams{ + ID: id, + } +} + +type QuerySubscriptionsForAddressParams struct { + Address sdk.AccAddress `json:"address"` +} + +func NewQuerySubscriptionsForAddressParams(address sdk.AccAddress) QuerySubscriptionsForAddressParams { + return QuerySubscriptionsForAddressParams{ + Address: address, + } +} + +type QuerySubscriptionsForPlanParams struct { + ID uint64 `json:"id"` +} + +func NewQuerySubscriptionsForPlanParams(id uint64) QuerySubscriptionsForPlanParams { + return QuerySubscriptionsForPlanParams{ + ID: id, + } +} + +type QuerySubscriptionsForNodeParams struct { + Address hub.NodeAddress `json:"address"` +} + +func NewQuerySubscriptionsForNodeParams(address hub.NodeAddress) QuerySubscriptionsForNodeParams { + return QuerySubscriptionsForNodeParams{ + Address: address, + } +} + +type QueryMembersForSubscriptionParams struct { + ID uint64 `json:"id"` +} + +func NewQueryMembersForSubscriptionParams(id uint64) QueryMembersForSubscriptionParams { + return QueryMembersForSubscriptionParams{ + ID: id, + } +} diff --git a/x/dvpn/subscription/types/subscription.go b/x/dvpn/subscription/types/subscription.go new file mode 100644 index 00000000..169d3e58 --- /dev/null +++ b/x/dvpn/subscription/types/subscription.go @@ -0,0 +1,76 @@ +package types + +import ( + "fmt" + "strings" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +type Subscription struct { + ID uint64 `json:"id"` + Address sdk.AccAddress `json:"address"` + + Plan uint64 `json:"plan,omitempty"` + Duration time.Duration `json:"duration,omitempty"` + TotalDuration time.Duration `json:"total_duration,omitempty"` + ExpiresAt time.Time `json:"expires_at,omitempty"` + + Node hub.NodeAddress `json:"node,omitempty"` + Price sdk.Coin `json:"price,omitempty"` + Deposit sdk.Coin `json:"deposit,omitempty"` + + Bandwidth hub.Bandwidth `json:"bandwidth"` + TotalBandwidth hub.Bandwidth `json:"total_bandwidth"` + Status hub.Status `json:"status"` + StatusAt time.Time `json:"status_at"` +} + +func (s Subscription) String() string { + if s.Plan == 0 { + return fmt.Sprintf(strings.TrimSpace(` +ID: %d +Address: %s +Node: %s +Price: %s +Deposit: %s +Bandwidth: %s +Total bandwidth: %s +Status: %s +Status at: %s +`), s.ID, s.Address, s.Node, s.Price, s.Deposit, s.Bandwidth, s.TotalBandwidth, s.Status, s.StatusAt) + } + + return fmt.Sprintf(strings.TrimSpace(` +ID: %d +Address: %s +Plan: %d +Duration: %s +Total duration: %s +Bandwidth: %s +Total bandwidth: %s +Expires at: %s +Status: %s +Status at: %s +`), s.ID, s.Address, s.Plan, s.Duration, s.TotalDuration, s.Bandwidth, s.TotalBandwidth, s.ExpiresAt, s.Status, s.StatusAt) +} + +func (s Subscription) Amount() sdk.Coin { + amount := s.Bandwidth. + CeilTo(hub.Gigabyte.Quo(s.Price.Amount)). + Sum(). + Mul(s.Price.Amount). + Quo(hub.Gigabyte) + + coin := sdk.NewCoin(s.Price.Denom, amount) + if s.Deposit.IsLT(coin) { + return s.Deposit + } + + return coin +} + +type Subscriptions []Subscription diff --git a/x/dvpn/types/codec.go b/x/dvpn/types/codec.go new file mode 100644 index 00000000..d0a42d64 --- /dev/null +++ b/x/dvpn/types/codec.go @@ -0,0 +1,32 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec" + + "github.com/sentinel-official/hub/x/dvpn/deposit" + "github.com/sentinel-official/hub/x/dvpn/node" + "github.com/sentinel-official/hub/x/dvpn/plan" + "github.com/sentinel-official/hub/x/dvpn/provider" + "github.com/sentinel-official/hub/x/dvpn/session" + "github.com/sentinel-official/hub/x/dvpn/subscription" +) + +var ( + ModuleCdc *codec.Codec +) + +func init() { + ModuleCdc = codec.New() + codec.RegisterCrypto(ModuleCdc) + RegisterCodec(ModuleCdc) + ModuleCdc.Seal() +} + +func RegisterCodec(cdc *codec.Codec) { + deposit.RegisterCodec(cdc) + provider.RegisterCodec(cdc) + node.RegisterCodec(cdc) + plan.RegisterCodec(cdc) + subscription.RegisterCodec(cdc) + session.RegisterCodec(cdc) +} diff --git a/x/dvpn/types/errors.go b/x/dvpn/types/errors.go new file mode 100644 index 00000000..abc9fbba --- /dev/null +++ b/x/dvpn/types/errors.go @@ -0,0 +1,39 @@ +package types + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + + hub "github.com/sentinel-official/hub/types" +) + +const ( + Codespace = sdk.CodespaceType("dvpn") +) + +const ( + errorCodeUnknownMsgType = iota + 101 + errorCodeUnknownQueryType +) + +const ( + errorMsgUnknownMsgType = "unknown message type: %s" + errorMsgUnknownQueryType = "unknown query type: %s" +) + +func ErrorMarshal() sdk.Error { + return sdk.NewError(Codespace, hub.ErrorCodeMarshal, hub.ErrorMsgMarshal) +} + +func ErrorUnmarshal() sdk.Error { + return sdk.NewError(Codespace, hub.ErrorCodeUnmarshal, hub.ErrorMsgUnmarshal) +} + +func ErrorUnknownMsgType(v string) sdk.Error { + return sdk.NewError(Codespace, errorCodeUnknownMsgType, fmt.Sprintf(errorMsgUnknownMsgType, v)) +} + +func ErrorUnknownQueryType(v string) sdk.Error { + return sdk.NewError(Codespace, errorCodeUnknownQueryType, fmt.Sprintf(errorMsgUnknownQueryType, v)) +} diff --git a/x/dvpn/types/genesis.go b/x/dvpn/types/genesis.go new file mode 100644 index 00000000..5d12d759 --- /dev/null +++ b/x/dvpn/types/genesis.go @@ -0,0 +1,42 @@ +package types + +import ( + "github.com/sentinel-official/hub/x/dvpn/deposit" + "github.com/sentinel-official/hub/x/dvpn/node" + "github.com/sentinel-official/hub/x/dvpn/plan" + "github.com/sentinel-official/hub/x/dvpn/provider" + "github.com/sentinel-official/hub/x/dvpn/session" + "github.com/sentinel-official/hub/x/dvpn/subscription" +) + +type GenesisState struct { + Deposits deposit.GenesisState `json:"deposits"` + Providers provider.GenesisState `json:"providers"` + Nodes node.GenesisState `json:"nodes"` + Plans plan.GenesisState `json:"plans"` + Subscriptions subscription.GenesisState `json:"subscriptions"` + Sessions session.GenesisState `json:"sessions"` +} + +func NewGenesisState(deposits deposit.GenesisState, providers provider.GenesisState, nodes node.GenesisState, + plans plan.GenesisState, subscriptions subscription.GenesisState, sessions session.GenesisState) GenesisState { + return GenesisState{ + Deposits: deposits, + Providers: providers, + Nodes: nodes, + Plans: plans, + Subscriptions: subscriptions, + Sessions: sessions, + } +} + +func DefaultGenesisState() GenesisState { + return GenesisState{ + Deposits: deposit.DefaultGenesisState(), + Providers: provider.DefaultGenesisState(), + Nodes: node.DefaultGenesisState(), + Plans: plan.DefaultGenesisState(), + Subscriptions: subscription.DefaultGenesisState(), + Sessions: session.DefaultGenesisState(), + } +} diff --git a/x/dvpn/types/keys.go b/x/dvpn/types/keys.go new file mode 100644 index 00000000..af819e45 --- /dev/null +++ b/x/dvpn/types/keys.go @@ -0,0 +1,8 @@ +package types + +const ( + ModuleName = "dvpn" + RouterKey = ModuleName + QuerierRoute = ModuleName + StoreKey = ModuleName +) diff --git a/x/dvpn/types/override.go b/x/dvpn/types/override.go new file mode 100644 index 00000000..592c34a4 --- /dev/null +++ b/x/dvpn/types/override.go @@ -0,0 +1,26 @@ +package types + +import ( + deposit "github.com/sentinel-official/hub/x/dvpn/deposit/types" + node "github.com/sentinel-official/hub/x/dvpn/node/types" + plan "github.com/sentinel-official/hub/x/dvpn/plan/types" + provider "github.com/sentinel-official/hub/x/dvpn/provider/types" + session "github.com/sentinel-official/hub/x/dvpn/session/types" + subscription "github.com/sentinel-official/hub/x/dvpn/subscription/types" +) + +func init() { + deposit.RouterKey = ModuleName + provider.RouterKey = ModuleName + node.RouterKey = ModuleName + plan.RouterKey = ModuleName + subscription.RouterKey = ModuleName + session.RouterKey = ModuleName + + deposit.StoreKey = ModuleName + provider.StoreKey = ModuleName + node.StoreKey = ModuleName + plan.StoreKey = ModuleName + subscription.StoreKey = ModuleName + session.StoreKey = ModuleName +} diff --git a/x/vpn/alias.go b/x/vpn/alias.go deleted file mode 100644 index fc21a87e..00000000 --- a/x/vpn/alias.go +++ /dev/null @@ -1,146 +0,0 @@ -// nolint -// autogenerated code using github.com/rigelrozanski/multitool -// aliases generated for the following subdirectories: -// ALIASGEN: github.com/sentinel-official/hub/x/vpn/types/ -// ALIASGEN: github.com/sentinel-official/hub/x/vpn/keeper/ -// ALIASGEN: github.com/sentinel-official/hub/x/vpn/querier/ -package vpn - -import ( - "github.com/sentinel-official/hub/x/vpn/keeper" - "github.com/sentinel-official/hub/x/vpn/querier" - "github.com/sentinel-official/hub/x/vpn/types" -) - -const ( - Codespace = types.Codespace - ModuleName = types.ModuleName - QuerierRoute = types.QuerierRoute - RouterKey = types.RouterKey - StoreKeySession = types.StoreKeySession - StoreKeyNode = types.StoreKeyNode - StoreKeySubscription = types.StoreKeySubscription - StatusRegistered = types.StatusRegistered - StatusActive = types.StatusActive - StatusInactive = types.StatusInactive - StatusDeRegistered = types.StatusDeRegistered - QueryNode = types.QueryNode - QueryNodesOfAddress = types.QueryNodesOfAddress - QueryAllNodes = types.QueryAllNodes - QuerySubscription = types.QuerySubscription - QuerySubscriptionsOfNode = types.QuerySubscriptionsOfNode - QuerySubscriptionsOfAddress = types.QuerySubscriptionsOfAddress - QueryAllSubscriptions = types.QueryAllSubscriptions - QuerySessionsCountOfSubscription = types.QuerySessionsCountOfSubscription - QuerySession = types.QuerySession - QuerySessionOfSubscription = types.QuerySessionOfSubscription - QuerySessionsOfSubscription = types.QuerySessionsOfSubscription - QueryAllSessions = types.QueryAllSessions - DefaultParamspace = keeper.DefaultParamspace -) - -var ( - // functions aliases - RegisterCodec = types.RegisterCodec - ErrorMarshal = types.ErrorMarshal - ErrorUnmarshal = types.ErrorUnmarshal - ErrorUnknownMsgType = types.ErrorUnknownMsgType - ErrorInvalidQueryType = types.ErrorInvalidQueryType - ErrorInvalidField = types.ErrorInvalidField - ErrorUnauthorized = types.ErrorUnauthorized - ErrorNodeDoesNotExist = types.ErrorNodeDoesNotExist - ErrorInvalidNodeStatus = types.ErrorInvalidNodeStatus - ErrorInvalidDeposit = types.ErrorInvalidDeposit - ErrorSubscriptionDoesNotExist = types.ErrorSubscriptionDoesNotExist - ErrorSubscriptionAlreadyExists = types.ErrorSubscriptionAlreadyExists - ErrorInvalidSubscriptionStatus = types.ErrorInvalidSubscriptionStatus - ErrorInvalidBandwidth = types.ErrorInvalidBandwidth - ErrorInvalidBandwidthSignature = types.ErrorInvalidBandwidthSignature - ErrorSessionAlreadyExists = types.ErrorSessionAlreadyExists - ErrorInvalidSessionStatus = types.ErrorInvalidSessionStatus - NewGenesisState = types.NewGenesisState - DefaultGenesisState = types.DefaultGenesisState - NodeKey = types.NodeKey - NodesCountOfAddressKey = types.NodesCountOfAddressKey - NodeIDByAddressKey = types.NodeIDByAddressKey - SubscriptionKey = types.SubscriptionKey - SubscriptionsCountOfNodeKey = types.SubscriptionsCountOfNodeKey - SubscriptionIDByNodeIDKey = types.SubscriptionIDByNodeIDKey - SubscriptionsCountOfAddressKey = types.SubscriptionsCountOfAddressKey - SubscriptionIDByAddressKey = types.SubscriptionIDByAddressKey - SessionKey = types.SessionKey - SessionsCountOfSubscriptionKey = types.SessionsCountOfSubscriptionKey - SessionIDBySubscriptionIDKey = types.SessionIDBySubscriptionIDKey - ActiveNodeIDsKey = types.ActiveNodeIDsKey - ActiveSessionIDsKey = types.ActiveSessionIDsKey - NewMsgRegisterNode = types.NewMsgRegisterNode - NewMsgUpdateNodeInfo = types.NewMsgUpdateNodeInfo - NewMsgDeregisterNode = types.NewMsgDeregisterNode - NewParams = types.NewParams - DefaultParams = types.DefaultParams - NewQueryNodeParams = types.NewQueryNodeParams - NewQueryNodesOfAddressParams = types.NewQueryNodesOfAddressParams - NewQuerySubscriptionParams = types.NewQuerySubscriptionParams - NewQuerySubscriptionsOfNodePrams = types.NewQuerySubscriptionsOfNodePrams - NewQuerySubscriptionsOfAddressParams = types.NewQuerySubscriptionsOfAddressParams - NewQuerySessionsCountOfSubscriptionParams = types.NewQuerySessionsCountOfSubscriptionParams - NewQuerySessionParams = types.NewQuerySessionParams - NewQuerySessionOfSubscriptionPrams = types.NewQuerySessionOfSubscriptionPrams - NewQuerySessionsOfSubscriptionPrams = types.NewQuerySessionsOfSubscriptionPrams - NewMsgUpdateSessionInfo = types.NewMsgUpdateSessionInfo - NewMsgStartSubscription = types.NewMsgStartSubscription - NewMsgEndSubscription = types.NewMsgEndSubscription - NewKeeper = keeper.NewKeeper - ParamKeyTable = keeper.ParamKeyTable - NewQuerier = querier.NewQuerier - RandomNode = keeper.RandomNode - RandomSubscription = keeper.RandomSubscription - RandomSession = keeper.RandomSession - - // variable aliases - ModuleCdc = types.ModuleCdc - NodesCountKey = types.NodesCountKey - NodeKeyPrefix = types.NodeKeyPrefix - NodesCountOfAddressKeyPrefix = types.NodesCountOfAddressKeyPrefix - NodeIDByAddressKeyPrefix = types.NodeIDByAddressKeyPrefix - SubscriptionsCountKey = types.SubscriptionsCountKey - SubscriptionKeyPrefix = types.SubscriptionKeyPrefix - SubscriptionsCountOfNodeKeyPrefix = types.SubscriptionsCountOfNodeKeyPrefix - SubscriptionIDByNodeIDKeyPrefix = types.SubscriptionIDByNodeIDKeyPrefix - SubscriptionsCountOfAddressKeyPrefix = types.SubscriptionsCountOfAddressKeyPrefix - SubscriptionIDByAddressKeyPrefix = types.SubscriptionIDByAddressKeyPrefix - SessionsCountKey = types.SessionsCountKey - SessionKeyPrefix = types.SessionKeyPrefix - SessionsCountOfSubscriptionKeyPrefix = types.SessionsCountOfSubscriptionKeyPrefix - SessionIDBySubscriptionIDKeyPrefix = types.SessionIDBySubscriptionIDKeyPrefix - DefaultFreeNodesCount = types.DefaultFreeNodesCount - DefaultDeposit = types.DefaultDeposit - DefaultSessionInactiveInterval = types.DefaultSessionInactiveInterval - KeyFreeNodesCount = types.KeyFreeNodesCount - KeyDeposit = types.KeyDeposit - KeySessionInactiveInterval = types.KeySessionInactiveInterval -) - -type ( - GenesisState = types.GenesisState - Node = types.Node - MsgRegisterNode = types.MsgRegisterNode - MsgUpdateNodeInfo = types.MsgUpdateNodeInfo - MsgDeregisterNode = types.MsgDeregisterNode - Params = types.Params - QueryNodeParams = types.QueryNodeParams - QueryNodesOfAddressPrams = types.QueryNodesOfAddressPrams - QuerySubscriptionParams = types.QuerySubscriptionParams - QuerySubscriptionsOfNodePrams = types.QuerySubscriptionsOfNodePrams - QuerySubscriptionsOfAddressParams = types.QuerySubscriptionsOfAddressParams - QuerySessionsCountOfSubscriptionParams = types.QuerySessionsCountOfSubscriptionParams - QuerySessionParams = types.QuerySessionParams - QuerySessionOfSubscriptionPrams = types.QuerySessionOfSubscriptionPrams - QuerySessionsOfSubscriptionPrams = types.QuerySessionsOfSubscriptionPrams - Session = types.Session - MsgUpdateSessionInfo = types.MsgUpdateSessionInfo - Subscription = types.Subscription - MsgStartSubscription = types.MsgStartSubscription - MsgEndSubscription = types.MsgEndSubscription - Keeper = keeper.Keeper -) diff --git a/x/vpn/client/cli/cli.go b/x/vpn/client/cli/cli.go deleted file mode 100644 index c65ed019..00000000 --- a/x/vpn/client/cli/cli.go +++ /dev/null @@ -1,82 +0,0 @@ -package cli - -import ( - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/spf13/cobra" -) - -func GetQueryCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "vpn", - Short: "Querying commands for the vpn module", - } - - cmd.AddCommand(client.GetCommands( - QueryNodeCmd(cdc), - QueryNodesCmd(cdc), - QuerySubscriptionCmd(cdc), - QuerySubscriptionsCmd(cdc), - QuerySessionCmd(cdc), - QuerySessionsCmd(cdc), - )...) - - return cmd -} - -func GetTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "vpn", - Short: "VPN transactions subcommands", - } - - cmd.AddCommand( - nodeTxCmd(cdc), - subscriptionTxCmd(cdc), - sessionTxCmd(cdc)) - - return cmd -} - -func nodeTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "node", - Short: "Node transactions subcommands", - } - - cmd.AddCommand(client.PostCommands( - RegisterNodeTxCmd(cdc), - UpdateNodeInfoTxCmd(cdc), - DeregisterNodeTxCmd(cdc), - )...) - - return cmd -} - -func subscriptionTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "subscription", - Short: "Client subscription subcommands", - } - - cmd.AddCommand(client.PostCommands( - StartSubscriptionTxCmd(cdc), - EndSubscriptionTxCmd(cdc), - )...) - - return cmd -} - -func sessionTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "session", - Short: "Session transactions subcommands", - } - - cmd.AddCommand(client.PostCommands( - SignSessionBandwidthTxCmd(cdc), - UpdateSessionInfoTxCmd(cdc), - )...) - - return cmd -} diff --git a/x/vpn/client/cli/deregister_node.go b/x/vpn/client/cli/deregister_node.go deleted file mode 100644 index 8f56ce7b..00000000 --- a/x/vpn/client/cli/deregister_node.go +++ /dev/null @@ -1,37 +0,0 @@ -package cli - -import ( - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - "github.com/spf13/cobra" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func DeregisterNodeTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "deregister", - Short: "Deregister node", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) - ctx := context.NewCLIContext().WithCodec(cdc) - - id, err := hub.NewNodeIDFromString(args[0]) - if err != nil { - return err - } - - fromAddress := ctx.GetFromAddress() - - msg := types.NewMsgDeregisterNode(fromAddress, id) - return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) - }, - } - - return cmd -} diff --git a/x/vpn/client/cli/end_subscription.go b/x/vpn/client/cli/end_subscription.go deleted file mode 100644 index 2eae4592..00000000 --- a/x/vpn/client/cli/end_subscription.go +++ /dev/null @@ -1,37 +0,0 @@ -package cli - -import ( - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - "github.com/spf13/cobra" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func EndSubscriptionTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "end", - Short: "End subscription", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) - ctx := context.NewCLIContext().WithCodec(cdc) - - id, err := hub.NewSubscriptionIDFromString(args[0]) - if err != nil { - return err - } - - fromAddress := ctx.GetFromAddress() - - msg := types.NewMsgEndSubscription(fromAddress, id) - return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) - }, - } - - return cmd -} diff --git a/x/vpn/client/cli/flags.go b/x/vpn/client/cli/flags.go deleted file mode 100644 index fe4ac398..00000000 --- a/x/vpn/client/cli/flags.go +++ /dev/null @@ -1,19 +0,0 @@ -package cli - -const ( - flagMoniker = "moniker" - flagDeposit = "deposit" - flagUpload = "upload" - flagUploadSpeed = "upload-speed" - flagDownload = "download" - flagDownloadSpeed = "download-speed" - flagEncryption = "encryption" - flagPricesPerGB = "prices-per-gb" - flagType = "type" - flagVersion = "version" - flagNodeID = "node-id" - flagAddress = "address" - flagClientSign = "client-sign" - flagNodeOwnerSign = "node-owner-sign" - flagSubscriptionID = "subscription-id" -) diff --git a/x/vpn/client/cli/query_nodes.go b/x/vpn/client/cli/query_nodes.go deleted file mode 100644 index f1587d23..00000000 --- a/x/vpn/client/cli/query_nodes.go +++ /dev/null @@ -1,67 +0,0 @@ -package cli - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/sentinel-official/hub/x/vpn/client/common" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func QueryNodeCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "node", - Short: "Query node", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - ctx := context.NewCLIContext().WithCodec(cdc) - - node, err := common.QueryNode(ctx, args[0]) - if err != nil { - return err - } - - fmt.Println(node) - return nil - }, - } - - return cmd -} - -func QueryNodesCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "nodes", - Short: "Query nodes", - RunE: func(cmd *cobra.Command, args []string) (err error) { - ctx := context.NewCLIContext().WithCodec(cdc) - - address := viper.GetString(flagAddress) - - var nodes []types.Node - if address != "" { - nodes, err = common.QueryNodesOfAddress(ctx, address) - } else { - nodes, err = common.QueryAllNodes(ctx) - } - - if err != nil { - return err - } - - for _, node := range nodes { - fmt.Println(node) - } - - return nil - }, - } - - cmd.Flags().String(flagAddress, "", "Account address") - - return cmd -} diff --git a/x/vpn/client/cli/query_sessions.go b/x/vpn/client/cli/query_sessions.go deleted file mode 100644 index c7cf44b8..00000000 --- a/x/vpn/client/cli/query_sessions.go +++ /dev/null @@ -1,67 +0,0 @@ -package cli - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/sentinel-official/hub/x/vpn/client/common" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func QuerySessionCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "session", - Short: "Query session", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - ctx := context.NewCLIContext().WithCodec(cdc) - - session, err := common.QuerySession(ctx, args[0]) - if err != nil { - return err - } - - fmt.Println(session) - return nil - }, - } - - return cmd -} - -func QuerySessionsCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "sessions", - Short: "Query sessions", - RunE: func(cmd *cobra.Command, args []string) (err error) { - ctx := context.NewCLIContext().WithCodec(cdc) - - id := viper.GetString(flagSubscriptionID) - - var sessions []types.Session - if id != "" { - sessions, err = common.QuerySessionsOfSubscription(ctx, id) - } else { - sessions, err = common.QueryAllSessions(ctx) - } - - if err != nil { - return err - } - - for _, session := range sessions { - fmt.Println(session) - } - - return nil - }, - } - - cmd.Flags().String(flagSubscriptionID, "", "Subscription ID") - - return cmd -} diff --git a/x/vpn/client/cli/query_subscriptions.go b/x/vpn/client/cli/query_subscriptions.go deleted file mode 100644 index 6c112cc1..00000000 --- a/x/vpn/client/cli/query_subscriptions.go +++ /dev/null @@ -1,71 +0,0 @@ -package cli - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/sentinel-official/hub/x/vpn/client/common" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func QuerySubscriptionCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "subscription", - Short: "Query subscription", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - ctx := context.NewCLIContext().WithCodec(cdc) - - subscription, err := common.QuerySubscription(ctx, args[0]) - if err != nil { - return err - } - - fmt.Println(subscription) - return nil - }, - } - - return cmd -} - -func QuerySubscriptionsCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "subscriptions", - Short: "Query subscriptions", - RunE: func(cmd *cobra.Command, args []string) (err error) { - ctx := context.NewCLIContext().WithCodec(cdc) - - id := viper.GetString(flagNodeID) - address := viper.GetString(flagAddress) - - var subscriptions []types.Subscription - if id != "" { - subscriptions, err = common.QuerySubscriptionsOfNode(ctx, id) - } else if address != "" { - subscriptions, err = common.QuerySubscriptionsOfAddress(ctx, address) - } else { - subscriptions, err = common.QueryAllSubscriptions(ctx) - } - - if err != nil { - return err - } - - for _, subscription := range subscriptions { - fmt.Println(subscription) - } - - return nil - }, - } - - cmd.Flags().String(flagNodeID, "", "Node ID") - cmd.Flags().String(flagAddress, "", "Account address") - - return cmd -} diff --git a/x/vpn/client/cli/register_node.go b/x/vpn/client/cli/register_node.go deleted file mode 100644 index 5d1565d6..00000000 --- a/x/vpn/client/cli/register_node.go +++ /dev/null @@ -1,63 +0,0 @@ -package cli - -import ( - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - "github.com/spf13/cobra" - "github.com/spf13/viper" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func RegisterNodeTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "register", - Short: "Register node", - RunE: func(cmd *cobra.Command, args []string) error { - txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) - ctx := context.NewCLIContext().WithCodec(cdc) - - _type := viper.GetString(flagType) - version := viper.GetString(flagVersion) - moniker := viper.GetString(flagMoniker) - pricesPerGB := viper.GetString(flagPricesPerGB) - internetSpeed := hub.Bandwidth{ - Upload: sdk.NewInt(viper.GetInt64(flagUploadSpeed)), - Download: sdk.NewInt(viper.GetInt64(flagDownloadSpeed)), - } - encryption := viper.GetString(flagEncryption) - - parsedPricesPerGB, err := sdk.ParseCoins(pricesPerGB) - if err != nil { - return err - } - - msg := types.NewMsgRegisterNode(ctx.FromAddress, _type, version, - moniker, parsedPricesPerGB, internetSpeed, encryption) - - return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) - }, - } - - cmd.Flags().String(flagType, "", "VPN node type") - cmd.Flags().String(flagVersion, "", "VPN node version") - cmd.Flags().String(flagMoniker, "", "Moniker") - cmd.Flags().String(flagPricesPerGB, "", "Prices per GB") - cmd.Flags().Int64(flagUploadSpeed, 0, "Internet upload speed in bytes/sec") - cmd.Flags().Int64(flagDownloadSpeed, 0, "Internet download speed in bytes/sec") - cmd.Flags().String(flagEncryption, "", "VPN encryption method") - - _ = cmd.MarkFlagRequired(flagType) - _ = cmd.MarkFlagRequired(flagVersion) - _ = cmd.MarkFlagRequired(flagMoniker) - _ = cmd.MarkFlagRequired(flagUploadSpeed) - _ = cmd.MarkFlagRequired(flagDownloadSpeed) - _ = cmd.MarkFlagRequired(flagEncryption) - _ = cmd.MarkFlagRequired(flagPricesPerGB) - - return cmd -} diff --git a/x/vpn/client/cli/session_bandwidth.go b/x/vpn/client/cli/session_bandwidth.go deleted file mode 100644 index db96331e..00000000 --- a/x/vpn/client/cli/session_bandwidth.go +++ /dev/null @@ -1,134 +0,0 @@ -package cli - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - "github.com/spf13/cobra" - "github.com/spf13/viper" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/client/common" - "github.com/sentinel-official/hub/x/vpn/types" -) - -// nolint:funlen -func SignSessionBandwidthTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "sign-bandwidth", - Short: "Sign session bandwidth", - RunE: func(cmd *cobra.Command, args []string) error { - ctx := context.NewCLIContext().WithCodec(cdc) - _id := viper.GetString(flagSubscriptionID) - bandwidth := hub.Bandwidth{ - Upload: sdk.NewInt(viper.GetInt64(flagUpload)), - Download: sdk.NewInt(viper.GetInt64(flagDownload)), - } - - scs, err := common.QuerySessionsCountOfSubscription(ctx, _id) - if err != nil { - return err - } - - id, err := hub.NewSubscriptionIDFromString(_id) - if err != nil { - return err - } - - data := hub.NewBandwidthSignatureData(id, scs, bandwidth).Bytes() - - passphrase, err := keys.GetPassphrase(ctx.FromName) - if err != nil { - return err - } - - kb, err := keys.NewKeyBaseFromHomeFlag() - if err != nil { - return err - } - - sigBytes, pubKey, err := kb.Sign(ctx.FromName, passphrase, data) - if err != nil { - return err - } - - stdSignature := auth.StdSignature{ - PubKey: pubKey, - Signature: sigBytes, - } - - bytes, err := cdc.MarshalJSON(stdSignature) - if err != nil { - return err - } - - fmt.Println(string(bytes)) - return nil - }, - } - - cmd.Flags().String(flagSubscriptionID, "", "Subscription ID") - cmd.Flags().Int64(flagUpload, 0, "Upload in in bytes") - cmd.Flags().Int64(flagDownload, 0, "Download in bytes") - - _ = cmd.MarkFlagRequired(flagSubscriptionID) - _ = cmd.MarkFlagRequired(flagUpload) - _ = cmd.MarkFlagRequired(flagDownload) - - return cmd -} - -func UpdateSessionInfoTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "update-session-info", - Short: "Update session info", - RunE: func(cmd *cobra.Command, args []string) error { - txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) - ctx := context.NewCLIContext().WithCodec(cdc) - - id, err := hub.NewSubscriptionIDFromString(viper.GetString(flagSubscriptionID)) - if err != nil { - return err - } - bandwidth := hub.Bandwidth{ - Upload: sdk.NewInt(viper.GetInt64(flagUpload)), - Download: sdk.NewInt(viper.GetInt64(flagDownload)), - } - nodeOwnerSignatureStr := viper.GetString(flagNodeOwnerSign) - clientSignatureStr := viper.GetString(flagClientSign) - - var nodeOwnerSignature auth.StdSignature - if err := cdc.UnmarshalJSON([]byte(nodeOwnerSignatureStr), &nodeOwnerSignature); err != nil { - return err - } - - var clientSignature auth.StdSignature - if err := cdc.UnmarshalJSON([]byte(clientSignatureStr), &clientSignature); err != nil { - return err - } - - msg := types.NewMsgUpdateSessionInfo(ctx.FromAddress, id, bandwidth, nodeOwnerSignature, clientSignature) - - return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) - }, - } - - cmd.Flags().String(flagSubscriptionID, "", "Subscription ID") - cmd.Flags().Int64(flagUpload, 0, "Upload in in bytes") - cmd.Flags().Int64(flagDownload, 0, "Download in bytes") - cmd.Flags().String(flagNodeOwnerSign, "", "Signature of the node owner") - cmd.Flags().String(flagClientSign, "", "Signature of the client") - - _ = cmd.MarkFlagRequired(flagSubscriptionID) - _ = cmd.MarkFlagRequired(flagUpload) - _ = cmd.MarkFlagRequired(flagDownload) - _ = cmd.MarkFlagRequired(flagNodeOwnerSign) - _ = cmd.MarkFlagRequired(flagClientSign) - - return cmd -} diff --git a/x/vpn/client/cli/start_subscription.go b/x/vpn/client/cli/start_subscription.go deleted file mode 100644 index 3d93c35d..00000000 --- a/x/vpn/client/cli/start_subscription.go +++ /dev/null @@ -1,50 +0,0 @@ -package cli - -import ( - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - "github.com/spf13/cobra" - "github.com/spf13/viper" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func StartSubscriptionTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "start", - Short: "Start subscription", - RunE: func(cmd *cobra.Command, args []string) error { - txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) - ctx := context.NewCLIContext().WithCodec(cdc) - - nodeID, err := hub.NewNodeIDFromString(viper.GetString(flagNodeID)) - if err != nil { - return err - } - - deposit := viper.GetString(flagDeposit) - - parsedDeposit, err := sdk.ParseCoin(deposit) - if err != nil { - return err - } - - fromAddress := ctx.GetFromAddress() - - msg := types.NewMsgStartSubscription(fromAddress, nodeID, parsedDeposit) - return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) - }, - } - - cmd.Flags().String(flagNodeID, "", "Node ID") - cmd.Flags().String(flagDeposit, "", "Deposit") - - _ = cmd.MarkFlagRequired(flagNodeID) - _ = cmd.MarkFlagRequired(flagDeposit) - - return cmd -} diff --git a/x/vpn/client/cli/update_node.go b/x/vpn/client/cli/update_node.go deleted file mode 100644 index 45e657c0..00000000 --- a/x/vpn/client/cli/update_node.go +++ /dev/null @@ -1,64 +0,0 @@ -package cli - -import ( - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - "github.com/spf13/cobra" - "github.com/spf13/viper" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func UpdateNodeInfoTxCmd(cdc *codec.Codec) *cobra.Command { - cmd := &cobra.Command{ - Use: "update-info", - Short: "Update info of the node", - RunE: func(cmd *cobra.Command, args []string) error { - txb := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc)) - ctx := context.NewCLIContext().WithCodec(cdc) - - nodeID, err := hub.NewNodeIDFromString(viper.GetString(flagNodeID)) - if err != nil { - return err - } - - _type := viper.GetString(flagType) - version := viper.GetString(flagVersion) - moniker := viper.GetString(flagMoniker) - pricesPerGB := viper.GetString(flagPricesPerGB) - internetSpeed := hub.Bandwidth{ - Upload: sdk.NewInt(viper.GetInt64(flagUploadSpeed)), - Download: sdk.NewInt(viper.GetInt64(flagDownloadSpeed)), - } - encryption := viper.GetString(flagEncryption) - - parsedPricesPerGB, err := sdk.ParseCoins(pricesPerGB) - if err != nil { - return err - } - - fromAddress := ctx.GetFromAddress() - - msg := types.NewMsgUpdateNodeInfo(fromAddress, nodeID, - _type, version, moniker, parsedPricesPerGB, internetSpeed, encryption) - return utils.GenerateOrBroadcastMsgs(ctx, txb, []sdk.Msg{msg}) - }, - } - - cmd.Flags().String(flagNodeID, "", "Node ID") - cmd.Flags().String(flagType, "", "VPN node type") - cmd.Flags().String(flagVersion, "", "VPN node version") - cmd.Flags().String(flagMoniker, "", "Moniker") - cmd.Flags().String(flagPricesPerGB, "", "Prices per GB") - cmd.Flags().Int64(flagUploadSpeed, 0, "Internet upload speed in bytes/sec") - cmd.Flags().Int64(flagDownloadSpeed, 0, "Internet download speed in bytes/sec") - cmd.Flags().String(flagEncryption, "", "VPN encryption method") - - _ = cmd.MarkFlagRequired(flagNodeID) - - return cmd -} diff --git a/x/vpn/client/common/query.go b/x/vpn/client/common/query.go deleted file mode 100644 index e1d6f3f9..00000000 --- a/x/vpn/client/common/query.go +++ /dev/null @@ -1,329 +0,0 @@ -package common - -import ( - "fmt" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func QueryNode(ctx context.CLIContext, s string) (*types.Node, error) { - id, err := hub.NewNodeIDFromString(s) - if err != nil { - return nil, err - } - params := types.NewQueryNodeParams(id) - - bytes, err := ctx.Codec.MarshalJSON(params) - if err != nil { - return nil, err - } - - path := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryNode) - res, _, err := ctx.QueryWithData(path, bytes) - if err != nil { - return nil, err - } - if res == nil { - return nil, fmt.Errorf("no node found") - } - - var node types.Node - if err := ctx.Codec.UnmarshalJSON(res, &node); err != nil { - return nil, err - } - - return &node, nil -} - -func QueryNodesOfAddress(ctx context.CLIContext, s string) ([]types.Node, error) { - address, err := sdk.AccAddressFromBech32(s) - if err != nil { - return nil, err - } - - params := types.NewQueryNodesOfAddressParams(address) - - bytes, err := ctx.Codec.MarshalJSON(params) - if err != nil { - return nil, err - } - - path := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryNodesOfAddress) - res, _, err := ctx.QueryWithData(path, bytes) - if err != nil { - return nil, err - } - if string(res) == "[]" || string(res) == "null" { - return nil, fmt.Errorf("no nodes found") - } - - var nodes []types.Node - if err := ctx.Codec.UnmarshalJSON(res, &nodes); err != nil { - return nil, err - } - - return nodes, nil -} - -func QueryAllNodes(ctx context.CLIContext) ([]types.Node, error) { - path := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryAllNodes) - res, _, err := ctx.QueryWithData(path, nil) - if err != nil { - return nil, err - } - if string(res) == "[]" || string(res) == "null" { - return nil, fmt.Errorf("no nodes found") - } - - var nodes []types.Node - if err := ctx.Codec.UnmarshalJSON(res, &nodes); err != nil { - return nil, err - } - - return nodes, nil -} - -func QuerySubscription(ctx context.CLIContext, s string) (*types.Subscription, error) { - id, err := hub.NewSubscriptionIDFromString(s) - if err != nil { - return nil, err - } - params := types.NewQuerySubscriptionParams(id) - - bytes, err := ctx.Codec.MarshalJSON(params) - if err != nil { - return nil, err - } - - path := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySubscription) - res, _, err := ctx.QueryWithData(path, bytes) - if err != nil { - return nil, err - } - if res == nil { - return nil, fmt.Errorf("no subscription found") - } - - var subscription types.Subscription - if err := ctx.Codec.UnmarshalJSON(res, &subscription); err != nil { - return nil, err - } - - return &subscription, nil -} - -func QuerySubscriptionsOfNode(ctx context.CLIContext, s string) ([]types.Subscription, error) { - id, err := hub.NewNodeIDFromString(s) - if err != nil { - return nil, err - } - params := types.NewQuerySubscriptionsOfNodePrams(id) - - bytes, err := ctx.Codec.MarshalJSON(params) - if err != nil { - return nil, err - } - - path := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySubscriptionsOfNode) - res, _, err := ctx.QueryWithData(path, bytes) - if err != nil { - return nil, err - } - if string(res) == "[]" || string(res) == "null" { - return nil, fmt.Errorf("no subscriptions found") - } - - var subscriptions []types.Subscription - if err := ctx.Codec.UnmarshalJSON(res, &subscriptions); err != nil { - return nil, err - } - - return subscriptions, nil -} - -func QuerySubscriptionsOfAddress(ctx context.CLIContext, s string) ([]types.Subscription, error) { - address, err := sdk.AccAddressFromBech32(s) - if err != nil { - return nil, err - } - - params := types.NewQuerySubscriptionsOfAddressParams(address) - - bytes, err := ctx.Codec.MarshalJSON(params) - if err != nil { - return nil, err - } - - path := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySubscriptionsOfAddress) - res, _, err := ctx.QueryWithData(path, bytes) - if err != nil { - return nil, err - } - if string(res) == "[]" || string(res) == "null" { - return nil, fmt.Errorf("no subscriptions found") - } - - var subscriptions []types.Subscription - if err := ctx.Codec.UnmarshalJSON(res, &subscriptions); err != nil { - return nil, err - } - - return subscriptions, nil -} - -func QueryAllSubscriptions(ctx context.CLIContext) ([]types.Subscription, error) { - path := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryAllSubscriptions) - res, _, err := ctx.QueryWithData(path, nil) - if err != nil { - return nil, err - } - if string(res) == "[]" || string(res) == "null" { - return nil, fmt.Errorf("no subscriptions found") - } - - var subscriptions []types.Subscription - if err := ctx.Codec.UnmarshalJSON(res, &subscriptions); err != nil { - return nil, err - } - - return subscriptions, nil -} - -func QuerySessionsCountOfSubscription(ctx context.CLIContext, s string) (uint64, error) { - id, err := hub.NewSubscriptionIDFromString(s) - if err != nil { - return 0, err - } - params := types.NewQuerySessionsCountOfSubscriptionParams(id) - - bytes, err := ctx.Codec.MarshalJSON(params) - if err != nil { - return 0, err - } - - path := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySessionsCountOfSubscription) - res, _, err := ctx.QueryWithData(path, bytes) - if err != nil { - return 0, err - } - if res == nil { - return 0, fmt.Errorf("no sessions count found") - } - - var count uint64 - if err := ctx.Codec.UnmarshalJSON(res, &count); err != nil { - return 0, err - } - - return count, nil -} - -func QuerySession(ctx context.CLIContext, s string) (*types.Session, error) { - id, err := hub.NewSessionIDFromString(s) - if err != nil { - return nil, err - } - - params := types.NewQuerySessionParams(id) - - bytes, err := ctx.Codec.MarshalJSON(params) - if err != nil { - return nil, err - } - - path := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySession) - res, _, err := ctx.QueryWithData(path, bytes) - if err != nil { - return nil, err - } - if res == nil { - return nil, fmt.Errorf("no session found") - } - - var session types.Session - if err := ctx.Codec.UnmarshalJSON(res, &session); err != nil { - return nil, err - } - - return &session, nil -} - -func QuerySessionOfSubscription(ctx context.CLIContext, s string, index uint64) (*types.Session, error) { - id, err := hub.NewSubscriptionIDFromString(s) - if err != nil { - return nil, err - } - params := types.NewQuerySessionOfSubscriptionPrams(id, index) - - bytes, err := ctx.Codec.MarshalJSON(params) - if err != nil { - return nil, err - } - - path := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySessionOfSubscription) - res, _, err := ctx.QueryWithData(path, bytes) - if err != nil { - return nil, err - } - if res == nil { - return nil, fmt.Errorf("no session found") - } - - var session types.Session - if err := ctx.Codec.UnmarshalJSON(res, &session); err != nil { - return nil, err - } - - return &session, nil -} - -func QuerySessionsOfSubscription(ctx context.CLIContext, s string) ([]types.Session, error) { - id, err := hub.NewSubscriptionIDFromString(s) - if err != nil { - return nil, err - } - params := types.NewQuerySessionsOfSubscriptionPrams(id) - - bytes, err := ctx.Codec.MarshalJSON(params) - if err != nil { - return nil, err - } - - path := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySessionsOfSubscription) - res, _, err := ctx.QueryWithData(path, bytes) - if err != nil { - return nil, err - } - if string(res) == "[]" || string(res) == "null" { - return nil, fmt.Errorf("no sessions found") - } - - var sessions []types.Session - if err := ctx.Codec.UnmarshalJSON(res, &sessions); err != nil { - return nil, err - } - - return sessions, nil -} - -func QueryAllSessions(ctx context.CLIContext) ([]types.Session, error) { - path := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryAllSessions) - res, _, err := ctx.QueryWithData(path, nil) - if err != nil { - return nil, err - } - if string(res) == "[]" || string(res) == "null" { - return nil, fmt.Errorf("no sessions found") - } - - var sessions []types.Session - if err := ctx.Codec.UnmarshalJSON(res, &sessions); err != nil { - return nil, err - } - - return sessions, nil -} diff --git a/x/vpn/client/rest/deregister_node.go b/x/vpn/client/rest/deregister_node.go deleted file mode 100644 index 3b4daf4c..00000000 --- a/x/vpn/client/rest/deregister_node.go +++ /dev/null @@ -1,54 +0,0 @@ -package rest - -import ( - "net/http" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - "github.com/gorilla/mux" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/types" -) - -type msgDeregisterNode struct { - BaseReq rest.BaseReq `json:"base_req"` -} - -func deregisterNodeHandlerFunc(ctx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req msgDeregisterNode - - if !rest.ReadRESTReq(w, r, ctx.Codec, &req) { - return - } - - req.BaseReq = req.BaseReq.Sanitize() - if !req.BaseReq.ValidateBasic(w) { - return - } - - fromAddress, err := sdk.AccAddressFromBech32(req.BaseReq.From) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - vars := mux.Vars(r) - id, err := hub.NewNodeIDFromString(vars["id"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - msg := types.NewMsgDeregisterNode(fromAddress, id) - if err := msg.ValidateBasic(); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - utils.WriteGenerateStdTxResponse(w, ctx, req.BaseReq, []sdk.Msg{msg}) - } -} diff --git a/x/vpn/client/rest/end_subscription.go b/x/vpn/client/rest/end_subscription.go deleted file mode 100644 index 4e301009..00000000 --- a/x/vpn/client/rest/end_subscription.go +++ /dev/null @@ -1,54 +0,0 @@ -package rest - -import ( - "net/http" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - "github.com/gorilla/mux" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/types" -) - -type msgEndSubscription struct { - BaseReq rest.BaseReq `json:"base_req"` -} - -func endSubscriptionHandlerFunc(ctx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req msgEndSubscription - - if !rest.ReadRESTReq(w, r, ctx.Codec, &req) { - return - } - - req.BaseReq = req.BaseReq.Sanitize() - if !req.BaseReq.ValidateBasic(w) { - return - } - - fromAddress, err := sdk.AccAddressFromBech32(req.BaseReq.From) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - vars := mux.Vars(r) - id, err := hub.NewSubscriptionIDFromString(vars["id"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - msg := types.NewMsgEndSubscription(fromAddress, id) - if err := msg.ValidateBasic(); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - utils.WriteGenerateStdTxResponse(w, ctx, req.BaseReq, []sdk.Msg{msg}) - } -} diff --git a/x/vpn/client/rest/query_nodes.go b/x/vpn/client/rest/query_nodes.go deleted file mode 100644 index 726b2e8c..00000000 --- a/x/vpn/client/rest/query_nodes.go +++ /dev/null @@ -1,51 +0,0 @@ -package rest - -import ( - "net/http" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/gorilla/mux" - - "github.com/sentinel-official/hub/x/vpn/client/common" -) - -func getNodeHandlerFunc(ctx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - - node, err := common.QueryNode(ctx, vars["id"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - rest.PostProcessResponse(w, ctx, node) - } -} - -func getNodesOfAddressHandlerFunc(ctx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - - nodes, err := common.QueryNodesOfAddress(ctx, vars["address"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - rest.PostProcessResponse(w, ctx, nodes) - } -} - -func getAllNodesHandlerFunc(ctx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - nodes, err := common.QueryAllNodes(ctx) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - rest.PostProcessResponse(w, ctx, nodes) - } -} diff --git a/x/vpn/client/rest/query_session.go b/x/vpn/client/rest/query_session.go deleted file mode 100644 index 34555b95..00000000 --- a/x/vpn/client/rest/query_session.go +++ /dev/null @@ -1,51 +0,0 @@ -package rest - -import ( - "net/http" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/gorilla/mux" - - "github.com/sentinel-official/hub/x/vpn/client/common" -) - -func getSessionHandlerFunc(ctx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - - session, err := common.QuerySession(ctx, vars["id"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - rest.PostProcessResponse(w, ctx, session) - } -} - -func getSessionsOfSubscriptionHandlerFunc(ctx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - - sessions, err := common.QuerySessionsOfSubscription(ctx, vars["id"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - rest.PostProcessResponse(w, ctx, sessions) - } -} - -func getAllSessionsHandlerFunc(ctx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - sessions, err := common.QueryAllSessions(ctx) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - rest.PostProcessResponse(w, ctx, sessions) - } -} diff --git a/x/vpn/client/rest/query_subscription.go b/x/vpn/client/rest/query_subscription.go deleted file mode 100644 index 5bc369cb..00000000 --- a/x/vpn/client/rest/query_subscription.go +++ /dev/null @@ -1,65 +0,0 @@ -package rest - -import ( - "net/http" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/gorilla/mux" - - "github.com/sentinel-official/hub/x/vpn/client/common" -) - -func getSubscriptionHandlerFunc(ctx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - - subscription, err := common.QuerySubscription(ctx, vars["id"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - rest.PostProcessResponse(w, ctx, subscription) - } -} - -func getSubscriptionsOfNodeHandlerFunc(ctx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - - subscriptions, err := common.QuerySubscriptionsOfNode(ctx, vars["id"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - rest.PostProcessResponse(w, ctx, subscriptions) - } -} - -func getSubscriptionsOfAddressHandlerFunc(ctx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - - subscriptions, err := common.QuerySubscriptionsOfAddress(ctx, vars["address"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - rest.PostProcessResponse(w, ctx, subscriptions) - } -} - -func getAllSubscriptionsHandlerFunc(ctx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - subscriptions, err := common.QueryAllSubscriptions(ctx) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - rest.PostProcessResponse(w, ctx, subscriptions) - } -} diff --git a/x/vpn/client/rest/register_node.go b/x/vpn/client/rest/register_node.go deleted file mode 100644 index 56a285cf..00000000 --- a/x/vpn/client/rest/register_node.go +++ /dev/null @@ -1,59 +0,0 @@ -package rest - -import ( - "net/http" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/types" -) - -type msgRegisterNode struct { - BaseReq rest.BaseReq `json:"base_req"` - Type string `json:"type"` - Version string `json:"version"` - Moniker string `json:"moniker"` - PricesPerGB string `json:"prices_per_gb"` - InternetSpeed hub.Bandwidth `json:"internet_speed"` - Encryption string `json:"encryption"` -} - -func registerNodeHandlerFunc(ctx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req msgRegisterNode - - if !rest.ReadRESTReq(w, r, ctx.Codec, &req) { - return - } - - req.BaseReq = req.BaseReq.Sanitize() - if !req.BaseReq.ValidateBasic(w) { - return - } - - fromAddress, err := sdk.AccAddressFromBech32(req.BaseReq.From) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - pricesPerGB, err := sdk.ParseCoins(req.PricesPerGB) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - msg := types.NewMsgRegisterNode(fromAddress, req.Type, req.Version, - req.Moniker, pricesPerGB, req.InternetSpeed, req.Encryption) - if err := msg.ValidateBasic(); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - utils.WriteGenerateStdTxResponse(w, ctx, req.BaseReq, []sdk.Msg{msg}) - } -} diff --git a/x/vpn/client/rest/rest.go b/x/vpn/client/rest/rest.go deleted file mode 100644 index ced57a39..00000000 --- a/x/vpn/client/rest/rest.go +++ /dev/null @@ -1,55 +0,0 @@ -package rest - -import ( - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/gorilla/mux" -) - -func RegisterRoutes(ctx context.CLIContext, r *mux.Router) { - registerTxRoutes(ctx, r) - registerQueryRoutes(ctx, r) -} - -func registerTxRoutes(ctx context.CLIContext, r *mux.Router) { - r.HandleFunc("/nodes", registerNodeHandlerFunc(ctx)). - Methods("POST") - r.HandleFunc("/nodes/{id}", deregisterNodeHandlerFunc(ctx)). - Methods("DELETE") - r.HandleFunc("/nodes/{id}/info", updateNodeInfoHandlerFunc(ctx)). - Methods("PUT") - r.HandleFunc("/nodes/{id}/subscriptions", startSubscriptionHandlerFunc(ctx)). - Methods("POST") - - r.HandleFunc("/subscriptions/{id}", endSubscriptionHandlerFunc(ctx)). - Methods("DELETE") - r.HandleFunc("/subscriptions/{id}/sessions/bandwidth/sign", signSessionBandwidthHandlerFunc(ctx)). - Methods("POST") - r.HandleFunc("/subscriptions/{id}/sessions", updateSessionInfoHandlerFunc(ctx)). - Methods("PUT") -} - -func registerQueryRoutes(ctx context.CLIContext, r *mux.Router) { - r.HandleFunc("/nodes", getAllNodesHandlerFunc(ctx)). - Methods("GET") - r.HandleFunc("/nodes/{id}", getNodeHandlerFunc(ctx)). - Methods("GET") - r.HandleFunc("/nodes/{id}/subscriptions", getSubscriptionsOfNodeHandlerFunc(ctx)). - Methods("GET") - - r.HandleFunc("/subscriptions", getAllSubscriptionsHandlerFunc(ctx)). - Methods("GET") - r.HandleFunc("/subscriptions/{id}", getSubscriptionHandlerFunc(ctx)). - Methods("GET") - r.HandleFunc("/subscriptions/{id}/sessions", getSessionsOfSubscriptionHandlerFunc(ctx)). - Methods("GET") - - r.HandleFunc("/sessions", getAllSessionsHandlerFunc(ctx)). - Methods("GET") - r.HandleFunc("/sessions/{id}", getSessionHandlerFunc(ctx)). - Methods("GET") - - r.HandleFunc("/accounts/{address}/subscriptions", getSubscriptionsOfAddressHandlerFunc(ctx)). - Methods("GET") - r.HandleFunc("/accounts/{address}/nodes", getNodesOfAddressHandlerFunc(ctx)). - Methods("GET") -} diff --git a/x/vpn/client/rest/session_bandwidth.go b/x/vpn/client/rest/session_bandwidth.go deleted file mode 100644 index 17440c7c..00000000 --- a/x/vpn/client/rest/session_bandwidth.go +++ /dev/null @@ -1,115 +0,0 @@ -package rest - -import ( - "net/http" - - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/client/keys" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - "github.com/gorilla/mux" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/client/common" - "github.com/sentinel-official/hub/x/vpn/types" -) - -type msgSignSessionBandwidth struct { - From string `json:"from"` - Password string `json:"password"` - Bandwidth hub.Bandwidth `json:"bandwidth"` -} - -func signSessionBandwidthHandlerFunc(ctx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req msgSignSessionBandwidth - vars := mux.Vars(r) - - if !rest.ReadRESTReq(w, r, ctx.Codec, &req) { - return - } - - scs, err := common.QuerySessionsCountOfSubscription(ctx, vars["id"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - id, err := hub.NewSubscriptionIDFromString(vars["id"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - data := hub.NewBandwidthSignatureData(id, scs, req.Bandwidth).Bytes() - - kb, err := keys.NewKeyBaseFromHomeFlag() - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - sigBytes, pubKey, err := kb.Sign(req.From, req.Password, data) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - stdSignature := auth.StdSignature{ - PubKey: pubKey, - Signature: sigBytes, - } - - bz, err := ctx.Codec.MarshalJSON(stdSignature) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - _, _ = w.Write(bz) - } -} - -type msgUpdateSessionBandwidthInfo struct { - BaseReq rest.BaseReq `json:"base_req"` - Bandwidth hub.Bandwidth `json:"bandwidth"` - NodeOwnerSign auth.StdSignature `json:"node_owner_sign"` - ClientSign auth.StdSignature `json:"client_sign"` -} - -func updateSessionInfoHandlerFunc(ctx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req msgUpdateSessionBandwidthInfo - vars := mux.Vars(r) - - if !rest.ReadRESTReq(w, r, ctx.Codec, &req) { - return - } - - req.BaseReq = req.BaseReq.Sanitize() - if !req.BaseReq.ValidateBasic(w) { - return - } - - fromAddress, err := sdk.AccAddressFromBech32(req.BaseReq.From) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - id, err := hub.NewSubscriptionIDFromString(vars["id"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - msg := types.NewMsgUpdateSessionInfo(fromAddress, id, req.Bandwidth, req.NodeOwnerSign, req.ClientSign) - if err := msg.ValidateBasic(); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - utils.WriteGenerateStdTxResponse(w, ctx, req.BaseReq, []sdk.Msg{msg}) - } -} diff --git a/x/vpn/client/rest/start_subscription.go b/x/vpn/client/rest/start_subscription.go deleted file mode 100644 index 2736b98e..00000000 --- a/x/vpn/client/rest/start_subscription.go +++ /dev/null @@ -1,60 +0,0 @@ -package rest - -import ( - "net/http" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - "github.com/gorilla/mux" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/types" -) - -type msgStartSubscription struct { - BaseReq rest.BaseReq `json:"base_req"` - Deposit string `json:"deposit"` -} - -func startSubscriptionHandlerFunc(ctx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req msgStartSubscription - - if !rest.ReadRESTReq(w, r, ctx.Codec, &req) { - return - } - - req.BaseReq = req.BaseReq.Sanitize() - if !req.BaseReq.ValidateBasic(w) { - return - } - - fromAddress, err := sdk.AccAddressFromBech32(req.BaseReq.From) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - deposit, err := sdk.ParseCoin(req.Deposit) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - vars := mux.Vars(r) - id, err := hub.NewNodeIDFromString(vars["id"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - msg := types.NewMsgStartSubscription(fromAddress, id, deposit) - if err := msg.ValidateBasic(); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - utils.WriteGenerateStdTxResponse(w, ctx, req.BaseReq, []sdk.Msg{msg}) - } -} diff --git a/x/vpn/client/rest/update_node.go b/x/vpn/client/rest/update_node.go deleted file mode 100644 index 724e61ce..00000000 --- a/x/vpn/client/rest/update_node.go +++ /dev/null @@ -1,66 +0,0 @@ -package rest - -import ( - "net/http" - - "github.com/cosmos/cosmos-sdk/client/context" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - "github.com/gorilla/mux" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/types" -) - -type msgUpdateNode struct { - BaseReq rest.BaseReq `json:"base_req"` - Moniker string `json:"moniker"` - PricesPerGB string `json:"prices_per_gb"` - InternetSpeed hub.Bandwidth `json:"internet_speed"` - Encryption string `json:"encryption"` - Type string `json:"type"` - Version string `json:"version"` -} - -func updateNodeInfoHandlerFunc(ctx context.CLIContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req msgUpdateNode - - if !rest.ReadRESTReq(w, r, ctx.Codec, &req) { - return - } - - req.BaseReq = req.BaseReq.Sanitize() - if !req.BaseReq.ValidateBasic(w) { - return - } - - fromAddress, err := sdk.AccAddressFromBech32(req.BaseReq.From) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - pricesPerGB, err := sdk.ParseCoins(req.PricesPerGB) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - vars := mux.Vars(r) - id, err := hub.NewNodeIDFromString(vars["id"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - msg := types.NewMsgUpdateNodeInfo(fromAddress, id, req.Type, req.Version, - req.Moniker, pricesPerGB, req.InternetSpeed, req.Encryption) - if err := msg.ValidateBasic(); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - utils.WriteGenerateStdTxResponse(w, ctx, req.BaseReq, []sdk.Msg{msg}) - } -} diff --git a/x/vpn/genesis.go b/x/vpn/genesis.go deleted file mode 100644 index 121effd9..00000000 --- a/x/vpn/genesis.go +++ /dev/null @@ -1,107 +0,0 @@ -package vpn - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/sentinel-official/hub/x/vpn/types" -) - -func InitGenesis(ctx sdk.Context, k Keeper, data types.GenesisState) { - k.SetParams(ctx, data.Params) - - for _, node := range data.Nodes { - k.SetNode(ctx, node) - - nca := k.GetNodesCountOfAddress(ctx, node.Owner) - k.SetNodeIDByAddress(ctx, node.Owner, nca, node.ID) - - k.SetNodesCount(ctx, k.GetNodesCount(ctx)+1) - k.SetNodesCountOfAddress(ctx, node.Owner, nca+1) - } - - for _, subscription := range data.Subscriptions { - k.SetSubscription(ctx, subscription) - - scn := k.GetSubscriptionsCountOfNode(ctx, subscription.NodeID) - k.SetSubscriptionIDByNodeID(ctx, subscription.NodeID, scn, subscription.ID) - - sca := k.GetSubscriptionsCountOfAddress(ctx, subscription.Client) - k.SetSubscriptionIDByAddress(ctx, subscription.Client, sca, subscription.ID) - - k.SetSubscriptionsCount(ctx, k.GetSubscriptionsCount(ctx)+1) - k.SetSubscriptionsCountOfNode(ctx, subscription.NodeID, scn+1) - k.SetSubscriptionsCountOfAddress(ctx, subscription.Client, sca+1) - } - - for _, session := range data.Sessions { - k.SetSession(ctx, session) - - scs := k.GetSessionsCountOfSubscription(ctx, session.SubscriptionID) - k.SetSessionIDBySubscriptionID(ctx, session.SubscriptionID, scs, session.ID) - - k.SetSessionsCount(ctx, k.GetSessionsCount(ctx)+1) - k.SetSessionsCountOfSubscription(ctx, session.SubscriptionID, scs+1) - } -} - -func ExportGenesis(ctx sdk.Context, k Keeper) types.GenesisState { - params := k.GetParams(ctx) - nodes := k.GetAllNodes(ctx) - subscriptions := k.GetAllSubscriptions(ctx) - sessions := k.GetAllSessions(ctx) - - return types.NewGenesisState(nodes, subscriptions, sessions, params) -} - -func ValidateGenesis(data types.GenesisState) error { - if err := data.Params.Validate(); err != nil { - return err - } - - sessionsMap := make(map[uint64]bool, len(data.Sessions)) - for _, session := range data.Sessions { - if err := session.IsValid(); err != nil { - return fmt.Errorf("%s for the %s", err.Error(), session) - } - - if sessionsMap[session.ID.Uint64()] { - return fmt.Errorf("duplicate id for the %s", session) - } - - sessionsMap[session.ID.Uint64()] = true - } - - subscriptionsMap := make(map[uint64]bool, len(data.Subscriptions)) - for _, subscription := range data.Subscriptions { - if err := subscription.IsValid(); err != nil { - return fmt.Errorf("%s for the %s", err.Error(), subscription) - } - - if subscriptionsMap[subscription.ID.Uint64()] { - return fmt.Errorf("duplicate id for the %s", subscription) - } - - subscriptionsMap[subscription.ID.Uint64()] = true - } - - nodeIDsMap := make(map[uint64]bool, len(data.Nodes)) - for _, node := range data.Nodes { - if err := node.IsValid(); err != nil { - return fmt.Errorf("%s for the %s", err.Error(), node) - } - - if node.Deposit.Denom != data.Params.Deposit.Denom { - return fmt.Errorf("invalid deposit for the %s", node) - } - - if nodeIDsMap[node.ID.Uint64()] { - return fmt.Errorf("duplicate id for the %s", node) - } - - nodeIDsMap[node.ID.Uint64()] = true - } - - return nil -} diff --git a/x/vpn/handler.go b/x/vpn/handler.go deleted file mode 100644 index 52e3ef87..00000000 --- a/x/vpn/handler.go +++ /dev/null @@ -1,293 +0,0 @@ -package vpn - -import ( - "bytes" - "reflect" - - sdk "github.com/cosmos/cosmos-sdk/types" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/keeper" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func NewHandler(k keeper.Keeper) sdk.Handler { - return func(ctx sdk.Context, msg sdk.Msg) sdk.Result { - switch msg := msg.(type) { - case types.MsgRegisterNode: - return handleRegisterNode(ctx, k, msg) - case types.MsgUpdateNodeInfo: - return handleUpdateNodeInfo(ctx, k, msg) - case types.MsgDeregisterNode: - return handleDeregisterNode(ctx, k, msg) - case types.MsgStartSubscription: - return handleStartSubscription(ctx, k, msg) - case types.MsgEndSubscription: - return handleEndSubscription(ctx, k, msg) - case types.MsgUpdateSessionInfo: - return handleUpdateSessionInfo(ctx, k, msg) - default: - return types.ErrorUnknownMsgType(reflect.TypeOf(msg).Name()).Result() - } - } -} - -func EndBlock(ctx sdk.Context, k keeper.Keeper) { - height := ctx.BlockHeight() - _height := height - k.SessionInactiveInterval(ctx) - - ids := k.GetActiveSessionIDs(ctx, _height) - for _, id := range ids { - session, _ := k.GetSession(ctx, id.(hub.SessionID)) - subscription, _ := k.GetSubscription(ctx, session.SubscriptionID) - - bandwidth := session.Bandwidth.CeilTo(hub.GB.Quo(subscription.PricePerGB.Amount)) - amount := bandwidth.Sum().Mul(subscription.PricePerGB.Amount).Quo(hub.GB) - pay := sdk.NewCoin(subscription.PricePerGB.Denom, amount) - - if !pay.IsZero() { - node, _ := k.GetNode(ctx, subscription.NodeID) - - if err := k.SendDeposit(ctx, subscription.Client, node.Owner, pay); err != nil { - panic(err) - } - } - - session.Status = types.StatusInactive - session.StatusModifiedAt = height - k.SetSession(ctx, session) - - subscription.RemainingDeposit = subscription.RemainingDeposit.Sub(pay) - subscription.RemainingBandwidth = subscription.RemainingBandwidth.Sub(bandwidth) - k.SetSubscription(ctx, subscription) - - scs := k.GetSessionsCountOfSubscription(ctx, subscription.ID) - k.SetSessionsCountOfSubscription(ctx, subscription.ID, scs+1) - } - - k.DeleteActiveSessionIDs(ctx, _height) -} - -func handleRegisterNode(ctx sdk.Context, k keeper.Keeper, msg types.MsgRegisterNode) sdk.Result { - nc := k.GetNodesCount(ctx) - node := types.Node{ - ID: hub.NewNodeID(nc), - Owner: msg.From, - Deposit: sdk.NewInt64Coin(k.Deposit(ctx).Denom, 0), - Type: msg.T, - Version: msg.Version, - Moniker: msg.Moniker, - PricesPerGB: msg.PricesPerGB, - InternetSpeed: msg.InternetSpeed, - Encryption: msg.Encryption, - Status: types.StatusRegistered, - StatusModifiedAt: ctx.BlockHeight(), - } - - nca := k.GetNodesCountOfAddress(ctx, node.Owner) - if nca >= k.FreeNodesCount(ctx) { - node.Deposit = k.Deposit(ctx) - - if err := k.AddDeposit(ctx, node.Owner, node.Deposit); err != nil { - return err.Result() - } - } - - k.SetNode(ctx, node) - k.SetNodeIDByAddress(ctx, node.Owner, nca, node.ID) - - k.SetNodesCount(ctx, nc+1) - k.SetNodesCountOfAddress(ctx, node.Owner, nca+1) - - return sdk.Result{Events: ctx.EventManager().Events()} -} - -func handleUpdateNodeInfo(ctx sdk.Context, k keeper.Keeper, msg types.MsgUpdateNodeInfo) sdk.Result { - node, found := k.GetNode(ctx, msg.ID) - if !found { - return types.ErrorNodeDoesNotExist().Result() - } - if !msg.From.Equals(node.Owner) { - return types.ErrorUnauthorized().Result() - } - if node.Status == types.StatusDeRegistered { - return types.ErrorInvalidNodeStatus().Result() - } - - _node := types.Node{ - Type: msg.T, - Version: msg.Version, - Moniker: msg.Moniker, - PricesPerGB: msg.PricesPerGB, - InternetSpeed: msg.InternetSpeed, - Encryption: msg.Encryption, - } - node = node.UpdateInfo(_node) - - k.SetNode(ctx, node) - - return sdk.Result{Events: ctx.EventManager().Events()} -} - -func handleDeregisterNode(ctx sdk.Context, k keeper.Keeper, msg types.MsgDeregisterNode) sdk.Result { - node, found := k.GetNode(ctx, msg.ID) - if !found { - return types.ErrorNodeDoesNotExist().Result() - } - if !msg.From.Equals(node.Owner) { - return types.ErrorUnauthorized().Result() - } - if node.Status == types.StatusDeRegistered { - return types.ErrorInvalidNodeStatus().Result() - } - - if node.Deposit.IsPositive() { - if err := k.SubtractDeposit(ctx, node.Owner, node.Deposit); err != nil { - return err.Result() - } - } - - node.Status = types.StatusDeRegistered - node.StatusModifiedAt = ctx.BlockHeight() - - k.SetNode(ctx, node) - - return sdk.Result{Events: ctx.EventManager().Events()} -} - -func handleStartSubscription(ctx sdk.Context, k keeper.Keeper, msg types.MsgStartSubscription) sdk.Result { - node, found := k.GetNode(ctx, msg.NodeID) - if !found { - return types.ErrorNodeDoesNotExist().Result() - } - if node.Status != types.StatusRegistered { - return types.ErrorInvalidNodeStatus().Result() - } - - if err := k.AddDeposit(ctx, msg.From, msg.Deposit); err != nil { - return err.Result() - } - - bandwidth, err := node.DepositToBandwidth(msg.Deposit) - if err != nil { - return err.Result() - } - - pricePerGB := node.FindPricePerGB(msg.Deposit.Denom) - - sc := k.GetSubscriptionsCount(ctx) - subscription := types.Subscription{ - ID: hub.NewSubscriptionID(sc), - NodeID: node.ID, - Client: msg.From, - PricePerGB: pricePerGB, - TotalDeposit: msg.Deposit, - RemainingDeposit: msg.Deposit, - RemainingBandwidth: bandwidth, - Status: types.StatusActive, - StatusModifiedAt: ctx.BlockHeight(), - } - - k.SetSubscription(ctx, subscription) - k.SetSubscriptionsCount(ctx, sc+1) - - nsc := k.GetSubscriptionsCountOfNode(ctx, node.ID) - k.SetSubscriptionIDByNodeID(ctx, node.ID, nsc, subscription.ID) - k.SetSubscriptionsCountOfNode(ctx, node.ID, nsc+1) - - sca := k.GetSubscriptionsCountOfAddress(ctx, subscription.Client) - k.SetSubscriptionIDByAddress(ctx, subscription.Client, sca, subscription.ID) - k.SetSubscriptionsCountOfAddress(ctx, subscription.Client, sca+1) - - return sdk.Result{Events: ctx.EventManager().Events()} -} - -func handleEndSubscription(ctx sdk.Context, k keeper.Keeper, msg types.MsgEndSubscription) sdk.Result { - subscription, found := k.GetSubscription(ctx, msg.ID) - if !found { - return types.ErrorSubscriptionDoesNotExist().Result() - } - if !msg.From.Equals(subscription.Client) { - return types.ErrorUnauthorized().Result() - } - if subscription.Status != types.StatusActive { - return types.ErrorInvalidSubscriptionStatus().Result() - } - - scs := k.GetSessionsCountOfSubscription(ctx, subscription.ID) - - _, found = k.GetSessionIDBySubscriptionID(ctx, subscription.ID, scs) - if found { - return types.ErrorSessionAlreadyExists().Result() - } - - if err := k.SubtractDeposit(ctx, subscription.Client, subscription.RemainingDeposit); err != nil { - return err.Result() - } - - subscription.Status = types.StatusInactive - subscription.StatusModifiedAt = ctx.BlockHeight() - - k.SetSubscription(ctx, subscription) - - return sdk.Result{Events: ctx.EventManager().Events()} -} - -func handleUpdateSessionInfo(ctx sdk.Context, k keeper.Keeper, msg types.MsgUpdateSessionInfo) sdk.Result { - subscription, found := k.GetSubscription(ctx, msg.SubscriptionID) - if !found { - return types.ErrorSubscriptionDoesNotExist().Result() - } - if subscription.Status == types.StatusInactive { - return types.ErrorInvalidSubscriptionStatus().Result() - } - if !bytes.Equal(msg.ClientSignature.PubKey.Address(), subscription.Client.Bytes()) { - return types.ErrorUnauthorized().Result() - } - - node, _ := k.GetNode(ctx, subscription.NodeID) - if !bytes.Equal(msg.NodeOwnerSignature.PubKey.Address(), node.Owner.Bytes()) { - return types.ErrorUnauthorized().Result() - } - - scs := k.GetSessionsCountOfSubscription(ctx, subscription.ID) - data := hub.NewBandwidthSignatureData(subscription.ID, scs, msg.Bandwidth).Bytes() - if !msg.NodeOwnerSignature.VerifyBytes(data, msg.NodeOwnerSignature.Signature) { - return types.ErrorInvalidBandwidthSignature().Result() - } - if !msg.ClientSignature.VerifyBytes(data, msg.ClientSignature.Signature) { - return types.ErrorInvalidBandwidthSignature().Result() - } - - if subscription.RemainingBandwidth.AnyLT(msg.Bandwidth) { - return types.ErrorInvalidBandwidth().Result() - } - - var session types.Session - - id, found := k.GetSessionIDBySubscriptionID(ctx, subscription.ID, scs) - if !found { - sc := k.GetSessionsCount(ctx) - session = types.Session{ - ID: hub.NewSessionID(sc), - SubscriptionID: subscription.ID, - Bandwidth: hub.NewBandwidthFromInt64(0, 0), - } - - k.SetSessionsCount(ctx, sc+1) - k.SetSessionIDBySubscriptionID(ctx, subscription.ID, scs, session.ID) - } else { - session, _ = k.GetSession(ctx, id) - } - - k.RemoveSessionIDFromActiveList(ctx, session.StatusModifiedAt, session.ID) - k.AddSessionIDToActiveList(ctx, ctx.BlockHeight(), session.ID) - - session.Bandwidth = msg.Bandwidth - session.Status = types.StatusActive - session.StatusModifiedAt = ctx.BlockHeight() - - k.SetSession(ctx, session) - - return sdk.Result{Events: ctx.EventManager().Events()} -} diff --git a/x/vpn/handler_test.go b/x/vpn/handler_test.go deleted file mode 100644 index 2e283c0e..00000000 --- a/x/vpn/handler_test.go +++ /dev/null @@ -1,735 +0,0 @@ -package vpn - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/keeper" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func Test_handleRegisterNode(t *testing.T) { - ctx, k, dk, bk := keeper.CreateTestInput(t, false) - - count := k.GetNodesCount(ctx) - require.Equal(t, uint64(0), count) - - count = k.GetNodesCountOfAddress(ctx, types.TestAddress1) - require.Equal(t, uint64(0), count) - - handler := NewHandler(k) - node := types.TestNode - - msg := NewMsgRegisterNode(node.Owner, node.Type, node.Version, node.Moniker, node.PricesPerGB, node.InternetSpeed, node.Encryption) - res := handler(ctx, *msg) - require.True(t, res.IsOK()) - - node, found := k.GetNode(ctx, hub.NewNodeID(0)) - require.Equal(t, true, found) - require.Equal(t, hub.NewNodeID(0), node.ID) - require.Equal(t, "moniker", node.Moniker) - - count = k.GetNodesCount(ctx) - require.Equal(t, uint64(1), count) - - count = k.GetNodesCountOfAddress(ctx, types.TestAddress1) - require.Equal(t, uint64(1), count) - - deposit, found := dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, false, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - - k.SetNodesCount(ctx, DefaultFreeNodesCount) - k.SetNodesCountOfAddress(ctx, types.TestAddress1, DefaultFreeNodesCount) - msg = NewMsgRegisterNode(node.Owner, node.Type, node.Version, node.Moniker, node.PricesPerGB, node.InternetSpeed, node.Encryption) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - count = k.GetNodesCount(ctx) - require.Equal(t, uint64(5), count) - - count = k.GetNodesCountOfAddress(ctx, types.TestAddress1) - require.Equal(t, uint64(5), count) - - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, false, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - - coins, err := bk.AddCoins(ctx, types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 100)}) - require.Nil(t, err) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, coins) - - coins = bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, coins) - - msg = NewMsgRegisterNode(node.Owner, node.Type, node.Version, node.Moniker, node.PricesPerGB, node.InternetSpeed, node.Encryption) - res = handler(ctx, *msg) - require.True(t, res.IsOK()) - - count = k.GetNodesCount(ctx) - require.Equal(t, uint64(6), count) - - count = k.GetNodesCountOfAddress(ctx, types.TestAddress1) - require.Equal(t, uint64(6), count) - - coins = bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins(nil), coins) - - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, deposit.Coins) - - count = k.GetNodesCount(ctx) - require.Equal(t, uint64(6), count) - - id := hub.NewNodeID(count - 1) - node, found = k.GetNode(ctx, id) - require.Equal(t, true, found) - require.Equal(t, id, node.ID) - - coins, err = bk.AddCoins(ctx, types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 100)}.Add(sdk.Coins{sdk.NewInt64Coin("stake", 100)})) - require.Nil(t, err) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}.Add(sdk.Coins{sdk.NewInt64Coin("stake", 100)}), coins) - - coins = bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}.Add(sdk.Coins{sdk.NewInt64Coin("stake", 100)}), coins) - - msg = NewMsgRegisterNode(node.Owner, node.Type, node.Version, node.Moniker, node.PricesPerGB, node.InternetSpeed, node.Encryption) - res = handler(ctx, *msg) - require.True(t, res.IsOK()) - - count = k.GetNodesCount(ctx) - require.Equal(t, uint64(7), count) - - count = k.GetNodesCountOfAddress(ctx, types.TestAddress1) - require.Equal(t, uint64(7), count) - - coins = bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, coins) - - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}.Add(sdk.Coins{sdk.NewInt64Coin("stake", 100)}), deposit.Coins) - - count = k.GetNodesCount(ctx) - require.Equal(t, uint64(7), count) - - id = hub.NewNodeID(count - 1) - node, found = k.GetNode(ctx, id) - require.Equal(t, true, found) - require.Equal(t, id, node.ID) -} - -func Test_handleUpdateNodeInfo(t *testing.T) { - ctx, k, _, _ := keeper.CreateTestInput(t, false) - - node, found := k.GetNode(ctx, hub.NewNodeID(0)) - require.Equal(t, false, found) - require.Equal(t, types.Node{}, node) - - handler := NewHandler(k) - - node = types.TestNode - node.Status = StatusDeRegistered - k.SetNode(ctx, node) - msg := NewMsgUpdateNodeInfo(node.Owner, node.ID, "new_node_type", "new_version", "new_moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, types.TestBandwidthPos1, "new_encryption") - res := handler(ctx, *msg) - require.False(t, res.IsOK()) - - msg = NewMsgUpdateNodeInfo(types.TestAddress2, node.ID, "new_node_type", "new_version", "new_moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, types.TestBandwidthPos1, "new_encryption") - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - node.Status = StatusInactive - k.SetNode(ctx, node) - msg = NewMsgUpdateNodeInfo(node.Owner, node.ID, "new_node_type", "new_version", "new_moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, types.TestBandwidthPos1, "new_encryption") - res = handler(ctx, *msg) - require.True(t, res.IsOK()) - - node, found = k.GetNode(ctx, node.ID) - require.Equal(t, true, found) - require.Equal(t, "new_node_type", node.Type) - require.Equal(t, "new_version", node.Version) - require.Equal(t, "new_moniker", node.Moniker) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, node.PricesPerGB) - require.Equal(t, "new_encryption", node.Encryption) - - node.Status = StatusRegistered - k.SetNode(ctx, node) - msg = NewMsgUpdateNodeInfo(node.Owner, node.ID, "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, types.TestBandwidthPos1, "encryption") - res = handler(ctx, *msg) - require.True(t, res.IsOK()) - - node, found = k.GetNode(ctx, node.ID) - require.Equal(t, true, found) - require.Equal(t, "node_type", node.Type) - require.Equal(t, "version", node.Version) - require.Equal(t, "moniker", node.Moniker) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, node.PricesPerGB) - require.Equal(t, "encryption", node.Encryption) -} - -func Test_handleDeregisterNode(t *testing.T) { - ctx, k, dk, bk := keeper.CreateTestInput(t, false) - - node, found := k.GetNode(ctx, hub.NewNodeID(0)) - require.Equal(t, false, found) - require.Equal(t, types.Node{}, node) - - handler := NewHandler(k) - - node = types.TestNode - node.Deposit = sdk.NewInt64Coin("stake", 0) - - node.Status = StatusDeRegistered - k.SetNode(ctx, node) - msg := NewMsgDeregisterNode(types.TestAddress2, node.ID) - res := handler(ctx, *msg) - require.False(t, res.IsOK()) - - node, found = k.GetNode(ctx, node.ID) - require.Equal(t, true, found) - require.Equal(t, StatusDeRegistered, node.Status) - - msg = NewMsgDeregisterNode(node.Owner, node.ID) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - node, found = k.GetNode(ctx, node.ID) - require.Equal(t, true, found) - require.Equal(t, StatusDeRegistered, node.Status) - - node.Status = StatusRegistered - k.SetNode(ctx, node) - msg = NewMsgDeregisterNode(types.TestAddress2, node.ID) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - node, found = k.GetNode(ctx, node.ID) - require.Equal(t, true, found) - require.Equal(t, StatusRegistered, node.Status) - - msg = NewMsgDeregisterNode(node.Owner, node.ID) - res = handler(ctx, *msg) - require.True(t, res.IsOK()) - - coins := bk.GetCoins(ctx, node.Owner) - require.Equal(t, sdk.Coins{}, coins) - - node, found = k.GetNode(ctx, node.ID) - require.Equal(t, true, found) - require.Equal(t, StatusDeRegistered, node.Status) - - node.Status = StatusRegistered - k.SetNode(ctx, node) - msg = NewMsgDeregisterNode(types.TestAddress2, node.ID) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - node, found = k.GetNode(ctx, node.ID) - require.Equal(t, true, found) - require.Equal(t, StatusRegistered, node.Status) - - node, found = k.GetNode(ctx, node.ID) - require.Equal(t, true, found) - require.Equal(t, StatusRegistered, node.Status) - - msg = NewMsgDeregisterNode(node.Owner, node.ID) - res = handler(ctx, *msg) - require.True(t, res.IsOK()) - - coins = bk.GetCoins(ctx, node.Owner) - require.Equal(t, sdk.Coins{}, coins) - - node, found = k.GetNode(ctx, node.ID) - require.Equal(t, true, found) - require.Equal(t, StatusDeRegistered, node.Status) - - coins, err := bk.AddCoins(ctx, node.Owner, sdk.Coins{sdk.NewInt64Coin("stake", 100)}.Add(sdk.Coins{sdk.NewInt64Coin("stake", 100)})) - require.Nil(t, err) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}.Add(sdk.Coins{sdk.NewInt64Coin("stake", 100)}), coins) - - err = k.AddDeposit(ctx, node.Owner, sdk.NewInt64Coin("stake", 100).Add(sdk.NewInt64Coin("stake", 100))) - require.Nil(t, err) - - node.Status = StatusDeRegistered - node.Deposit = sdk.NewInt64Coin("stake", 100).Add(sdk.NewInt64Coin("stake", 100)).Add(sdk.NewInt64Coin("stake", 100)) - k.SetNode(ctx, node) - msg = NewMsgDeregisterNode(types.TestAddress2, node.ID) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - node, found = k.GetNode(ctx, node.ID) - require.Equal(t, true, found) - require.Equal(t, StatusDeRegistered, node.Status) - - deposit, found := dk.GetDeposit(ctx, node.Owner) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}.Add(sdk.Coins{sdk.NewInt64Coin("stake", 100)}), deposit.Coins) - - msg = NewMsgDeregisterNode(node.Owner, node.ID) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}.Add(sdk.Coins{sdk.NewInt64Coin("stake", 100)}), deposit.Coins) - - coins = bk.GetCoins(ctx, node.Owner) - require.Equal(t, sdk.Coins(nil), coins) - - node, found = k.GetNode(ctx, node.ID) - require.Equal(t, true, found) - require.Equal(t, StatusDeRegistered, node.Status) - - node.Status = StatusRegistered - node.Deposit = sdk.NewInt64Coin("stake", 100) - k.SetNode(ctx, node) - msg = NewMsgDeregisterNode(types.TestAddress2, node.ID) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - node, found = k.GetNode(ctx, node.ID) - require.Equal(t, true, found) - require.Equal(t, StatusRegistered, node.Status) - - deposit, found = dk.GetDeposit(ctx, node.Owner) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}.Add(sdk.Coins{sdk.NewInt64Coin("stake", 100)}), deposit.Coins) - - msg = NewMsgDeregisterNode(node.Owner, node.ID) - res = handler(ctx, *msg) - require.True(t, res.IsOK()) - - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, deposit.Coins) - - coins = bk.GetCoins(ctx, node.Owner) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, coins) - - node, found = k.GetNode(ctx, node.ID) - require.Equal(t, true, found) - require.Equal(t, StatusDeRegistered, node.Status) -} - -func Test_handleStartSubscription(t *testing.T) { - ctx, k, dk, bk := keeper.CreateTestInput(t, false) - - node, found := k.GetNode(ctx, hub.NewNodeID(0)) - require.Equal(t, false, found) - require.Equal(t, types.Node{}, node) - - subscription, found := k.GetSubscription(ctx, hub.NewSubscriptionID(0)) - require.Equal(t, false, found) - require.Equal(t, types.Subscription{}, subscription) - - handler := NewHandler(k) - msg := NewMsgStartSubscription(types.TestAddress2, hub.NewNodeID(1), sdk.NewInt64Coin("stake", 100)) - res := handler(ctx, *msg) - require.False(t, res.IsOK()) - - node = types.TestNode - node.Status = StatusDeRegistered - k.SetNode(ctx, node) - msg = NewMsgStartSubscription(types.TestAddress2, node.ID, sdk.NewInt64Coin("stake", 100)) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - deposit, found := dk.GetDeposit(ctx, types.TestAddress2) - require.Equal(t, false, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - - subscription, found = k.GetSubscription(ctx, hub.NewSubscriptionID(0)) - require.Equal(t, false, found) - require.Equal(t, types.Subscription{}, subscription) - - node.Status = StatusRegistered - k.SetNode(ctx, node) - msg = NewMsgStartSubscription(types.TestAddress2, node.ID, sdk.NewInt64Coin("stake", 100)) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - deposit, found = dk.GetDeposit(ctx, types.TestAddress2) - require.Equal(t, false, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - - subscription, found = k.GetSubscription(ctx, hub.NewSubscriptionID(0)) - require.Equal(t, false, found) - require.Equal(t, types.Subscription{}, subscription) - - msg = NewMsgStartSubscription(types.TestAddress2, node.ID, sdk.NewInt64Coin("invalid", 100)) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - deposit, found = dk.GetDeposit(ctx, types.TestAddress2) - require.Equal(t, false, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - - subscription, found = k.GetSubscription(ctx, hub.NewSubscriptionID(0)) - require.Equal(t, false, found) - require.Equal(t, types.Subscription{}, subscription) - - coins, err := bk.AddCoins(ctx, types.TestAddress2, sdk.Coins{sdk.NewInt64Coin("stake", 100)}) - require.Nil(t, err) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, coins) - - msg = NewMsgStartSubscription(types.TestAddress2, node.ID, sdk.NewInt64Coin("stake", 100)) - res = handler(ctx, *msg) - require.True(t, res.IsOK()) - - coins = bk.GetCoins(ctx, types.TestAddress2) - require.Equal(t, sdk.Coins(nil), coins) - - deposit, found = dk.GetDeposit(ctx, types.TestAddress2) - require.Equal(t, true, found) - require.Equal(t, sdk.NewInt(100), deposit.Coins.AmountOf("stake")) - - subscription, found = k.GetSubscription(ctx, hub.NewSubscriptionID(0)) - require.Equal(t, true, found) - require.Equal(t, types.TestAddress2, subscription.Client) - require.Equal(t, hub.NewNodeID(0), subscription.NodeID) - - count := k.GetSubscriptionsCount(ctx) - require.Equal(t, uint64(1), count) - - id, found := k.GetSubscriptionIDByAddress(ctx, types.TestAddress2, 0) - require.Equal(t, true, found) - require.Equal(t, id, subscription.ID) - - id, found = k.GetSubscriptionIDByNodeID(ctx, node.ID, 0) - require.Equal(t, true, found) - require.Equal(t, id, subscription.ID) - - count = k.GetSubscriptionsCountOfAddress(ctx, types.TestAddress2) - require.Equal(t, uint64(1), count) - - subscriptions := k.GetSubscriptionsOfNode(ctx, node.ID) - require.Equal(t, []types.Subscription{types.TestSubscription}, subscriptions) - - msg = NewMsgStartSubscription(types.TestAddress2, node.ID, sdk.NewInt64Coin("stake", 100)) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - coins, err = bk.AddCoins(ctx, types.TestAddress2, sdk.Coins{sdk.NewInt64Coin("stake", 100)}.Add(sdk.Coins{sdk.NewInt64Coin("stake", 100)})) - require.Nil(t, err) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}.Add(sdk.Coins{sdk.NewInt64Coin("stake", 100)}), coins) - - msg = NewMsgStartSubscription(types.TestAddress2, node.ID, sdk.NewInt64Coin("stake", 100)) - res = handler(ctx, *msg) - require.True(t, res.IsOK()) - - coins = bk.GetCoins(ctx, types.TestAddress2) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, coins) - - deposit, found = dk.GetDeposit(ctx, types.TestAddress2) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 200)}, deposit.Coins) - - count = k.GetSubscriptionsCountOfAddress(ctx, types.TestAddress2) - require.Equal(t, uint64(2), count) - - subscriptionID := hub.NewSubscriptionID(count - 1) - subscription, found = k.GetSubscription(ctx, subscriptionID) - require.Equal(t, true, found) - require.Equal(t, types.TestAddress2, subscription.Client) - require.Equal(t, hub.NewNodeID(0), subscription.NodeID) - - count = k.GetSubscriptionsCount(ctx) - require.Equal(t, uint64(2), count) - - id, found = k.GetSubscriptionIDByAddress(ctx, types.TestAddress2, 1) - require.Equal(t, true, found) - require.Equal(t, id, subscriptionID) - - id, found = k.GetSubscriptionIDByNodeID(ctx, node.ID, 1) - require.Equal(t, true, found) - require.Equal(t, id, subscriptionID) - - subscriptions = k.GetSubscriptionsOfNode(ctx, node.ID) - require.Len(t, subscriptions, 2) - require.Equal(t, types.TestSubscription, subscriptions[0]) - require.Equal(t, subscription, subscriptions[1]) -} - -func Test_handleEndSubscription(t *testing.T) { - ctx, k, dk, bk := keeper.CreateTestInput(t, false) - - subscription, found := k.GetSubscription(ctx, hub.NewSubscriptionID(0)) - require.Equal(t, false, found) - require.Equal(t, types.Subscription{}, subscription) - - handler := NewHandler(k) - - subscription = types.TestSubscription - subscription.Status = StatusInactive - k.SetSubscription(ctx, subscription) - - msg := NewMsgEndSubscription(types.TestAddress1, subscription.ID) - res := handler(ctx, *msg) - require.False(t, res.IsOK()) - - subscription, found = k.GetSubscription(ctx, subscription.ID) - require.Equal(t, true, found) - - msg = NewMsgEndSubscription(types.TestAddress2, subscription.ID) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - subscription, found = k.GetSubscription(ctx, subscription.ID) - require.Equal(t, true, found) - - subscription.Status = StatusActive - k.SetSubscription(ctx, subscription) - msg = NewMsgEndSubscription(types.TestAddress1, hub.NewSubscriptionID(0)) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - subscription, found = k.GetSubscription(ctx, subscription.ID) - require.Equal(t, true, found) - - msg = NewMsgEndSubscription(types.TestAddress2, subscription.ID) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - subscription, found = k.GetSubscription(ctx, subscription.ID) - require.Equal(t, true, found) - - coins, err := bk.AddCoins(ctx, types.TestAddress2, sdk.Coins{sdk.NewInt64Coin("stake", 100)}) - require.Nil(t, err) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, coins) - - err = k.AddDeposit(ctx, types.TestAddress2, sdk.NewInt64Coin("stake", 100)) - require.Nil(t, err) - - coins = bk.GetCoins(ctx, types.TestAddress2) - require.Nil(t, err) - require.Equal(t, sdk.Coins(nil), coins) - - deposit, found := dk.GetDeposit(ctx, types.TestAddress2) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, deposit.Coins) - - subscription.Status = StatusInactive - k.SetSubscription(ctx, subscription) - - msg = NewMsgEndSubscription(types.TestAddress1, subscription.ID) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - subscription, found = k.GetSubscription(ctx, subscription.ID) - require.Equal(t, true, found) - - msg = NewMsgEndSubscription(types.TestAddress2, hub.NewSubscriptionID(0)) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - subscription, found = k.GetSubscription(ctx, subscription.ID) - require.Equal(t, true, found) - - subscription.Status = StatusActive - k.SetSubscription(ctx, subscription) - msg = NewMsgEndSubscription(types.TestAddress1, hub.NewSubscriptionID(0)) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - subscription, found = k.GetSubscription(ctx, subscription.ID) - require.Equal(t, true, found) - - msg = NewMsgEndSubscription(types.TestAddress2, subscription.ID) - res = handler(ctx, *msg) - require.True(t, res.IsOK()) - - subscription, found = k.GetSubscription(ctx, subscription.ID) - require.Equal(t, true, found) - require.Equal(t, StatusInactive, subscription.Status) - - deposit, found = dk.GetDeposit(ctx, types.TestAddress2) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - - coins = bk.GetCoins(ctx, types.TestAddress2) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, coins) - - coins = bk.GetCoins(ctx, types.TestAddress2) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, coins) - - err = k.AddDeposit(ctx, types.TestAddress2, sdk.NewInt64Coin("stake", 100)) - require.Nil(t, err) - - coins, err = bk.AddCoins(ctx, types.TestAddress2, sdk.Coins{sdk.NewInt64Coin("stake", 100)}) - require.Nil(t, err) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, coins) - - k.SetSubscription(ctx, types.TestSubscription) - k.SetSession(ctx, types.TestSession) - k.SetSessionsCountOfSubscription(ctx, subscription.ID, 1) - - msg = NewMsgEndSubscription(types.TestAddress2, subscription.ID) - res = handler(ctx, *msg) - require.True(t, res.IsOK()) - - k.SetSubscription(ctx, types.TestSubscription) - k.SetSession(ctx, types.TestSession) - k.SetSessionsCountOfSubscription(ctx, subscription.ID, 1) - k.SetSessionIDBySubscriptionID(ctx, subscription.ID, 1, hub.NewSessionID(0)) - - msg = NewMsgEndSubscription(types.TestAddress2, subscription.ID) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) -} - -func Test_handleUpdateSessionInfo(t *testing.T) { - ctx, k, _, _ := keeper.CreateTestInput(t, false) - - session, found := k.GetSession(ctx, hub.NewSessionID(0)) - require.Equal(t, false, found) - require.Equal(t, types.Session{}, session) - - handler := NewHandler(k) - msg := NewMsgUpdateSessionInfo(types.TestAddress2, hub.NewSubscriptionID(1), types.TestBandwidthPos1, types.TestNodeOwnerStdSignaturePos1, types.TestClientStdSignaturePos1) - res := handler(ctx, *msg) - require.False(t, res.IsOK()) - - subscription := types.TestSubscription - subscription.Status = StatusInactive - k.SetSubscription(ctx, subscription) - k.SetSessionsCountOfSubscription(ctx, subscription.ID, 0) - - msg = NewMsgUpdateSessionInfo(types.TestAddress2, subscription.ID, types.TestBandwidthPos1, types.TestNodeOwnerStdSignaturePos1, types.TestClientStdSignaturePos1) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - session, found = k.GetSession(ctx, hub.NewSessionID(0)) - require.Equal(t, false, found) - require.Equal(t, types.Session{}, session) - - count := k.GetSessionsCount(ctx) - require.Equal(t, uint64(0), count) - - count = k.GetSessionsCountOfSubscription(ctx, subscription.ID) - require.Equal(t, uint64(0), count) - - msg = NewMsgUpdateSessionInfo(subscription.Client, subscription.ID, types.TestBandwidthPos1, types.TestNodeOwnerStdSignaturePos1, types.TestClientStdSignaturePos1) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - node := types.TestNode - k.SetNode(ctx, node) - subscription.Status = StatusActive - k.SetSubscription(ctx, subscription) - k.SetSessionsCountOfSubscription(ctx, subscription.ID, 0) - msg = NewMsgUpdateSessionInfo(types.TestAddress2, subscription.ID, types.TestBandwidthPos1, types.TestClientStdSignaturePos1, types.TestNodeOwnerStdSignaturePos1) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - msg = NewMsgUpdateSessionInfo(types.TestAddress2, subscription.ID, types.TestBandwidthPos1, types.TestClientStdSignaturePos1, types.TestClientStdSignaturePos1) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - k.SetSessionsCountOfSubscription(ctx, subscription.ID, 1) - msg = NewMsgUpdateSessionInfo(types.TestAddress2, subscription.ID, types.TestBandwidthPos2, types.TestNodeOwnerStdSignaturePos2, types.TestClientStdSignaturePos2) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - msg = NewMsgUpdateSessionInfo(types.TestAddress2, subscription.ID, types.TestBandwidthPos1, types.TestNodeOwnerStdSignaturePos1, types.TestClientStdSignaturePos1) - res = handler(ctx, *msg) - require.True(t, res.IsOK()) - - id, _ := k.GetSessionIDBySubscriptionID(ctx, subscription.ID, k.GetSessionsCountOfSubscription(ctx, subscription.ID)) - session, found = k.GetSession(ctx, id) - require.Equal(t, true, found) - require.Equal(t, types.TestSession, session) - - count = k.GetSessionsCount(ctx) - require.Equal(t, uint64(1), count) - - count = k.GetSessionsCountOfSubscription(ctx, subscription.ID) - require.Equal(t, uint64(1), count) - msg = NewMsgUpdateSessionInfo(subscription.Client, subscription.ID, types.TestBandwidthPos1, types.TestNodeOwnerStdSignaturePos2, types.TestClientStdSignaturePos1) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - session, found = k.GetSession(ctx, session.ID) - require.Equal(t, true, found) - require.Equal(t, types.TestSession, session) - - count = k.GetSessionsCount(ctx) - require.Equal(t, uint64(1), count) - - count = k.GetSessionsCountOfSubscription(ctx, subscription.ID) - require.Equal(t, uint64(1), count) - - msg = NewMsgUpdateSessionInfo(subscription.Client, subscription.ID, types.TestBandwidthPos1, types.TestNodeOwnerStdSignaturePos1, types.TestClientStdSignaturePos2) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - session, found = k.GetSession(ctx, session.ID) - require.Equal(t, true, found) - require.Equal(t, types.TestSession, session) - - count = k.GetSessionsCount(ctx) - require.Equal(t, uint64(1), count) - - count = k.GetSessionsCountOfSubscription(ctx, subscription.ID) - require.Equal(t, uint64(1), count) - - msg = NewMsgUpdateSessionInfo(subscription.Client, subscription.ID, types.TestBandwidthPos2, types.TestNodeOwnerStdSignaturePos1, types.TestClientStdSignaturePos1) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - session, found = k.GetSession(ctx, session.ID) - require.Equal(t, true, found) - require.Equal(t, types.TestSession, session) - - count = k.GetSessionsCount(ctx) - require.Equal(t, uint64(1), count) - - count = k.GetSessionsCountOfSubscription(ctx, subscription.ID) - require.Equal(t, uint64(1), count) - - msg = NewMsgUpdateSessionInfo(subscription.Client, subscription.ID, types.TestBandwidthNeg, types.TestNodeOwnerStdSignatureNeg, types.TestClientStdSignatureNeg) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - session, found = k.GetSession(ctx, session.ID) - require.Equal(t, true, found) - require.Equal(t, types.TestSession, session) - - count = k.GetSessionsCount(ctx) - require.Equal(t, uint64(1), count) - - count = k.GetSessionsCountOfSubscription(ctx, subscription.ID) - require.Equal(t, uint64(1), count) - - msg = NewMsgUpdateSessionInfo(node.Owner, subscription.ID, types.TestBandwidthZero, types.TestNodeOwnerStdSignatureZero, types.TestClientStdSignatureZero) - res = handler(ctx, *msg) - require.False(t, res.IsOK()) - - session, found = k.GetSession(ctx, session.ID) - require.Equal(t, true, found) - require.Equal(t, types.TestSession, session) - - count = k.GetSessionsCount(ctx) - require.Equal(t, uint64(1), count) - - count = k.GetSessionsCountOfSubscription(ctx, subscription.ID) - require.Equal(t, uint64(1), count) - - msg = NewMsgUpdateSessionInfo(node.Owner, subscription.ID, types.TestBandwidthPos1, types.TestNodeOwnerStdSignaturePos1, types.TestClientStdSignaturePos1) - res = handler(ctx, *msg) - require.True(t, res.IsOK()) - - session, found = k.GetSession(ctx, hub.NewSessionID(0)) - require.Equal(t, true, found) - require.Equal(t, types.TestBandwidthPos1, session.Bandwidth) - - count = k.GetSessionsCount(ctx) - require.Equal(t, uint64(1), count) - - count = k.GetSessionsCountOfSubscription(ctx, subscription.ID) - require.Equal(t, uint64(1), count) -} diff --git a/x/vpn/keeper/deposit.go b/x/vpn/keeper/deposit.go deleted file mode 100644 index afdfbd20..00000000 --- a/x/vpn/keeper/deposit.go +++ /dev/null @@ -1,17 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func (k Keeper) AddDeposit(ctx sdk.Context, address sdk.AccAddress, coin sdk.Coin) sdk.Error { - return k.deposit.Add(ctx, address, sdk.Coins{coin}) -} - -func (k Keeper) SubtractDeposit(ctx sdk.Context, address sdk.AccAddress, coin sdk.Coin) sdk.Error { - return k.deposit.Subtract(ctx, address, sdk.Coins{coin}) -} - -func (k Keeper) SendDeposit(ctx sdk.Context, from, toAddress sdk.AccAddress, coin sdk.Coin) sdk.Error { - return k.deposit.SendCoinsFromDepositToAccount(ctx, from, toAddress, sdk.Coins{coin}) -} diff --git a/x/vpn/keeper/deposit_test.go b/x/vpn/keeper/deposit_test.go deleted file mode 100644 index afd5a069..00000000 --- a/x/vpn/keeper/deposit_test.go +++ /dev/null @@ -1,200 +0,0 @@ -package keeper - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/sentinel-official/hub/x/vpn/types" -) - -func TestKeeper_AddDeposit(t *testing.T) { - ctx, k, dk, bk := CreateTestInput(t, false) - - deposit, found := dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, false, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - - err := k.AddDeposit(ctx, types.TestAddress1, sdk.Coin{}) - require.NotNil(t, err) - err = k.AddDeposit(ctx, types.TestAddress1, sdk.Coin{Denom: "stake", Amount: sdk.NewInt(-100)}) - require.NotNil(t, err) - err = k.AddDeposit(ctx, types.TestAddress1, sdk.NewInt64Coin("stake", 0)) - require.NotNil(t, err) - err = k.AddDeposit(ctx, types.TestAddress1, sdk.NewInt64Coin("stake", 100)) - require.NotNil(t, err) - - coins, err := bk.AddCoins(ctx, types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 100)}) - require.Nil(t, err) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, coins) - - err = k.AddDeposit(ctx, types.TestAddress1, sdk.Coin{}) - require.NotNil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, false, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - - err = k.AddDeposit(ctx, types.TestAddress1, sdk.Coin{Denom: "stake", Amount: sdk.NewInt(-100)}) - require.NotNil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, false, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - - err = k.AddDeposit(ctx, types.TestAddress1, sdk.NewInt64Coin("stake", 0)) - require.NotNil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, false, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - - err = k.AddDeposit(ctx, types.TestAddress1, sdk.NewInt64Coin("stake", 100).Add(sdk.NewInt64Coin("stake", 100))) - require.NotNil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, false, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - - err = k.AddDeposit(ctx, types.TestAddress1, sdk.NewInt64Coin("stake", 100)) - require.Nil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, deposit.Coins) - - err = k.AddDeposit(ctx, types.TestAddress1, sdk.NewInt64Coin("stake", 100)) - require.NotNil(t, err) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, deposit.Coins) -} - -func TestKeeper_SubtractDeposit(t *testing.T) { - ctx, k, dk, bk := CreateTestInput(t, false) - - coins := bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins{}, coins) - deposit, found := dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, false, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - - err := k.SubtractDeposit(ctx, types.TestAddress1, sdk.Coin{}) - require.NotNil(t, err) - err = k.SubtractDeposit(ctx, types.TestAddress1, sdk.Coin{Denom: "stake", Amount: sdk.NewInt(-100)}) - require.NotNil(t, err) - err = k.SubtractDeposit(ctx, types.TestAddress1, sdk.NewInt64Coin("stake", 0)) - require.NotNil(t, err) - err = k.SubtractDeposit(ctx, types.TestAddress1, sdk.NewInt64Coin("stake", 100)) - require.NotNil(t, err) - - coins, err = bk.AddCoins(ctx, types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 100)}) - require.Nil(t, err) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, coins) - err = k.AddDeposit(ctx, types.TestAddress1, sdk.NewInt64Coin("stake", 100)) - require.Nil(t, err) - - err = k.SubtractDeposit(ctx, types.TestAddress1, sdk.Coin{Denom: "stake", Amount: sdk.NewInt(-100)}) - require.NotNil(t, err) - coins = bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins(nil), coins) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, deposit.Coins) - - err = k.SubtractDeposit(ctx, types.TestAddress1, sdk.NewInt64Coin("stake", 0)) - require.NotNil(t, err) - coins = bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins(nil), coins) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, deposit.Coins) - - err = k.SubtractDeposit(ctx, types.TestAddress1, sdk.NewInt64Coin("stake", 100).Add(sdk.NewInt64Coin("stake", 100))) - require.NotNil(t, err) - coins = bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins(nil), coins) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, deposit.Coins) - - err = k.SubtractDeposit(ctx, types.TestAddress1, sdk.NewInt64Coin("stake", 100)) - require.Nil(t, err) - coins = bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, coins) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - - err = k.SubtractDeposit(ctx, types.TestAddress1, sdk.NewInt64Coin("stake", 100)) - require.NotNil(t, err) - coins = bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, coins) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) -} - -func TestKeeper_SendDeposit(t *testing.T) { - ctx, k, dk, bk := CreateTestInput(t, false) - - coins := bk.GetCoins(ctx, types.TestAddress1) - require.Equal(t, sdk.Coins{}, coins) - - coins = bk.GetCoins(ctx, types.TestAddress2) - require.Equal(t, sdk.Coins{}, coins) - deposit, found := dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, false, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - - err := k.SendDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.Coin{}) - require.NotNil(t, err) - err = k.SendDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.Coin{Denom: "stake", Amount: sdk.NewInt(-100)}) - require.NotNil(t, err) - err = k.SendDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.NewInt64Coin("stake", 0)) - require.NotNil(t, err) - err = k.SendDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.NewInt64Coin("stake", 100)) - require.NotNil(t, err) - - coins, err = bk.AddCoins(ctx, types.TestAddress1, sdk.Coins{sdk.NewInt64Coin("stake", 100)}) - require.Nil(t, err) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, coins) - err = k.AddDeposit(ctx, types.TestAddress1, sdk.NewInt64Coin("stake", 100)) - require.Nil(t, err) - - err = k.SendDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.Coin{Denom: "stake", Amount: sdk.NewInt(-100)}) - require.NotNil(t, err) - coins = bk.GetCoins(ctx, types.TestAddress2) - require.Equal(t, sdk.Coins{}, coins) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, deposit.Coins) - - err = k.SendDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.NewInt64Coin("stake", 0)) - require.NotNil(t, err) - coins = bk.GetCoins(ctx, types.TestAddress2) - require.Equal(t, sdk.Coins{}, coins) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, deposit.Coins) - - err = k.SendDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.NewInt64Coin("stake", 100).Add(sdk.NewInt64Coin("stake", 100))) - require.NotNil(t, err) - coins = bk.GetCoins(ctx, types.TestAddress2) - require.Equal(t, sdk.Coins{}, coins) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, deposit.Coins) - - err = k.SendDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.NewInt64Coin("stake", 100)) - require.Nil(t, err) - coins = bk.GetCoins(ctx, types.TestAddress2) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, coins) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) - - err = k.SendDeposit(ctx, types.TestAddress1, types.TestAddress2, sdk.NewInt64Coin("stake", 100)) - require.NotNil(t, err) - coins = bk.GetCoins(ctx, types.TestAddress2) - require.Equal(t, sdk.Coins{sdk.NewInt64Coin("stake", 100)}, coins) - deposit, found = dk.GetDeposit(ctx, types.TestAddress1) - require.Equal(t, true, found) - require.Equal(t, sdk.Coins(nil), deposit.Coins) -} diff --git a/x/vpn/keeper/keeper.go b/x/vpn/keeper/keeper.go deleted file mode 100644 index c7e13da5..00000000 --- a/x/vpn/keeper/keeper.go +++ /dev/null @@ -1,30 +0,0 @@ -package keeper - -import ( - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/params" - - "github.com/sentinel-official/hub/x/deposit" -) - -type Keeper struct { - nodeKey sdk.StoreKey - subscriptionKey sdk.StoreKey - sessionKey sdk.StoreKey - cdc *codec.Codec - paramStore params.Subspace - deposit deposit.Keeper -} - -func NewKeeper(cdc *codec.Codec, nodeKey, subscriptionKey, sessionKey sdk.StoreKey, - paramStore params.Subspace, dk deposit.Keeper) Keeper { - return Keeper{ - nodeKey: nodeKey, - subscriptionKey: subscriptionKey, - sessionKey: sessionKey, - cdc: cdc, - paramStore: paramStore.WithKeyTable(ParamKeyTable()), - deposit: dk, - } -} diff --git a/x/vpn/keeper/node.go b/x/vpn/keeper/node.go deleted file mode 100644 index a58fac13..00000000 --- a/x/vpn/keeper/node.go +++ /dev/null @@ -1,191 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func (k Keeper) SetNodesCount(ctx sdk.Context, count uint64) { - value := k.cdc.MustMarshalBinaryLengthPrefixed(count) - - store := ctx.KVStore(k.nodeKey) - store.Set(types.NodesCountKey, value) -} - -func (k Keeper) GetNodesCount(ctx sdk.Context) (count uint64) { - store := ctx.KVStore(k.nodeKey) - - value := store.Get(types.NodesCountKey) - if value == nil { - return 0 - } - - k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &count) - return count -} - -func (k Keeper) SetNode(ctx sdk.Context, node types.Node) { - key := types.NodeKey(node.ID) - - value := k.cdc.MustMarshalBinaryLengthPrefixed(node) - - store := ctx.KVStore(k.nodeKey) - store.Set(key, value) -} - -func (k Keeper) GetNode(ctx sdk.Context, id hub.NodeID) (node types.Node, found bool) { - store := ctx.KVStore(k.nodeKey) - - key := types.NodeKey(id) - value := store.Get(key) - if value == nil { - return node, false - } - - k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &node) - return node, true -} - -func (k Keeper) SetNodesCountOfAddress(ctx sdk.Context, address sdk.AccAddress, count uint64) { - key := types.NodesCountOfAddressKey(address) - value := k.cdc.MustMarshalBinaryLengthPrefixed(count) - - store := ctx.KVStore(k.nodeKey) - store.Set(key, value) -} - -func (k Keeper) GetNodesCountOfAddress(ctx sdk.Context, address sdk.AccAddress) (count uint64) { - store := ctx.KVStore(k.nodeKey) - - key := types.NodesCountOfAddressKey(address) - value := store.Get(key) - if value == nil { - return 0 - } - - k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &count) - return count -} - -func (k Keeper) SetNodeIDByAddress(ctx sdk.Context, address sdk.AccAddress, i uint64, id hub.NodeID) { - key := types.NodeIDByAddressKey(address, i) - value := k.cdc.MustMarshalBinaryLengthPrefixed(id) - - store := ctx.KVStore(k.nodeKey) - store.Set(key, value) -} - -func (k Keeper) GetNodeIDByAddress(ctx sdk.Context, address sdk.AccAddress, i uint64) (id hub.NodeID, found bool) { - store := ctx.KVStore(k.nodeKey) - - key := types.NodeIDByAddressKey(address, i) - value := store.Get(key) - if value == nil { - return hub.NewNodeID(0), false - } - - k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &id) - return id, true -} - -func (k Keeper) SetActiveNodeIDs(ctx sdk.Context, height int64, ids hub.IDs) { - ids = ids.Sort() - - key := types.ActiveNodeIDsKey(height) - value := k.cdc.MustMarshalBinaryLengthPrefixed(ids) - - store := ctx.KVStore(k.nodeKey) - store.Set(key, value) -} - -func (k Keeper) GetActiveNodeIDs(ctx sdk.Context, height int64) (ids hub.IDs) { - store := ctx.KVStore(k.nodeKey) - - key := types.ActiveNodeIDsKey(height) - value := store.Get(key) - if value == nil { - return ids - } - - k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &ids) - return ids -} - -func (k Keeper) DeleteActiveNodeIDs(ctx sdk.Context, height int64) { - store := ctx.KVStore(k.nodeKey) - - key := types.ActiveNodeIDsKey(height) - store.Delete(key) -} - -func (k Keeper) GetNodesOfAddress(ctx sdk.Context, address sdk.AccAddress) (nodes []types.Node) { - count := k.GetNodesCountOfAddress(ctx, address) - - nodes = make([]types.Node, 0, count) - for i := uint64(0); i < count; i++ { - id, _ := k.GetNodeIDByAddress(ctx, address, i) - - node, _ := k.GetNode(ctx, id) - nodes = append(nodes, node) - } - - return nodes -} - -func (k Keeper) GetAllNodes(ctx sdk.Context) (nodes []types.Node) { - store := ctx.KVStore(k.nodeKey) - - iter := sdk.KVStorePrefixIterator(store, types.NodeKeyPrefix) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - var node types.Node - k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &node) - nodes = append(nodes, node) - } - - return nodes -} - -func (k Keeper) IterateNodes(ctx sdk.Context, fn func(index int64, node types.Node) (stop bool)) { - store := ctx.KVStore(k.nodeKey) - - iterator := sdk.KVStorePrefixIterator(store, types.NodeKeyPrefix) - defer iterator.Close() - - for i := int64(0); iterator.Valid(); iterator.Next() { - var node types.Node - k.cdc.MustUnmarshalBinaryLengthPrefixed(iterator.Value(), &node) - - if stop := fn(i, node); stop { - break - } - i++ - } -} - -func (k Keeper) AddNodeIDToActiveList(ctx sdk.Context, height int64, id hub.NodeID) { - ids := k.GetActiveNodeIDs(ctx, height) - - index := ids.Search(id) - if index != len(ids) { - return - } - - ids = ids.Append(id) - k.SetActiveNodeIDs(ctx, height, ids) -} - -func (k Keeper) RemoveNodeIDFromActiveList(ctx sdk.Context, height int64, id hub.NodeID) { - ids := k.GetActiveNodeIDs(ctx, height) - - index := ids.Search(id) - if index == len(ids) { - return - } - - ids = ids.Delete(index) - k.SetActiveNodeIDs(ctx, height, ids) -} diff --git a/x/vpn/keeper/node_test.go b/x/vpn/keeper/node_test.go deleted file mode 100644 index 3cd8efe7..00000000 --- a/x/vpn/keeper/node_test.go +++ /dev/null @@ -1,299 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/stretchr/testify/require" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func TestKeeper_SetNodesCount(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - count := k.GetNodesCount(ctx) - require.Equal(t, uint64(0), count) - - k.SetNodesCount(ctx, 0) - count = k.GetNodesCount(ctx) - require.Equal(t, uint64(0), count) - - k.SetNodesCount(ctx, 1) - count = k.GetNodesCount(ctx) - require.Equal(t, uint64(1), count) - - k.SetNodesCount(ctx, 2) - count = k.GetNodesCount(ctx) - require.Equal(t, uint64(2), count) -} - -func TestKeeper_GetNodesCount(t *testing.T) { - TestKeeper_SetNodesCount(t) -} - -func TestKeeper_SetNode(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - _, found := k.GetNode(ctx, hub.NewNodeID(0)) - require.Equal(t, false, found) - - k.SetNode(ctx, types.TestNode) - node, found := k.GetNode(ctx, types.TestNode.ID) - require.Equal(t, true, found) - require.Equal(t, types.TestNode, node) -} - -func TestKeeper_GetNode(t *testing.T) { - TestKeeper_SetNode(t) -} - -func TestKeeper_SetNodesCountOfAddress(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - count := k.GetNodesCountOfAddress(ctx, types.TestAddress1) - require.Equal(t, uint64(0), count) - - k.SetNodesCountOfAddress(ctx, []byte(""), 1) - count = k.GetNodesCountOfAddress(ctx, []byte("")) - require.Equal(t, uint64(1), count) - - k.SetNodesCountOfAddress(ctx, types.TestAddress1, 1) - count = k.GetNodesCountOfAddress(ctx, types.TestAddress1) - require.Equal(t, uint64(1), count) - - k.SetNodesCountOfAddress(ctx, types.TestAddress2, 2) - count = k.GetNodesCountOfAddress(ctx, types.TestAddress2) - require.Equal(t, uint64(2), count) - - count = k.GetNodesCountOfAddress(ctx, types.TestAddress1) - require.Equal(t, uint64(1), count) - - k.SetNodesCountOfAddress(ctx, types.TestAddress1, 0) - count = k.GetNodesCountOfAddress(ctx, types.TestAddress1) - require.Equal(t, uint64(0), count) - - count = k.GetNodesCountOfAddress(ctx, types.TestAddress2) - require.Equal(t, uint64(2), count) - - k.SetNodesCountOfAddress(ctx, types.TestAddress2, 0) - count = k.GetNodesCountOfAddress(ctx, types.TestAddress2) - require.Equal(t, uint64(0), count) -} - -func TestKeeper_GetNodesCountOfAddress(t *testing.T) { - TestKeeper_SetNodesCountOfAddress(t) -} - -func TestKeeper_SetNodeIDByAddress(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - id, found := k.GetNodeIDByAddress(ctx, types.TestAddress1, 0) - require.Equal(t, false, found) - require.Equal(t, hub.NewNodeID(0), id) - - k.SetNodeIDByAddress(ctx, []byte(""), 0, hub.NewNodeID(0)) - id, found = k.GetNodeIDByAddress(ctx, []byte(""), 0) - require.Equal(t, true, found) - require.Equal(t, hub.NewNodeID(0), id) - - k.SetNodeIDByAddress(ctx, types.TestAddress1, 0, hub.NewNodeID(0)) - id, found = k.GetNodeIDByAddress(ctx, types.TestAddress1, 0) - require.Equal(t, true, found) - require.Equal(t, hub.NewNodeID(0), id) - - k.SetNodeIDByAddress(ctx, types.TestAddress2, 0, hub.NewNodeID(0)) - id, found = k.GetNodeIDByAddress(ctx, types.TestAddress2, 0) - require.Equal(t, true, found) - require.Equal(t, hub.NewNodeID(0), id) - - k.SetNodeIDByAddress(ctx, types.TestAddress1, 1, hub.NewNodeID(1)) - id, found = k.GetNodeIDByAddress(ctx, types.TestAddress1, 1) - require.Equal(t, true, found) - require.Equal(t, hub.NewNodeID(1), id) - - k.SetNodeIDByAddress(ctx, types.TestAddress2, 1, hub.NewNodeID(1)) - id, found = k.GetNodeIDByAddress(ctx, types.TestAddress2, 1) - require.Equal(t, true, found) - require.Equal(t, hub.NewNodeID(1), id) -} - -func TestKeeper_GetNodeIDByAddress(t *testing.T) { - TestKeeper_SetNodeIDByAddress(t) -} - -func TestKeeper_SetActiveNodeIDs(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - ids := k.GetActiveNodeIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - - k.SetActiveNodeIDs(ctx, 1, hub.IDs{}) - ids = k.GetActiveNodeIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - - k.SetActiveNodeIDs(ctx, 1, hub.IDs(nil)) - ids = k.GetActiveNodeIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - - k.SetActiveNodeIDs(ctx, 1, hub.IDs{hub.NewNodeID(0)}) - ids = k.GetActiveNodeIDs(ctx, 1) - require.Equal(t, hub.IDs{hub.NewNodeID(0)}, ids) - - k.SetActiveNodeIDs(ctx, 1, hub.IDs{hub.NewNodeID(0)}.Append(hub.NewNodeID(0))) - ids = k.GetActiveNodeIDs(ctx, 1) - require.Equal(t, hub.IDs{hub.NewNodeID(0)}.Append(hub.NewNodeID(0)).Sort(), ids) - - k.SetActiveNodeIDs(ctx, 1, hub.IDs{}) - ids = k.GetActiveNodeIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - - ids = k.GetActiveNodeIDs(ctx, 2) - require.Equal(t, hub.IDs(nil), ids) - - k.SetActiveNodeIDs(ctx, 2, hub.IDs{}) - ids = k.GetActiveNodeIDs(ctx, 2) - require.Equal(t, hub.IDs(nil), ids) - - k.SetActiveNodeIDs(ctx, 2, hub.IDs(nil)) - ids = k.GetActiveNodeIDs(ctx, 2) - require.Equal(t, hub.IDs(nil), ids) - - k.SetActiveNodeIDs(ctx, 2, hub.IDs{hub.NewNodeID(0)}) - ids = k.GetActiveNodeIDs(ctx, 2) - require.Equal(t, hub.IDs{hub.NewNodeID(0)}, ids) - - k.SetActiveNodeIDs(ctx, 2, hub.IDs{hub.NewNodeID(0)}.Append(hub.NewNodeID(0))) - ids = k.GetActiveNodeIDs(ctx, 2) - require.Equal(t, hub.IDs{hub.NewNodeID(0)}.Append(hub.NewNodeID(0)).Sort(), ids) - - k.SetActiveNodeIDs(ctx, 2, hub.IDs{}) - ids = k.GetActiveNodeIDs(ctx, 2) - require.Equal(t, hub.IDs(nil), ids) -} - -func TestKeeper_GetActiveNodeIDs(t *testing.T) { - TestKeeper_SetActiveNodeIDs(t) -} - -func TestKeeper_DeleteActiveNodeIDs(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - ids := k.GetActiveNodeIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - - k.DeleteActiveNodeIDs(ctx, 1) - ids = k.GetActiveNodeIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - - k.SetActiveNodeIDs(ctx, 1, hub.IDs{hub.NewNodeID(0)}) - k.DeleteActiveNodeIDs(ctx, 1) - ids = k.GetActiveNodeIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - - k.SetActiveNodeIDs(ctx, 2, hub.IDs{hub.NewNodeID(0), hub.NewNodeID(1)}) - k.DeleteActiveNodeIDs(ctx, 3) - ids = k.GetActiveNodeIDs(ctx, 2) - require.Equal(t, hub.IDs{hub.NewNodeID(0), hub.NewNodeID(1)}, ids) - - k.DeleteActiveNodeIDs(ctx, 2) - ids = k.GetActiveNodeIDs(ctx, 2) - require.Equal(t, hub.IDs(nil), ids) -} - -func TestKeeper_GetNodesOfAddress(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - nodes := k.GetNodesOfAddress(ctx, types.TestAddress1) - require.Equal(t, []types.Node{}, nodes) - - k.SetNode(ctx, types.TestNode) - k.SetNodeIDByAddress(ctx, types.TestAddress1, 0, hub.NewNodeID(0)) - k.SetNodesCountOfAddress(ctx, types.TestAddress1, 1) - - nodes = k.GetNodesOfAddress(ctx, []byte("")) - require.Equal(t, []types.Node{}, nodes) - nodes = k.GetNodesOfAddress(ctx, types.TestAddress2) - require.Equal(t, []types.Node{}, nodes) - nodes = k.GetNodesOfAddress(ctx, types.TestAddress1) - require.Equal(t, []types.Node{types.TestNode}, nodes) - - k.SetNode(ctx, types.TestNode) - k.SetNodeIDByAddress(ctx, types.TestAddress2, 0, hub.NewNodeID(0)) - k.SetNodesCountOfAddress(ctx, types.TestAddress2, 1) - - nodes = k.GetNodesOfAddress(ctx, types.TestAddress2) - require.Equal(t, []types.Node{types.TestNode}, nodes) - - node := types.TestNode - node.ID = hub.NewNodeID(1) - k.SetNode(ctx, node) - k.SetNodeIDByAddress(ctx, types.TestAddress2, 1, hub.NewNodeID(1)) - k.SetNodesCountOfAddress(ctx, types.TestAddress2, 2) - - nodes = k.GetNodesOfAddress(ctx, types.TestAddress2) - require.Equal(t, append([]types.Node{types.TestNode}, node), nodes) -} - -func TestKeeper_GetAllNodes(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - nodes := k.GetAllNodes(ctx) - require.Equal(t, []types.Node(nil), nodes) - - k.SetNode(ctx, types.TestNode) - nodes = k.GetAllNodes(ctx) - require.Equal(t, []types.Node{types.TestNode}, nodes) - - node := types.TestNode - node.ID = hub.NewNodeID(1) - k.SetNode(ctx, node) - nodes = k.GetAllNodes(ctx) - require.Equal(t, append([]types.Node{types.TestNode}, node), nodes) - - k.SetNode(ctx, types.TestNode) - nodes = k.GetAllNodes(ctx) - require.Equal(t, append([]types.Node{types.TestNode}, node), nodes) -} - -func TestKeeper_AddNodeIDToActiveList(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - ids := k.GetActiveNodeIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - - k.AddNodeIDToActiveList(ctx, 1, hub.NewNodeID(0)) - ids = k.GetActiveNodeIDs(ctx, 1) - require.Equal(t, hub.IDs{hub.NewNodeID(0)}, ids) - - k.AddNodeIDToActiveList(ctx, 2, hub.NewNodeID(0)) - k.AddNodeIDToActiveList(ctx, 2, hub.NewNodeID(1)) - ids = k.GetActiveNodeIDs(ctx, 2) - require.Equal(t, hub.IDs{hub.NewNodeID(0)}.Append(hub.NewNodeID(1)).Sort(), ids) -} - -func TestKeeper_RemoveNodeIDFromActiveList(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - ids := k.GetActiveNodeIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - - k.AddNodeIDToActiveList(ctx, 1, hub.NewNodeID(0)) - k.RemoveNodeIDFromActiveList(ctx, 1, hub.NewNodeID(1)) - ids = k.GetActiveNodeIDs(ctx, 1) - require.Equal(t, hub.IDs{hub.NewNodeID(0)}, ids) - - k.RemoveNodeIDFromActiveList(ctx, 1, hub.NewNodeID(0)) - ids = k.GetActiveNodeIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - - k.AddNodeIDToActiveList(ctx, 2, hub.NewNodeID(0)) - k.AddNodeIDToActiveList(ctx, 2, hub.NewNodeID(1)) - k.RemoveNodeIDFromActiveList(ctx, 2, hub.NewNodeID(1)) - ids = k.GetActiveNodeIDs(ctx, 2) - require.Equal(t, hub.IDs{hub.NewNodeID(0)}, ids) - - k.RemoveNodeIDFromActiveList(ctx, 2, hub.NewNodeID(0)) - ids = k.GetActiveNodeIDs(ctx, 2) - require.Equal(t, hub.IDs(nil), ids) -} diff --git a/x/vpn/keeper/params.go b/x/vpn/keeper/params.go deleted file mode 100644 index 64396afd..00000000 --- a/x/vpn/keeper/params.go +++ /dev/null @@ -1,43 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/params" - - "github.com/sentinel-official/hub/x/vpn/types" -) - -const ( - DefaultParamspace = types.ModuleName -) - -func ParamKeyTable() params.KeyTable { - return params.NewKeyTable().RegisterParamSet(&types.Params{}) -} - -func (k Keeper) FreeNodesCount(ctx sdk.Context) (res uint64) { - k.paramStore.Get(ctx, types.KeyFreeNodesCount, &res) - return -} - -func (k Keeper) Deposit(ctx sdk.Context) (res sdk.Coin) { - k.paramStore.Get(ctx, types.KeyDeposit, &res) - return -} - -func (k Keeper) SessionInactiveInterval(ctx sdk.Context) (res int64) { - k.paramStore.Get(ctx, types.KeySessionInactiveInterval, &res) - return -} - -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - return types.NewParams( - k.FreeNodesCount(ctx), - k.Deposit(ctx), - k.SessionInactiveInterval(ctx), - ) -} - -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramStore.SetParamSet(ctx, ¶ms) -} diff --git a/x/vpn/keeper/session.go b/x/vpn/keeper/session.go deleted file mode 100644 index f73a684d..00000000 --- a/x/vpn/keeper/session.go +++ /dev/null @@ -1,175 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func (k Keeper) SetSessionsCount(ctx sdk.Context, count uint64) { - value := k.cdc.MustMarshalBinaryLengthPrefixed(count) - - store := ctx.KVStore(k.sessionKey) - store.Set(types.SessionsCountKey, value) -} - -func (k Keeper) GetSessionsCount(ctx sdk.Context) (count uint64) { - store := ctx.KVStore(k.sessionKey) - - value := store.Get(types.SessionsCountKey) - if value == nil { - return 0 - } - - k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &count) - return count -} - -func (k Keeper) SetSession(ctx sdk.Context, session types.Session) { - key := types.SessionKey(session.ID) - value := k.cdc.MustMarshalBinaryLengthPrefixed(session) - - store := ctx.KVStore(k.sessionKey) - store.Set(key, value) -} - -func (k Keeper) GetSession(ctx sdk.Context, id hub.SessionID) (session types.Session, found bool) { - store := ctx.KVStore(k.sessionKey) - - key := types.SessionKey(id) - value := store.Get(key) - if value == nil { - return session, false - } - - k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &session) - return session, true -} - -func (k Keeper) SetSessionsCountOfSubscription(ctx sdk.Context, id hub.SubscriptionID, count uint64) { - key := types.SessionsCountOfSubscriptionKey(id) - value := k.cdc.MustMarshalBinaryLengthPrefixed(count) - - store := ctx.KVStore(k.sessionKey) - store.Set(key, value) -} - -func (k Keeper) GetSessionsCountOfSubscription(ctx sdk.Context, id hub.SubscriptionID) (count uint64) { - store := ctx.KVStore(k.sessionKey) - - key := types.SessionsCountOfSubscriptionKey(id) - value := store.Get(key) - if value == nil { - return 0 - } - - k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &count) - - return count -} - -func (k Keeper) SetSessionIDBySubscriptionID(ctx sdk.Context, i hub.SubscriptionID, j uint64, id hub.SessionID) { - key := types.SessionIDBySubscriptionIDKey(i, j) - value := k.cdc.MustMarshalBinaryLengthPrefixed(id) - - store := ctx.KVStore(k.sessionKey) - store.Set(key, value) -} - -func (k Keeper) GetSessionIDBySubscriptionID(ctx sdk.Context, - i hub.SubscriptionID, j uint64) (id hub.SessionID, found bool) { - store := ctx.KVStore(k.sessionKey) - - key := types.SessionIDBySubscriptionIDKey(i, j) - value := store.Get(key) - if value == nil { - return hub.NewSessionID(0), false - } - - k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &id) - return id, true -} - -func (k Keeper) SetActiveSessionIDs(ctx sdk.Context, height int64, ids hub.IDs) { - ids.Sort() - - key := types.ActiveSessionIDsKey(height) - value := k.cdc.MustMarshalBinaryLengthPrefixed(ids) - - store := ctx.KVStore(k.sessionKey) - store.Set(key, value) -} - -func (k Keeper) GetActiveSessionIDs(ctx sdk.Context, height int64) (ids hub.IDs) { - store := ctx.KVStore(k.sessionKey) - - key := types.ActiveSessionIDsKey(height) - value := store.Get(key) - if value == nil { - return ids - } - - k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &ids) - return ids -} - -func (k Keeper) DeleteActiveSessionIDs(ctx sdk.Context, height int64) { - store := ctx.KVStore(k.sessionKey) - - key := types.ActiveSessionIDsKey(height) - store.Delete(key) -} - -func (k Keeper) GetSessionsOfSubscription(ctx sdk.Context, id hub.SubscriptionID) (sessions []types.Session) { - count := k.GetSessionsCountOfSubscription(ctx, id) - - sessions = make([]types.Session, 0, count) - for i := uint64(0); i < count; i++ { - _id, _ := k.GetSessionIDBySubscriptionID(ctx, id, i) - - session, _ := k.GetSession(ctx, _id) - sessions = append(sessions, session) - } - - return sessions -} - -func (k Keeper) GetAllSessions(ctx sdk.Context) (sessions []types.Session) { - store := ctx.KVStore(k.sessionKey) - - iter := sdk.KVStorePrefixIterator(store, types.SessionKeyPrefix) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - var session types.Session - k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &session) - sessions = append(sessions, session) - } - - return sessions -} - -func (k Keeper) AddSessionIDToActiveList(ctx sdk.Context, height int64, id hub.SessionID) { - ids := k.GetActiveSessionIDs(ctx, height) - - index := ids.Search(id) - if index != len(ids) { - return - } - - ids = ids.Append(id) - k.SetActiveSessionIDs(ctx, height, ids) -} - -func (k Keeper) RemoveSessionIDFromActiveList(ctx sdk.Context, height int64, id hub.SessionID) { - ids := k.GetActiveSessionIDs(ctx, height) - - index := ids.Search(id) - if index == len(ids) { - return - } - - ids = ids.Delete(index) - k.SetActiveSessionIDs(ctx, height, ids) -} diff --git a/x/vpn/keeper/session_test.go b/x/vpn/keeper/session_test.go deleted file mode 100644 index 11522725..00000000 --- a/x/vpn/keeper/session_test.go +++ /dev/null @@ -1,271 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/stretchr/testify/require" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func TestKeeper_SetSessionsCount(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - count := k.GetSessionsCount(ctx) - require.Equal(t, uint64(0), count) - - k.SetSessionsCount(ctx, 1) - count = k.GetSessionsCount(ctx) - require.Equal(t, uint64(1), count) - - k.SetSessionsCount(ctx, 0) - count = k.GetSessionsCount(ctx) - require.Equal(t, uint64(0), count) - - k.SetSessionsCount(ctx, 2) - count = k.GetSessionsCount(ctx) - require.Equal(t, uint64(2), count) -} - -func TestKeeper_GetSessionsCount(t *testing.T) { - TestKeeper_SetSessionsCount(t) -} - -func TestKeeper_SetSession(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - _, found := k.GetSession(ctx, hub.NewSessionID(0)) - require.Equal(t, false, found) - - k.SetSession(ctx, types.TestSession) - result, found := k.GetSession(ctx, types.TestSession.ID) - require.Equal(t, true, found) - require.Equal(t, types.TestSession, result) -} - -func TestKeeper_GetSession(t *testing.T) { - TestKeeper_SetNode(t) -} - -func TestKeeper_SetSessionsCountOfSubscription(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - count := k.GetSessionsCountOfSubscription(ctx, hub.NewSubscriptionID(0)) - require.Equal(t, uint64(0), count) - - k.SetSessionsCountOfSubscription(ctx, hub.NewSubscriptionID(0), 1) - count = k.GetSessionsCountOfSubscription(ctx, hub.NewSubscriptionID(0)) - require.Equal(t, uint64(1), count) - - k.SetSessionsCountOfSubscription(ctx, hub.NewSubscriptionID(1), 1) - count = k.GetSessionsCountOfSubscription(ctx, hub.NewSubscriptionID(1)) - require.Equal(t, uint64(1), count) - - k.SetSessionsCountOfSubscription(ctx, hub.NewSubscriptionID(0), 2) - count = k.GetSessionsCountOfSubscription(ctx, hub.NewSubscriptionID(0)) - require.Equal(t, uint64(2), count) -} - -func TestKeeper_GetSessionsCountOfSubscription(t *testing.T) { - TestKeeper_SetSessionsCountOfSubscription(t) -} - -func TestKeeper_SetSessionIDBySubscriptionID(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - _, found := k.GetSessionIDBySubscriptionID(ctx, hub.NewSubscriptionID(1), 1) - require.Equal(t, false, found) - - k.SetSessionIDBySubscriptionID(ctx, hub.NewSubscriptionID(0), 2, hub.NewSessionID(0)) - id, found := k.GetSessionIDBySubscriptionID(ctx, hub.NewSubscriptionID(0), 2) - require.Equal(t, true, found) - require.Equal(t, hub.NewSessionID(0), id) - - k.SetSessionIDBySubscriptionID(ctx, hub.NewSubscriptionID(0), 3, hub.NewSessionID(1)) - id, found = k.GetSessionIDBySubscriptionID(ctx, hub.NewSubscriptionID(0), 3) - require.Equal(t, true, found) - require.Equal(t, hub.NewSessionID(1), id) - - k.SetSessionIDBySubscriptionID(ctx, hub.NewSubscriptionID(1), 4, hub.NewSessionID(0)) - id, found = k.GetSessionIDBySubscriptionID(ctx, hub.NewSubscriptionID(1), 4) - require.Equal(t, true, found) - require.Equal(t, hub.NewSessionID(0), id) - - k.SetSessionIDBySubscriptionID(ctx, hub.NewSubscriptionID(1), 5, hub.NewSessionID(1)) - id, found = k.GetSessionIDBySubscriptionID(ctx, hub.NewSubscriptionID(1), 5) - require.Equal(t, true, found) - require.Equal(t, hub.NewSessionID(1), id) -} - -func TestKeeper_GetSessionIDBySubscriptionID(t *testing.T) { - TestKeeper_SetSessionIDBySubscriptionID(t) -} - -func TestKeeper_SetActiveSessionIDs(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - ids := k.GetActiveSessionIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - - k.SetActiveSessionIDs(ctx, 1, hub.IDs{}) - ids = k.GetActiveSessionIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - - k.SetActiveSessionIDs(ctx, 1, hub.IDs(nil)) - ids = k.GetActiveSessionIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - - k.SetActiveSessionIDs(ctx, 1, hub.IDs{hub.NewSessionID(0)}) - ids = k.GetActiveSessionIDs(ctx, 1) - require.Equal(t, hub.IDs{hub.NewSessionID(0)}, ids) - - k.SetActiveSessionIDs(ctx, 1, hub.IDs{hub.NewSessionID(0)}.Append(hub.NewSessionID(0))) - ids = k.GetActiveSessionIDs(ctx, 1) - require.Equal(t, hub.IDs{hub.NewSessionID(0)}.Append(hub.NewSessionID(0)).Sort(), ids) - - k.SetActiveSessionIDs(ctx, 1, hub.IDs{}) - ids = k.GetActiveSessionIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - - ids = k.GetActiveSessionIDs(ctx, 2) - require.Equal(t, hub.IDs(nil), ids) - - k.SetActiveSessionIDs(ctx, 2, hub.IDs{}) - ids = k.GetActiveSessionIDs(ctx, 2) - require.Equal(t, hub.IDs(nil), ids) - - k.SetActiveSessionIDs(ctx, 2, hub.IDs(nil)) - ids = k.GetActiveSessionIDs(ctx, 2) - require.Equal(t, hub.IDs(nil), ids) - - k.SetActiveSessionIDs(ctx, 2, hub.IDs{hub.NewSessionID(0)}) - ids = k.GetActiveSessionIDs(ctx, 2) - require.Equal(t, hub.IDs{hub.NewSessionID(0)}, ids) - - k.SetActiveSessionIDs(ctx, 2, hub.IDs{hub.NewSessionID(0)}.Append(hub.NewSessionID(0))) - ids = k.GetActiveSessionIDs(ctx, 2) - require.Equal(t, hub.IDs{hub.NewSessionID(0)}.Append(hub.NewSessionID(0)).Sort(), ids) - - k.SetActiveSessionIDs(ctx, 2, hub.IDs{}) - ids = k.GetActiveSessionIDs(ctx, 2) - require.Equal(t, hub.IDs(nil), ids) -} - -func TestKeeper_GetActiveSessionIDs(t *testing.T) { - TestKeeper_SetActiveSessionIDs(t) -} - -func TestKeeper_DeleteActiveSessionIDs(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - ids := k.GetActiveSessionIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - k.DeleteActiveSessionIDs(ctx, 1) - ids = k.GetActiveSessionIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - - k.SetActiveSessionIDs(ctx, 1, hub.IDs{hub.NewSessionID(0)}) - k.DeleteActiveSessionIDs(ctx, 1) - ids = k.GetActiveSessionIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - - k.SetActiveSessionIDs(ctx, 1, hub.IDs{hub.NewSessionID(0)}.Append(hub.NewSessionID(1))) - k.DeleteActiveSessionIDs(ctx, 2) - ids = k.GetActiveSessionIDs(ctx, 1) - require.Equal(t, hub.IDs{hub.NewSessionID(0)}.Append(hub.NewSessionID(1)), ids) - - k.DeleteActiveSessionIDs(ctx, 1) - ids = k.GetActiveSessionIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) -} - -func TestKeeper_GetSessionsOfSubscription(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - sessions := k.GetSessionsOfSubscription(ctx, hub.NewSubscriptionID(0)) - require.Equal(t, []types.Session{}, sessions) - - k.SetSession(ctx, types.TestSession) - k.SetSessionIDBySubscriptionID(ctx, hub.NewSubscriptionID(0), 0, hub.NewSessionID(0)) - k.SetSessionsCountOfSubscription(ctx, hub.NewSubscriptionID(0), 1) - - sessions = k.GetSessionsOfSubscription(ctx, hub.NewSubscriptionID(1)) - require.Equal(t, []types.Session{}, sessions) - sessions = k.GetSessionsOfSubscription(ctx, hub.NewSubscriptionID(0)) - require.Equal(t, []types.Session{types.TestSession}, sessions) - - session := types.TestSession - session.ID = hub.NewSessionID(1) - k.SetSession(ctx, session) - k.SetSessionIDBySubscriptionID(ctx, hub.NewSubscriptionID(0), 1, hub.NewSessionID(1)) - k.SetSessionsCountOfSubscription(ctx, hub.NewSubscriptionID(0), 2) - sessions = k.GetSessionsOfSubscription(ctx, hub.NewSubscriptionID(0)) - require.Equal(t, append([]types.Session{types.TestSession}, session), sessions) -} - -func TestKeeper_GetAllSessions(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - sessions := k.GetAllSessions(ctx) - require.Equal(t, []types.Session(nil), sessions) - - k.SetSession(ctx, types.TestSession) - sessions = k.GetAllSessions(ctx) - require.Equal(t, []types.Session{types.TestSession}, sessions) - - session := types.TestSession - session.ID = hub.NewSessionID(1) - k.SetSession(ctx, session) - sessions = k.GetAllSessions(ctx) - require.Equal(t, append([]types.Session{types.TestSession}, session), sessions) - - k.SetSession(ctx, types.TestSession) - sessions = k.GetAllSessions(ctx) - require.Equal(t, append([]types.Session{types.TestSession}, session), sessions) -} - -func TestKeeper_AddSessionIDToActiveList(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - ids := k.GetActiveSessionIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - - k.AddSessionIDToActiveList(ctx, 1, hub.NewSessionID(0)) - ids = k.GetActiveSessionIDs(ctx, 1) - require.Equal(t, hub.IDs{hub.NewSessionID(0)}, ids) - - k.AddSessionIDToActiveList(ctx, 1, hub.NewSessionID(1)) - ids = k.GetActiveSessionIDs(ctx, 1) - require.Equal(t, hub.IDs{hub.NewSessionID(0)}.Append(hub.NewSessionID(1)), ids) - - k.AddSessionIDToActiveList(ctx, 2, hub.NewSessionID(0)) - k.AddSessionIDToActiveList(ctx, 2, hub.NewSessionID(1)) - require.Equal(t, hub.IDs{hub.NewSessionID(0)}.Append(hub.NewSessionID(1)), ids) -} - -func TestKeeper_RemoveSessionIDFromActiveList(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - ids := k.GetActiveSessionIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - - k.AddSessionIDToActiveList(ctx, 1, hub.NewSessionID(0)) - k.RemoveSessionIDFromActiveList(ctx, 1, hub.NewSessionID(1)) - ids = k.GetActiveSessionIDs(ctx, 1) - require.Equal(t, hub.IDs{hub.NewSessionID(0)}, ids) - - k.RemoveSessionIDFromActiveList(ctx, 1, hub.NewSessionID(0)) - ids = k.GetActiveSessionIDs(ctx, 1) - require.Equal(t, hub.IDs(nil), ids) - - k.AddSessionIDToActiveList(ctx, 3, hub.NewSessionID(0)) - k.AddSessionIDToActiveList(ctx, 3, hub.NewSessionID(1)) - k.RemoveSessionIDFromActiveList(ctx, 3, hub.NewSessionID(1)) - ids = k.GetActiveSessionIDs(ctx, 3) - require.Equal(t, hub.IDs{hub.NewSessionID(0)}, ids) - - k.RemoveSessionIDFromActiveList(ctx, 3, hub.NewSessionID(0)) - ids = k.GetActiveSessionIDs(ctx, 3) - require.Equal(t, hub.IDs(nil), ids) -} diff --git a/x/vpn/keeper/subscription.go b/x/vpn/keeper/subscription.go deleted file mode 100644 index ce14e794..00000000 --- a/x/vpn/keeper/subscription.go +++ /dev/null @@ -1,195 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func (k Keeper) SetSubscriptionsCount(ctx sdk.Context, count uint64) { - value := k.cdc.MustMarshalBinaryLengthPrefixed(count) - - store := ctx.KVStore(k.subscriptionKey) - store.Set(types.SubscriptionsCountKey, value) -} - -func (k Keeper) GetSubscriptionsCount(ctx sdk.Context) (count uint64) { - store := ctx.KVStore(k.subscriptionKey) - - value := store.Get(types.SubscriptionsCountKey) - if value == nil { - return 0 - } - - k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &count) - return count -} - -func (k Keeper) SetSubscription(ctx sdk.Context, subscription types.Subscription) { - key := types.SubscriptionKey(subscription.ID) - value := k.cdc.MustMarshalBinaryLengthPrefixed(subscription) - - store := ctx.KVStore(k.subscriptionKey) - store.Set(key, value) -} - -func (k Keeper) GetSubscription(ctx sdk.Context, id hub.SubscriptionID) (subscription types.Subscription, found bool) { - store := ctx.KVStore(k.subscriptionKey) - - key := types.SubscriptionKey(id) - value := store.Get(key) - if value == nil { - return subscription, false - } - - k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &subscription) - return subscription, true -} - -func (k Keeper) SetSubscriptionsCountOfNode(ctx sdk.Context, id hub.NodeID, count uint64) { - key := types.SubscriptionsCountOfNodeKey(id) - value := k.cdc.MustMarshalBinaryLengthPrefixed(count) - - store := ctx.KVStore(k.subscriptionKey) - store.Set(key, value) -} - -func (k Keeper) GetSubscriptionsCountOfNode(ctx sdk.Context, id hub.NodeID) (count uint64) { - store := ctx.KVStore(k.subscriptionKey) - - key := types.SubscriptionsCountOfNodeKey(id) - value := store.Get(key) - if value == nil { - return 0 - } - - k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &count) - return count -} - -func (k Keeper) SetSubscriptionIDByNodeID(ctx sdk.Context, i hub.NodeID, j uint64, id hub.SubscriptionID) { - key := types.SubscriptionIDByNodeIDKey(i, j) - value := k.cdc.MustMarshalBinaryLengthPrefixed(id) - - store := ctx.KVStore(k.subscriptionKey) - store.Set(key, value) -} - -func (k Keeper) GetSubscriptionIDByNodeID(ctx sdk.Context, i hub.NodeID, j uint64) (id hub.SubscriptionID, found bool) { - store := ctx.KVStore(k.subscriptionKey) - - key := types.SubscriptionIDByNodeIDKey(i, j) - value := store.Get(key) - if value == nil { - return hub.NewSubscriptionID(0), false - } - - k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &id) - return id, true -} - -func (k Keeper) SetSubscriptionsCountOfAddress(ctx sdk.Context, address sdk.AccAddress, count uint64) { - key := types.SubscriptionsCountOfAddressKey(address) - value := k.cdc.MustMarshalBinaryLengthPrefixed(count) - - store := ctx.KVStore(k.subscriptionKey) - store.Set(key, value) -} - -func (k Keeper) GetSubscriptionsCountOfAddress(ctx sdk.Context, address sdk.AccAddress) (count uint64) { - store := ctx.KVStore(k.subscriptionKey) - - key := types.SubscriptionsCountOfAddressKey(address) - value := store.Get(key) - if value == nil { - return 0 - } - - k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &count) - return count -} - -func (k Keeper) SetSubscriptionIDByAddress(ctx sdk.Context, address sdk.AccAddress, i uint64, id hub.SubscriptionID) { - key := types.SubscriptionIDByAddressKey(address, i) - value := k.cdc.MustMarshalBinaryLengthPrefixed(id) - - store := ctx.KVStore(k.subscriptionKey) - store.Set(key, value) -} - -func (k Keeper) GetSubscriptionIDByAddress(ctx sdk.Context, - address sdk.AccAddress, i uint64) (id hub.SubscriptionID, found bool) { - store := ctx.KVStore(k.subscriptionKey) - - key := types.SubscriptionIDByAddressKey(address, i) - value := store.Get(key) - if value == nil { - return hub.NewSubscriptionID(0), false - } - - k.cdc.MustUnmarshalBinaryLengthPrefixed(value, &id) - return id, true -} - -func (k Keeper) GetSubscriptionsOfNode(ctx sdk.Context, id hub.NodeID) (subscriptions []types.Subscription) { - count := k.GetSubscriptionsCountOfNode(ctx, id) - - subscriptions = make([]types.Subscription, 0, count) - for i := uint64(0); i < count; i++ { - _id, _ := k.GetSubscriptionIDByNodeID(ctx, id, i) - - subscription, _ := k.GetSubscription(ctx, _id) - subscriptions = append(subscriptions, subscription) - } - - return subscriptions -} - -func (k Keeper) GetSubscriptionsOfAddress(ctx sdk.Context, - address sdk.AccAddress) (subscriptions []types.Subscription) { - count := k.GetSubscriptionsCountOfAddress(ctx, address) - - subscriptions = make([]types.Subscription, 0, count) - for i := uint64(0); i < count; i++ { - id, _ := k.GetSubscriptionIDByAddress(ctx, address, i) - - subscription, _ := k.GetSubscription(ctx, id) - subscriptions = append(subscriptions, subscription) - } - - return subscriptions -} - -func (k Keeper) GetAllSubscriptions(ctx sdk.Context) (subscriptions []types.Subscription) { - store := ctx.KVStore(k.subscriptionKey) - - iter := sdk.KVStorePrefixIterator(store, types.SubscriptionKeyPrefix) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - var subscription types.Subscription - k.cdc.MustUnmarshalBinaryLengthPrefixed(iter.Value(), &subscription) - subscriptions = append(subscriptions, subscription) - } - - return subscriptions -} - -func (k Keeper) IterateSubscriptions(ctx sdk.Context, - fn func(index int64, subscription types.Subscription) (stop bool)) { - store := ctx.KVStore(k.subscriptionKey) - - iterator := sdk.KVStorePrefixIterator(store, types.SubscriptionKeyPrefix) - defer iterator.Close() - - for i := int64(0); iterator.Valid(); iterator.Next() { - var subscription types.Subscription - k.cdc.MustUnmarshalBinaryLengthPrefixed(iterator.Value(), &subscription) - - if stop := fn(i, subscription); stop { - break - } - i++ - } -} diff --git a/x/vpn/keeper/subscription_test.go b/x/vpn/keeper/subscription_test.go deleted file mode 100644 index 49c418cb..00000000 --- a/x/vpn/keeper/subscription_test.go +++ /dev/null @@ -1,234 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/stretchr/testify/require" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func TestKeeper_SetSubscriptionsCount(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - count := k.GetSubscriptionsCount(ctx) - require.Equal(t, uint64(0), count) - - k.SetSubscriptionsCount(ctx, 1) - count = k.GetSubscriptionsCount(ctx) - require.Equal(t, uint64(1), count) - - k.SetSubscriptionsCount(ctx, 2) - count = k.GetSubscriptionsCount(ctx) - require.Equal(t, uint64(2), count) - - k.SetSubscriptionsCount(ctx, 3) - count = k.GetSubscriptionsCount(ctx) - require.Equal(t, uint64(3), count) -} - -func TestKeeper_GetSubscriptionsCount(t *testing.T) { - TestKeeper_SetSubscriptionsCount(t) -} - -func TestKeeper_SetSubscription(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - _, found := k.GetSubscription(ctx, hub.NewSubscriptionID(0)) - require.Equal(t, false, found) - - k.SetSubscription(ctx, types.TestSubscription) - result, found := k.GetSubscription(ctx, types.TestSubscription.ID) - require.Equal(t, true, found) - require.Equal(t, types.TestSubscription, result) -} - -func TestKeeper_GetSubscription(t *testing.T) { - TestKeeper_SetSubscription(t) -} - -func TestKeeper_SetSubscriptionsCountOfNode(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - count := k.GetSubscriptionsCountOfNode(ctx, hub.NewNodeID(0)) - require.Equal(t, uint64(0), count) - - k.SetSubscriptionsCountOfNode(ctx, hub.NewNodeID(0), 1) - count = k.GetSubscriptionsCountOfNode(ctx, hub.NewNodeID(0)) - require.Equal(t, uint64(1), count) - - k.SetSubscriptionsCountOfNode(ctx, hub.NewNodeID(0), 2) - count = k.GetSubscriptionsCountOfNode(ctx, hub.NewNodeID(0)) - require.Equal(t, uint64(2), count) - - k.SetSubscriptionsCountOfNode(ctx, hub.NewNodeID(0), 1) - count = k.GetSubscriptionsCountOfNode(ctx, hub.NewNodeID(0)) - require.Equal(t, uint64(1), count) -} - -func TestKeeper_GetSubscriptionsCountOfNode(t *testing.T) { - TestKeeper_SetSubscriptionsCountOfNode(t) -} - -func TestKeeper_SetSubscriptionIDByNodeID(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - _, found := k.GetSubscriptionIDByNodeID(ctx, hub.NewNodeID(0), 1) - require.Equal(t, false, found) - - k.SetSubscriptionIDByNodeID(ctx, hub.NewNodeID(0), 1, hub.NewSubscriptionID(0)) - id, found := k.GetSubscriptionIDByNodeID(ctx, hub.NewNodeID(0), 1) - require.Equal(t, true, found) - require.Equal(t, hub.NewSubscriptionID(0), id) - - k.SetSubscriptionIDByNodeID(ctx, hub.NewNodeID(0), 2, hub.NewSubscriptionID(1)) - id, found = k.GetSubscriptionIDByNodeID(ctx, hub.NewNodeID(0), 2) - require.Equal(t, true, found) - require.Equal(t, hub.NewSubscriptionID(1), id) - - k.SetSubscriptionIDByNodeID(ctx, hub.NewNodeID(1), 1, hub.NewSubscriptionID(0)) - id, found = k.GetSubscriptionIDByNodeID(ctx, hub.NewNodeID(1), 1) - require.Equal(t, true, found) - require.Equal(t, hub.NewSubscriptionID(0), id) - - k.SetSubscriptionIDByNodeID(ctx, hub.NewNodeID(1), 2, hub.NewSubscriptionID(1)) - id, found = k.GetSubscriptionIDByNodeID(ctx, hub.NewNodeID(1), 2) - require.Equal(t, true, found) - require.Equal(t, hub.NewSubscriptionID(1), id) -} - -func TestKeeper_GetSubscriptionIDByNodeID(t *testing.T) { - TestKeeper_SetSubscriptionIDByNodeID(t) -} - -func TestKeeper_SetSubscriptionsCountOfAddress(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - count := k.GetSubscriptionsCountOfAddress(ctx, types.TestAddress1) - require.Equal(t, uint64(0), count) - - k.SetSubscriptionsCountOfAddress(ctx, []byte(""), 1) - count = k.GetSubscriptionsCountOfAddress(ctx, []byte("")) - require.Equal(t, uint64(1), count) - - k.SetSubscriptionsCountOfAddress(ctx, types.TestAddress1, 1) - count = k.GetSubscriptionsCountOfAddress(ctx, types.TestAddress1) - require.Equal(t, uint64(1), count) - - k.SetSubscriptionsCountOfAddress(ctx, types.TestAddress1, 2) - count = k.GetSubscriptionsCountOfAddress(ctx, types.TestAddress1) - require.Equal(t, uint64(2), count) - - k.SetSubscriptionsCountOfAddress(ctx, types.TestAddress1, 1) - count = k.GetSubscriptionsCountOfAddress(ctx, types.TestAddress1) - require.Equal(t, uint64(1), count) - - k.SetSubscriptionsCountOfAddress(ctx, types.TestAddress2, 1) - count = k.GetSubscriptionsCountOfAddress(ctx, types.TestAddress2) - require.Equal(t, uint64(1), count) -} - -func TestKeeper_GetSubscriptionsCountOfAddress(t *testing.T) { - TestKeeper_SetSubscriptionsCountOfAddress(t) -} - -func TestKeeper_SetSubscriptionIDByAddress(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - _, found := k.GetSubscriptionIDByAddress(ctx, types.TestAddress1, 1) - require.Equal(t, false, found) - - k.SetSubscriptionIDByAddress(ctx, []byte(""), 1, hub.NewSubscriptionID(0)) - id, found := k.GetSubscriptionIDByAddress(ctx, []byte(""), 1) - require.Equal(t, true, found) - require.Equal(t, hub.NewSubscriptionID(0), id) - - k.SetSubscriptionIDByAddress(ctx, []byte(""), 2, hub.NewSubscriptionID(1)) - id, found = k.GetSubscriptionIDByAddress(ctx, []byte(""), 2) - require.Equal(t, true, found) - require.Equal(t, hub.NewSubscriptionID(1), id) - - k.SetSubscriptionIDByAddress(ctx, types.TestAddress1, 1, hub.NewSubscriptionID(0)) - id, found = k.GetSubscriptionIDByAddress(ctx, types.TestAddress1, 1) - require.Equal(t, true, found) - require.Equal(t, hub.NewSubscriptionID(0), id) - - k.SetSubscriptionIDByAddress(ctx, types.TestAddress1, 2, hub.NewSubscriptionID(1)) - id, found = k.GetSubscriptionIDByAddress(ctx, types.TestAddress1, 2) - require.Equal(t, true, found) - require.Equal(t, hub.NewSubscriptionID(1), id) - - k.SetSubscriptionIDByAddress(ctx, types.TestAddress2, 1, hub.NewSubscriptionID(0)) - id, found = k.GetSubscriptionIDByAddress(ctx, types.TestAddress2, 1) - require.Equal(t, true, found) - require.Equal(t, hub.NewSubscriptionID(0), id) - - k.SetSubscriptionIDByAddress(ctx, types.TestAddress2, 1, hub.NewSubscriptionID(1)) - id, found = k.GetSubscriptionIDByAddress(ctx, types.TestAddress1, 2) - require.Equal(t, true, found) - require.Equal(t, hub.NewSubscriptionID(1), id) -} - -func TestKeeper_GetSubscriptionIDByAddress(t *testing.T) { - TestKeeper_SetSubscriptionIDByAddress(t) -} - -func TestKeeper_GetSubscriptionsOfNode(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - subscriptions := k.GetSubscriptionsOfNode(ctx, hub.NewNodeID(0)) - require.Equal(t, []types.Subscription{}, subscriptions) - - k.SetSubscription(ctx, types.TestSubscription) - k.SetSubscriptionsCountOfNode(ctx, hub.NewNodeID(0), 1) - - subscriptions = k.GetSubscriptionsOfNode(ctx, hub.NewNodeID(0)) - require.Equal(t, []types.Subscription{types.TestSubscription}, subscriptions) - - k.SetSubscription(ctx, types.TestSubscription) - k.SetSubscriptionsCountOfNode(ctx, hub.NewNodeID(0), 2) - - subscriptions = k.GetSubscriptionsOfNode(ctx, hub.NewNodeID(0)) - require.Equal(t, append([]types.Subscription{types.TestSubscription}, types.TestSubscription), subscriptions) -} - -func TestKeeper_GetSubscriptionsOfAddress(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - subscriptions := k.GetSubscriptionsOfNode(ctx, hub.NewNodeID(0)) - require.Equal(t, []types.Subscription{}, subscriptions) - - k.SetSubscription(ctx, types.TestSubscription) - k.SetSubscriptionsCountOfNode(ctx, hub.NewNodeID(0), 1) - - subscriptions = k.GetSubscriptionsOfNode(ctx, hub.NewNodeID(0)) - require.Equal(t, []types.Subscription{types.TestSubscription}, subscriptions) - - k.SetSubscription(ctx, types.TestSubscription) - k.SetSubscriptionsCountOfNode(ctx, hub.NewNodeID(0), 2) - - subscriptions = k.GetSubscriptionsOfNode(ctx, hub.NewNodeID(0)) - require.Equal(t, append([]types.Subscription{types.TestSubscription}, types.TestSubscription), subscriptions) -} - -func TestKeeper_GetAllSubscriptions(t *testing.T) { - ctx, k, _, _ := CreateTestInput(t, false) - - subscriptions := k.GetAllSubscriptions(ctx) - require.Equal(t, []types.Subscription(nil), subscriptions) - - k.SetSubscription(ctx, types.TestSubscription) - subscriptions = k.GetAllSubscriptions(ctx) - require.Equal(t, []types.Subscription{types.TestSubscription}, subscriptions) - - subscription := types.TestSubscription - subscription.ID = hub.NewSubscriptionID(1) - k.SetSubscription(ctx, subscription) - subscriptions = k.GetAllSubscriptions(ctx) - require.Equal(t, append([]types.Subscription{types.TestSubscription}, subscription), subscriptions) - - k.SetSubscription(ctx, types.TestSubscription) - subscriptions = k.GetAllSubscriptions(ctx) - require.Equal(t, append([]types.Subscription{types.TestSubscription}, subscription), subscriptions) -} diff --git a/x/vpn/keeper/test_common.go b/x/vpn/keeper/test_common.go deleted file mode 100644 index 2b42512f..00000000 --- a/x/vpn/keeper/test_common.go +++ /dev/null @@ -1,98 +0,0 @@ -package keeper - -import ( - "math/rand" - "testing" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/supply" - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - db "github.com/tendermint/tm-db" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/deposit" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func CreateTestInput(t *testing.T, isCheckTx bool) (sdk.Context, Keeper, deposit.Keeper, bank.Keeper) { - keyParams := sdk.NewKVStoreKey(params.StoreKey) - keyAccount := sdk.NewKVStoreKey(auth.StoreKey) - keySupply := sdk.NewKVStoreKey(supply.StoreKey) - keyDeposit := sdk.NewKVStoreKey(deposit.StoreKey) - keyNode := sdk.NewKVStoreKey(types.StoreKeyNode) - keySubscription := sdk.NewKVStoreKey(types.StoreKeySubscription) - keySession := sdk.NewKVStoreKey(types.StoreKeySession) - tkeyParams := sdk.NewTransientStoreKey(params.TStoreKey) - - mdb := db.NewMemDB() - ms := store.NewCommitMultiStore(mdb) - ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, mdb) - ms.MountStoreWithDB(keyAccount, sdk.StoreTypeIAVL, mdb) - ms.MountStoreWithDB(keySupply, sdk.StoreTypeIAVL, mdb) - ms.MountStoreWithDB(keyDeposit, sdk.StoreTypeIAVL, mdb) - ms.MountStoreWithDB(keyNode, sdk.StoreTypeIAVL, mdb) - ms.MountStoreWithDB(keySubscription, sdk.StoreTypeIAVL, mdb) - ms.MountStoreWithDB(keySession, sdk.StoreTypeIAVL, mdb) - ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, mdb) - require.Nil(t, ms.LoadLatestVersion()) - - depositAccount := supply.NewEmptyModuleAccount(types.ModuleName) - blacklist := make(map[string]bool) - blacklist[depositAccount.String()] = true - accountPermissions := map[string][]string{ - deposit.ModuleName: nil, - } - - cdc := MakeTestCodec() - ctx := sdk.NewContext(ms, abci.Header{ChainID: "chain-id"}, isCheckTx, log.NewNopLogger()) - - pk := params.NewKeeper(cdc, keyParams, tkeyParams, params.DefaultCodespace) - ak := auth.NewAccountKeeper(cdc, keyAccount, pk.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount) - bk := bank.NewBaseKeeper(ak, pk.Subspace(bank.DefaultParamspace), bank.DefaultCodespace, blacklist) - sk := supply.NewKeeper(cdc, keySupply, ak, bk, accountPermissions) - dk := deposit.NewKeeper(cdc, keyDeposit, sk) - vk := NewKeeper(cdc, keyNode, keySubscription, keySession, pk.Subspace(DefaultParamspace), dk) - - sk.SetModuleAccount(ctx, depositAccount) - vk.SetParams(ctx, types.DefaultParams()) - - return ctx, vk, dk, bk -} - -func MakeTestCodec() *codec.Codec { - var cdc = codec.New() - codec.RegisterCrypto(cdc) - auth.RegisterCodec(cdc) - supply.RegisterCodec(cdc) - types.RegisterCodec(cdc) - hub.RegisterCodec(cdc) - return cdc -} - -func RandomNode(r *rand.Rand, ctx sdk.Context, keeper Keeper) types.Node { - nodes := keeper.GetAllNodes(ctx) - i := r.Intn(len(nodes)) - - return nodes[i] -} - -func RandomSubscription(r *rand.Rand, ctx sdk.Context, keeper Keeper) types.Subscription { - subscriptions := keeper.GetAllSubscriptions(ctx) - i := r.Intn(len(subscriptions)) - - return subscriptions[i] -} - -func RandomSession(r *rand.Rand, ctx sdk.Context, keeper Keeper) types.Session { - sessions := keeper.GetAllSessions(ctx) - i := r.Intn(len(sessions)) - - return sessions[i] -} diff --git a/x/vpn/querier/node_test.go b/x/vpn/querier/node_test.go deleted file mode 100644 index 18f077fe..00000000 --- a/x/vpn/querier/node_test.go +++ /dev/null @@ -1,155 +0,0 @@ -package querier - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/keeper" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func Test_queryNode(t *testing.T) { - ctx, k, _, _ := keeper.CreateTestInput(t, false) - cdc := keeper.MakeTestCodec() - - var err error - var node types.Node - - req := abci.RequestQuery{ - Path: fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryNode), - Data: []byte{}, - } - - res, _err := queryNode(ctx, req, k) - require.NotNil(t, _err) - require.Equal(t, []byte(nil), res) - require.Len(t, res, 0) - - k.SetNode(ctx, types.TestNode) - req.Data, err = cdc.MarshalJSON(types.NewQueryNodeParams(hub.NewNodeID(0))) - require.Nil(t, err) - - res, _err = queryNode(ctx, req, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - require.NotNil(t, res) - - err = cdc.UnmarshalJSON(res, &node) - require.Nil(t, err) - require.Equal(t, types.TestNode, node) - - a := hub.NewNodeID(1) - req.Data, err = cdc.MarshalJSON(types.NewQueryNodeParams(a)) - require.Nil(t, err) - - res, _err = queryNode(ctx, req, k) - require.Nil(t, res) - require.Equal(t, []byte(nil), res) - require.Len(t, res, 0) -} - -func Test_queryNodesOfAddress(t *testing.T) { - ctx, k, _, _ := keeper.CreateTestInput(t, false) - cdc := keeper.MakeTestCodec() - var err error - var nodes []types.Node - - req := abci.RequestQuery{ - Path: fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryNodesOfAddress), - Data: []byte{}, - } - - res, _err := queryNodesOfAddress(ctx, req, k) - require.NotNil(t, _err) - require.Equal(t, []byte(nil), res) - require.Len(t, res, 0) - - k.SetNode(ctx, types.TestNode) - k.SetNodesCountOfAddress(ctx, types.TestAddress1, 1) - k.SetNodeIDByAddress(ctx, types.TestAddress1, 0, hub.NewNodeID(0)) - - req.Data, err = cdc.MarshalJSON(types.NewQueryNodesOfAddressParams([]byte(""))) - require.Nil(t, err) - - res, _err = queryNodesOfAddress(ctx, req, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - require.NotNil(t, res) - - err = cdc.UnmarshalJSON(res, &nodes) - require.Nil(t, err) - require.NotEqual(t, []types.Node{types.TestNode}, nodes) - - k.SetNode(ctx, types.TestNode) - req.Data, err = cdc.MarshalJSON(types.NewQueryNodesOfAddressParams(types.TestAddress1)) - require.Nil(t, err) - - res, _err = queryNodesOfAddress(ctx, req, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - require.NotNil(t, res) - - err = cdc.UnmarshalJSON(res, &nodes) - require.Nil(t, err) - require.Equal(t, []types.Node{types.TestNode}, nodes) - - req.Data, err = cdc.MarshalJSON(types.NewQueryNodesOfAddressParams(types.TestAddress2)) - require.Nil(t, err) - - res, _err = queryNodesOfAddress(ctx, req, k) - require.NotNil(t, res) - require.NotEqual(t, []byte(nil), res) - - err = cdc.UnmarshalJSON(res, &nodes) - require.Nil(t, err) - require.NotEqual(t, []types.Node{types.TestNode}, nodes) -} - -func Test_queryAllNodes(t *testing.T) { - ctx, k, _, _ := keeper.CreateTestInput(t, false) - cdc := keeper.MakeTestCodec() - var err error - var nodes []types.Node - - res, _err := queryAllNodes(ctx, k) - require.Nil(t, _err) - require.Equal(t, []byte("null"), res) - - err = cdc.UnmarshalJSON(res, &nodes) - require.Nil(t, err) - require.NotEqual(t, []types.Node{types.TestNode}, nodes) - - err = cdc.UnmarshalJSON(res, &nodes) - require.Nil(t, err) - require.NotEqual(t, []types.Node{types.TestNode}, nodes) - - k.SetNode(ctx, types.TestNode) - require.Nil(t, err) - - res, _err = queryAllNodes(ctx, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - require.NotNil(t, res) - - err = cdc.UnmarshalJSON(res, &nodes) - require.Nil(t, err) - require.Equal(t, []types.Node{types.TestNode}, nodes) - - node := types.TestNode - node.ID = hub.NewNodeID(1) - k.SetNode(ctx, node) - require.Nil(t, err) - - res, _err = queryAllNodes(ctx, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - require.NotNil(t, res) - - err = cdc.UnmarshalJSON(res, &nodes) - require.Nil(t, err) - require.Equal(t, append([]types.Node{types.TestNode}, node), nodes) -} diff --git a/x/vpn/querier/querier.go b/x/vpn/querier/querier.go deleted file mode 100644 index 34e3cfa0..00000000 --- a/x/vpn/querier/querier.go +++ /dev/null @@ -1,42 +0,0 @@ -package querier - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/sentinel-official/hub/x/vpn/keeper" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func NewQuerier(k keeper.Keeper) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, sdk.Error) { - switch path[0] { - case types.QueryNode: - return queryNode(ctx, req, k) - case types.QueryNodesOfAddress: - return queryNodesOfAddress(ctx, req, k) - case types.QueryAllNodes: - return queryAllNodes(ctx, k) - case types.QuerySubscription: - return querySubscription(ctx, req, k) - case types.QuerySubscriptionsOfNode: - return querySubscriptionsOfNode(ctx, req, k) - case types.QuerySubscriptionsOfAddress: - return querySubscriptionsOfAddress(ctx, req, k) - case types.QueryAllSubscriptions: - return queryAllSubscriptions(ctx, k) - case types.QuerySessionsCountOfSubscription: - return querySessionsCountOfSubscription(ctx, req, k) - case types.QuerySession: - return querySession(ctx, req, k) - case types.QuerySessionOfSubscription: - return querySessionOfSubscription(ctx, req, k) - case types.QuerySessionsOfSubscription: - return querySessionsOfSubscription(ctx, req, k) - case types.QueryAllSessions: - return queryAllSessions(ctx, k) - default: - return nil, types.ErrorInvalidQueryType(path[0]) - } - } -} diff --git a/x/vpn/querier/session.go b/x/vpn/querier/session.go deleted file mode 100644 index 8a199e8a..00000000 --- a/x/vpn/querier/session.go +++ /dev/null @@ -1,79 +0,0 @@ -package querier - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/sentinel-official/hub/x/vpn/keeper" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func querySession(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { - var params types.QuerySessionParams - if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, types.ErrorUnmarshal() - } - - session, found := k.GetSession(ctx, params.ID) - if !found { - return nil, nil - } - - res, err := types.ModuleCdc.MarshalJSON(session) - if err != nil { - return nil, types.ErrorMarshal() - } - - return res, nil -} - -func querySessionOfSubscription(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { - var params types.QuerySessionOfSubscriptionPrams - if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, types.ErrorUnmarshal() - } - - id, found := k.GetSessionIDBySubscriptionID(ctx, params.ID, params.Index) - if !found { - return nil, nil - } - - session, found := k.GetSession(ctx, id) - if !found { - return nil, nil - } - - res, err := types.ModuleCdc.MarshalJSON(session) - if err != nil { - return nil, types.ErrorMarshal() - } - - return res, nil -} - -func querySessionsOfSubscription(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { - var params types.QuerySessionsOfSubscriptionPrams - if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, types.ErrorUnmarshal() - } - - sessions := k.GetSessionsOfSubscription(ctx, params.ID) - - res, err := types.ModuleCdc.MarshalJSON(sessions) - if err != nil { - return nil, types.ErrorMarshal() - } - - return res, nil -} - -func queryAllSessions(ctx sdk.Context, k keeper.Keeper) ([]byte, sdk.Error) { - sessions := k.GetAllSessions(ctx) - - res, err := types.ModuleCdc.MarshalJSON(sessions) - if err != nil { - return nil, types.ErrorMarshal() - } - - return res, nil -} diff --git a/x/vpn/querier/session_test.go b/x/vpn/querier/session_test.go deleted file mode 100644 index 3a94295b..00000000 --- a/x/vpn/querier/session_test.go +++ /dev/null @@ -1,199 +0,0 @@ -package querier - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/keeper" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func Test_querySession(t *testing.T) { - ctx, k, _, _ := keeper.CreateTestInput(t, false) - cdc := keeper.MakeTestCodec() - var err error - var session types.Session - - req := abci.RequestQuery{ - Path: fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySession), - Data: []byte{}, - } - - res, _err := querySession(ctx, req, k) - require.NotNil(t, _err) - require.Equal(t, []byte(nil), res) - require.Len(t, res, 0) - - k.SetSession(ctx, types.TestSession) - req.Data, err = cdc.MarshalJSON(types.NewQuerySessionParams(hub.NewSessionID(0))) - require.Nil(t, err) - - res, _err = querySession(ctx, req, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - require.NotNil(t, res) - - err = cdc.UnmarshalJSON(res, &session) - require.Nil(t, err) - require.Equal(t, types.TestSession, session) - - req.Data, err = cdc.MarshalJSON(types.NewQuerySessionParams(hub.NewSessionID(1))) - require.Nil(t, err) - - res, _err = querySession(ctx, req, k) - require.Nil(t, res) - require.Equal(t, []byte(nil), res) - require.Len(t, res, 0) -} - -func Test_querySessionOfSubscription(t *testing.T) { - ctx, k, _, _ := keeper.CreateTestInput(t, false) - cdc := keeper.MakeTestCodec() - var err error - var session types.Session - - req := abci.RequestQuery{ - Path: fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySessionOfSubscription), - Data: []byte{}, - } - - res, _err := querySessionOfSubscription(ctx, req, k) - require.NotNil(t, _err) - require.Equal(t, []byte(nil), res) - require.Len(t, res, 0) - - k.SetSubscription(ctx, types.TestSubscription) - k.SetSessionIDBySubscriptionID(ctx, types.TestSubscription.ID, 0, types.TestSession.ID) - k.SetSessionsCountOfSubscription(ctx, types.TestSubscription.ID, 1) - - req.Data, err = cdc.MarshalJSON(types.NewQuerySessionsOfSubscriptionPrams(hub.NewSubscriptionID(0))) - require.Nil(t, err) - - res, _err = querySessionOfSubscription(ctx, req, k) - require.Nil(t, err) - require.Equal(t, []byte(nil), res) - require.Nil(t, res) - - err = cdc.UnmarshalJSON(res, &session) - require.NotEqual(t, types.TestSession, session) - - k.SetSession(ctx, types.TestSession) - req.Data, err = cdc.MarshalJSON(types.NewQuerySessionsOfSubscriptionPrams(hub.NewSubscriptionID(0))) - require.Nil(t, err) - - res, _err = querySessionOfSubscription(ctx, req, k) - require.Nil(t, err) - require.NotEqual(t, []byte(nil), res) - require.NotNil(t, res) - - err = cdc.UnmarshalJSON(res, &session) - require.Nil(t, err) - require.Equal(t, types.TestSession, session) - - req.Data, err = cdc.MarshalJSON(types.NewQuerySessionsOfSubscriptionPrams(hub.NewSubscriptionID(1))) - require.Nil(t, err) - - res, _err = querySessionOfSubscription(ctx, req, k) - require.Nil(t, err) - require.Equal(t, []byte(nil), res) - require.Nil(t, res) - - err = cdc.UnmarshalJSON(res, &session) - require.NotNil(t, err) -} - -func Test_querySessionsOfSubscription(t *testing.T) { - ctx, k, _, _ := keeper.CreateTestInput(t, false) - cdc := keeper.MakeTestCodec() - var err error - var sessions []types.Session - - req := abci.RequestQuery{ - Path: fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySessionsOfSubscription), - Data: []byte{}, - } - - res, _err := querySessionsOfSubscription(ctx, req, k) - require.NotNil(t, _err) - require.Equal(t, []byte(nil), res) - require.Len(t, res, 0) - - k.SetSubscription(ctx, types.TestSubscription) - k.SetSession(ctx, types.TestSession) - k.SetSessionIDBySubscriptionID(ctx, types.TestSubscription.ID, 0, types.TestSession.ID) - k.SetSessionsCountOfSubscription(ctx, types.TestSubscription.ID, 1) - - req.Data, err = cdc.MarshalJSON(types.NewQuerySessionsOfSubscriptionPrams(hub.NewSubscriptionID(0))) - require.Nil(t, err) - - res, _err = querySessionsOfSubscription(ctx, req, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - - err = cdc.UnmarshalJSON(res, &sessions) - require.Nil(t, err) - require.Equal(t, []types.Session{types.TestSession}, sessions) - - session := types.TestSession - session.ID = hub.NewSessionID(1) - k.SetSession(ctx, session) - k.SetSessionIDBySubscriptionID(ctx, types.TestSubscription.ID, 0, session.ID) - k.SetSessionsCountOfSubscription(ctx, types.TestSubscription.ID, 2) - - res, _err = querySessionsOfSubscription(ctx, req, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - - err = cdc.UnmarshalJSON(res, &sessions) - require.Nil(t, err) - require.Len(t, sessions, 2) -} - -func Test_queryAllSessions(t *testing.T) { - ctx, k, _, _ := keeper.CreateTestInput(t, false) - cdc := keeper.MakeTestCodec() - var err error - var sessions []types.Session - - res, _err := queryAllSessions(ctx, k) - require.Nil(t, _err) - require.Equal(t, []byte("null"), res) - - err = cdc.UnmarshalJSON(res, &sessions) - require.Nil(t, err) - require.NotEqual(t, []types.Session{types.TestSession}, sessions) - - err = cdc.UnmarshalJSON(res, &sessions) - require.Nil(t, err) - require.NotEqual(t, []types.Session{types.TestSession}, sessions) - - k.SetSession(ctx, types.TestSession) - require.Nil(t, err) - - res, _err = queryAllSessions(ctx, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - require.NotNil(t, res) - - err = cdc.UnmarshalJSON(res, &sessions) - require.Nil(t, err) - require.Equal(t, []types.Session{types.TestSession}, sessions) - - session := types.TestSession - session.ID = hub.NewSessionID(1) - k.SetSession(ctx, session) - require.Nil(t, err) - - res, _err = queryAllSessions(ctx, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - require.NotNil(t, res) - - err = cdc.UnmarshalJSON(res, &sessions) - require.Nil(t, err) - require.Equal(t, append([]types.Session{types.TestSession}, session), sessions) -} diff --git a/x/vpn/querier/subscription.go b/x/vpn/querier/subscription.go deleted file mode 100644 index 8aacf277..00000000 --- a/x/vpn/querier/subscription.go +++ /dev/null @@ -1,87 +0,0 @@ -package querier - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/sentinel-official/hub/x/vpn/keeper" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func querySubscription(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { - var params types.QuerySubscriptionParams - if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, types.ErrorUnmarshal() - } - - subscription, found := k.GetSubscription(ctx, params.ID) - if !found { - return nil, nil - } - - res, err := types.ModuleCdc.MarshalJSON(subscription) - if err != nil { - return nil, types.ErrorMarshal() - } - - return res, nil -} - -func querySubscriptionsOfNode(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { - var params types.QuerySubscriptionsOfNodePrams - if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, types.ErrorUnmarshal() - } - - subscriptions := k.GetSubscriptionsOfNode(ctx, params.ID) - - res, err := types.ModuleCdc.MarshalJSON(subscriptions) - if err != nil { - return nil, types.ErrorMarshal() - } - - return res, nil -} - -func querySubscriptionsOfAddress(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { - var params types.QuerySubscriptionsOfAddressParams - if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, types.ErrorUnmarshal() - } - - subscriptions := k.GetSubscriptionsOfAddress(ctx, params.Address) - - res, err := types.ModuleCdc.MarshalJSON(subscriptions) - if err != nil { - return nil, types.ErrorMarshal() - } - - return res, nil -} - -func queryAllSubscriptions(ctx sdk.Context, k keeper.Keeper) ([]byte, sdk.Error) { - subscriptions := k.GetAllSubscriptions(ctx) - - res, err := types.ModuleCdc.MarshalJSON(subscriptions) - if err != nil { - return nil, types.ErrorMarshal() - } - - return res, nil -} - -func querySessionsCountOfSubscription(ctx sdk.Context, req abci.RequestQuery, k keeper.Keeper) ([]byte, sdk.Error) { - var params types.QuerySessionsCountOfSubscriptionParams - if err := types.ModuleCdc.UnmarshalJSON(req.Data, ¶ms); err != nil { - return nil, types.ErrorUnmarshal() - } - - count := k.GetSessionsCountOfSubscription(ctx, params.ID) - - res, err := types.ModuleCdc.MarshalJSON(count) - if err != nil { - return nil, types.ErrorMarshal() - } - - return res, nil -} diff --git a/x/vpn/querier/subscription_test.go b/x/vpn/querier/subscription_test.go deleted file mode 100644 index 67a6620f..00000000 --- a/x/vpn/querier/subscription_test.go +++ /dev/null @@ -1,259 +0,0 @@ -package querier - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/keeper" - "github.com/sentinel-official/hub/x/vpn/types" -) - -func Test_querySubscription(t *testing.T) { - ctx, k, _, _ := keeper.CreateTestInput(t, false) - cdc := keeper.MakeTestCodec() - var err error - var subscription types.Subscription - - req := abci.RequestQuery{ - Path: fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySubscription), - Data: []byte{}, - } - - res, _err := querySubscription(ctx, req, k) - require.NotNil(t, _err) - require.Equal(t, []byte(nil), res) - require.Len(t, res, 0) - - k.SetSubscription(ctx, types.TestSubscription) - req.Data, err = cdc.MarshalJSON(types.NewQuerySubscriptionParams(hub.NewSubscriptionID(0))) - require.Nil(t, err) - - res, _err = querySubscription(ctx, req, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - require.NotNil(t, res) - - err = cdc.UnmarshalJSON(res, &subscription) - require.Nil(t, err) - require.Equal(t, types.TestSubscription, subscription) - - req.Data, err = cdc.MarshalJSON(types.NewQuerySubscriptionParams(hub.NewSubscriptionID(1))) - require.Nil(t, err) - - res, _err = querySubscription(ctx, req, k) - require.Nil(t, res) - require.Equal(t, []byte(nil), res) - require.Len(t, res, 0) -} - -func Test_querySubscriptionsOfNode(t *testing.T) { - ctx, k, _, _ := keeper.CreateTestInput(t, false) - cdc := keeper.MakeTestCodec() - var err error - var subscriptions []types.Subscription - - req := abci.RequestQuery{ - Path: fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySubscriptionsOfNode), - Data: []byte{}, - } - - res, _err := querySubscriptionsOfNode(ctx, req, k) - require.NotNil(t, _err) - require.Equal(t, []byte(nil), res) - require.Len(t, res, 0) - - k.SetSubscription(ctx, types.TestSubscription) - k.SetSubscriptionsCountOfNode(ctx, types.TestNode.ID, 1) - k.SetSubscriptionIDByNodeID(ctx, types.TestNode.ID, 0, types.TestSubscription.ID) - - req.Data, err = cdc.MarshalJSON(types.NewQuerySubscriptionsOfNodePrams(hub.NewNodeID(0))) - require.Nil(t, err) - - res, _err = querySubscriptionsOfNode(ctx, req, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - - err = cdc.UnmarshalJSON(res, &subscriptions) - require.Nil(t, err) - require.Equal(t, []types.Subscription{types.TestSubscription}, subscriptions) - - req.Data, err = cdc.MarshalJSON(types.NewQuerySubscriptionsOfNodePrams(hub.NewNodeID(1))) - require.Nil(t, err) - - res, _err = querySubscriptionsOfNode(ctx, req, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - - err = cdc.UnmarshalJSON(res, &subscriptions) - require.Nil(t, err) - require.NotEqual(t, []types.Subscription{types.TestSubscription}, subscriptions) -} - -func Test_querySubscriptionsOfAddress(t *testing.T) { - ctx, k, _, _ := keeper.CreateTestInput(t, false) - cdc := keeper.MakeTestCodec() - var err error - var subscriptions []types.Subscription - - req := abci.RequestQuery{ - Path: fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySubscriptionsOfAddress), - Data: []byte{}, - } - - res, _err := querySubscriptionsOfAddress(ctx, req, k) - require.NotNil(t, _err) - require.Equal(t, []byte(nil), res) - require.Len(t, res, 0) - - k.SetSubscription(ctx, types.TestSubscription) - k.SetSubscriptionsCountOfAddress(ctx, types.TestAddress1, 1) - k.SetSubscriptionIDByAddress(ctx, types.TestAddress1, 0, types.TestSubscription.ID) - - req.Data, err = cdc.MarshalJSON(types.NewQuerySubscriptionsOfAddressParams([]byte(""))) - require.Nil(t, err) - - res, _err = querySubscriptionsOfAddress(ctx, req, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - - err = cdc.UnmarshalJSON(res, &subscriptions) - require.Nil(t, err) - require.NotEqual(t, []types.Subscription{types.TestSubscription}, subscriptions) - - req.Data, err = cdc.MarshalJSON(types.NewQuerySubscriptionsOfAddressParams(types.TestAddress1)) - require.Nil(t, err) - - res, _err = querySubscriptionsOfAddress(ctx, req, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - - err = cdc.UnmarshalJSON(res, &subscriptions) - require.Nil(t, err) - require.Equal(t, []types.Subscription{types.TestSubscription}, subscriptions) - - req.Data, err = cdc.MarshalJSON(types.NewQuerySubscriptionsOfAddressParams(types.TestAddress2)) - require.Nil(t, err) - - res, _err = querySubscriptionsOfAddress(ctx, req, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - - err = cdc.UnmarshalJSON(res, &subscriptions) - require.Nil(t, err) - require.NotEqual(t, []types.Subscription{types.TestSubscription}, subscriptions) -} - -func Test_queryAllSubscriptions(t *testing.T) { - ctx, k, _, _ := keeper.CreateTestInput(t, false) - cdc := keeper.MakeTestCodec() - var err error - var subscriptions []types.Subscription - - res, _err := queryAllSubscriptions(ctx, k) - require.Nil(t, _err) - require.Equal(t, []byte("null"), res) - - err = cdc.UnmarshalJSON(res, &subscriptions) - require.Nil(t, err) - require.NotEqual(t, []types.Subscription{types.TestSubscription}, subscriptions) - - err = cdc.UnmarshalJSON(res, &subscriptions) - require.Nil(t, err) - require.NotEqual(t, []types.Subscription{types.TestSubscription}, subscriptions) - - k.SetSubscription(ctx, types.TestSubscription) - require.Nil(t, err) - - res, _err = queryAllSubscriptions(ctx, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - require.NotNil(t, res) - - err = cdc.UnmarshalJSON(res, &subscriptions) - require.Nil(t, err) - require.Equal(t, []types.Subscription{types.TestSubscription}, subscriptions) - - subscription := types.TestSubscription - subscription.ID = hub.NewSubscriptionID(1) - k.SetSubscription(ctx, subscription) - require.Nil(t, err) - - res, _err = queryAllSubscriptions(ctx, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - require.NotNil(t, res) - - err = cdc.UnmarshalJSON(res, &subscriptions) - require.Nil(t, err) - require.Equal(t, append([]types.Subscription{types.TestSubscription}, subscription), subscriptions) -} - -func Test_querySessionsCountOfSubscription(t *testing.T) { - ctx, k, _, _ := keeper.CreateTestInput(t, false) - cdc := keeper.MakeTestCodec() - var err error - var count uint64 - - req := abci.RequestQuery{ - Path: fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QuerySessionsCountOfSubscription), - Data: []byte{}, - } - - res, _err := querySessionsCountOfSubscription(ctx, req, k) - require.NotNil(t, _err) - require.Equal(t, []byte(nil), res) - require.Len(t, res, 0) - - k.SetSessionsCountOfSubscription(ctx, hub.NewSubscriptionID(0), 1) - req.Data, err = cdc.MarshalJSON(types.NewQuerySessionsCountOfSubscriptionParams(hub.NewSubscriptionID(0))) - require.Nil(t, err) - - res, _err = querySessionsCountOfSubscription(ctx, req, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - - err = cdc.UnmarshalJSON(res, &count) - require.Nil(t, err) - - require.Equal(t, uint64(1), count) - - k.SetSessionsCountOfSubscription(ctx, hub.NewSubscriptionID(0), 2) - req.Data, err = cdc.MarshalJSON(types.NewQuerySessionsCountOfSubscriptionParams(hub.NewSubscriptionID(0))) - require.Nil(t, err) - - res, _err = querySessionsCountOfSubscription(ctx, req, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - - err = cdc.UnmarshalJSON(res, &count) - require.Nil(t, err) - require.Equal(t, uint64(2), count) - - k.SetSessionsCountOfSubscription(ctx, hub.NewSubscriptionID(1), 1) - req.Data, err = cdc.MarshalJSON(types.NewQuerySessionsCountOfSubscriptionParams(hub.NewSubscriptionID(1))) - require.Nil(t, err) - - res, _err = querySessionsCountOfSubscription(ctx, req, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - - err = cdc.UnmarshalJSON(res, &count) - require.Nil(t, err) - require.Equal(t, uint64(1), count) - - k.SetSessionsCountOfSubscription(ctx, hub.NewSubscriptionID(1), 2) - req.Data, err = cdc.MarshalJSON(types.NewQuerySessionsCountOfSubscriptionParams(hub.NewSubscriptionID(1))) - require.Nil(t, err) - - res, _err = querySessionsCountOfSubscription(ctx, req, k) - require.Nil(t, _err) - require.NotEqual(t, []byte(nil), res) - - err = cdc.UnmarshalJSON(res, &count) - require.Nil(t, err) - require.Equal(t, uint64(2), count) -} diff --git a/x/vpn/simulation/msgs.go b/x/vpn/simulation/msgs.go deleted file mode 100644 index 4d4dbe77..00000000 --- a/x/vpn/simulation/msgs.go +++ /dev/null @@ -1,195 +0,0 @@ -package simulation - -import ( - "fmt" - "math/rand" - - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/simulation" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn" -) - -func SimulateMsgRegisterNode(keeper vpn.Keeper) simulation.Operation { - handler := vpn.NewHandler(keeper) - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simulation.Account) ( - simulation.OperationMsg, []simulation.FutureOperation, error) { - randomAcc := simulation.RandomAcc(r, accounts) - - msg := vpn.NewMsgRegisterNode(randomAcc.Address, - getRandomType(r), getRandomVersion(r), getRandomMoniker(r), - getRandomCoins(r), getRandomBandwidth(r), getRandomEncryption(r)) - - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(vpn.ModuleName), nil, - fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) - } - - ok := handler(ctx, *msg).IsOK() - return simulation.NewOperationMsg(msg, ok, ""), nil, nil - } -} - -func SimulateMsgUpdateNodeInfo(keeper vpn.Keeper) simulation.Operation { - handler := vpn.NewHandler(keeper) - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simulation.Account) ( - simulation.OperationMsg, []simulation.FutureOperation, error) { - if len(keeper.GetAllNodes(ctx)) == 0 { - return simulation.NoOpMsg(vpn.ModuleName), nil, nil - } - - node := vpn.RandomNode(r, ctx, keeper) - msg := vpn.NewMsgUpdateNodeInfo(node.Owner, node.ID, - getRandomType(r), getRandomVersion(r), getRandomMoniker(r), - getRandomCoins(r), getRandomBandwidth(r), getRandomEncryption(r)) - - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(vpn.ModuleName), nil, - fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) - } - - ok := handler(ctx, *msg).IsOK() - return simulation.NewOperationMsg(msg, ok, ""), nil, nil - } -} - -func SimulateMsgDeregisterNode(keeper vpn.Keeper) simulation.Operation { - handler := vpn.NewHandler(keeper) - - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simulation.Account) ( - simulation.OperationMsg, []simulation.FutureOperation, error) { - if len(keeper.GetAllNodes(ctx)) == 0 { - return simulation.NoOpMsg(vpn.ModuleName), nil, nil - } - - node := vpn.RandomNode(r, ctx, keeper) - msg := vpn.NewMsgDeregisterNode(node.Owner, node.ID) - - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(vpn.ModuleName), nil, - fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) - } - - ok := handler(ctx, *msg).IsOK() - return simulation.NewOperationMsg(msg, ok, ""), nil, nil - } -} - -func SimulateMsgStartSubscription(keeper vpn.Keeper) simulation.Operation { - handler := vpn.NewHandler(keeper) - - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simulation.Account) ( - simulation.OperationMsg, []simulation.FutureOperation, error) { - if len(keeper.GetAllNodes(ctx)) == 0 { - return simulation.NoOpMsg(vpn.ModuleName), nil, nil - } - - node := vpn.RandomNode(r, ctx, keeper) - node.Status = vpn.StatusRegistered - keeper.SetNode(ctx, node) - - randomAcc := simulation.RandomAcc(r, accounts) - msg := vpn.NewMsgStartSubscription(randomAcc.Address, node.ID, getRandomCoin(r)) - - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(vpn.ModuleName), nil, - fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) - } - - ok := handler(ctx, *msg).IsOK() - return simulation.NewOperationMsg(msg, ok, ""), nil, nil - } -} - -func SimulateMsgEndSubscription(keeper vpn.Keeper) simulation.Operation { - handler := vpn.NewHandler(keeper) - - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simulation.Account) ( - simulation.OperationMsg, []simulation.FutureOperation, error) { - if len(keeper.GetAllSubscriptions(ctx)) == 0 { - return simulation.NoOpMsg(vpn.ModuleName), nil, nil - } - - subscription := vpn.RandomSubscription(r, ctx, keeper) - msg := vpn.NewMsgEndSubscription(subscription.Client, subscription.ID) - - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(vpn.ModuleName), nil, - fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) - } - - ok := handler(ctx, *msg).IsOK() - return simulation.NewOperationMsg(msg, ok, ""), nil, nil - } -} - -func SimulateMsgUpdateSessionInfo(keeper vpn.Keeper) simulation.Operation { - handler := vpn.NewHandler(keeper) - - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simulation.Account) ( - simulation.OperationMsg, []simulation.FutureOperation, error) { - if len(keeper.GetAllSessions(ctx)) == 0 { - return simulation.NoOpMsg(vpn.ModuleName), nil, nil - } - - clientAccount := simulation.RandomAcc(r, accounts) - nodeOwnerAccount := simulation.RandomAcc(r, accounts) - - session := vpn.RandomSession(r, ctx, keeper) - subscription, _ := keeper.GetSubscription(ctx, session.SubscriptionID) - - subscription.Status = vpn.StatusActive - subscription.Client = clientAccount.Address - keeper.SetSubscription(ctx, subscription) - - scs := keeper.GetSessionsCountOfSubscription(ctx, subscription.ID) - node, _ := keeper.GetNode(ctx, subscription.NodeID) - node.Owner = nodeOwnerAccount.Address - keeper.SetNode(ctx, node) - - bandwidth := getRandomBandwidth(r) - - bandWidthSignData := hub.NewBandwidthSignatureData(subscription.ID, scs, bandwidth) - clientAccountSignedData, _ := clientAccount.PrivKey.Sign(bandWidthSignData.Bytes()) - nodeOwnerAccountSignedData, _ := nodeOwnerAccount.PrivKey.Sign(bandWidthSignData.Bytes()) - - clienStdSig := auth.StdSignature{ - PubKey: clientAccount.PubKey, - Signature: clientAccountSignedData, - } - nodeOwnerStdSig := auth.StdSignature{ - PubKey: nodeOwnerAccount.PubKey, - Signature: nodeOwnerAccountSignedData, - } - - msg := vpn.NewMsgUpdateSessionInfo(clientAccount.Address, session.SubscriptionID, - bandwidth, nodeOwnerStdSig, clienStdSig) - - if msg.ValidateBasic() != nil { - return simulation.NoOpMsg(vpn.ModuleName), nil, - fmt.Errorf("expected msg to pass ValidateBasic: %s", msg.GetSignBytes()) - } - - ok := handler(ctx, *msg).IsOK() - return simulation.NewOperationMsg(msg, ok, ""), nil, nil - } -} - -func SimulateEndBlock(keeper vpn.Keeper) simulation.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simulation.Account) ( - simulation.OperationMsg, []simulation.FutureOperation, error) { - if len(keeper.GetAllNodes(ctx)) == 0 { - return simulation.NoOpMsg(vpn.ModuleName), nil, nil - } - - if len(keeper.GetAllSessions(ctx)) == 0 { - return simulation.NoOpMsg(vpn.ModuleName), nil, nil - } - - vpn.EndBlock(ctx, keeper) - return simulation.NewOperationMsgBasic(vpn.ModuleName, "end_block", "", true, nil), nil, nil - } -} diff --git a/x/vpn/simulation/params.go b/x/vpn/simulation/params.go deleted file mode 100644 index d38af4d6..00000000 --- a/x/vpn/simulation/params.go +++ /dev/null @@ -1,7 +0,0 @@ -package simulation - -const ( - FreeNodesCount = "free_node_count" - Deposit = "deposit" - SessionInactiveInterval = "session_inactive_interval" -) diff --git a/x/vpn/simulation/util.go b/x/vpn/simulation/util.go deleted file mode 100644 index 4bd1ac0b..00000000 --- a/x/vpn/simulation/util.go +++ /dev/null @@ -1,130 +0,0 @@ -package simulation - -import ( - "math/rand" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/simulation" - - hub "github.com/sentinel-official/hub/types" - "github.com/sentinel-official/hub/x/vpn/types" -) - -var ( - denoms = []string{"stake", "xxx", "yyy", "zzz"} - statuses = []string{types.StatusRegistered, types.StatusDeRegistered} -) - -func getRandomDenom(r *rand.Rand) string { - index := r.Intn(len(denoms)) - return denoms[index] -} - -func getRandomStatus(r *rand.Rand) string { - index := r.Intn(len(statuses)) - return statuses[index] -} - -func getRandomNodeID(r *rand.Rand) hub.NodeID { - i := uint64(r.Int63n(10)) - - return hub.NewNodeID(i) -} -func getRandomSessionID(r *rand.Rand) hub.SessionID { - i := uint64(r.Int63n(10)) - - return hub.NewSessionID(i) -} -func getRandomSubscriptionID(r *rand.Rand) hub.SubscriptionID { - i := uint64(r.Int63n(10)) - - return hub.NewSubscriptionID(i) -} - -func getRandomEncryption(r *rand.Rand) string { - return simulation.RandStringOfLength(r, 10) -} - -func getRandomType(r *rand.Rand) string { - return simulation.RandStringOfLength(r, 10) -} - -func getRandomVersion(r *rand.Rand) string { - return simulation.RandStringOfLength(r, 10) -} - -func getRandomMoniker(r *rand.Rand) string { - return simulation.RandStringOfLength(r, 10) -} - -func getRandomCoin(r *rand.Rand) sdk.Coin { - denom := getRandomDenom(r) - amount := simulation.RandIntBetween(r, 1, 1000) - - return sdk.NewCoin(denom, sdk.NewInt(int64(amount))) -} - -func getRandomCoins(r *rand.Rand) (coins sdk.Coins) { - coins = append(coins, getRandomCoin(r)) - - size := r.Intn(2) - for i := 0; i < size; i++ { - coin := getRandomCoin(r) - if coins == nil || coins.AmountOf(coin.Denom).IsZero() { - coins = append(coins, coin) - } - } - - return coins.Sort() -} - -func getRandomBandwidth(r *rand.Rand) hub.Bandwidth { - upload := r.Int63n(hub.GB.Int64()) - download := r.Int63n(hub.GB.Int64()) - - return hub.NewBandwidthFromInt64(upload, download) -} - -func GenerateRandomNode(r *rand.Rand) types.Node { - node := types.Node{ - ID: getRandomNodeID(r), - Owner: nil, - Deposit: getRandomCoin(r), - Type: getRandomType(r), - Version: getRandomVersion(r), - Moniker: getRandomMoniker(r), - PricesPerGB: getRandomCoins(r), - InternetSpeed: getRandomBandwidth(r), - Encryption: getRandomEncryption(r), - Status: getRandomStatus(r), - StatusModifiedAt: 0, - } - return node -} - -func GenerateRandomSubscription(r *rand.Rand, node types.Node) types.Subscription { - subscription := types.Subscription{ - ID: getRandomSubscriptionID(r), - NodeID: node.ID, - Client: nil, - PricePerGB: getRandomCoin(r), - TotalDeposit: getRandomCoin(r), - RemainingDeposit: getRandomCoin(r), - RemainingBandwidth: getRandomBandwidth(r), - Status: getRandomStatus(r), - StatusModifiedAt: 0, - } - - return subscription -} - -func GenerateRandomSession(r *rand.Rand, id hub.SubscriptionID) types.Session { - session := types.Session{ - ID: getRandomSessionID(r), - SubscriptionID: id, - Bandwidth: getRandomBandwidth(r), - Status: getRandomStatus(r), - StatusModifiedAt: 0, - } - return session -} diff --git a/x/vpn/types/codec.go b/x/vpn/types/codec.go deleted file mode 100644 index 400f30ee..00000000 --- a/x/vpn/types/codec.go +++ /dev/null @@ -1,25 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" -) - -var ( - ModuleCdc *codec.Codec -) - -func RegisterCodec(cdc *codec.Codec) { - cdc.RegisterConcrete(MsgRegisterNode{}, "x/vpn/MsgRegisterNode", nil) - cdc.RegisterConcrete(MsgUpdateNodeInfo{}, "x/vpn/MsgUpdateNodeInfo", nil) - cdc.RegisterConcrete(MsgDeregisterNode{}, "x/vpn/MsgDeregisterNode", nil) - cdc.RegisterConcrete(MsgStartSubscription{}, "x/vpn/MsgStartSubscription", nil) - cdc.RegisterConcrete(MsgEndSubscription{}, "x/vpn/MsgEndSubscription", nil) - cdc.RegisterConcrete(MsgUpdateSessionInfo{}, "x/vpn/MsgUpdateSessionInfo", nil) -} - -func init() { - ModuleCdc = codec.New() - RegisterCodec(ModuleCdc) - codec.RegisterCrypto(ModuleCdc) - ModuleCdc.Seal() -} diff --git a/x/vpn/types/errors.go b/x/vpn/types/errors.go deleted file mode 100644 index 73f6daf1..00000000 --- a/x/vpn/types/errors.go +++ /dev/null @@ -1,105 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - hub "github.com/sentinel-official/hub/types" -) - -const ( - Codespace = sdk.CodespaceType("vpn") - - errCodeUnknownMsgType = 101 - errCodeUnknownQueryType = 102 - errCodeInvalidField = 103 - errCodeUnauthorized = 104 - errCodeNodeDoesNotExist = 105 - errCodeInvalidNodeStatus = 106 - errCodeInvalidDeposit = 107 - errCodeSubscriptionDoesNotExist = 108 - errCodeSubscriptionAlreadyExists = 109 - errCodeInvalidSubscriptionStatus = 110 - errCodeInvalidBandwidth = 111 - errCodeInvalidBandwidthSignature = 112 - errCodeSessionAlreadyExists = 113 - errCodeInvalidSessionStatus = 114 - - errMsgUnknownMsgType = "Unknown message type: " - errMsgUnknownQueryType = "Invalid query type: " - errMsgInvalidField = "Invalid field: " - errMsgUnauthorized = "Unauthorized" - errMsgNodeDoesNotExist = "Node does not exist" - errMsgInvalidNodeStatus = "Invalid node status" - errMsgInvalidDeposit = "Invalid deposit" - errMsgSubscriptionDoesNotExist = "Subscription does not exist" - errMsgSubscriptionAlreadyExists = "Subscription already exists" - errMsgInvalidSubscriptionStatus = "Invalid subscription status" - errMsgInvalidBandwidth = "Invalid bandwidth" - errMsgInvalidBandwidthSignature = "Invalid bandwidth signature" - errMsgSessionAlreadyExists = "Session is active" - errMsgInvalidSessionStatus = "Invalid session status" -) - -func ErrorMarshal() sdk.Error { - return sdk.NewError(Codespace, hub.ErrCodeMarshal, hub.ErrMsgMarshal) -} - -func ErrorUnmarshal() sdk.Error { - return sdk.NewError(Codespace, hub.ErrCodeUnmarshal, hub.ErrMsgUnmarshal) -} - -func ErrorUnknownMsgType(msgType string) sdk.Error { - return sdk.NewError(Codespace, errCodeUnknownMsgType, errMsgUnknownMsgType+msgType) -} - -func ErrorInvalidQueryType(queryType string) sdk.Error { - return sdk.NewError(Codespace, errCodeUnknownQueryType, errMsgUnknownQueryType+queryType) -} - -func ErrorInvalidField(field string) sdk.Error { - return sdk.NewError(Codespace, errCodeInvalidField, errMsgInvalidField+field) -} - -func ErrorUnauthorized() sdk.Error { - return sdk.NewError(Codespace, errCodeUnauthorized, errMsgUnauthorized) -} - -func ErrorNodeDoesNotExist() sdk.Error { - return sdk.NewError(Codespace, errCodeNodeDoesNotExist, errMsgNodeDoesNotExist) -} - -func ErrorInvalidNodeStatus() sdk.Error { - return sdk.NewError(Codespace, errCodeInvalidNodeStatus, errMsgInvalidNodeStatus) -} - -func ErrorInvalidDeposit() sdk.Error { - return sdk.NewError(Codespace, errCodeInvalidDeposit, errMsgInvalidDeposit) -} - -func ErrorSubscriptionDoesNotExist() sdk.Error { - return sdk.NewError(Codespace, errCodeSubscriptionDoesNotExist, errMsgSubscriptionDoesNotExist) -} - -func ErrorSubscriptionAlreadyExists() sdk.Error { - return sdk.NewError(Codespace, errCodeSubscriptionAlreadyExists, errMsgSubscriptionAlreadyExists) -} - -func ErrorInvalidSubscriptionStatus() sdk.Error { - return sdk.NewError(Codespace, errCodeInvalidSubscriptionStatus, errMsgInvalidSubscriptionStatus) -} - -func ErrorInvalidBandwidth() sdk.Error { - return sdk.NewError(Codespace, errCodeInvalidBandwidth, errMsgInvalidBandwidth) -} - -func ErrorInvalidBandwidthSignature() sdk.Error { - return sdk.NewError(Codespace, errCodeInvalidBandwidthSignature, errMsgInvalidBandwidthSignature) -} - -func ErrorSessionAlreadyExists() sdk.Error { - return sdk.NewError(Codespace, errCodeSessionAlreadyExists, errMsgSessionAlreadyExists) -} - -func ErrorInvalidSessionStatus() sdk.Error { - return sdk.NewError(Codespace, errCodeInvalidSessionStatus, errMsgInvalidSessionStatus) -} diff --git a/x/vpn/types/genesis.go b/x/vpn/types/genesis.go deleted file mode 100644 index f8d44661..00000000 --- a/x/vpn/types/genesis.go +++ /dev/null @@ -1,23 +0,0 @@ -package types - -type GenesisState struct { - Nodes []Node `json:"nodes"` - Subscriptions []Subscription `json:"subscriptions"` - Sessions []Session `json:"sessions"` - Params Params `json:"params"` -} - -func NewGenesisState(nodes []Node, subscriptions []Subscription, sessions []Session, params Params) GenesisState { - return GenesisState{ - Nodes: nodes, - Subscriptions: subscriptions, - Sessions: sessions, - Params: params, - } -} - -func DefaultGenesisState() GenesisState { - return GenesisState{ - Params: DefaultParams(), - } -} diff --git a/x/vpn/types/keys.go b/x/vpn/types/keys.go deleted file mode 100644 index 992013ef..00000000 --- a/x/vpn/types/keys.go +++ /dev/null @@ -1,98 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - hub "github.com/sentinel-official/hub/types" -) - -const ( - ModuleName = "vpn" - QuerierRoute = ModuleName - RouterKey = ModuleName - - StoreKeySession = "vpn_session" - StoreKeyNode = "vpn_node" - StoreKeySubscription = "vpn_subscription" - - StatusRegistered = "REGISTERED" - StatusDeRegistered = "DE-REGISTERED" - - StatusActive = "ACTIVE" - StatusInactive = "INACTIVE" -) - -var ( - NodesCountKey = []byte{0x00} - NodeKeyPrefix = []byte{0x01} - NodesCountOfAddressKeyPrefix = []byte{0x02} - NodeIDByAddressKeyPrefix = []byte{0x03} - - SubscriptionsCountKey = []byte{0x00} - SubscriptionKeyPrefix = []byte{0x01} - SubscriptionsCountOfNodeKeyPrefix = []byte{0x02} - SubscriptionIDByNodeIDKeyPrefix = []byte{0x03} - SubscriptionsCountOfAddressKeyPrefix = []byte{0x04} - SubscriptionIDByAddressKeyPrefix = []byte{0x05} - - SessionsCountKey = []byte{0x00} - SessionKeyPrefix = []byte{0x01} - SessionsCountOfSubscriptionKeyPrefix = []byte{0x02} - SessionIDBySubscriptionIDKeyPrefix = []byte{0x03} -) - -func NodeKey(id hub.NodeID) []byte { - return append(NodeKeyPrefix, id.Bytes()...) -} - -func NodesCountOfAddressKey(address sdk.AccAddress) []byte { - return append(NodesCountOfAddressKeyPrefix, address.Bytes()...) -} - -func NodeIDByAddressKey(address sdk.AccAddress, i uint64) []byte { - return append(NodeIDByAddressKeyPrefix, - append(address.Bytes(), sdk.Uint64ToBigEndian(i)...)...) -} - -func SubscriptionKey(id hub.SubscriptionID) []byte { - return append(SubscriptionKeyPrefix, id.Bytes()...) -} - -func SubscriptionsCountOfNodeKey(id hub.NodeID) []byte { - return append(SubscriptionsCountOfNodeKeyPrefix, id.Bytes()...) -} - -func SubscriptionIDByNodeIDKey(id hub.NodeID, i uint64) []byte { - return append(SubscriptionIDByNodeIDKeyPrefix, - append(id.Bytes(), sdk.Uint64ToBigEndian(i)...)...) -} - -func SubscriptionsCountOfAddressKey(address sdk.AccAddress) []byte { - return append(SubscriptionsCountOfAddressKeyPrefix, address.Bytes()...) -} - -func SubscriptionIDByAddressKey(address sdk.AccAddress, i uint64) []byte { - return append(SubscriptionIDByAddressKeyPrefix, - append(address.Bytes(), sdk.Uint64ToBigEndian(i)...)...) -} - -func SessionKey(id hub.SessionID) []byte { - return append(SessionKeyPrefix, id.Bytes()...) -} - -func SessionsCountOfSubscriptionKey(id hub.SubscriptionID) []byte { - return append(SessionsCountOfSubscriptionKeyPrefix, id.Bytes()...) -} - -func SessionIDBySubscriptionIDKey(id hub.SubscriptionID, i uint64) []byte { - return append(SessionIDBySubscriptionIDKeyPrefix, - append(id.Bytes(), sdk.Uint64ToBigEndian(i)...)...) -} - -func ActiveNodeIDsKey(height int64) []byte { - return sdk.Uint64ToBigEndian(uint64(height)) -} - -func ActiveSessionIDsKey(height int64) []byte { - return sdk.Uint64ToBigEndian(uint64(height)) -} diff --git a/x/vpn/types/node.go b/x/vpn/types/node.go deleted file mode 100644 index 14ecf5f5..00000000 --- a/x/vpn/types/node.go +++ /dev/null @@ -1,126 +0,0 @@ -package types - -import ( - "fmt" - "sort" - - sdk "github.com/cosmos/cosmos-sdk/types" - - hub "github.com/sentinel-official/hub/types" -) - -type Node struct { - ID hub.NodeID `json:"id"` - Owner sdk.AccAddress `json:"owner"` - Deposit sdk.Coin `json:"deposit"` - - Type string `json:"type"` - Version string `json:"version"` - Moniker string `json:"moniker"` - PricesPerGB sdk.Coins `json:"prices_per_gb"` - InternetSpeed hub.Bandwidth `json:"internet_speed"` - Encryption string `json:"encryption"` - - Status string `json:"status"` - StatusModifiedAt int64 `json:"status_modified_at"` -} - -func (n Node) String() string { - return fmt.Sprintf(`Node - ID: %s - Owner Address: %s - Deposit: %s - Type: %s - Version: %s - Moniker: %s - Price Per GB: %s - Internet Speed: %s - Encryption: %s - Status: %s - Status Modified At: %d`, n.ID, n.Owner, n.Deposit, n.Type, n.Version, - n.Moniker, n.PricesPerGB, n.InternetSpeed, n.Encryption, - n.Status, n.StatusModifiedAt) -} - -func (n Node) UpdateInfo(_node Node) Node { - if _node.Type != "" { - n.Type = _node.Type - } - if _node.Version != "" { - n.Version = _node.Version - } - if _node.Moniker != "" { - n.Moniker = _node.Moniker - } - if _node.PricesPerGB != nil && - _node.PricesPerGB.Len() > 0 && _node.PricesPerGB.IsValid() { - n.PricesPerGB = _node.PricesPerGB - } - if !_node.InternetSpeed.AnyNil() && _node.InternetSpeed.AllPositive() { - n.InternetSpeed = _node.InternetSpeed - } - if _node.Encryption != "" { - n.Encryption = _node.Encryption - } - - return n -} - -func (n Node) FindPricePerGB(denom string) (coin sdk.Coin) { - index := sort.Search(n.PricesPerGB.Len(), func(i int) bool { - return n.PricesPerGB[i].Denom >= denom - }) - - if index == n.PricesPerGB.Len() || - (index < n.PricesPerGB.Len() && n.PricesPerGB[index].Denom != denom) { - return coin - } - - return n.PricesPerGB[index] -} - -func (n Node) DepositToBandwidth(deposit sdk.Coin) (bandwidth hub.Bandwidth, err sdk.Error) { - pricePerGB := n.FindPricePerGB(deposit.Denom) - if pricePerGB.Denom == "" || pricePerGB.Amount.IsZero() { - return bandwidth, ErrorInvalidDeposit() - } - - x := deposit.Amount.Mul(hub.MB500).Quo(pricePerGB.Amount) - return hub.NewBandwidth(x, x), nil -} - -func (n Node) IsValid() error { - if n.Owner == nil || n.Owner.Empty() { - return fmt.Errorf("invalid owner") - } - if n.Deposit.Denom == "" { - return fmt.Errorf("invalid deposit") - } - if n.Type == "" || len(n.Type) < 4 || len(n.Type) > 16 { - return fmt.Errorf("invalid type") - } - - if n.Version == "" || len(n.Version) < 4 || len(n.Version) > 16 { - return fmt.Errorf("invalid version") - } - if n.Moniker == "" || len(n.Moniker) < 4 || len(n.Moniker) > 32 { - return fmt.Errorf("invalid moniker") - } - if n.PricesPerGB == nil || !n.PricesPerGB.IsValid() { - return fmt.Errorf("invalid price per gb") - } - if n.InternetSpeed.AnyNil() || !n.InternetSpeed.AllPositive() { - return fmt.Errorf("invalid internet speed") - } - - if n.Encryption == "" || len(n.Encryption) < 4 || len(n.Encryption) > 16 { - return fmt.Errorf("invalid encryption") - } - - if n.Status != StatusRegistered && - n.Status != StatusDeRegistered { - return fmt.Errorf("invalid status") - } - - return nil -} diff --git a/x/vpn/types/node_msgs.go b/x/vpn/types/node_msgs.go deleted file mode 100644 index 8f58d751..00000000 --- a/x/vpn/types/node_msgs.go +++ /dev/null @@ -1,193 +0,0 @@ -package types - -import ( - "encoding/json" - - sdk "github.com/cosmos/cosmos-sdk/types" - - hub "github.com/sentinel-official/hub/types" -) - -var _ sdk.Msg = (*MsgRegisterNode)(nil) - -type MsgRegisterNode struct { - From sdk.AccAddress `json:"from"` - T string `json:"type"` - Version string `json:"version"` - Moniker string `json:"moniker"` - PricesPerGB sdk.Coins `json:"prices_per_gb"` - InternetSpeed hub.Bandwidth `json:"internet_speed"` - Encryption string `json:"encryption"` -} - -func (msg MsgRegisterNode) Type() string { - return "register_node" -} - -func (msg MsgRegisterNode) ValidateBasic() sdk.Error { - if msg.From == nil || msg.From.Empty() { - return ErrorInvalidField("from") - } - if msg.T == "" { - return ErrorInvalidField("type") - } - if msg.Version == "" { - return ErrorInvalidField("version") - } - if len(msg.Moniker) > 128 { - return ErrorInvalidField("moniker") - } - if msg.PricesPerGB == nil || - msg.PricesPerGB.Len() == 0 || !msg.PricesPerGB.IsValid() { - return ErrorInvalidField("prices_per_gb") - } - if !msg.InternetSpeed.AllPositive() { - return ErrorInvalidField("internet_speed") - } - if msg.Encryption == "" { - return ErrorInvalidField("encryption") - } - - return nil -} - -func (msg MsgRegisterNode) GetSignBytes() []byte { - bz, err := json.Marshal(msg) - if err != nil { - panic(err) - } - - return bz -} - -func (msg MsgRegisterNode) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.From} -} - -func (msg MsgRegisterNode) Route() string { - return RouterKey -} - -func NewMsgRegisterNode(from sdk.AccAddress, - t, version, moniker string, pricesPerGB sdk.Coins, - internetSpeed hub.Bandwidth, encryption string) *MsgRegisterNode { - return &MsgRegisterNode{ - From: from, - T: t, - Version: version, - Moniker: moniker, - PricesPerGB: pricesPerGB, - InternetSpeed: internetSpeed, - Encryption: encryption, - } -} - -var _ sdk.Msg = (*MsgUpdateNodeInfo)(nil) - -type MsgUpdateNodeInfo struct { - From sdk.AccAddress `json:"from"` - ID hub.NodeID `json:"id"` - T string `json:"type"` - Version string `json:"version"` - Moniker string `json:"moniker"` - PricesPerGB sdk.Coins `json:"prices_per_gb"` - InternetSpeed hub.Bandwidth `json:"internet_speed"` - Encryption string `json:"encryption"` -} - -func (msg MsgUpdateNodeInfo) Type() string { - return "update_node_info" -} - -func (msg MsgUpdateNodeInfo) ValidateBasic() sdk.Error { - if msg.From == nil || msg.From.Empty() { - return ErrorInvalidField("from") - } - if len(msg.Moniker) > 128 { - return ErrorInvalidField("moniker") - } - if msg.PricesPerGB != nil && - (msg.PricesPerGB.Len() == 0 || !msg.PricesPerGB.IsValid()) { - return ErrorInvalidField("prices_per_gb") - } - if msg.InternetSpeed.AnyNegative() { - return ErrorInvalidField("internet_speed") - } - - return nil -} - -func (msg MsgUpdateNodeInfo) GetSignBytes() []byte { - bz, err := json.Marshal(msg) - if err != nil { - panic(err) - } - - return bz -} - -func (msg MsgUpdateNodeInfo) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.From} -} - -func (msg MsgUpdateNodeInfo) Route() string { - return RouterKey -} - -func NewMsgUpdateNodeInfo(from sdk.AccAddress, id hub.NodeID, - t, version, moniker string, pricesPerGB sdk.Coins, - internetSpeed hub.Bandwidth, encryption string) *MsgUpdateNodeInfo { - return &MsgUpdateNodeInfo{ - From: from, - ID: id, - T: t, - Version: version, - Moniker: moniker, - PricesPerGB: pricesPerGB, - InternetSpeed: internetSpeed, - Encryption: encryption, - } -} - -var _ sdk.Msg = (*MsgDeregisterNode)(nil) - -type MsgDeregisterNode struct { - From sdk.AccAddress `json:"from"` - ID hub.NodeID `json:"id"` -} - -func (msg MsgDeregisterNode) Type() string { - return "deregister_node" -} - -func (msg MsgDeregisterNode) ValidateBasic() sdk.Error { - if msg.From == nil || msg.From.Empty() { - return ErrorInvalidField("from") - } - - return nil -} - -func (msg MsgDeregisterNode) GetSignBytes() []byte { - bz, err := json.Marshal(msg) - if err != nil { - panic(err) - } - - return bz -} - -func (msg MsgDeregisterNode) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.From} -} - -func (msg MsgDeregisterNode) Route() string { - return RouterKey -} - -func NewMsgDeregisterNode(from sdk.AccAddress, id hub.NodeID) *MsgDeregisterNode { - return &MsgDeregisterNode{ - From: from, - ID: id, - } -} diff --git a/x/vpn/types/node_msgs_test.go b/x/vpn/types/node_msgs_test.go deleted file mode 100644 index db018e95..00000000 --- a/x/vpn/types/node_msgs_test.go +++ /dev/null @@ -1,258 +0,0 @@ -package types - -import ( - "encoding/json" - "reflect" - "strings" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - hub "github.com/sentinel-official/hub/types" -) - -func TestMsgRegisterNode_ValidateBasic(t *testing.T) { - tests := []struct { - name string - msg *MsgRegisterNode - want sdk.Error - }{ - { - "from is nil", - NewMsgRegisterNode(nil, "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption"), - ErrorInvalidField("from"), - }, { - "from is empty", - NewMsgRegisterNode([]byte(""), "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption"), - ErrorInvalidField("from"), - }, { - "node_type is empty", - NewMsgRegisterNode(TestAddress1, "", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption"), - ErrorInvalidField("type"), - }, { - "version is empty", - NewMsgRegisterNode(TestAddress1, "node_type", "", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption"), - ErrorInvalidField("version"), - }, { - "node_moniker length is greater than 128", - NewMsgRegisterNode(TestAddress1, "node_type", "version", strings.Repeat("X", 130), sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption"), - ErrorInvalidField("moniker"), - }, { - "prices_per_gb is nil", - NewMsgRegisterNode(TestAddress1, "node_type", "version", "moniker", nil, TestBandwidthPos1, "encryption"), - ErrorInvalidField("prices_per_gb"), - }, { - "prices_per_gb is empty", - NewMsgRegisterNode(TestAddress1, "node_type", "version", "moniker", sdk.Coins{}, TestBandwidthPos1, "encryption"), - ErrorInvalidField("prices_per_gb"), - }, { - "prices_per_gb is negative", - NewMsgRegisterNode(TestAddress1, "node_type", "version", "moniker", sdk.Coins{sdk.Coin{"stake", sdk.NewInt(-100)}}, TestBandwidthPos1, "encryption"), - ErrorInvalidField("prices_per_gb"), - }, { - "prices_per_gb is zero", - NewMsgRegisterNode(TestAddress1, "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 0)}, TestBandwidthPos1, "encryption"), - ErrorInvalidField("prices_per_gb"), - }, { - "internet_speed is negative", - NewMsgRegisterNode(TestAddress1, "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthNeg, "encryption"), - ErrorInvalidField("internet_speed"), - }, { - "internet_speed is zero", - NewMsgRegisterNode(TestAddress1, "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthZero, "encryption"), - ErrorInvalidField("internet_speed"), - }, { - "encryption is empty", - NewMsgRegisterNode(TestAddress1, "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, ""), - ErrorInvalidField("encryption"), - }, { - "valid", - NewMsgRegisterNode(TestAddress1, "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption"), - nil, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - if got := tc.msg.ValidateBasic(); !reflect.DeepEqual(got, tc.want) { - t.Errorf("\ngot = %vwant = %v", got, tc.want) - } - }) - } -} - -func TestMsgRegisterNode_GetSignBytes(t *testing.T) { - msg := NewMsgRegisterNode(TestAddress1, "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption") - msgBytes, err := json.Marshal(msg) - if err != nil { - panic(err) - } - - require.Equal(t, msgBytes, msg.GetSignBytes()) -} - -func TestMsgRegisterNode_GetSigners(t *testing.T) { - msg := NewMsgRegisterNode(TestAddress1, "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption") - require.Equal(t, []sdk.AccAddress{TestAddress1}, msg.GetSigners()) -} - -func TestMsgRegisterNode_Type(t *testing.T) { - msg := NewMsgRegisterNode(TestAddress1, "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption") - require.Equal(t, "register_node", msg.Type()) -} - -func TestMsgRegisterNode_Route(t *testing.T) { - msg := NewMsgRegisterNode(TestAddress1, "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption") - require.Equal(t, RouterKey, msg.Route()) -} - -func TestMsgUpdateNodeInfo_ValidateBasic(t *testing.T) { - tests := []struct { - name string - msg *MsgUpdateNodeInfo - want sdk.Error - }{ - { - "from is nil", - NewMsgUpdateNodeInfo(nil, hub.NewNodeID(1), "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption"), - ErrorInvalidField("from"), - }, { - "from is empty", - NewMsgUpdateNodeInfo([]byte(""), hub.NewNodeID(1), "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption"), - ErrorInvalidField("from"), - }, { - "node_moniker length is greater than 128", - NewMsgUpdateNodeInfo(TestAddress1, hub.NewNodeID(1), "node_type", "version", strings.Repeat("X", 130), sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption"), - ErrorInvalidField("moniker"), - }, { - "prices_per_gb is nil", - NewMsgUpdateNodeInfo(TestAddress1, hub.NewNodeID(1), "node_type", "version", "moniker", nil, TestBandwidthPos1, "encryption"), - nil, - }, { - "prices_per_gb is empty", - NewMsgUpdateNodeInfo(TestAddress1, hub.NewNodeID(1), "node_type", "version", "moniker", sdk.Coins{}, TestBandwidthPos1, "encryption"), - ErrorInvalidField("prices_per_gb"), - }, { - "prices_per_gb is negative", - NewMsgUpdateNodeInfo(TestAddress1, hub.NewNodeID(1), "node_type", "version", "moniker", sdk.Coins{sdk.Coin{"stake", sdk.NewInt(-100)}}, TestBandwidthPos1, "encryption"), - ErrorInvalidField("prices_per_gb"), - }, { - "prices_per_gb is zero", - NewMsgUpdateNodeInfo(TestAddress1, hub.NewNodeID(1), "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 0)}, TestBandwidthPos1, "encryption"), - ErrorInvalidField("prices_per_gb"), - }, { - "internet_speed is zero", - NewMsgUpdateNodeInfo(TestAddress1, hub.NewNodeID(1), "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthZero, "encryption"), - nil, - }, { - "internet_speed is negative", - NewMsgUpdateNodeInfo(TestAddress1, hub.NewNodeID(1), "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthNeg, "encryption"), - ErrorInvalidField("internet_speed"), - }, { - "encryption is empty", - NewMsgUpdateNodeInfo(TestAddress1, hub.NewNodeID(1), "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, ""), - nil, - }, { - "type is empty", - NewMsgUpdateNodeInfo(TestAddress1, hub.NewNodeID(1), "", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption"), - nil, - }, { - "version is empty", - NewMsgUpdateNodeInfo(TestAddress1, hub.NewNodeID(1), "node_type", "", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption"), - nil, - }, { - "valid", - NewMsgUpdateNodeInfo(TestAddress1, hub.NewNodeID(1), "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption"), - nil, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - if got := tc.msg.ValidateBasic(); !reflect.DeepEqual(got, tc.want) { - t.Errorf("\ngot = %vwant = %v", got, tc.want) - } - }) - } -} - -func TestMsgUpdateNode_GetSignBytes(t *testing.T) { - msg := NewMsgUpdateNodeInfo(TestAddress1, hub.NewNodeID(1), "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption") - msgBytes, err := json.Marshal(msg) - if err != nil { - panic(err) - } - - require.Equal(t, msgBytes, msg.GetSignBytes()) -} - -func TestMsgUpdateNode_GetSigners(t *testing.T) { - msg := NewMsgUpdateNodeInfo(TestAddress1, hub.NewNodeID(1), "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption") - require.Equal(t, []sdk.AccAddress{TestAddress1}, msg.GetSigners()) -} - -func TestMsgUpdateNode_Type(t *testing.T) { - msg := NewMsgUpdateNodeInfo(TestAddress1, hub.NewNodeID(1), "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption") - require.Equal(t, "update_node_info", msg.Type()) -} - -func TestMsgUpdateNode_Route(t *testing.T) { - msg := NewMsgUpdateNodeInfo(TestAddress1, hub.NewNodeID(1), "node_type", "version", "moniker", sdk.Coins{sdk.NewInt64Coin("stake", 100)}, TestBandwidthPos1, "encryption") - require.Equal(t, RouterKey, msg.Route()) -} - -func TestMsgDeregisterNode_ValidateBasic(t *testing.T) { - tests := []struct { - name string - msg *MsgDeregisterNode - want sdk.Error - }{ - { - "from is nil", - NewMsgDeregisterNode(nil, hub.NewNodeID(1)), - ErrorInvalidField("from"), - }, { - "from is empty", - NewMsgDeregisterNode([]byte(""), hub.NewNodeID(1)), - ErrorInvalidField("from"), - }, { - "valid", - NewMsgDeregisterNode(TestAddress1, hub.NewNodeID(1)), - nil, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - if got := tc.msg.ValidateBasic(); !reflect.DeepEqual(got, tc.want) { - t.Errorf("\ngot = %vwant = %v", got, tc.want) - } - }) - } -} - -func TestMsgDeregisterNode_GetSignBytes(t *testing.T) { - msg := NewMsgDeregisterNode(TestAddress1, hub.NewNodeID(1)) - msgBytes, err := json.Marshal(msg) - if err != nil { - panic(err) - } - - require.Equal(t, msgBytes, msg.GetSignBytes()) -} - -func TestMsgDeregisterNode_GetSigners(t *testing.T) { - msg := NewMsgDeregisterNode(TestAddress1, hub.NewNodeID(1)) - require.Equal(t, []sdk.AccAddress{TestAddress1}, msg.GetSigners()) -} - -func TestMsgDeregisterNode_Type(t *testing.T) { - msg := NewMsgDeregisterNode(TestAddress1, hub.NewNodeID(1)) - require.Equal(t, "deregister_node", msg.Type()) -} - -func TestMsgDeregisterNode_Route(t *testing.T) { - msg := NewMsgDeregisterNode(TestAddress1, hub.NewNodeID(1)) - require.Equal(t, RouterKey, msg.Route()) -} diff --git a/x/vpn/types/node_test.go b/x/vpn/types/node_test.go deleted file mode 100644 index ef37a6ce..00000000 --- a/x/vpn/types/node_test.go +++ /dev/null @@ -1,126 +0,0 @@ -package types - -import ( - "reflect" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - hub "github.com/sentinel-official/hub/types" -) - -func TestNode_UpdateInfo(t *testing.T) { - tests := []struct { - name string - info Node - want Node - }{ - { - "node_moniker is empty", - Node{Moniker: ""}, - Node{}, - }, { - "node_moniker length Valid", - Node{Moniker: "moniker"}, - Node{Moniker: "moniker"}, - }, { - "prices_per_gb is nil", - Node{PricesPerGB: nil}, - Node{}, - }, { - "prices_per_gb is empty", - Node{PricesPerGB: sdk.Coins{}}, - Node{}, - }, { - "prices_per_gb is negative", - Node{PricesPerGB: sdk.Coins{sdk.Coin{"stake", sdk.NewInt(-100)}}}, - Node{}, - }, { - "prices_per_gb is zero", - Node{PricesPerGB: sdk.Coins{sdk.NewInt64Coin("stake", 0)}}, - Node{}, - }, { - "prices_per_gb is positive", - Node{PricesPerGB: sdk.Coins{sdk.NewInt64Coin("stake", 100)}}, - Node{PricesPerGB: sdk.Coins{sdk.NewInt64Coin("stake", 100)}}, - }, { - "net_speed is empty", - Node{InternetSpeed: hub.Bandwidth{}}, - Node{}, - }, { - "net_speed is negative", - Node{InternetSpeed: TestBandwidthNeg}, - Node{}, - }, { - "net_speed is zero", - Node{InternetSpeed: TestBandwidthZero}, - Node{}, - }, { - "net_speed is positive", - Node{InternetSpeed: TestBandwidthPos1}, - Node{InternetSpeed: TestBandwidthPos1}, - }, { - "encryption is empty", - Node{Encryption: ""}, - Node{}, - }, { - "encryption is valid", - Node{Encryption: "encryption"}, - Node{Encryption: "encryption"}, - }, { - "node_type is empty", - Node{Type: ""}, - Node{}, - }, { - "node_type is valid", - Node{Type: "node_type"}, - Node{Type: "node_type"}, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - node := Node{}.UpdateInfo(tc.info) - if !reflect.DeepEqual(node, tc.want) { - t.Errorf("\ngot = %vwant = %v", node, tc.want) - } - }) - } -} - -func TestNode_FindPricePerGB(t *testing.T) { - var node Node - require.Equal(t, node.FindPricePerGB("stake"), sdk.Coin{}) - - node = Node{PricesPerGB: nil} - require.Equal(t, node.FindPricePerGB("stake"), sdk.Coin{}) - - node = Node{PricesPerGB: sdk.Coins{}} - require.Equal(t, node.FindPricePerGB("stake"), sdk.Coin{}) - - node = Node{PricesPerGB: sdk.Coins{sdk.NewInt64Coin("stake", 100)}} - require.Equal(t, node.FindPricePerGB("stake"), sdk.NewInt64Coin("stake", 100)) -} - -func TestNode_DepositToBandwidth(t *testing.T) { - node := Node{ - PricesPerGB: sdk.Coins{sdk.NewInt64Coin("stake", 100)}, - Deposit: sdk.NewInt64Coin("stake", 100), - } - - _, err := node.DepositToBandwidth(sdk.Coin{}) - require.NotNil(t, err) - - bandwidth, err := node.DepositToBandwidth(sdk.NewInt64Coin("stake", 0)) - require.Nil(t, err) - reflect.DeepEqual(TestBandwidthZero, bandwidth) - - bandwidth, err = node.DepositToBandwidth(sdk.Coin{Denom: "stake", Amount: sdk.NewInt(-100)}) - require.Nil(t, err) - reflect.DeepEqual(TestBandwidthNeg, bandwidth) - - bandwidth, err = node.DepositToBandwidth(sdk.NewInt64Coin("stake", 100)) - require.Nil(t, err) - reflect.DeepEqual(TestBandwidthPos1, bandwidth) -} diff --git a/x/vpn/types/params.go b/x/vpn/types/params.go deleted file mode 100644 index 77e731ce..00000000 --- a/x/vpn/types/params.go +++ /dev/null @@ -1,71 +0,0 @@ -package types - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/params/subspace" -) - -var ( - DefaultFreeNodesCount uint64 = 5 - DefaultDeposit = sdk.NewInt64Coin("stake", 100) - DefaultSessionInactiveInterval int64 = 25 -) - -var ( - KeyFreeNodesCount = []byte("FreeNodesCount") - KeyDeposit = []byte("Deposit") - KeySessionInactiveInterval = []byte("SessionInactiveInterval") -) - -var _ params.ParamSet = (*Params)(nil) - -type Params struct { - FreeNodesCount uint64 `json:"free_nodes_count"` - Deposit sdk.Coin `json:"deposit"` - SessionInactiveInterval int64 `json:"session_inactive_interval"` -} - -func NewParams(freeNodesCount uint64, deposit sdk.Coin, sessionInactiveInterval int64) Params { - return Params{ - FreeNodesCount: freeNodesCount, - Deposit: deposit, - SessionInactiveInterval: sessionInactiveInterval, - } -} - -func (p Params) String() string { - return fmt.Sprintf(`Params - Free Nodes Count: %d - Deposit: %s - Session Inactive Interval: %d`, p.FreeNodesCount, p.Deposit, p.SessionInactiveInterval) -} - -func (p *Params) ParamSetPairs() subspace.ParamSetPairs { - return params.ParamSetPairs{ - {Key: KeyFreeNodesCount, Value: &p.FreeNodesCount}, - {Key: KeyDeposit, Value: &p.Deposit}, - {Key: KeySessionInactiveInterval, Value: &p.SessionInactiveInterval}, - } -} - -func DefaultParams() Params { - return Params{ - FreeNodesCount: DefaultFreeNodesCount, - Deposit: DefaultDeposit, - SessionInactiveInterval: DefaultSessionInactiveInterval, - } -} - -func (p Params) Validate() error { - if !p.Deposit.IsValid() { - return fmt.Errorf("deposit is invalid: %s ", p.Deposit.String()) - } - if p.SessionInactiveInterval < 0 { - return fmt.Errorf("SessionInactiveInterval: %d should be positive interger", p.SessionInactiveInterval) - } - - return nil -} diff --git a/x/vpn/types/querier.go b/x/vpn/types/querier.go deleted file mode 100644 index 642e07a2..00000000 --- a/x/vpn/types/querier.go +++ /dev/null @@ -1,116 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - hub "github.com/sentinel-official/hub/types" -) - -const ( - QueryNode = "node" - QueryNodesOfAddress = "nodes_of_address" - QueryAllNodes = "all_nodes" - - QuerySubscription = "subscription" - QuerySubscriptionsOfNode = "subscriptions_of_node" - QuerySubscriptionsOfAddress = "subscriptions_of_address" - QueryAllSubscriptions = "all_subscriptions" - QuerySessionsCountOfSubscription = "sessions_count_of_subscription" - - QuerySession = "session" - QuerySessionOfSubscription = "session_of_subscription" - QuerySessionsOfSubscription = "sessions_of_subscription" - QueryAllSessions = "all_sessions" -) - -type QueryNodeParams struct { - ID hub.NodeID -} - -func NewQueryNodeParams(id hub.NodeID) QueryNodeParams { - return QueryNodeParams{ - ID: id, - } -} - -type QueryNodesOfAddressPrams struct { - Address sdk.AccAddress -} - -func NewQueryNodesOfAddressParams(address sdk.AccAddress) QueryNodesOfAddressPrams { - return QueryNodesOfAddressPrams{ - Address: address, - } -} - -type QuerySubscriptionParams struct { - ID hub.SubscriptionID -} - -func NewQuerySubscriptionParams(id hub.SubscriptionID) QuerySubscriptionParams { - return QuerySubscriptionParams{ - ID: id, - } -} - -type QuerySubscriptionsOfNodePrams struct { - ID hub.NodeID -} - -func NewQuerySubscriptionsOfNodePrams(id hub.NodeID) QuerySubscriptionsOfNodePrams { - return QuerySubscriptionsOfNodePrams{ - ID: id, - } -} - -type QuerySubscriptionsOfAddressParams struct { - Address sdk.AccAddress -} - -func NewQuerySubscriptionsOfAddressParams(address sdk.AccAddress) QuerySubscriptionsOfAddressParams { - return QuerySubscriptionsOfAddressParams{ - Address: address, - } -} - -type QuerySessionsCountOfSubscriptionParams struct { - ID hub.SubscriptionID -} - -func NewQuerySessionsCountOfSubscriptionParams(id hub.SubscriptionID) QuerySessionsCountOfSubscriptionParams { - return QuerySessionsCountOfSubscriptionParams{ - ID: id, - } -} - -type QuerySessionParams struct { - ID hub.SessionID -} - -func NewQuerySessionParams(id hub.SessionID) QuerySessionParams { - return QuerySessionParams{ - ID: id, - } -} - -type QuerySessionOfSubscriptionPrams struct { - ID hub.SubscriptionID - Index uint64 -} - -func NewQuerySessionOfSubscriptionPrams(id hub.SubscriptionID, index uint64) QuerySessionOfSubscriptionPrams { - return QuerySessionOfSubscriptionPrams{ - ID: id, - Index: index, - } -} - -type QuerySessionsOfSubscriptionPrams struct { - ID hub.SubscriptionID -} - -func NewQuerySessionsOfSubscriptionPrams(id hub.SubscriptionID) QuerySessionsOfSubscriptionPrams { - return QuerySessionsOfSubscriptionPrams{ - ID: id, - } -} diff --git a/x/vpn/types/session.go b/x/vpn/types/session.go deleted file mode 100644 index 26e0323c..00000000 --- a/x/vpn/types/session.go +++ /dev/null @@ -1,35 +0,0 @@ -package types - -import ( - "fmt" - - hub "github.com/sentinel-official/hub/types" -) - -type Session struct { - ID hub.SessionID `json:"id"` - SubscriptionID hub.SubscriptionID `json:"subscription_id"` - Bandwidth hub.Bandwidth `json:"bandwidth"` - Status string `json:"status"` - StatusModifiedAt int64 `json:"status_modified_at"` -} - -func (s Session) String() string { - return fmt.Sprintf(`Session - ID: %s - Subscription ID: %s - Bandwidth: %s - Status: %s - Status Modified At: %d`, s.ID, s.SubscriptionID, s.Bandwidth, s.Status, s.StatusModifiedAt) -} - -func (s Session) IsValid() error { - if s.Bandwidth.AnyNil() { - return fmt.Errorf("invalid bandwidth") - } - if s.Status != StatusRegistered && s.Status != StatusDeRegistered { - return fmt.Errorf("invalid status") - } - - return nil -} diff --git a/x/vpn/types/session_msgs.go b/x/vpn/types/session_msgs.go deleted file mode 100644 index b8017615..00000000 --- a/x/vpn/types/session_msgs.go +++ /dev/null @@ -1,70 +0,0 @@ -package types - -import ( - "encoding/json" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - - hub "github.com/sentinel-official/hub/types" -) - -var _ sdk.Msg = (*MsgUpdateSessionInfo)(nil) - -type MsgUpdateSessionInfo struct { - From sdk.AccAddress `json:"from"` - SubscriptionID hub.SubscriptionID `json:"subscription_id"` - Bandwidth hub.Bandwidth `json:"bandwidth"` - NodeOwnerSignature auth.StdSignature `json:"node_owner_signature"` - ClientSignature auth.StdSignature `json:"client_signature"` -} - -func (msg MsgUpdateSessionInfo) Type() string { - return "update_session_info" -} - -func (msg MsgUpdateSessionInfo) ValidateBasic() sdk.Error { - if msg.From == nil || msg.From.Empty() { - return ErrorInvalidField("from") - } - if !msg.Bandwidth.AllPositive() { - return ErrorInvalidField("bandwidth") - } - if msg.NodeOwnerSignature.Signature == nil || msg.NodeOwnerSignature.PubKey == nil { - return ErrorInvalidField("node_owner_signature") - } - if msg.ClientSignature.Signature == nil || msg.ClientSignature.PubKey == nil { - return ErrorInvalidField("client_signature") - } - - return nil -} - -func (msg MsgUpdateSessionInfo) GetSignBytes() []byte { - bz, err := json.Marshal(msg) - if err != nil { - panic(err) - } - - return bz -} - -func (msg MsgUpdateSessionInfo) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.From} -} - -func (msg MsgUpdateSessionInfo) Route() string { - return RouterKey -} - -func NewMsgUpdateSessionInfo(from sdk.AccAddress, - subscriptionID hub.SubscriptionID, bandwidth hub.Bandwidth, - nodeOwnerSignature, clientSignature auth.StdSignature) *MsgUpdateSessionInfo { - return &MsgUpdateSessionInfo{ - From: from, - SubscriptionID: subscriptionID, - Bandwidth: bandwidth, - NodeOwnerSignature: nodeOwnerSignature, - ClientSignature: clientSignature, - } -} diff --git a/x/vpn/types/session_msgs_test.go b/x/vpn/types/session_msgs_test.go deleted file mode 100644 index 149557df..00000000 --- a/x/vpn/types/session_msgs_test.go +++ /dev/null @@ -1,88 +0,0 @@ -package types - -import ( - "encoding/json" - "reflect" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/stretchr/testify/require" - - hub "github.com/sentinel-official/hub/types" -) - -func TestMsgUpdateSessionInfo_ValidateBasic(t *testing.T) { - tests := []struct { - name string - msg *MsgUpdateSessionInfo - want sdk.Error - }{ - { - "from is nil", - NewMsgUpdateSessionInfo(nil, hub.NewSubscriptionID(1), TestBandwidthPos1, TestNodeOwnerStdSignaturePos1, TestClientStdSignaturePos1), - ErrorInvalidField("from"), - }, { - "from is empty", - NewMsgUpdateSessionInfo([]byte(""), hub.NewSubscriptionID(1), TestBandwidthPos1, TestNodeOwnerStdSignaturePos1, TestClientStdSignaturePos1), - ErrorInvalidField("from"), - }, { - "bandwidth is zero", - NewMsgUpdateSessionInfo(TestAddress1, hub.NewSubscriptionID(1), TestBandwidthZero, TestNodeOwnerStdSignaturePos1, TestClientStdSignaturePos1), - ErrorInvalidField("bandwidth"), - }, { - "bandwidth is neg", - NewMsgUpdateSessionInfo(TestAddress1, hub.NewSubscriptionID(1), TestBandwidthNeg, TestNodeOwnerStdSignaturePos1, TestClientStdSignaturePos1), - ErrorInvalidField("bandwidth"), - }, { - "bandwidth is zero", - NewMsgUpdateSessionInfo(TestAddress1, hub.NewSubscriptionID(1), TestBandwidthZero, TestNodeOwnerStdSignaturePos1, TestClientStdSignaturePos1), - ErrorInvalidField("bandwidth"), - }, { - "node owner sign is empty ", - NewMsgUpdateSessionInfo(TestAddress1, hub.NewSubscriptionID(1), TestBandwidthPos1, auth.StdSignature{}, TestClientStdSignaturePos1), - ErrorInvalidField("node_owner_signature"), - }, { - "client sign is empty ", - NewMsgUpdateSessionInfo(TestAddress1, hub.NewSubscriptionID(1), TestBandwidthPos1, TestNodeOwnerStdSignaturePos1, auth.StdSignature{}), - ErrorInvalidField("client_signature"), - }, { - "valid ", - NewMsgUpdateSessionInfo(TestAddress1, hub.NewSubscriptionID(1), TestBandwidthPos1, TestNodeOwnerStdSignaturePos1, TestClientStdSignaturePos1), - nil, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - if got := tc.msg.ValidateBasic(); !reflect.DeepEqual(got, tc.want) { - t.Errorf("\ngot = %vwant = %v", got, tc.want) - } - }) - } -} - -func TestMsgUpdateSessionInfo_GetSignBytes(t *testing.T) { - msg := NewMsgUpdateSessionInfo(TestAddress1, hub.NewSubscriptionID(1), TestBandwidthPos1, TestNodeOwnerStdSignaturePos1, TestClientStdSignaturePos1) - msgBytes, err := json.Marshal(msg) - if err != nil { - panic(err) - } - - require.Equal(t, msgBytes, msg.GetSignBytes()) -} - -func TestMsgUpdateSessionInfo_GetSigners(t *testing.T) { - msg := NewMsgUpdateSessionInfo(TestAddress1, hub.NewSubscriptionID(1), TestBandwidthPos1, TestNodeOwnerStdSignaturePos1, TestClientStdSignaturePos1) - require.Equal(t, []sdk.AccAddress{TestAddress1}, msg.GetSigners()) -} - -func TestMsgUpdateSessionInfo_Type(t *testing.T) { - msg := NewMsgUpdateSessionInfo(TestAddress1, hub.NewSubscriptionID(1), TestBandwidthPos1, TestNodeOwnerStdSignaturePos1, TestClientStdSignaturePos1) - require.Equal(t, "update_session_info", msg.Type()) -} - -func TestMsgUpdateSessionInfo_Route(t *testing.T) { - msg := NewMsgUpdateSessionInfo(TestAddress1, hub.NewSubscriptionID(1), TestBandwidthPos1, TestNodeOwnerStdSignaturePos1, TestClientStdSignaturePos1) - require.Equal(t, RouterKey, msg.Route()) -} diff --git a/x/vpn/types/subscription.go b/x/vpn/types/subscription.go deleted file mode 100644 index db29100a..00000000 --- a/x/vpn/types/subscription.go +++ /dev/null @@ -1,68 +0,0 @@ -package types - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - - hub "github.com/sentinel-official/hub/types" -) - -type Subscription struct { - ID hub.SubscriptionID `json:"id"` - NodeID hub.NodeID `json:"node_id"` - Client sdk.AccAddress `json:"client"` - PricePerGB sdk.Coin `json:"price_per_gb"` - TotalDeposit sdk.Coin `json:"total_deposit"` - RemainingDeposit sdk.Coin `json:"remaining_deposit"` - RemainingBandwidth hub.Bandwidth `json:"remaining_bandwidth"` - Status string `json:"status"` - StatusModifiedAt int64 `json:"status_modified_at"` -} - -func (s Subscription) TotalBandwidth() hub.Bandwidth { - x := s.TotalDeposit.Amount. - Mul(hub.MB500). - Quo(s.PricePerGB.Amount) - - return hub.NewBandwidth(x, x) -} - -func (s Subscription) String() string { - return fmt.Sprintf(`Subscription - ID: %s - Node ID: %s - Client Address: %s - Price Per GB: %s - Total Deposit: %s - Total Bandwidth: %s - Remaining Deposit: %s - Remaining Bandwidth: %s - Status: %s - Status Modified At: %d`, s.ID, s.NodeID, s.Client, - s.PricePerGB, s.TotalDeposit, s.TotalBandwidth(), - s.RemainingDeposit, s.RemainingBandwidth, s.Status, s.StatusModifiedAt) -} - -func (s Subscription) IsValid() error { - if s.Client == nil || s.Client.Empty() { - return fmt.Errorf("invalid client") - } - if s.PricePerGB.Denom == "" || s.PricePerGB.IsZero() { - return fmt.Errorf("invalid price per gb") - } - if s.TotalDeposit.Denom != s.PricePerGB.Denom || s.TotalDeposit.IsZero() { - return fmt.Errorf("invalid total deposit") - } - if s.RemainingDeposit.Denom != s.TotalDeposit.Denom || s.TotalDeposit.IsLT(s.RemainingDeposit) { - return fmt.Errorf("invalid remaining deposit") - } - if s.RemainingBandwidth.AnyNil() || s.TotalBandwidth().AnyLT(s.RemainingBandwidth) { - return fmt.Errorf("invalid total remaining bandwidth") - } - if s.Status != StatusActive && s.Status != StatusInactive { - return fmt.Errorf("invalid status") - } - - return nil -} diff --git a/x/vpn/types/subscription_msgs.go b/x/vpn/types/subscription_msgs.go deleted file mode 100644 index fcd30482..00000000 --- a/x/vpn/types/subscription_msgs.go +++ /dev/null @@ -1,100 +0,0 @@ -package types - -import ( - "encoding/json" - - sdk "github.com/cosmos/cosmos-sdk/types" - - hub "github.com/sentinel-official/hub/types" -) - -var _ sdk.Msg = (*MsgStartSubscription)(nil) - -type MsgStartSubscription struct { - From sdk.AccAddress `json:"from"` - NodeID hub.NodeID `json:"node_id"` - Deposit sdk.Coin `json:"deposit"` -} - -func (msg MsgStartSubscription) Type() string { - return "start_subscription" -} - -func (msg MsgStartSubscription) ValidateBasic() sdk.Error { - if msg.From == nil || msg.From.Empty() { - return ErrorInvalidField("from") - } - if msg.Deposit.Denom == "" || !msg.Deposit.IsPositive() { - return ErrorInvalidField("deposit") - } - - return nil -} - -func (msg MsgStartSubscription) GetSignBytes() []byte { - bz, err := json.Marshal(msg) - if err != nil { - panic(err) - } - - return bz -} - -func (msg MsgStartSubscription) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.From} -} - -func (msg MsgStartSubscription) Route() string { - return RouterKey -} - -func NewMsgStartSubscription(from sdk.AccAddress, nodeID hub.NodeID, deposit sdk.Coin) *MsgStartSubscription { - return &MsgStartSubscription{ - From: from, - NodeID: nodeID, - Deposit: deposit, - } -} - -var _ sdk.Msg = (*MsgEndSubscription)(nil) - -type MsgEndSubscription struct { - From sdk.AccAddress `json:"from"` - ID hub.SubscriptionID `json:"id"` -} - -func (msg MsgEndSubscription) Type() string { - return "end_subscription" -} - -func (msg MsgEndSubscription) ValidateBasic() sdk.Error { - if msg.From == nil || msg.From.Empty() { - return ErrorInvalidField("from") - } - - return nil -} - -func (msg MsgEndSubscription) GetSignBytes() []byte { - bz, err := json.Marshal(msg) - if err != nil { - panic(err) - } - - return bz -} - -func (msg MsgEndSubscription) GetSigners() []sdk.AccAddress { - return []sdk.AccAddress{msg.From} -} - -func (msg MsgEndSubscription) Route() string { - return RouterKey -} - -func NewMsgEndSubscription(from sdk.AccAddress, id hub.SubscriptionID) *MsgEndSubscription { - return &MsgEndSubscription{ - From: from, - ID: id, - } -} diff --git a/x/vpn/types/subscription_msgs_test.go b/x/vpn/types/subscription_msgs_test.go deleted file mode 100644 index c578884c..00000000 --- a/x/vpn/types/subscription_msgs_test.go +++ /dev/null @@ -1,130 +0,0 @@ -package types - -import ( - "encoding/json" - "reflect" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - hub "github.com/sentinel-official/hub/types" -) - -func TestMsgStartSubscription_ValidateBasic(t *testing.T) { - tests := []struct { - name string - msg *MsgStartSubscription - want sdk.Error - }{ - { - "from is nil", - NewMsgStartSubscription(nil, hub.NewNodeID(1), sdk.NewInt64Coin("stake", 100)), - ErrorInvalidField("from"), - }, { - "from is empty", - NewMsgStartSubscription([]byte(""), hub.NewNodeID(1), sdk.NewInt64Coin("stake", 100)), - ErrorInvalidField("from"), - }, { - "deposit is empty", - NewMsgStartSubscription(TestAddress1, hub.NewNodeID(1), sdk.Coin{}), - ErrorInvalidField("deposit"), - }, { - "deposit is zero", - NewMsgStartSubscription(TestAddress1, hub.NewNodeID(1), sdk.NewInt64Coin("stake", 0)), - ErrorInvalidField("deposit"), - }, { - "valid", - NewMsgStartSubscription(TestAddress1, hub.NewNodeID(1), sdk.NewInt64Coin("stake", 100)), - nil, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - if got := tc.msg.ValidateBasic(); !reflect.DeepEqual(got, tc.want) { - t.Errorf("\ngot = %vwant = %v", got, tc.want) - } - }) - } -} - -func TestMsgStartSubscription_GetSignBytes(t *testing.T) { - msg := NewMsgStartSubscription(TestAddress1, hub.NewNodeID(1), sdk.NewInt64Coin("stake", 100)) - msgBytes, err := json.Marshal(msg) - if err != nil { - panic(err) - } - - require.Equal(t, msgBytes, msg.GetSignBytes()) -} - -func TestMsgStartSubscription_GetSigners(t *testing.T) { - msg := NewMsgStartSubscription(TestAddress1, hub.NewNodeID(1), sdk.NewInt64Coin("stake", 100)) - require.Equal(t, []sdk.AccAddress{TestAddress1}, msg.GetSigners()) -} - -func TestMsgStartSubscription_Type(t *testing.T) { - msg := NewMsgStartSubscription(TestAddress1, hub.NewNodeID(1), sdk.NewInt64Coin("stake", 100)) - require.Equal(t, "start_subscription", msg.Type()) -} - -func TestMsgStartSubscription_Route(t *testing.T) { - msg := NewMsgStartSubscription(TestAddress1, hub.NewNodeID(1), sdk.NewInt64Coin("stake", 100)) - require.Equal(t, RouterKey, msg.Route()) -} - -func TestMsgEndSubscription_ValidateBasic(t *testing.T) { - tests := []struct { - name string - msg *MsgEndSubscription - want sdk.Error - }{ - { - "from is nil", - NewMsgEndSubscription(nil, hub.NewSubscriptionID(1)), - ErrorInvalidField("from"), - }, { - "from is empty", - NewMsgEndSubscription([]byte(""), hub.NewSubscriptionID(1)), - ErrorInvalidField("from"), - }, { - "valid", - NewMsgEndSubscription(TestAddress1, hub.NewSubscriptionID(1)), - nil, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - if got := tc.msg.ValidateBasic(); !reflect.DeepEqual(got, tc.want) { - t.Errorf("\ngot = %vwant = %v", got, tc.want) - } - }) - } -} - -func TestMsgEndSubscription_GetSignBytes(t *testing.T) { - msg := NewMsgEndSubscription(TestAddress1, hub.NewSubscriptionID(1)) - msgBytes, err := json.Marshal(msg) - if err != nil { - panic(err) - } - - require.Equal(t, msgBytes, msg.GetSignBytes()) -} - -func TestMsgEndSubscription_GetSigners(t *testing.T) { - msg := NewMsgEndSubscription(TestAddress1, hub.NewSubscriptionID(1)) - require.Equal(t, []sdk.AccAddress{TestAddress1}, msg.GetSigners()) -} - -func TestMsgEndSubscription_Type(t *testing.T) { - msg := NewMsgEndSubscription(TestAddress1, hub.NewSubscriptionID(1)) - require.Equal(t, "end_subscription", msg.Type()) -} - -func TestMsgEndSubscription_Route(t *testing.T) { - msg := NewMsgEndSubscription(TestAddress1, hub.NewSubscriptionID(1)) - require.Equal(t, RouterKey, msg.Route()) -} diff --git a/x/vpn/types/test_common.go b/x/vpn/types/test_common.go deleted file mode 100644 index ad9ba2bd..00000000 --- a/x/vpn/types/test_common.go +++ /dev/null @@ -1,74 +0,0 @@ -// nolint -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/tendermint/tendermint/crypto/ed25519" - - hub "github.com/sentinel-official/hub/types" -) - -var ( - TestPrivKey1 = ed25519.GenPrivKey() - TestPrivKey2 = ed25519.GenPrivKey() - TestPubkey1 = TestPrivKey1.PubKey() - TestPubkey2 = TestPrivKey2.PubKey() - TestAddress1 = sdk.AccAddress(TestPubkey1.Address()) - TestAddress2 = sdk.AccAddress(TestPubkey2.Address()) - TestNode = Node{ - ID: hub.NewNodeID(0), - Owner: TestAddress1, - Deposit: sdk.NewInt64Coin("stake", 100), - Type: "node_type", - Version: "version", - Moniker: "moniker", - PricesPerGB: sdk.Coins{sdk.NewInt64Coin("stake", 100)}, - InternetSpeed: TestBandwidthPos1, - Encryption: "encryption", - Status: StatusDeRegistered, - StatusModifiedAt: 1, - } - TestSubscription = Subscription{ - ID: hub.NewSubscriptionID(0), - NodeID: hub.NewNodeID(0), - Client: TestAddress2, - PricePerGB: sdk.NewInt64Coin("stake", 100), - TotalDeposit: sdk.NewInt64Coin("stake", 100), - RemainingDeposit: sdk.NewInt64Coin("stake", 100), - RemainingBandwidth: TestBandwidthPos1, - Status: StatusActive, - StatusModifiedAt: 0, - } - TestSession = Session{ - ID: hub.NewSessionID(0), - SubscriptionID: hub.NewSubscriptionID(0), - Bandwidth: TestBandwidthPos1, - Status: StatusActive, - StatusModifiedAt: 0, - } - TestBandwidthNeg = hub.NewBandwidth(sdk.NewInt(-500000000), sdk.NewInt(-500000000)) - TestBandwidthZero = hub.NewBandwidth(sdk.NewInt(0), sdk.NewInt(0)) - TestBandwidthPos1 = hub.NewBandwidth(sdk.NewInt(500000000), sdk.NewInt(500000000)) - TestBandwidthPos2 = TestBandwidthPos1.Add(TestBandwidthPos1) - TestBandWidthSignDataNeg = hub.NewBandwidthSignatureData(hub.NewSubscriptionID(0), 0, TestBandwidthNeg) - TestNodeOwnerSignBandWidthNeg, _ = TestPrivKey1.Sign(TestBandWidthSignDataNeg.Bytes()) - TestNodeOwnerStdSignatureNeg = auth.StdSignature{PubKey: TestPubkey1, Signature: TestNodeOwnerSignBandWidthNeg} - TestClientSignBandWidthNeg, _ = TestPrivKey2.Sign(TestBandWidthSignDataNeg.Bytes()) - TestClientStdSignatureNeg = auth.StdSignature{PubKey: TestPubkey2, Signature: TestClientSignBandWidthNeg} - TestBandWidthSignDataZero = hub.NewBandwidthSignatureData(hub.NewSubscriptionID(0), 0, TestBandwidthZero) - TestNodeOwnerSignBandWidthZero, _ = TestPrivKey1.Sign(TestBandWidthSignDataZero.Bytes()) - TestNodeOwnerStdSignatureZero = auth.StdSignature{PubKey: TestPubkey1, Signature: TestNodeOwnerSignBandWidthZero} - TestClientSignBandWidthZero, _ = TestPrivKey2.Sign(TestBandWidthSignDataZero.Bytes()) - TestClientStdSignatureZero = auth.StdSignature{PubKey: TestPubkey2, Signature: TestClientSignBandWidthZero} - TestBandWidthSignDataPos1 = hub.NewBandwidthSignatureData(hub.NewSubscriptionID(0), 1, TestBandwidthPos1) - TestNodeOwnerSignBandWidthPos1, _ = TestPrivKey1.Sign(TestBandWidthSignDataPos1.Bytes()) - TestNodeOwnerStdSignaturePos1 = auth.StdSignature{PubKey: TestPubkey1, Signature: TestNodeOwnerSignBandWidthPos1} - TestClientSignBandWidthPos1, _ = TestPrivKey2.Sign(TestBandWidthSignDataPos1.Bytes()) - TestClientStdSignaturePos1 = auth.StdSignature{PubKey: TestPubkey2, Signature: TestClientSignBandWidthPos1} - TestBandWidthSignDataPos2 = hub.NewBandwidthSignatureData(hub.NewSubscriptionID(0), 1, TestBandwidthPos2) - TestNodeOwnerSignBandWidthPos2, _ = TestPrivKey1.Sign(TestBandWidthSignDataPos2.Bytes()) - TestNodeOwnerStdSignaturePos2 = auth.StdSignature{PubKey: TestPubkey1, Signature: TestNodeOwnerSignBandWidthPos2} - TestClientSignBandWidthPos2, _ = TestPrivKey2.Sign(TestBandWidthSignDataPos2.Bytes()) - TestClientStdSignaturePos2 = auth.StdSignature{PubKey: TestPubkey2, Signature: TestClientSignBandWidthPos2} -)