diff --git a/app/app.go b/app/app.go index fea7de6f1..3fa3a1d0b 100644 --- a/app/app.go +++ b/app/app.go @@ -2,6 +2,10 @@ package app import ( "fmt" + "io" + "net/http" + "os" + "path/filepath" store "github.com/cosmos/cosmos-sdk/store/types" @@ -94,11 +98,6 @@ import ( reg "github.com/enigmampc/SecretNetwork/x/registration" "github.com/spf13/cast" - "io" - "net/http" - "os" - "path/filepath" - "github.com/gorilla/mux" "github.com/rakyll/statik/fs" abci "github.com/tendermint/tendermint/abci/types" @@ -242,13 +241,12 @@ func NewSecretNetworkApp( skipUpgradeHeights map[int64]bool, homePath string, invCheckPeriod uint, - //enabledProposals []compute.ProposalType, + // enabledProposals []compute.ProposalType, bootstrap bool, appOpts servertypes.AppOptions, computeConfig *compute.WasmConfig, baseAppOptions ...func(*baseapp.BaseApp), ) *SecretNetworkApp { - encodingConfig := MakeEncodingConfig() appCodec, legacyAmino := encodingConfig.Marshaler, encodingConfig.Amino interfaceRegistry := encodingConfig.InterfaceRegistry @@ -258,7 +256,7 @@ func NewSecretNetworkApp( bApp.SetCommitMultiStoreTracer(traceStore) bApp.SetVersion(version.Version) bApp.SetInterfaceRegistry(interfaceRegistry) - //bApp.GRPCQueryRouter().RegisterSimulateService(bApp.Simulate, interfaceRegistry) + // bApp.GRPCQueryRouter().RegisterSimulateService(bApp.Simulate, interfaceRegistry) keys := sdk.NewKVStoreKeys( authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, @@ -446,7 +444,7 @@ func NewSecretNetworkApp( // NOTE: we may consider parsing `appOpts` inside module constructors. For the moment // we prefer to be more strict in what arguments the modules expect. - var skipGenesisInvariants = cast.ToBool(appOpts.Get(crisis.FlagSkipGenesisInvariants)) + skipGenesisInvariants := cast.ToBool(appOpts.Get(crisis.FlagSkipGenesisInvariants)) // NOTE: Any module instantiated in the module manager that is later modified // must be passed by reference here. @@ -542,7 +540,7 @@ func NewSecretNetworkApp( govtypes.ModuleName, paramstypes.ModuleName, upgradetypes.ModuleName, - //custom modules + // custom modules compute.ModuleName, reg.ModuleName, @@ -589,7 +587,7 @@ func NewSecretNetworkApp( // evidence.NewAppModule(app.evidenceKeeper), //) - //app.sm.RegisterStoreDecoders() + // app.sm.RegisterStoreDecoders() // initialize stores app.MountKVStores(keys) diff --git a/app/config.go b/app/config.go index bca32c030..fc2950fcf 100644 --- a/app/config.go +++ b/app/config.go @@ -52,44 +52,42 @@ import ( "github.com/enigmampc/SecretNetwork/x/registration" ) -var ( - mbasics = module.NewBasicManager( - append([]module.AppModuleBasic{ - authz.AppModuleBasic{}, - // accounts, fees. - auth.AppModuleBasic{}, - // genesis utilities - genutil.AppModuleBasic{}, - // tokens, token balance. - bank.AppModuleBasic{}, - capability.AppModuleBasic{}, - // validator staking - staking.AppModuleBasic{}, - // inflation - mint.AppModuleBasic{}, - // distribution of fess and inflation - distr.AppModuleBasic{}, - // governance functionality (voting) - gov.NewAppModuleBasic( - paramsclient.ProposalHandler, distrclient.ProposalHandler, - upgradeclient.ProposalHandler, upgradeclient.CancelProposalHandler, - ), - // chain parameters - params.AppModuleBasic{}, - crisis.AppModuleBasic{}, - slashing.AppModuleBasic{}, - ibc.AppModuleBasic{}, - upgrade.AppModuleBasic{}, - evidence.AppModuleBasic{}, - transfer.AppModuleBasic{}, - vesting.AppModuleBasic{}, - feegrantmodule.AppModuleBasic{}, - ica.AppModuleBasic{}, - }, - // our stuff - customModuleBasics()..., - )..., - ) +var mbasics = module.NewBasicManager( + append([]module.AppModuleBasic{ + authz.AppModuleBasic{}, + // accounts, fees. + auth.AppModuleBasic{}, + // genesis utilities + genutil.AppModuleBasic{}, + // tokens, token balance. + bank.AppModuleBasic{}, + capability.AppModuleBasic{}, + // validator staking + staking.AppModuleBasic{}, + // inflation + mint.AppModuleBasic{}, + // distribution of fess and inflation + distr.AppModuleBasic{}, + // governance functionality (voting) + gov.NewAppModuleBasic( + paramsclient.ProposalHandler, distrclient.ProposalHandler, + upgradeclient.ProposalHandler, upgradeclient.CancelProposalHandler, + ), + // chain parameters + params.AppModuleBasic{}, + crisis.AppModuleBasic{}, + slashing.AppModuleBasic{}, + ibc.AppModuleBasic{}, + upgrade.AppModuleBasic{}, + evidence.AppModuleBasic{}, + transfer.AppModuleBasic{}, + vesting.AppModuleBasic{}, + feegrantmodule.AppModuleBasic{}, + ica.AppModuleBasic{}, + }, + // our stuff + customModuleBasics()..., + )..., ) func customKVStoreKeys() []string { @@ -163,5 +161,4 @@ func transientStoreKeys() map[string]*sdk.TransientStoreKey { func memStoreKeys() map[string]*sdk.MemoryStoreKey { return sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) - } diff --git a/app/export.go b/app/export.go index e476ec61f..d1267e5bb 100644 --- a/app/export.go +++ b/app/export.go @@ -2,6 +2,7 @@ package app import ( "encoding/json" + servertypes "github.com/cosmos/cosmos-sdk/server/types" sdk "github.com/cosmos/cosmos-sdk/types" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" @@ -103,7 +104,6 @@ func (app *SecretNetworkApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllow // reinitialize all validators app.stakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { - // donate any unwithdrawn outstanding reward fraction tokens to the community pool scraps := app.distrKeeper.GetValidatorOutstandingRewardsCoins(ctx, val.GetOperator()) feePool := app.distrKeeper.GetFeePool(ctx) diff --git a/app/legacy/migrate.go b/app/legacy/migrate.go index 170ea8471..53cafd533 100644 --- a/app/legacy/migrate.go +++ b/app/legacy/migrate.go @@ -3,10 +3,11 @@ package legacy import ( "encoding/json" "fmt" - "github.com/cosmos/cosmos-sdk/x/authz" "io/ioutil" "time" + "github.com/cosmos/cosmos-sdk/x/authz" + "github.com/pkg/errors" "github.com/spf13/cobra" tmjson "github.com/tendermint/tendermint/libs/json" diff --git a/app/legacy/v120/migrate.go b/app/legacy/v120/migrate.go index c3409b114..1654f15aa 100644 --- a/app/legacy/v120/migrate.go +++ b/app/legacy/v120/migrate.go @@ -2,6 +2,7 @@ package legacy import ( "fmt" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" diff --git a/app/upgrades/v1.3/upgrades.go b/app/upgrades/v1.3/upgrades.go index 283f6bef5..41af2fca0 100644 --- a/app/upgrades/v1.3/upgrades.go +++ b/app/upgrades/v1.3/upgrades.go @@ -15,7 +15,6 @@ const UpgradeName = "v1.3" func CreateUpgradeHandler(mm *module.Manager, icamodule *icamodule.AppModule, configurator module.Configurator, ) upgradetypes.UpgradeHandler { return func(ctx sdk.Context, _ upgradetypes.Plan, vm module.VersionMap) (module.VersionMap, error) { - // Assaf: Set version map for all modules because for some // reason it's not already set in upgradekeepr. // We upgrade from cosmos-sdk v0.44.5 to v0.45.4 and ibc-go v1.1.5 to v3.0.0 diff --git a/cmd/secretd/attestation.go b/cmd/secretd/attestation.go index 71be2f7d7..a9bc95ce9 100644 --- a/cmd/secretd/attestation.go +++ b/cmd/secretd/attestation.go @@ -9,6 +9,12 @@ import ( "encoding/hex" "encoding/json" "fmt" + "io/ioutil" + "log" + "net/http" + "os" + "path/filepath" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" @@ -19,25 +25,25 @@ import ( reg "github.com/enigmampc/SecretNetwork/x/registration" ra "github.com/enigmampc/SecretNetwork/x/registration/remote_attestation" "github.com/spf13/cobra" - "io/ioutil" - "log" - "net/http" - "os" - "path/filepath" ) -const flagReset = "reset" -const flagPulsar = "pulsar" -const flagCustomRegistrationService = "registration-service" +const ( + flagReset = "reset" + flagPulsar = "pulsar" + flagCustomRegistrationService = "registration-service" +) -const flagLegacyRegistrationNode = "registration-node" -const flagLegacyBootstrapNode = "node" +const ( + flagLegacyRegistrationNode = "registration-node" + flagLegacyBootstrapNode = "node" +) -const mainnetRegistrationService = "https://mainnet-register.scrtlabs.com/api/registernode" -const pulsarRegistrationService = "https://testnet-register.scrtlabs.com/api/registernode" +const ( + mainnetRegistrationService = "https://mainnet-register.scrtlabs.com/api/registernode" + pulsarRegistrationService = "https://testnet-register.scrtlabs.com/api/registernode" +) func InitAttestation() *cobra.Command { - cmd := &cobra.Command{ Use: "init-enclave [output-file]", Short: "Perform remote attestation of the enclave", @@ -47,7 +53,6 @@ blockchain. Writes the certificate in DER format to ~/attestation_cert `, Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { - sgxSecretsDir := os.Getenv("SCRT_SGX_STORAGE") if sgxSecretsDir == "" { sgxSecretsDir = os.ExpandEnv("/opt/secret/.sgx_secrets") @@ -55,7 +60,7 @@ blockchain. Writes the certificate in DER format to ~/attestation_cert // create sgx secrets dir if it doesn't exist if _, err := os.Stat(sgxSecretsDir); !os.IsNotExist(err) { - err := os.MkdirAll(sgxSecretsDir, 0777) + err := os.MkdirAll(sgxSecretsDir, 0o777) if err != nil { return err } @@ -109,7 +114,6 @@ blockchain. Writes the certificate in DER format to ~/attestation_cert } func InitBootstrapCmd() *cobra.Command { - cmd := &cobra.Command{ Use: "init-bootstrap [node-exchange-file] [io-exchange-file]", Short: "Perform bootstrap initialization", @@ -224,7 +228,6 @@ func ParseCert() *cobra.Command { "register the node, during node initialization", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - // parse coins trying to be sent cert, err := ioutil.ReadFile(args[0]) if err != nil { @@ -251,7 +254,6 @@ func ConfigureSecret() *cobra.Command { "seed that was written on-chain", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - cert, err := ioutil.ReadFile(args[0]) if err != nil { return err @@ -287,7 +289,7 @@ func ConfigureSecret() *cobra.Command { seedFilePath := filepath.Join(nodeDir, reg.SecretNodeSeedConfig) - err = ioutil.WriteFile(seedFilePath, cfgBytes, 0664) + err = ioutil.WriteFile(seedFilePath, cfgBytes, 0o664) if err != nil { return err } @@ -306,7 +308,6 @@ func HealthCheck() *cobra.Command { Long: "Help diagnose issues by performing a basic sanity test that SGX is working properly", Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { - res, err := api.HealthCheck() if err != nil { return fmt.Errorf("failed to start enclave. Enclave returned: %s", err) @@ -328,7 +329,6 @@ func ResetEnclave() *cobra.Command { "You will have to go through registration again to be able to start the node", Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { - homeDir, err := cmd.Flags().GetString(flags.FlagHome) if err != nil { return err @@ -359,7 +359,7 @@ func ResetEnclave() *cobra.Command { if err != nil { return err } - err := os.MkdirAll(sgxSecretsDir, 0777) + err := os.MkdirAll(sgxSecretsDir, 0o777) if err != nil { return err } @@ -393,7 +393,6 @@ type ErrorResponse struct { // AutoRegisterNode *** EXPERIMENTAL *** func AutoRegisterNode() *cobra.Command { - cmd := &cobra.Command{ Use: "auto-register", Short: "Perform remote attestation of the enclave", @@ -402,7 +401,6 @@ Please report any issues with this command `, Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { - sgxSecretsFolder := os.Getenv("SCRT_SGX_STORAGE") if sgxSecretsFolder == "" { sgxSecretsFolder = os.ExpandEnv("/opt/secret/.sgx_secrets") @@ -552,7 +550,7 @@ Please report any issues with this command // create seed directory if it doesn't exist _, err = os.Stat(seedCfgDir) if os.IsNotExist(err) { - err = os.MkdirAll(seedCfgDir, 0777) + err = os.MkdirAll(seedCfgDir, 0o777) if err != nil { return fmt.Errorf("failed to create directory '%s': %w", seedCfgDir, err) } @@ -561,7 +559,7 @@ Please report any issues with this command // write seed to file - if file doesn't exist, write it. If it does, delete the existing one and create this _, err = os.Stat(seedCfgFile) if os.IsNotExist(err) { - err = ioutil.WriteFile(seedCfgFile, cfgBytes, 0644) + err = ioutil.WriteFile(seedCfgFile, cfgBytes, 0o644) if err != nil { return err } @@ -571,7 +569,7 @@ Please report any issues with this command return fmt.Errorf("failed to modify file '%s': %w", seedCfgFile, err) } - err = ioutil.WriteFile(seedCfgFile, cfgBytes, 0644) + err = ioutil.WriteFile(seedCfgFile, cfgBytes, 0o644) if err != nil { return fmt.Errorf("failed to create file '%s': %w", seedCfgFile, err) } diff --git a/cmd/secretd/cli_attestation.go b/cmd/secretd/cli_attestation.go index 143b4cefb..3fcecb04c 100644 --- a/cmd/secretd/cli_attestation.go +++ b/cmd/secretd/cli_attestation.go @@ -1,3 +1,4 @@ +//go:build secretcli // +build secretcli package main @@ -9,7 +10,6 @@ import ( const flagReset = "reset" func InitAttestation() *cobra.Command { - cmd := &cobra.Command{ Use: "init-enclave [output-file]", Short: "Perform remote attestation of the enclave", @@ -29,7 +29,6 @@ blockchain. Writes the certificate in DER format to ~/attestation_cert } func InitBootstrapCmd() *cobra.Command { - cmd := &cobra.Command{ Use: "init-bootstrap [node-exchange-file] [io-exchange-file]", Short: "Perform bootstrap initialization", diff --git a/cmd/secretd/genaccounts.go b/cmd/secretd/genaccounts.go index f9ec63813..e4bf9b8c7 100644 --- a/cmd/secretd/genaccounts.go +++ b/cmd/secretd/genaccounts.go @@ -4,6 +4,7 @@ import ( "bufio" "encoding/json" "fmt" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/crypto/keyring" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -30,7 +31,6 @@ const ( // AddGenesisAccountCmd returns add-genesis-account cobra Command. func AddGenesisAccountCmd(defaultNodeHome string) *cobra.Command { - cmd := &cobra.Command{ Use: "add-genesis-account [address_or_key_name] [coin][,[coin]]", Short: "Add a genesis account to genesis.json", @@ -183,11 +183,11 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa } cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") - //cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|kwallet|pass|test)") - //cmd.Flags().String(flagClientHome, defaultClientHome, "client's home directory") - //cmd.Flags().String(flagVestingAmt, "", "amount of coins for vesting accounts") - //cmd.Flags().Uint64(flagVestingStart, 0, "schedule start time (unix epoch) for vesting accounts") - //cmd.Flags().Uint64(flagVestingEnd, 0, "schedule end time (unix epoch) for vesting accounts") + // cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|kwallet|pass|test)") + // cmd.Flags().String(flagClientHome, defaultClientHome, "client's home directory") + // cmd.Flags().String(flagVestingAmt, "", "amount of coins for vesting accounts") + // cmd.Flags().Uint64(flagVestingStart, 0, "schedule start time (unix epoch) for vesting accounts") + // cmd.Flags().Uint64(flagVestingEnd, 0, "schedule end time (unix epoch) for vesting accounts") flags.AddQueryFlagsToCmd(cmd) return cmd diff --git a/cmd/secretd/init.go b/cmd/secretd/init.go index a96665263..58c1f4225 100644 --- a/cmd/secretd/init.go +++ b/cmd/secretd/init.go @@ -92,7 +92,7 @@ func InitCmd(mbm module.BasicManager, defaultNodeHome string) *cobra.Command { "ab6394e953e0b570bb1deeb5a8b387aa0dc6188a@scrt-seed-02.scrtlabs.com:26656", // SCRT Labs 2 "9cdaa5856e0245ecd73bd464308fb990fbc53b57@scrt-seed-03.scrtlabs.com:26656", // SCRT Labs 3 } - //Override default settings in config.toml + // Override default settings in config.toml config.P2P.Seeds = strings.Join(seeds[:], ",") } diff --git a/cmd/secretd/root.go b/cmd/secretd/root.go index 5cad82256..01db0b558 100644 --- a/cmd/secretd/root.go +++ b/cmd/secretd/root.go @@ -50,8 +50,11 @@ import ( // thanks @terra-project for this fix const flagLegacyHdPath = "legacy-hd-path" -const flagIsBootstrap = "bootstrap" -const cfgFileName = "config.toml" + +const ( + flagIsBootstrap = "bootstrap" + cfgFileName = "config.toml" +) var bootstrap bool @@ -91,7 +94,7 @@ func NewRootCmd() (*cobra.Command, app.EncodingConfig) { WithLegacyAmino(encodingConfig.Amino). WithInput(os.Stdin). WithAccountRetriever(types.AccountRetriever{}). - //WithBroadcastMode(flags.BroadcastBlock). + // WithBroadcastMode(flags.BroadcastBlock). WithHomeDir(app.DefaultNodeHome). WithViper("SECRET") @@ -118,12 +121,12 @@ func NewRootCmd() (*cobra.Command, app.EncodingConfig) { secretAppTemplate, secretAppConfig := initAppConfig() - //ctx := server.GetServerContextFromCmd(cmd) + // ctx := server.GetServerContextFromCmd(cmd) - //bindFlags(cmd, ctx.Viper) + // bindFlags(cmd, ctx.Viper) return server.InterceptConfigsPreRunHandler(cmd, secretAppTemplate, secretAppConfig) - //return initConfig(&initClientCtx, cmd) + // return initConfig(&initClientCtx, cmd) }, SilenceUsage: true, } @@ -157,7 +160,7 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig app.EncodingConfig) { rootCmd.AddCommand( InitCmd(app.ModuleBasics(), app.DefaultNodeHome), - //updateTmParamsAndInit(app.ModuleBasics(), app.DefaultNodeHome), + // updateTmParamsAndInit(app.ModuleBasics(), app.DefaultNodeHome), genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome), secretlegacy.MigrateGenesisCmd(), genutilcli.GenTxCmd(app.ModuleBasics(), encodingConfig.TxConfig, banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome), @@ -245,7 +248,7 @@ func txCommand() *cobra.Command { authcmd.GetEncodeCommand(), authcmd.GetDecodeCommand(), flags.LineBreak, - //vestingcli.GetTxCmd(), + // vestingcli.GetTxCmd(), S20GetTxCmd(), ) @@ -310,7 +313,6 @@ func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts serverty func exportAppStateAndTMValidators( logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailWhiteList []string, appOpts servertypes.AppOptions, ) (servertypes.ExportedApp, error) { - bootstrap := viper.GetBool("bootstrap") encCfg := app.MakeEncodingConfig() @@ -361,7 +363,6 @@ func initConfig(ctx *client.Context, cmd *cobra.Command) error { cmd.PersistentFlags().Bool(flagLegacyHdPath, false, "Flag to specify the command uses old HD path - use this for ledger compatibility") _, err := cmd.PersistentFlags().GetBool(flagLegacyHdPath) - if err != nil { return err } diff --git a/cmd/secretd/secret20.go b/cmd/secretd/secret20.go index cea3e5589..3a5663de7 100644 --- a/cmd/secretd/secret20.go +++ b/cmd/secretd/secret20.go @@ -6,6 +6,9 @@ import ( "encoding/json" "errors" "fmt" + "strconv" + "strings" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" sdk "github.com/cosmos/cosmos-sdk/types" @@ -13,12 +16,12 @@ import ( "github.com/enigmampc/SecretNetwork/x/compute/client/cli" "github.com/spf13/cobra" "github.com/spf13/viper" - "strconv" - "strings" ) -const MessageBlockSize = 256 -const flagAmount = "amount" +const ( + MessageBlockSize = 256 + flagAmount = "amount" +) // S20GetQueryCmd GetQueryCmd returns the cli query commands for this module func S20GetQueryCmd() *cobra.Command { @@ -69,7 +72,6 @@ func S20TransferHistoryCmd() *cobra.Command { Long: `Print out transfer you have been a part of - either as a sender or recipient`, Args: cobra.RangeArgs(3, 5), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientQueryContext(cmd) contractAddr, err := addressFromBechOrLabel(args[0], cliCtx) @@ -129,7 +131,6 @@ func S20TransactionHistoryCmd() *cobra.Command { Unlike the transfers query, this query shows all kinds of transactions with the contract.`, Args: cobra.RangeArgs(3, 5), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientQueryContext(cmd) contractAddr, err := addressFromBechOrLabel(args[0], cliCtx) @@ -189,7 +190,6 @@ func S20BalanceCmd() *cobra.Command { key yet, use the "create-viewing-key" command. Otherwise, you can still see your current balance using a raw transaction`, Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx, err := client.GetClientQueryContext(cmd) contractAddr, err := addressFromBechOrLabel(args[0], cliCtx) @@ -246,7 +246,6 @@ func s20TransferCmd() *cobra.Command { Long: `Transfer tokens to another address`, Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { - ////inBuf := bufio.NewReader(cmd.InOrStdin()) cliCtx, err := client.GetClientTxContext(cmd) @@ -288,8 +287,7 @@ func s20CreatingViewingKey() *cobra.Command { This way you can perform balance and transaction history queries without waiting for a transaction on-chain.`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - - //inBuf := bufio.NewReader(cmd.InOrStdin()) + // inBuf := bufio.NewReader(cmd.InOrStdin()) cliCtx, err := client.GetClientTxContext(cmd) contractAddr, err := addressFromBechOrLabel(args[0], cliCtx) @@ -327,8 +325,7 @@ func s20SetViewingKey() *cobra.Command { you're doing`, Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - - //inBuf := bufio.NewReader(cmd.InOrStdin()) + // inBuf := bufio.NewReader(cmd.InOrStdin()) cliCtx, err := client.GetClientTxContext(cmd) contractAddr, err := addressFromBechOrLabel(args[0], cliCtx) @@ -357,8 +354,7 @@ func s20DepositCmd() *cobra.Command { Long: `Convert your SCRT into a secret token. This command will only work if the token supports native currency conversion`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - - //inBuf := bufio.NewReader(cmd.InOrStdin()) + // inBuf := bufio.NewReader(cmd.InOrStdin()) cliCtx, err := client.GetClientTxContext(cmd) contractAddr, err := addressFromBechOrLabel(args[0], cliCtx) @@ -391,8 +387,7 @@ func s20Redeem() *cobra.Command { Long: `Convert your secret token back to SCRT. This command will only work if the token supports native currency conversion`, Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - - //inBuf := bufio.NewReader(cmd.InOrStdin()) + // inBuf := bufio.NewReader(cmd.InOrStdin()) cliCtx, err := client.GetClientTxContext(cmd) contractAddr, err := addressFromBechOrLabel(args[0], cliCtx) @@ -428,8 +423,7 @@ func s20SendCmd() *cobra.Command { If no callback provided, this is identical to 'transfer'.`, Args: cobra.RangeArgs(3, 4), RunE: func(cmd *cobra.Command, args []string) error { - - //inBuf := bufio.NewReader(cmd.InOrStdin()) + // inBuf := bufio.NewReader(cmd.InOrStdin()) cliCtx, err := client.GetClientTxContext(cmd) contractAddr, err := addressFromBechOrLabel(args[0], cliCtx) @@ -474,8 +468,7 @@ func s20BurnCmd() *cobra.Command { WARNING! This action is irreversible and permanent! use at your own risk`, Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - - //inBuf := bufio.NewReader(cmd.InOrStdin()) + // inBuf := bufio.NewReader(cmd.InOrStdin()) cliCtx, err := client.GetClientTxContext(cmd) contractAddr, err := addressFromBechOrLabel(args[0], cliCtx) diff --git a/go-cosmwasm/api/callbacks.go b/go-cosmwasm/api/callbacks.go index 97a7f5fc4..315c56d72 100644 --- a/go-cosmwasm/api/callbacks.go +++ b/go-cosmwasm/api/callbacks.go @@ -1,3 +1,4 @@ +//go:build !secretcli // +build !secretcli package api @@ -302,8 +303,10 @@ func cNext(ref C.iterator_t, gasMeter *C.gas_meter_t, usedGas *C.uint64_t, key * /***** GoAPI *******/ -type HumanizeAddress func([]byte) (string, uint64, error) -type CanonicalizeAddress func(string) ([]byte, uint64, error) +type ( + HumanizeAddress func([]byte) (string, uint64, error) + CanonicalizeAddress func(string) ([]byte, uint64, error) +) type GoAPI struct { HumanAddress HumanizeAddress diff --git a/go-cosmwasm/api/callbacks_cgo.go b/go-cosmwasm/api/callbacks_cgo.go index 98a453e96..d734cc73f 100644 --- a/go-cosmwasm/api/callbacks_cgo.go +++ b/go-cosmwasm/api/callbacks_cgo.go @@ -1,3 +1,4 @@ +//go:build !secretcli // +build !secretcli package api diff --git a/go-cosmwasm/api/callbacks_cgo_mock.go b/go-cosmwasm/api/callbacks_cgo_mock.go index 56ef5102c..cafb234be 100644 --- a/go-cosmwasm/api/callbacks_cgo_mock.go +++ b/go-cosmwasm/api/callbacks_cgo_mock.go @@ -1,3 +1,4 @@ +//go:build secretcli // +build secretcli package api diff --git a/go-cosmwasm/api/callbacks_mock.go b/go-cosmwasm/api/callbacks_mock.go index 9a72c3fdb..56bc58aee 100644 --- a/go-cosmwasm/api/callbacks_mock.go +++ b/go-cosmwasm/api/callbacks_mock.go @@ -1,3 +1,4 @@ +//go:build secretcli // +build secretcli package api diff --git a/go-cosmwasm/api/iterator.go b/go-cosmwasm/api/iterator.go index 0d2fe8e68..352cef898 100644 --- a/go-cosmwasm/api/iterator.go +++ b/go-cosmwasm/api/iterator.go @@ -1,8 +1,9 @@ package api import ( - dbm "github.com/tendermint/tm-db" "sync" + + dbm "github.com/tendermint/tm-db" ) // frame stores all Iterators for one contract diff --git a/go-cosmwasm/api/lib.go b/go-cosmwasm/api/lib.go index 41006acad..5beea91a9 100644 --- a/go-cosmwasm/api/lib.go +++ b/go-cosmwasm/api/lib.go @@ -19,13 +19,16 @@ import ( // nice aliases to the rust names type i32 = C.int32_t -type i64 = C.int64_t -type u64 = C.uint64_t -type u32 = C.uint32_t -type u8 = C.uint8_t -type u8_ptr = *C.uint8_t -type usize = C.uintptr_t -type cint = C.int + +type ( + i64 = C.int64_t + u64 = C.uint64_t + u32 = C.uint32_t + u8 = C.uint8_t + u8_ptr = *C.uint8_t + usize = C.uintptr_t + cint = C.int +) type Cache struct { ptr *C.cache_t @@ -267,7 +270,6 @@ func AnalyzeCode( defer runtime.KeepAlive(codeHash) errMsg := C.Buffer{} report, err := C.analyze_code(cache.ptr, cs, &errMsg) - if err != nil { return nil, errorWithMessage(err, errMsg) } diff --git a/go-cosmwasm/api/lib_mock.go b/go-cosmwasm/api/lib_mock.go index 94d304040..77facfb9b 100644 --- a/go-cosmwasm/api/lib_mock.go +++ b/go-cosmwasm/api/lib_mock.go @@ -77,7 +77,7 @@ func InitCache(dataDir string, supportedFeatures string, cacheSize uint64) (Cach } func ReleaseCache(cache Cache) { - //C.release_cache(cache.ptr) + // C.release_cache(cache.ptr) } func InitEnclaveRuntime(ModuleCacheSize uint8) error { diff --git a/go-cosmwasm/api/link_muslc.go b/go-cosmwasm/api/link_muslc.go index f3b7ed4ac..b829c62d1 100644 --- a/go-cosmwasm/api/link_muslc.go +++ b/go-cosmwasm/api/link_muslc.go @@ -1,3 +1,4 @@ +//go:build linux && muslc // +build linux,muslc package api diff --git a/go-cosmwasm/api/link_std.go b/go-cosmwasm/api/link_std.go index b5bd2e4d8..703122fb1 100644 --- a/go-cosmwasm/api/link_std.go +++ b/go-cosmwasm/api/link_std.go @@ -1,3 +1,4 @@ +//go:build !secretcli && linux && !muslc && !darwin // +build !secretcli,linux,!muslc,!darwin package api diff --git a/go-cosmwasm/api/memory.go b/go-cosmwasm/api/memory.go index 94859c445..5e8afe8be 100644 --- a/go-cosmwasm/api/memory.go +++ b/go-cosmwasm/api/memory.go @@ -1,3 +1,4 @@ +//go:build !secretcli // +build !secretcli package api @@ -63,7 +64,7 @@ func receiveVector(b C.Buffer) []byte { // Copy the contents of a vector that was allocated on the Rust side. // Unlike receiveVector, we do not free it, because it will be manually // freed on the Rust side after control returns to it. -//This should be used in places like callbacks from Rust to Go. +// This should be used in places like callbacks from Rust to Go. func receiveSlice(b C.Buffer) []byte { if bufIsNil(b) { return nil diff --git a/go-cosmwasm/cmd/main.go b/go-cosmwasm/cmd/main.go index 1b1856dc8..149d3ccf4 100644 --- a/go-cosmwasm/cmd/main.go +++ b/go-cosmwasm/cmd/main.go @@ -18,9 +18,8 @@ func main() { } fmt.Println("Loaded!") - os.MkdirAll("tmp", 0755) + os.MkdirAll("tmp", 0o755) wasmer, err := wasm.NewWasmer("tmp", "staking", 0, 15) - if err != nil { panic(err) } diff --git a/go-cosmwasm/types/queries.go b/go-cosmwasm/types/queries.go index f84d061ac..ca9c7b19b 100644 --- a/go-cosmwasm/types/queries.go +++ b/go-cosmwasm/types/queries.go @@ -250,8 +250,10 @@ type MintQuery struct { BondedRatio *MintingBondedRatioQuery `json:"bonded_ratio,omitempty"` } -type MintingBondedRatioQuery struct{} -type MintingInflationQuery struct{} +type ( + MintingBondedRatioQuery struct{} + MintingInflationQuery struct{} +) type MintingInflationResponse struct { InflationRate string `json:"inflation_rate"` @@ -319,7 +321,7 @@ func (d ProposalsResponse) MarshalJSON() ([]byte, error) { if len(d.Proposals) == 0 { return []byte("{\"proposals\": []}"), nil } - var raw = d.Proposals + raw := d.Proposals asBytes, err := json.Marshal(raw) if err != nil { return nil, err diff --git a/go-cosmwasm/types/queries_test.go b/go-cosmwasm/types/queries_test.go index 861b507e3..ebaca168f 100644 --- a/go-cosmwasm/types/queries_test.go +++ b/go-cosmwasm/types/queries_test.go @@ -2,9 +2,10 @@ package types import ( "encoding/json" + "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "testing" ) func TestDelegationWithEmptyArray(t *testing.T) { diff --git a/go-cosmwasm/types/systemerror.go b/go-cosmwasm/types/systemerror.go index bdfd6639e..064c9ae18 100644 --- a/go-cosmwasm/types/systemerror.go +++ b/go-cosmwasm/types/systemerror.go @@ -7,12 +7,12 @@ import ( // SystemError captures all errors returned from the Rust code as SystemError. // Exactly one of the fields should be set. type SystemError struct { - InvalidRequest *InvalidRequest `json:"invalid_request,omitempty"` - InvalidResponse *InvalidResponse `json:"invalid_response,omitempty"` - NoSuchContract *NoSuchContract `json:"no_such_contract,omitempty"` - Unknown *Unknown `json:"unknown,omitempty"` - UnsupportedRequest *UnsupportedRequest `json:"unsupported_request,omitempty"` - ExceededRecursionLimit *ExceededRecursionLimit `json:"exceeded_recursion_limit,omitempty"` + InvalidRequest *InvalidRequest `json:"invalid_request,omitempty"` + InvalidResponse *InvalidResponse `json:"invalid_response,omitempty"` + NoSuchContract *NoSuchContract `json:"no_such_contract,omitempty"` + Unknown *Unknown `json:"unknown,omitempty"` + UnsupportedRequest *UnsupportedRequest `json:"unsupported_request,omitempty"` + ExceededRecursionLimit *ExceededRecursionLimit `json:"exceeded_recursion_limit,omitempty"` } var ( diff --git a/types/util/prefix.go b/types/util/prefix.go index 06b08fdd7..61129d056 100644 --- a/types/util/prefix.go +++ b/types/util/prefix.go @@ -19,13 +19,11 @@ const ( CoinPurpose = 44 ) -var ( - // AddressVerifier secret address verifier - AddressVerifier = func(bz []byte) error { - if n := len(bz); n != 20 { - return fmt.Errorf("incorrect address length %d", n) - } - - return nil +// AddressVerifier secret address verifier +var AddressVerifier = func(bz []byte) error { + if n := len(bz); n != 20 { + return fmt.Errorf("incorrect address length %d", n) } -) + + return nil +} diff --git a/x/compute/client/cli/query.go b/x/compute/client/cli/query.go index 7f29ad06e..a718cd027 100644 --- a/x/compute/client/cli/query.go +++ b/x/compute/client/cli/query.go @@ -7,14 +7,13 @@ import ( "encoding/json" "errors" "fmt" + "io/ioutil" + "strconv" "github.com/gogo/protobuf/proto" authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" - "io/ioutil" - "strconv" - sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" cosmwasmTypes "github.com/enigmampc/SecretNetwork/go-cosmwasm/types" flag "github.com/spf13/pflag" @@ -219,7 +218,7 @@ func GetCmdQueryCode() *cobra.Command { } fmt.Printf("Downloading wasm code to %s\n", args[1]) - return ioutil.WriteFile(args[1], code.Data, 0644) + return ioutil.WriteFile(args[1], code.Data, 0o644) }, } @@ -558,7 +557,6 @@ func QueryWithData(contractAddress sdk.AccAddress, queryData []byte, cliCtx clie nonce := queryData[:32] res, _, err := cliCtx.QueryWithData(route, queryData) - if err != nil { if types.ErrContainsQueryError(err) { errorPlainBz, err := wasmCtx.DecryptError(err.Error(), "query", nonce) diff --git a/x/compute/client/cli/tx.go b/x/compute/client/cli/tx.go index e502ae839..606cc6c07 100644 --- a/x/compute/client/cli/tx.go +++ b/x/compute/client/cli/tx.go @@ -48,9 +48,9 @@ func GetTxCmd() *cobra.Command { InstantiateContractCmd(), ExecuteContractCmd(), // Currently not supporting these commands - //MigrateContractCmd(cdc), - //UpdateContractAdminCmd(cdc), - //ClearContractAdminCmd(cdc), + // MigrateContractCmd(cdc), + // UpdateContractAdminCmd(cdc), + // ClearContractAdminCmd(cdc), ) return txCmd } diff --git a/x/compute/client/rest/tx.go b/x/compute/client/rest/tx.go index 33fc9479e..d630e09c9 100644 --- a/x/compute/client/rest/tx.go +++ b/x/compute/client/rest/tx.go @@ -1,11 +1,12 @@ package rest import ( - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/tx" "net/http" "strconv" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/tx" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/gorilla/mux" diff --git a/x/compute/client/utils/utils.go b/x/compute/client/utils/utils.go index dd865b417..a64041bfc 100644 --- a/x/compute/client/utils/utils.go +++ b/x/compute/client/utils/utils.go @@ -98,7 +98,7 @@ func (ctx WASMContext) GetTxSenderKeyPair() (privkey []byte, pubkey []byte, er e return nil, nil, err } - err = ioutil.WriteFile(keyPairFilePath, keyPairJSONBytes, 0644) + err = ioutil.WriteFile(keyPairFilePath, keyPairJSONBytes, 0o644) if err != nil { return nil, nil, err } diff --git a/x/compute/client/utils/utils_test.go b/x/compute/client/utils/utils_test.go index 0594a9a96..86f7ce67b 100644 --- a/x/compute/client/utils/utils_test.go +++ b/x/compute/client/utils/utils_test.go @@ -1,14 +1,14 @@ package utils import ( - "github.com/stretchr/testify/require" "io/ioutil" "testing" + + "github.com/stretchr/testify/require" ) func GetTestData() ([]byte, []byte, []byte, error) { wasmCode, err := ioutil.ReadFile("../../internal/keeper/testdata/contract.wasm") - if err != nil { return nil, nil, nil, err } @@ -46,8 +46,10 @@ func TestIsGzip(t *testing.T) { func TestGzipIt(t *testing.T) { wasmCode, someRandomStr, _, err := GetTestData() - originalGzipData := []byte{31, 139, 8, 0, 0, 0, 0, 0, 0, 255, 202, 72, 205, 201, 201, 87, 40, 207, 47, 202, 73, 1, - 4, 0, 0, 255, 255, 133, 17, 74, 13, 11, 0, 0, 0} + originalGzipData := []byte{ + 31, 139, 8, 0, 0, 0, 0, 0, 0, 255, 202, 72, 205, 201, 201, 87, 40, 207, 47, 202, 73, 1, + 4, 0, 0, 255, 255, 133, 17, 74, 13, 11, 0, 0, 0, + } require.NoError(t, err) diff --git a/x/compute/handler.go b/x/compute/handler.go index 5cd26b42e..71e56c7d4 100644 --- a/x/compute/handler.go +++ b/x/compute/handler.go @@ -122,7 +122,6 @@ func handleExecute(ctx sdk.Context, k Keeper, msg *MsgExecuteContract) (*sdk.Res msg.SentFunds, msg.CallbackSig, ) - if err != nil { return res, err } diff --git a/x/compute/internal/keeper/genesis.go b/x/compute/internal/keeper/genesis.go index f69866168..5be357ee6 100644 --- a/x/compute/internal/keeper/genesis.go +++ b/x/compute/internal/keeper/genesis.go @@ -46,7 +46,7 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) error if keeper.peekAutoIncrementID(ctx, types.KeyLastInstanceID) <= uint64(maxContractID) { return sdkerrors.Wrapf(types.ErrInvalid, "seq %s must be greater %d ", string(types.KeyLastInstanceID), maxContractID) } - //keeper.setParams(ctx, data.Params) + // keeper.setParams(ctx, data.Params) return nil } @@ -55,7 +55,7 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) error func ExportGenesis(ctx sdk.Context, keeper Keeper) *types.GenesisState { var genState types.GenesisState - //genState.Params = keeper.GetParams(ctx) + // genState.Params = keeper.GetParams(ctx) keeper.IterateCodeInfos(ctx, func(codeID uint64, info types.CodeInfo) bool { bytecode, err := keeper.GetByteCode(ctx, codeID) diff --git a/x/compute/internal/keeper/gov_test.go b/x/compute/internal/keeper/gov_test.go index 23e0509f6..dd3d72915 100644 --- a/x/compute/internal/keeper/gov_test.go +++ b/x/compute/internal/keeper/gov_test.go @@ -15,9 +15,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov/types" ) -var ( - TestProposal = types.NewTextProposal("Test", "description") -) +var TestProposal = types.NewTextProposal("Test", "description") type GovInitMsg struct{} diff --git a/x/compute/internal/keeper/handler_plugin.go b/x/compute/internal/keeper/handler_plugin.go index 59331beb8..f557fcffc 100644 --- a/x/compute/internal/keeper/handler_plugin.go +++ b/x/compute/internal/keeper/handler_plugin.go @@ -72,7 +72,8 @@ func NewMessageHandler( channelKeeper channelkeeper.Keeper, capabilityKeeper capabilitykeeper.ScopedKeeper, portSource types.ICS20TransferPortSource, - unpacker codectypes.AnyUnpacker) Messenger { + unpacker codectypes.AnyUnpacker, +) Messenger { encoders := DefaultEncoders(portSource, unpacker).Merge(customEncoders) return NewMessageHandlerChain( NewSDKMessageHandler(router, encoders), @@ -140,14 +141,16 @@ func (h IBCRawPacketHandler) DispatchMsg(ctx sdk.Context, _ sdk.AccAddress, cont return nil, nil, h.channelKeeper.SendPacket(ctx, channelCap, packet) } -type BankEncoder func(sender sdk.AccAddress, msg *v1wasmTypes.BankMsg) ([]sdk.Msg, error) -type CustomEncoder func(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) -type DistributionEncoder func(sender sdk.AccAddress, msg *v1wasmTypes.DistributionMsg) ([]sdk.Msg, error) -type GovEncoder func(sender sdk.AccAddress, msg *v1wasmTypes.GovMsg) ([]sdk.Msg, error) -type IBCEncoder func(ctx sdk.Context, sender sdk.AccAddress, contractIBCPortID string, msg *v1wasmTypes.IBCMsg) ([]sdk.Msg, error) -type StakingEncoder func(sender sdk.AccAddress, msg *v1wasmTypes.StakingMsg) ([]sdk.Msg, error) -type StargateEncoder func(sender sdk.AccAddress, msg *v1wasmTypes.StargateMsg) ([]sdk.Msg, error) -type WasmEncoder func(sender sdk.AccAddress, msg *v1wasmTypes.WasmMsg) ([]sdk.Msg, error) +type ( + BankEncoder func(sender sdk.AccAddress, msg *v1wasmTypes.BankMsg) ([]sdk.Msg, error) + CustomEncoder func(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) + DistributionEncoder func(sender sdk.AccAddress, msg *v1wasmTypes.DistributionMsg) ([]sdk.Msg, error) + GovEncoder func(sender sdk.AccAddress, msg *v1wasmTypes.GovMsg) ([]sdk.Msg, error) + IBCEncoder func(ctx sdk.Context, sender sdk.AccAddress, contractIBCPortID string, msg *v1wasmTypes.IBCMsg) ([]sdk.Msg, error) + StakingEncoder func(sender sdk.AccAddress, msg *v1wasmTypes.StakingMsg) ([]sdk.Msg, error) + StargateEncoder func(sender sdk.AccAddress, msg *v1wasmTypes.StargateMsg) ([]sdk.Msg, error) + WasmEncoder func(sender sdk.AccAddress, msg *v1wasmTypes.WasmMsg) ([]sdk.Msg, error) +) type MessageEncoders struct { Bank BankEncoder @@ -524,7 +527,6 @@ func (h MessageHandler) DispatchMsg(ctx sdk.Context, contractAddr sdk.AccAddress ) for _, sdkMsg := range sdkMsgs { sdkEvents, sdkData, err := h.handleSdkMessage(ctx, contractAddr, sdkMsg) - if err != nil { data = append(data, sdkData) return nil, data, err @@ -536,7 +538,7 @@ func (h MessageHandler) DispatchMsg(ctx sdk.Context, contractAddr sdk.AccAddress return events, data, nil - //return nil, nil, sdkerrors.Wrap(types.ErrInvalidMsg, "Unknown variant of CosmosMsgVersion") + // return nil, nil, sdkerrors.Wrap(types.ErrInvalidMsg, "Unknown variant of CosmosMsgVersion") } func (h MessageHandler) handleSdkMessage(ctx sdk.Context, contractAddr sdk.Address, msg sdk.Msg) (sdk.Events, []byte, error) { diff --git a/x/compute/internal/keeper/handler_plugin_test.go b/x/compute/internal/keeper/handler_plugin_test.go index 38f4f81d1..7c7dc4eb7 100644 --- a/x/compute/internal/keeper/handler_plugin_test.go +++ b/x/compute/internal/keeper/handler_plugin_test.go @@ -282,5 +282,4 @@ func TestEncoding(t *testing.T) { } }) } - } diff --git a/x/compute/internal/keeper/ioutil.go b/x/compute/internal/keeper/ioutil.go index 640545e1c..e7906d1cc 100644 --- a/x/compute/internal/keeper/ioutil.go +++ b/x/compute/internal/keeper/ioutil.go @@ -3,9 +3,10 @@ package keeper import ( "bytes" "compress/gzip" - "github.com/enigmampc/SecretNetwork/x/compute/internal/types" "io" "io/ioutil" + + "github.com/enigmampc/SecretNetwork/x/compute/internal/types" ) // magic bytes to identify gzip. diff --git a/x/compute/internal/keeper/ioutil_test.go b/x/compute/internal/keeper/ioutil_test.go index a6d3c7ff4..8944cae5b 100644 --- a/x/compute/internal/keeper/ioutil_test.go +++ b/x/compute/internal/keeper/ioutil_test.go @@ -77,7 +77,6 @@ func TestUncompress(t *testing.T) { require.Equal(t, spec.expResult, r) }) } - } func asGzip(src string) []byte { diff --git a/x/compute/internal/keeper/keeper.go b/x/compute/internal/keeper/keeper.go index f886bfa79..ea7559963 100644 --- a/x/compute/internal/keeper/keeper.go +++ b/x/compute/internal/keeper/keeper.go @@ -74,7 +74,7 @@ type Keeper struct { queryGasLimit uint64 serviceRouter MsgServiceRouter // authZPolicy AuthorizationPolicy - //paramSpace subspace.Subspace + // paramSpace subspace.Subspace } // MsgServiceRouter expected MsgServiceRouter interface @@ -332,7 +332,6 @@ func V010MsgToV1SubMsg(contractAddress string, msg v010wasmTypes.CosmosMsg) (v1w Instantiate: msg.Wasm.Instantiate, }, } - } else if msg.Gov != nil { subMsg.Msg = v1wasmTypes.CosmosMsg{ Gov: &v1wasmTypes.GovMsg{ @@ -734,7 +733,6 @@ func (k Keeper) GetContractAddress(ctx sdk.Context, label string) sdk.AccAddress } func (k Keeper) GetContractHash(ctx sdk.Context, contractAddress sdk.AccAddress) []byte { - codeId := k.GetContractInfo(ctx, contractAddress).CodeID hash := k.GetCodeInfo(ctx, codeId).CodeHash @@ -766,13 +764,12 @@ func (k Keeper) setContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress, func (k Keeper) setContractCustomInfo(ctx sdk.Context, contractAddress sdk.AccAddress, contract *types.ContractCustomInfo) { store := ctx.KVStore(k.storeKey) store.Set(types.GetContractEnclaveKey(contractAddress), contract.EnclaveKey) - //println(fmt.Sprintf("Setting enclave key: %x: %x\n", types.GetContractEnclaveKey(contractAddress), contract.EnclaveKey)) + // println(fmt.Sprintf("Setting enclave key: %x: %x\n", types.GetContractEnclaveKey(contractAddress), contract.EnclaveKey)) store.Set(types.GetContractLabelPrefix(contract.Label), contractAddress) - //println(fmt.Sprintf("Setting label: %x: %x\n", types.GetContractLabelPrefix(contract.Label), contractAddress)) + // println(fmt.Sprintf("Setting label: %x: %x\n", types.GetContractLabelPrefix(contract.Label), contractAddress)) } func (k Keeper) IterateContractInfo(ctx sdk.Context, cb func(sdk.AccAddress, types.ContractInfo, types.ContractCustomInfo) bool) { - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.ContractKeyPrefix) iter := prefixStore.Iterator(nil, nil) for ; iter.Valid(); iter.Next() { @@ -780,8 +777,8 @@ func (k Keeper) IterateContractInfo(ctx sdk.Context, cb func(sdk.AccAddress, typ k.cdc.MustUnmarshal(iter.Value(), &contract) enclaveId := ctx.KVStore(k.storeKey).Get(types.GetContractEnclaveKey(iter.Key())) - //println(fmt.Sprintf("Setting enclave key: %x: %x\n", types.GetContractEnclaveKey(iter.Key()), enclaveId)) - //println(fmt.Sprintf("Setting label: %x: %x\n", types.GetContractLabelPrefix(contract.Label), contract.Label)) + // println(fmt.Sprintf("Setting enclave key: %x: %x\n", types.GetContractEnclaveKey(iter.Key()), enclaveId)) + // println(fmt.Sprintf("Setting label: %x: %x\n", types.GetContractLabelPrefix(contract.Label), contract.Label)) contractCustomInfo := types.ContractCustomInfo{ EnclaveKey: enclaveId, @@ -942,7 +939,6 @@ func contractAddress(codeID, instanceID uint64) sdk.AccAddress { // overflow 32 bits. This is highly improbable, but something that could be refactored. contractID := codeID<<32 + instanceID return addrFromUint64(contractID) - } func (k Keeper) GetNextCodeID(ctx sdk.Context) uint64 { @@ -1078,7 +1074,7 @@ func (k Keeper) reply(ctx sdk.Context, contractAddress sdk.AccAddress, reply v1w // instantiate wasm contract gas := gasForContract(ctx) marshaledReply, error := json.Marshal(reply) - //marshaledReply = append(replyToContractHash, marshaledReply...) + // marshaledReply = append(replyToContractHash, marshaledReply...) marshaledReply = append(ogTx[0:64], marshaledReply...) if error != nil { @@ -1110,5 +1106,4 @@ func (k Keeper) reply(ctx sdk.Context, contractAddress sdk.AccAddress, reply v1w default: return nil, sdkerrors.Wrap(types.ErrReplyFailed, fmt.Sprintf("cannot detect response type: %+v", res)) } - } diff --git a/x/compute/internal/keeper/keeper_test.go b/x/compute/internal/keeper/keeper_test.go index e13a51584..58a7cf179 100644 --- a/x/compute/internal/keeper/keeper_test.go +++ b/x/compute/internal/keeper/keeper_test.go @@ -279,7 +279,7 @@ func TestIsSimulationMode(t *testing.T) { } for msg := range specs { t.Run(msg, func(t *testing.T) { - //require.Equal(t, spec.exp, isSimulationMode(spec.ctx)) + // require.Equal(t, spec.exp, isSimulationMode(spec.ctx)) }) } } @@ -596,7 +596,7 @@ func TestExecute(t *testing.T) { initMsgBz, err := json.Marshal(initMsg) key := keeper.GetCodeInfo(ctx, contractID).CodeHash - //keyStr := hex.EncodeToString(key) + // keyStr := hex.EncodeToString(key) msg := types.SecretMsg{ CodeHash: []byte(hex.EncodeToString(key)), @@ -647,12 +647,12 @@ func TestExecute(t *testing.T) { gasBefore = ctx.GasMeter().GasConsumed() require.NoError(t, err) - //res, _, _, err := execHelper(t, keeper, trialCtx, addr, creator, `{"release":{}}`, true, false, defaultGasForTests) + // res, _, _, err := execHelper(t, keeper, trialCtx, addr, creator, `{"release":{}}`, true, false, defaultGasForTests) initMsgBz = []byte(`{"release":{}}`) key = keeper.GetCodeInfo(ctx, contractID).CodeHash - //keyStr := hex.EncodeToString(key) + // keyStr := hex.EncodeToString(key) msg = types.SecretMsg{ CodeHash: []byte(hex.EncodeToString(key)), diff --git a/x/compute/internal/keeper/legacy_querier.go b/x/compute/internal/keeper/legacy_querier.go index 5269b8af7..949c7e9c1 100644 --- a/x/compute/internal/keeper/legacy_querier.go +++ b/x/compute/internal/keeper/legacy_querier.go @@ -21,7 +21,7 @@ const ( QueryContractAddress = "label" QueryContractKey = "contract-key" QueryContractHash = "contract-hash" - //QueryContractHistory = "contract-history" + // QueryContractHistory = "contract-history" ) const QueryMethodContractStateSmart = "smart" @@ -106,7 +106,7 @@ func NewLegacyQuerier(keeper Keeper) sdk.Querier { return nil, nil } - //bz, err = keeper.legacyAmino.MarshalJSON(rsp) + // bz, err = keeper.legacyAmino.MarshalJSON(rsp) bz, err = json.MarshalIndent(rsp, "", " ") if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) @@ -159,5 +159,4 @@ func queryContractState(ctx sdk.Context, bech, queryMethod string, data []byte, } return bz, nil */ - } diff --git a/x/compute/internal/keeper/param_verification_test.go b/x/compute/internal/keeper/param_verification_test.go index 146b9f3d3..37a253f74 100644 --- a/x/compute/internal/keeper/param_verification_test.go +++ b/x/compute/internal/keeper/param_verification_test.go @@ -78,6 +78,7 @@ func multisigTxCreator( signModeHandler := multisigTxCreatorForExisting(t, ctx, multisigAccount, signers, actualSigners, sdkMsg) return signModeHandler, signers, multisigAccount } + func multisigTxCreatorForExisting( t *testing.T, ctx *sdk.Context, multisigAccount Account, signers []Account, actualSigners int, sdkMsg sdk.Msg, ) authsigning.SignModeHandler { @@ -803,7 +804,7 @@ func TestInvalidKeyType(t *testing.T) { initMsgBz, err := wasmCtx.Encrypt(msg.Serialize()) require.NoError(t, err) - //nonce := initMsgBz[0:32] + // nonce := initMsgBz[0:32] sdkMsg := types.MsgInstantiateContract{ Sender: edAddr, diff --git a/x/compute/internal/keeper/querier.go b/x/compute/internal/keeper/querier.go index 494330fa5..5a30da3cf 100644 --- a/x/compute/internal/keeper/querier.go +++ b/x/compute/internal/keeper/querier.go @@ -118,7 +118,6 @@ func (q GrpcQuerier) SmartContractState(c context.Context, req *types.QuerySmart return nil, types.ErrNotFound } return &types.QuerySmartContractStateResponse{Data: rsp}, nil - } func (q GrpcQuerier) Code(c context.Context, req *types.QueryCodeRequest) (*types.QueryCodeResponse, error) { @@ -159,7 +158,6 @@ func (q GrpcQuerier) AddressByLabel(c context.Context, req *types.QueryContractA return nil, types.ErrNotFound } return &types.QueryContractAddressByLabelResponse{Address: rsp}, nil - } func (q GrpcQuerier) ContractKey(c context.Context, req *types.QueryContractKeyRequest) (*types.QueryContractKeyResponse, error) { @@ -175,7 +173,6 @@ func (q GrpcQuerier) ContractKey(c context.Context, req *types.QueryContractKeyR return nil, types.ErrNotFound } return &types.QueryContractKeyResponse{Key: rsp}, nil - } func (q GrpcQuerier) ContractHash(c context.Context, req *types.QueryContractHashRequest) (*types.QueryContractHashResponse, error) { @@ -191,7 +188,6 @@ func (q GrpcQuerier) ContractHash(c context.Context, req *types.QueryContractHas return nil, types.ErrNotFound } return &types.QueryContractHashResponse{CodeHash: rsp}, nil - } func queryContractInfo(ctx sdk.Context, addr sdk.AccAddress, keeper Keeper) (*types.ContractInfoWithAddress, error) { diff --git a/x/compute/internal/keeper/querier_test.go b/x/compute/internal/keeper/querier_test.go index f0f4f2c34..e92d834a3 100644 --- a/x/compute/internal/keeper/querier_test.go +++ b/x/compute/internal/keeper/querier_test.go @@ -92,7 +92,7 @@ func TestQueryContractLabel(t *testing.T) { for msg, spec := range specs { t.Run(msg, func(t *testing.T) { - //binResult, err := q(ctx, spec.srcPath, spec.srcReq) + // binResult, err := q(ctx, spec.srcPath, spec.srcReq) binResult, err := q(ctx, spec.srcPath, spec.srcReq) // require.True(t, spec.expErr.Is(err), "unexpected error") require.True(t, spec.expErr.Is(err), err) diff --git a/x/compute/internal/keeper/query_plugins.go b/x/compute/internal/keeper/query_plugins.go index fcd934322..66d201222 100644 --- a/x/compute/internal/keeper/query_plugins.go +++ b/x/compute/internal/keeper/query_plugins.go @@ -2,9 +2,10 @@ package keeper import ( "encoding/json" - "github.com/enigmampc/SecretNetwork/x/compute/internal/types" "strings" + "github.com/enigmampc/SecretNetwork/x/compute/internal/types" + "github.com/cosmos/cosmos-sdk/codec" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" @@ -171,7 +172,6 @@ func MintQuerier(keeper mintkeeper.Keeper) func(ctx sdk.Context, request *wasmTy } return nil, wasmTypes.UnsupportedRequest{Kind: "unknown MintQuery variant"} } - } func DistQuerier(keeper distrkeeper.Keeper) func(ctx sdk.Context, request *wasmTypes.DistQuery) ([]byte, error) { @@ -278,7 +278,7 @@ func StakingQuerier(keeper stakingkeeper.Keeper, distKeeper distrkeeper.Keeper) } if request.Validators != nil { validators := keeper.GetBondedValidatorsByPower(ctx) - //validators := keeper.GetAllValidators(ctx) + // validators := keeper.GetAllValidators(ctx) wasmVals := make([]wasmTypes.Validator, len(validators)) for i, v := range validators { wasmVals[i] = wasmTypes.Validator{ @@ -360,7 +360,6 @@ func sdkToUnbondingDelegations(bondDenom string, delegations stakingtypes.Unbond result := make([]wasmTypes.Delegation, len(delegations)) for i, d := range delegations { - for _, e := range d.Entries { wasmCoin := wasmTypes.Coin{ @@ -375,7 +374,6 @@ func sdkToUnbondingDelegations(bondDenom string, delegations stakingtypes.Unbond } } - } return result, nil } diff --git a/x/compute/internal/keeper/reflect_test.go b/x/compute/internal/keeper/reflect_test.go index 4a9866760..6db764ebb 100644 --- a/x/compute/internal/keeper/reflect_test.go +++ b/x/compute/internal/keeper/reflect_test.go @@ -157,7 +157,6 @@ func TestMaskReflectContractSend(t *testing.T) { checkAccount(t, ctx, accKeeper, keeper.bankKeeper, maskAddr, sdk.NewCoins(sdk.NewInt64Coin("denom", 26000))) // 40k - 14k (from send) checkAccount(t, ctx, accKeeper, keeper.bankKeeper, escrowAddr, sdk.Coins{}) // emptied reserved checkAccount(t, ctx, accKeeper, keeper.bankKeeper, bob, sdk.NewCoins(sdk.NewInt64Coin("denom", 39000))) // all escrow of 25k + 14k - } func TestMaskReflectCustomMsg(t *testing.T) { @@ -428,7 +427,6 @@ func reflectPlugins() *QueryPlugins { } func performCustomQuery(_ sdk.Context, request json.RawMessage) ([]byte, error) { - var custom reflectCustomQuery err := json.Unmarshal(request, &custom) if err != nil { diff --git a/x/compute/internal/keeper/secret_contracts_test.go b/x/compute/internal/keeper/secret_contracts_test.go index 07cdc0485..a67da8404 100644 --- a/x/compute/internal/keeper/secret_contracts_test.go +++ b/x/compute/internal/keeper/secret_contracts_test.go @@ -1575,6 +1575,7 @@ func TestExternalQueryCalleePanic(t *testing.T) { }) } } + func TestExternalQueryCalleeStdError(t *testing.T) { for _, testContract := range testContracts { t.Run(testContract.CosmWasmVersion, func(t *testing.T) { @@ -1626,7 +1627,6 @@ func TestExternalQueryBadSenderABI(t *testing.T) { require.Equal(t, "test_contract::contract::QueryMsg", err.ParseErr.Target) require.Equal(t, "Invalid type", err.ParseErr.Msg) } - }) } } diff --git a/x/compute/internal/keeper/test_common.go b/x/compute/internal/keeper/test_common.go index 9007e7bad..f008fc1ad 100644 --- a/x/compute/internal/keeper/test_common.go +++ b/x/compute/internal/keeper/test_common.go @@ -93,8 +93,10 @@ import ( "github.com/enigmampc/SecretNetwork/x/registration" ) -const flagLRUCacheSize = "lru_size" -const flagQueryGasLimit = "query_gas_limit" +const ( + flagLRUCacheSize = "lru_size" + flagQueryGasLimit = "query_gas_limit" +) var _ wasmtypes.ICS20TransferPortSource = &MockIBCTransferKeeper{} @@ -122,16 +124,17 @@ var ModuleBasics = module.NewBasicManager( params.AppModuleBasic{}, crisis.AppModuleBasic{}, slashing.AppModuleBasic{}, - //ibc.AppModuleBasic{}, + // ibc.AppModuleBasic{}, upgrade.AppModuleBasic{}, evidence.AppModuleBasic{}, - //transfer.AppModuleBasic{}, + // transfer.AppModuleBasic{}, registration.AppModuleBasic{}, ) func MakeTestCodec() codec.Codec { return MakeEncodingConfig().Marshaler } + func MakeEncodingConfig() simappparams.EncodingConfig { amino := codec.NewLegacyAmino() interfaceRegistry := types.NewInterfaceRegistry() @@ -257,14 +260,14 @@ func CreateTestInput(t *testing.T, isCheckTx bool, supportedFeatures string, enc blockedAddrs, ) - //bankParams = bankParams.SetSendEnabledParam(sdk.DefaultBondDenom, true) + // bankParams = bankParams.SetSendEnabledParam(sdk.DefaultBondDenom, true) bankKeeper.SetParams(ctx, banktypes.DefaultParams()) stakingSubsp, _ := paramsKeeper.GetSubspace(stakingtypes.ModuleName) stakingKeeper := stakingkeeper.NewKeeper(encodingConfig.Marshaler, keyStaking, authKeeper, bankKeeper, stakingSubsp) stakingKeeper.SetParams(ctx, TestingStakeParams) - //mintSubsp, _ := paramsKeeper.GetSubspace(minttypes.ModuleName) + // mintSubsp, _ := paramsKeeper.GetSubspace(minttypes.ModuleName) //mintKeeper := mintkeeper.NewKeeper(encodingConfig.Marshaler, // keyBank, @@ -303,8 +306,8 @@ func CreateTestInput(t *testing.T, isCheckTx bool, supportedFeatures string, enc err = bankKeeper.MintCoins(ctx, faucetAccountName, totalSupply) require.NoError(t, err) - //err = bankKeeper.SendCoinsFromModuleToAccount(ctx, faucetAccountName, distrAcc.GetAddress(), totalSupply) - //require.NoError(t, err) + // err = bankKeeper.SendCoinsFromModuleToAccount(ctx, faucetAccountName, distrAcc.GetAddress(), totalSupply) + // require.NoError(t, err) notBondedPool := authtypes.NewEmptyModuleAccount(stakingtypes.NotBondedPoolName, authtypes.Burner, authtypes.Staking) bondPool := authtypes.NewEmptyModuleAccount(stakingtypes.BondedPoolName, authtypes.Burner, authtypes.Staking) @@ -330,14 +333,14 @@ func CreateTestInput(t *testing.T, isCheckTx bool, supportedFeatures string, enc AddRoute(govtypes.RouterKey, govtypes.ProposalHandler). AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(paramsKeeper)). AddRoute(distrtypes.RouterKey, distribution.NewCommunityPoolSpendProposalHandler(distKeeper)) - //AddRoute(wasmtypes.RouterKey, NewWasmProposalHandler(keeper, wasmtypes.EnableAllProposals)) + // AddRoute(wasmtypes.RouterKey, NewWasmProposalHandler(keeper, wasmtypes.EnableAllProposals)) govKeeper := govkeeper.NewKeeper( encodingConfig.Marshaler, keyGov, paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govtypes.ParamKeyTable()), authKeeper, bankKeeper, stakingKeeper, govRouter, ) // bank := bankKeeper. - //bk := bank.Keeper(bankKeeper) + // bk := bank.Keeper(bankKeeper) mintSubsp, _ := paramsKeeper.GetSubspace(minttypes.ModuleName) mintKeeper := mintkeeper.NewKeeper(encodingConfig.Marshaler, mintStore, mintSubsp, stakingKeeper, authKeeper, bankKeeper, authtypes.FeeCollectorName) @@ -390,17 +393,17 @@ func CreateTestInput(t *testing.T, isCheckTx bool, supportedFeatures string, enc ) // todo: new grpc routing - //serviceRouter := baseapp.NewMsgServiceRouter() + // serviceRouter := baseapp.NewMsgServiceRouter() - //serviceRouter.SetInterfaceRegistry(encodingConfig.InterfaceRegistry) - //bankMsgServer := bankkeeper.NewMsgServerImpl(bankKeeper) - //stakingMsgServer := stakingkeeper.NewMsgServerImpl(stakingKeeper) - //distrMsgServer := distrkeeper.NewMsgServerImpl(distKeeper) - //wasmMsgServer := NewMsgServerImpl(keeper) + // serviceRouter.SetInterfaceRegistry(encodingConfig.InterfaceRegistry) + // bankMsgServer := bankkeeper.NewMsgServerImpl(bankKeeper) + // stakingMsgServer := stakingkeeper.NewMsgServerImpl(stakingKeeper) + // distrMsgServer := distrkeeper.NewMsgServerImpl(distKeeper) + // wasmMsgServer := NewMsgServerImpl(keeper) - //banktypes.RegisterMsgServer(serviceRouter, bankMsgServer) - //stakingtypes.RegisterMsgServer(serviceRouter, stakingMsgServer) - //distrtypes.RegisterMsgServer(serviceRouter, distrMsgServer) + // banktypes.RegisterMsgServer(serviceRouter, bankMsgServer) + // stakingtypes.RegisterMsgServer(serviceRouter, stakingMsgServer) + // distrtypes.RegisterMsgServer(serviceRouter, distrMsgServer) keeper := NewKeeper( encodingConfig.Marshaler, @@ -424,7 +427,7 @@ func CreateTestInput(t *testing.T, isCheckTx bool, supportedFeatures string, enc encoders, queriers, ) - //keeper.setParams(ctx, wasmtypes.DefaultParams()) + // keeper.setParams(ctx, wasmtypes.DefaultParams()) // add wasm handler so we can loop-back (contracts calling contracts) router.AddRoute(sdk.NewRoute(wasmtypes.RouterKey, TestHandler(keeper))) diff --git a/x/compute/internal/keeper/test_fuzz.go b/x/compute/internal/keeper/test_fuzz.go index b345f2805..c5d625beb 100644 --- a/x/compute/internal/keeper/test_fuzz.go +++ b/x/compute/internal/keeper/test_fuzz.go @@ -1,8 +1,8 @@ package keeper import ( - "github.com/enigmampc/SecretNetwork/x/compute/internal/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/enigmampc/SecretNetwork/x/compute/internal/types" fuzz "github.com/google/gofuzz" tmBytes "github.com/tendermint/tendermint/libs/bytes" ) diff --git a/x/compute/internal/types/msg_test.go b/x/compute/internal/types/msg_test.go index 35f7db37c..3ab8fa108 100644 --- a/x/compute/internal/types/msg_test.go +++ b/x/compute/internal/types/msg_test.go @@ -31,13 +31,12 @@ func TestBuilderRegexp(t *testing.T) { assert.Error(t, err) } }) - } } func TestStoreCodeValidation(t *testing.T) { badAddress := sdk.AccAddress(make([]byte, 2000)) - //require.NoError(t, err) + // require.NoError(t, err) // proper address size goodAddress := sdk.AccAddress(make([]byte, 20)) @@ -239,7 +238,7 @@ func TestInstantiateContractValidation(t *testing.T) { func TestExecuteContractValidation(t *testing.T) { badAddress := sdk.AccAddress(make([]byte, 2000)) - //require.NoError(t, err) + // require.NoError(t, err) // proper address size goodAddress := sdk.AccAddress(make([]byte, 20)) diff --git a/x/compute/internal/types/types.go b/x/compute/internal/types/types.go index 456c941a9..b36c03854 100644 --- a/x/compute/internal/types/types.go +++ b/x/compute/internal/types/types.go @@ -15,9 +15,11 @@ import ( "github.com/spf13/cast" ) -const defaultLRUCacheSize = uint64(0) -const defaultEnclaveLRUCacheSize = uint8(0) // can safely go up to 15 -const defaultQueryGasLimit = uint64(10_000_000) +const ( + defaultLRUCacheSize = uint64(0) + defaultEnclaveLRUCacheSize = uint8(0) // can safely go up to 15 + defaultQueryGasLimit = uint64(10_000_000) +) // base64 of a 64 byte key type ContractKey string @@ -66,6 +68,7 @@ func NewContractInfo(codeID uint64, creator sdk.AccAddress, label string, create Created: createdAt, } } + func (c *ContractInfo) ValidateBasic() error { if c.CodeID == 0 { return sdkerrors.Wrap(ErrEmpty, "code id") diff --git a/x/mauth/keeper/keeper_test.go b/x/mauth/keeper/keeper_test.go index debda201f..1f57b1ec5 100644 --- a/x/mauth/keeper/keeper_test.go +++ b/x/mauth/keeper/keeper_test.go @@ -2,9 +2,10 @@ package keeper_test import ( "encoding/json" + "testing" + "github.com/cosmos/cosmos-sdk/simapp" "github.com/enigmampc/SecretNetwork/x/compute" - "testing" "github.com/stretchr/testify/suite" "github.com/tendermint/tendermint/crypto" diff --git a/x/mauth/keeper/msg_server_test.go b/x/mauth/keeper/msg_server_test.go index 8de620e90..262ddf14c 100644 --- a/x/mauth/keeper/msg_server_test.go +++ b/x/mauth/keeper/msg_server_test.go @@ -74,7 +74,6 @@ func (suite *KeeperTestSuite) TestRegisterInterchainAccount() { suite.Require().Error(err) suite.Require().Nil(res) } - }) } } diff --git a/x/mauth/types/msgs.go b/x/mauth/types/msgs.go index 634c5bce5..1eaaa96b1 100644 --- a/x/mauth/types/msgs.go +++ b/x/mauth/types/msgs.go @@ -75,9 +75,7 @@ func PackTxMsgAny(sdkMsg sdk.Msg) (*codectypes.Any, error) { // UnpackInterfaces implements codectypes.UnpackInterfacesMessage func (msg MsgSubmitTx) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - var ( - sdkMsg sdk.Msg - ) + var sdkMsg sdk.Msg return unpacker.UnpackAny(msg.Msg, &sdkMsg) } @@ -99,7 +97,6 @@ func (msg MsgSubmitTx) GetSigners() []sdk.AccAddress { // ValidateBasic implements sdk.Msg func (msg MsgSubmitTx) ValidateBasic() error { - if len(msg.Msg.GetValue()) == 0 { return fmt.Errorf("can't execute an empty msg") } diff --git a/x/registration/client/cli/query.go b/x/registration/client/cli/query.go index dd564b1eb..e879ddc49 100644 --- a/x/registration/client/cli/query.go +++ b/x/registration/client/cli/query.go @@ -90,12 +90,12 @@ func GetCmdMasterParams() *cobra.Command { return err } - err = ioutil.WriteFile(types.IoExchMasterCertPath, certs.IoMasterCertificate.Bytes, 0644) + err = ioutil.WriteFile(types.IoExchMasterCertPath, certs.IoMasterCertificate.Bytes, 0o644) if err != nil { return err } - err = ioutil.WriteFile(types.NodeExchMasterCertPath, certs.NodeExchMasterCertificate.Bytes, 0644) + err = ioutil.WriteFile(types.NodeExchMasterCertPath, certs.NodeExchMasterCertificate.Bytes, 0o644) if err != nil { return err } diff --git a/x/registration/client/cli/tx.go b/x/registration/client/cli/tx.go index e381b850c..5dc855267 100644 --- a/x/registration/client/cli/tx.go +++ b/x/registration/client/cli/tx.go @@ -1,12 +1,13 @@ package cli import ( + "io/ioutil" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/enigmampc/SecretNetwork/x/registration/internal/types" "github.com/spf13/cobra" - "io/ioutil" ) // GetTxCmd returns the transaction commands for this module @@ -31,7 +32,7 @@ func AuthenticateNodeCmd() *cobra.Command { Short: "Upload a certificate to authenticate the node", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - //clientCtx := client.GetClientContextFromCmd(cmd) + // clientCtx := client.GetClientContextFromCmd(cmd) clientCtx, err := client.GetClientTxContext(cmd) if err != nil { return err diff --git a/x/registration/client/rest/query.go b/x/registration/client/rest/query.go index d0c71ba1e..941a21bab 100644 --- a/x/registration/client/rest/query.go +++ b/x/registration/client/rest/query.go @@ -5,10 +5,11 @@ import ( "encoding/hex" "encoding/json" "fmt" + "net/http" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/types/rest" ra "github.com/enigmampc/SecretNetwork/x/registration/remote_attestation" - "net/http" "github.com/enigmampc/SecretNetwork/x/registration/internal/keeper" "github.com/enigmampc/SecretNetwork/x/registration/internal/types" @@ -168,7 +169,6 @@ func newArgDecoder(def func(string) ([]byte, error)) *argumentDecoder { } func (a *argumentDecoder) DecodeString(s string) ([]byte, error) { - switch a.encoding { case "hex": return hex.DecodeString(s) diff --git a/x/registration/client/rest/tx.go b/x/registration/client/rest/tx.go index f377c66e6..91c2abbb4 100644 --- a/x/registration/client/rest/tx.go +++ b/x/registration/client/rest/tx.go @@ -6,9 +6,9 @@ import ( ) func registerTxRoutes(cliCtx client.Context, r *mux.Router) { - //r.HandleFunc("/wasm/code", storeCodeHandlerFn(cliCtx)).Methods("POST") - //r.HandleFunc("/wasm/code/{codeId}", instantiateContractHandlerFn(cliCtx)).Methods("POST") - //r.HandleFunc("/wasm/contract/{contractAddr}", executeContractHandlerFn(cliCtx)).Methods("POST") + // r.HandleFunc("/wasm/code", storeCodeHandlerFn(cliCtx)).Methods("POST") + // r.HandleFunc("/wasm/code/{codeId}", instantiateContractHandlerFn(cliCtx)).Methods("POST") + // r.HandleFunc("/wasm/contract/{contractAddr}", executeContractHandlerFn(cliCtx)).Methods("POST") } // limit max bytes read to prevent gzip bombs diff --git a/x/registration/handler.go b/x/registration/handler.go index b365f90b7..32a1c3125 100644 --- a/x/registration/handler.go +++ b/x/registration/handler.go @@ -3,6 +3,7 @@ package registration import ( "encoding/hex" "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/enigmampc/SecretNetwork/x/registration/internal/types" diff --git a/x/registration/internal/keeper/genesis.go b/x/registration/internal/keeper/genesis.go index b92de2e08..d3600a20a 100644 --- a/x/registration/internal/keeper/genesis.go +++ b/x/registration/internal/keeper/genesis.go @@ -2,6 +2,7 @@ package keeper import ( "encoding/json" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/enigmampc/SecretNetwork/x/registration/internal/types" @@ -10,7 +11,6 @@ import ( // InitGenesis sets supply information for genesis. // func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) { - if data.IoMasterCertificate != nil && data.NodeExchMasterCertificate != nil { // keeper.setMasterPublicKey(ctx, data.MasterPublic) keeper.setMasterCertificate(ctx, *data.IoMasterCertificate, types.MasterIoKeyId) diff --git a/x/registration/internal/keeper/genesis_test.go b/x/registration/internal/keeper/genesis_test.go index 410aba057..99fd4dca9 100644 --- a/x/registration/internal/keeper/genesis_test.go +++ b/x/registration/internal/keeper/genesis_test.go @@ -1,12 +1,13 @@ package keeper import ( - "github.com/enigmampc/SecretNetwork/x/registration/internal/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "io/ioutil" "os" "testing" + + "github.com/enigmampc/SecretNetwork/x/registration/internal/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestInitGenesisNoMaster(t *testing.T) { diff --git a/x/registration/internal/keeper/keeper.go b/x/registration/internal/keeper/keeper.go index 6818ffdbe..3c49c55b1 100644 --- a/x/registration/internal/keeper/keeper.go +++ b/x/registration/internal/keeper/keeper.go @@ -5,13 +5,14 @@ import ( "encoding/hex" "encoding/json" "fmt" + "path/filepath" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/auth/legacy/legacytx" "github.com/enigmampc/SecretNetwork/x/registration/internal/types" ra "github.com/enigmampc/SecretNetwork/x/registration/remote_attestation" - "path/filepath" ) // Keeper will have a reference to Wasmer with it's own data directory. @@ -24,7 +25,6 @@ type Keeper struct { // NewKeeper creates a new contract Keeper instance func NewKeeper(cdc codec.BinaryCodec, storeKey sdk.StoreKey, router sdk.Router, enclave EnclaveInterface, homeDir string, bootstrap bool) Keeper { - if !bootstrap { InitializeNode(homeDir, enclave) } @@ -38,7 +38,6 @@ func NewKeeper(cdc codec.BinaryCodec, storeKey sdk.StoreKey, router sdk.Router, } func InitializeNode(homeDir string, enclave EnclaveInterface) { - seedPath := filepath.Join(homeDir, types.SecretNodeCfgFolder, types.SecretNodeSeedConfig) if !fileExists(seedPath) { diff --git a/x/registration/internal/keeper/keeper_test.go b/x/registration/internal/keeper/keeper_test.go index 0bbcc0f72..8ed51f22c 100644 --- a/x/registration/internal/keeper/keeper_test.go +++ b/x/registration/internal/keeper/keeper_test.go @@ -1,15 +1,16 @@ package keeper import ( + "io/ioutil" + "os" + "path/filepath" + "testing" + sdk "github.com/cosmos/cosmos-sdk/types" eng "github.com/enigmampc/SecretNetwork/types" "github.com/enigmampc/SecretNetwork/x/registration/internal/types" ra "github.com/enigmampc/SecretNetwork/x/registration/remote_attestation" "github.com/stretchr/testify/require" - "io/ioutil" - "os" - "path/filepath" - "testing" ) func init() { @@ -35,10 +36,10 @@ func TestNewKeeper_Node(t *testing.T) { seedPath := filepath.Join(tempDir, types.SecretNodeCfgFolder, types.SecretNodeSeedConfig) - err = os.MkdirAll(filepath.Join(tempDir, types.SecretNodeCfgFolder), 0700) + err = os.MkdirAll(filepath.Join(tempDir, types.SecretNodeCfgFolder), 0o700) require.NoError(t, err) - err = ioutil.WriteFile(seedPath, CreateTestSeedConfig(t), 0700) + err = ioutil.WriteFile(seedPath, CreateTestSeedConfig(t), 0o700) require.NoError(t, err) _, regKeeper := CreateTestInput(t, false, tempDir, false) @@ -89,5 +90,4 @@ func TestKeeper_RegisterNode(t *testing.T) { _, err = regKeeper.RegisterNode(ctx, cert) require.NoError(t, err) - } diff --git a/x/registration/internal/keeper/legacy_querier.go b/x/registration/internal/keeper/legacy_querier.go index a759eb065..c9b450eea 100644 --- a/x/registration/internal/keeper/legacy_querier.go +++ b/x/registration/internal/keeper/legacy_querier.go @@ -3,10 +3,11 @@ package keeper import ( "encoding/hex" "encoding/json" + "reflect" + sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" abci "github.com/tendermint/tendermint/abci/types" - "reflect" ) const ( diff --git a/x/registration/internal/keeper/querier.go b/x/registration/internal/keeper/querier.go index b60712707..36ddb4bdb 100644 --- a/x/registration/internal/keeper/querier.go +++ b/x/registration/internal/keeper/querier.go @@ -2,6 +2,7 @@ package keeper import ( "context" + "github.com/golang/protobuf/ptypes/empty" sdk "github.com/cosmos/cosmos-sdk/types" diff --git a/x/registration/internal/keeper/querier_test.go b/x/registration/internal/keeper/querier_test.go index c78ed835f..13034f152 100644 --- a/x/registration/internal/keeper/querier_test.go +++ b/x/registration/internal/keeper/querier_test.go @@ -5,13 +5,14 @@ package keeper import ( "encoding/hex" "encoding/json" - sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/enigmampc/SecretNetwork/x/registration/internal/types" - ra "github.com/enigmampc/SecretNetwork/x/registration/remote_attestation" "io/ioutil" "os" "testing" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/enigmampc/SecretNetwork/x/registration/internal/types" + ra "github.com/enigmampc/SecretNetwork/x/registration/remote_attestation" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" ) diff --git a/x/registration/internal/keeper/registration.go b/x/registration/internal/keeper/registration.go index 681e40f4c..735b0f44b 100644 --- a/x/registration/internal/keeper/registration.go +++ b/x/registration/internal/keeper/registration.go @@ -52,7 +52,7 @@ func (k Keeper) isMasterCertificateDefined(ctx sdk.Context, certType string) boo func (k Keeper) getRegistrationInfo(ctx sdk.Context, publicKey types.NodeID) *types.RegistrationNodeInfo { store := ctx.KVStore(k.storeKey) var nodeInfo types.RegistrationNodeInfo - //fmt.Println("pubkey", hex.EncodeToString(publicKey)) + // fmt.Println("pubkey", hex.EncodeToString(publicKey)) certBz := store.Get(types.RegistrationKeyPrefix(publicKey)) if certBz == nil { @@ -84,8 +84,8 @@ func (k Keeper) SetRegistrationInfo(ctx sdk.Context, certificate types.Registrat return } - //fmt.Println("pubkey", hex.EncodeToString(publicKey)) - //fmt.Println("EncryptedSeed", hex.EncodeToString(certificate.EncryptedSeed)) + // fmt.Println("pubkey", hex.EncodeToString(publicKey)) + // fmt.Println("EncryptedSeed", hex.EncodeToString(certificate.EncryptedSeed)) store.Set(types.RegistrationKeyPrefix(publicKey), k.cdc.MustMarshal(&certificate)) } diff --git a/x/registration/internal/keeper/test_common.go b/x/registration/internal/keeper/test_common.go index c2f17aef4..b773f49e7 100644 --- a/x/registration/internal/keeper/test_common.go +++ b/x/registration/internal/keeper/test_common.go @@ -3,6 +3,9 @@ package keeper import ( "encoding/base64" "encoding/json" + "io/ioutil" + "os" + "testing" "github.com/cosmos/cosmos-sdk/simapp/params" "github.com/cosmos/cosmos-sdk/std" @@ -20,10 +23,7 @@ import ( "github.com/cosmos/ibc-go/v3/modules/apps/transfer" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - //ibc "github.com/cosmos/cosmos-sdk/x/ibc/core" - "io/ioutil" - "os" - "testing" + // ibc "github.com/cosmos/cosmos-sdk/x/ibc/core" "github.com/cosmos/cosmos-sdk/x/mint" paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" @@ -45,7 +45,6 @@ import ( ) func CreateTestSeedConfig(t *testing.T) []byte { - seed := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" cert, err := ioutil.ReadFile("../../testdata/attestation_cert_sw") require.NoError(t, err) @@ -73,7 +72,7 @@ var ModuleBasics = module.NewBasicManager( ), crisis.AppModuleBasic{}, slashing.AppModuleBasic{}, - //ibc.AppModuleBasic{}, + // ibc.AppModuleBasic{}, upgrade.AppModuleBasic{}, evidence.AppModuleBasic{}, transfer.AppModuleBasic{}, @@ -82,6 +81,7 @@ var ModuleBasics = module.NewBasicManager( func MakeTestCodec() codec.Codec { return MakeEncodingConfig().Marshaler } + func MakeEncodingConfig() params.EncodingConfig { amino := codec.NewLegacyAmino() interfaceRegistry := types.NewInterfaceRegistry() @@ -102,7 +102,6 @@ func MakeEncodingConfig() params.EncodingConfig { } func CreateTestInput(t *testing.T, isCheckTx bool, tempDir string, bootstrap bool) (sdk.Context, Keeper) { - err := os.Setenv("SGX_MODE", "SW") require.Nil(t, err) diff --git a/x/registration/internal/types/genesis.go b/x/registration/internal/types/genesis.go index ef05f0157..124a2c7b9 100644 --- a/x/registration/internal/types/genesis.go +++ b/x/registration/internal/types/genesis.go @@ -3,7 +3,6 @@ package types // ValidateGenesis performs basic validation of supply genesis data returning an // error for any failed validation criteria. func ValidateGenesis(data GenesisState) error { - // todo: do we want to use this, or just fail if they don't exist? //if data.IoMasterCertificate == nil { diff --git a/x/registration/internal/types/msg_test.go b/x/registration/internal/types/msg_test.go index faa9ce746..2a5d36610 100644 --- a/x/registration/internal/types/msg_test.go +++ b/x/registration/internal/types/msg_test.go @@ -16,7 +16,7 @@ func TestMsgRaAuthenticateRoute(t *testing.T) { cert, err := ioutil.ReadFile("../../testdata/attestation_cert_sw") require.NoError(t, err) // coins := sdk.NewCoins(sdk.NewInt64Coin("atom", 10)) - var msg = RaAuthenticate{ + msg := RaAuthenticate{ addr1, cert, } @@ -26,7 +26,6 @@ func TestMsgRaAuthenticateRoute(t *testing.T) { } func TestMsgSendValidation(t *testing.T) { - _ = os.Setenv("SGX_MODE", "SW") addr0 := sdk.AccAddress([]byte("qwlnmxj7prpx8rysxm2u")) @@ -44,10 +43,11 @@ func TestMsgSendValidation(t *testing.T) { cases := []struct { valid bool tx RaAuthenticate - }{{true, RaAuthenticate{ - addr0, - cert, - }}, + }{ + {true, RaAuthenticate{ + addr0, + cert, + }}, // invalid address send {false, RaAuthenticate{ addr0, @@ -75,7 +75,7 @@ func TestMsgSendGetSignBytes(t *testing.T) { cert, err := ioutil.ReadFile("../../testdata/attestation_cert_sw") require.NoError(t, err) - var msg = RaAuthenticate{ + msg := RaAuthenticate{ addr0, cert, } @@ -90,7 +90,7 @@ func TestMsgSendGetSigners(t *testing.T) { cert, err := ioutil.ReadFile("../../testdata/attestation_cert_sw") require.NoError(t, err) - var msg = RaAuthenticate{ + msg := RaAuthenticate{ addr0, cert, } diff --git a/x/registration/internal/types/types.go b/x/registration/internal/types/types.go index a4d5ba0a1..924955611 100644 --- a/x/registration/internal/types/types.go +++ b/x/registration/internal/types/types.go @@ -5,16 +5,20 @@ import ( "encoding/hex" ) -const EnclaveRegistrationKey = "new_node_seed_exchange_keypair.sealed" -const PublicKeyLength = 64 // encoded length -const EncryptedKeyLength = 96 // encoded length -const MasterNodeKeyId = "NodeExchMasterKey" -const MasterIoKeyId = "IoExchMasterKey" -const SecretNodeSeedConfig = "seed.json" -const SecretNodeCfgFolder = ".node" +const ( + EnclaveRegistrationKey = "new_node_seed_exchange_keypair.sealed" + PublicKeyLength = 64 // encoded length + EncryptedKeyLength = 96 // encoded length + MasterNodeKeyId = "NodeExchMasterKey" + MasterIoKeyId = "IoExchMasterKey" + SecretNodeSeedConfig = "seed.json" + SecretNodeCfgFolder = ".node" +) -const NodeExchMasterCertPath = "node-master-cert.der" -const IoExchMasterCertPath = "io-master-cert.der" +const ( + NodeExchMasterCertPath = "node-master-cert.der" + IoExchMasterCertPath = "io-master-cert.der" +) const AttestationCertPath = "attestation_cert.der" diff --git a/x/registration/module.go b/x/registration/module.go index d1a5563c3..0e4f2fce9 100644 --- a/x/registration/module.go +++ b/x/registration/module.go @@ -3,13 +3,14 @@ package registration import ( "context" "encoding/json" + "math/rand" + "github.com/cosmos/cosmos-sdk/client" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/enigmampc/SecretNetwork/x/registration/internal/keeper" "github.com/enigmampc/SecretNetwork/x/registration/internal/types" "github.com/grpc-ecosystem/grpc-gateway/runtime" - "math/rand" "github.com/gorilla/mux" "github.com/spf13/cobra" diff --git a/x/registration/remote_attestation/fuzz_test.go b/x/registration/remote_attestation/fuzz_test.go index e974766aa..12d6676ab 100644 --- a/x/registration/remote_attestation/fuzz_test.go +++ b/x/registration/remote_attestation/fuzz_test.go @@ -1,5 +1,6 @@ // rename this to fuzz.go if you want to run the fuzzer +//go:build gofuzz // +build gofuzz package remote_attestation diff --git a/x/registration/remote_attestation/ra_test.go b/x/registration/remote_attestation/ra_test.go index 7985003d1..42c51281e 100644 --- a/x/registration/remote_attestation/ra_test.go +++ b/x/registration/remote_attestation/ra_test.go @@ -1,10 +1,11 @@ package remote_attestation import ( - "github.com/stretchr/testify/require" "io/ioutil" "os" "testing" + + "github.com/stretchr/testify/require" ) func Test_ValidateCertificateHwMode(t *testing.T) { @@ -39,8 +40,7 @@ func Test_InvalidRandomDataAsCert(t *testing.T) { } func Test_FuzzCrashers(t *testing.T) { - - var crashers = [][]byte{ + crashers := [][]byte{ []byte("\x06\b*\x86H\xce=\x03\x01\a0\xd80r0"), []byte("\x06\b*\x86H\xce=\x03\x01\a\f\x1cEnigmaCh" + "ain Node Ce000000000"), diff --git a/x/registration/remote_attestation/remote_attestation.go b/x/registration/remote_attestation/remote_attestation.go index 6d345614a..e63ade54f 100644 --- a/x/registration/remote_attestation/remote_attestation.go +++ b/x/registration/remote_attestation/remote_attestation.go @@ -7,8 +7,9 @@ import ( "encoding/hex" "encoding/json" "fmt" - "github.com/pkg/errors" "time" + + "github.com/pkg/errors" ) /* @@ -134,7 +135,7 @@ func verifyCert(payload []byte) ([]byte, error) { // note: there's no way to not validate the time, and we don't want to write this code // ourselves. We also can't just ignore the error message, since that means that the rest of // the validation didn't happen (time is validated early on) - CurrentTime: time.Date(2023, 11, 04, 00, 00, 00, 00, time.UTC), + CurrentTime: time.Date(2023, 11, 0o4, 0o0, 0o0, 0o0, 0o0, time.UTC), } if _, err := certServer.Verify(opts); err != nil { @@ -159,11 +160,11 @@ func verifyAttReport(attnReportRaw []byte, pubK []byte) ([]byte, error) { // 1. Check timestamp is within 24H if qr.Timestamp != "" { - //timeFixed := qr.Timestamp + "+0000" - //timeFixed := qr.Timestamp + "Z" - //ts, _ := time.Parse(time.RFC3339, timeFixed) - //now := time.Now().Unix() - //fmt.Println("Time diff = ", now-ts.Unix()) + // timeFixed := qr.Timestamp + "+0000" + // timeFixed := qr.Timestamp + "Z" + // ts, _ := time.Parse(time.RFC3339, timeFixed) + // now := time.Now().Unix() + // fmt.Println("Time diff = ", now-ts.Unix()) } else { return nil, errors.New("Failed to fetch timestamp from attestation report") } @@ -171,7 +172,7 @@ func verifyAttReport(attnReportRaw []byte, pubK []byte) ([]byte, error) { // 2. Verify quote status (mandatory field) if qr.IsvEnclaveQuoteStatus != "" { - //fmt.Println("isvEnclaveQuoteStatus = ", qr.IsvEnclaveQuoteStatus) + // fmt.Println("isvEnclaveQuoteStatus = ", qr.IsvEnclaveQuoteStatus) switch qr.IsvEnclaveQuoteStatus { case "OK": break @@ -240,13 +241,13 @@ func verifyAttReport(attnReportRaw []byte, pubK []byte) ([]byte, error) { qrData := parseReport(qb, quoteHex) // todo: possibly verify mr signer/enclave? - //fmt.Println("Quote = [" + quoteBytes[:len(quoteBytes)-2] + "]") - //fmt.Println("sgx quote version = ", qrData.version) - //fmt.Println("sgx quote signature type = ", qrData.signType) - //fmt.Println("sgx quote report_data = ", qrData.reportBody.reportData) - //fmt.Println("sgx quote mr_enclave = ", qrData.reportBody.mrEnclave) - //fmt.Println("sgx quote mr_signer = ", qrData.reportBody.mrSigner) - //fmt.Println("Anticipated public key = ", pubHex) + // fmt.Println("Quote = [" + quoteBytes[:len(quoteBytes)-2] + "]") + // fmt.Println("sgx quote version = ", qrData.version) + // fmt.Println("sgx quote signature type = ", qrData.signType) + // fmt.Println("sgx quote report_data = ", qrData.reportBody.reportData) + // fmt.Println("sgx quote mr_enclave = ", qrData.reportBody.mrEnclave) + // fmt.Println("sgx quote mr_signer = ", qrData.reportBody.mrSigner) + // fmt.Println("Anticipated public key = ", pubHex) if qrData.ReportBody.ReportData != pubHex { // err := errors.New("Failed to authenticate certificate public key")