diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 06dedc1f2..5c2e1328f 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -12,5 +12,5 @@ jobs: - name: golangci-lint uses: golangci/golangci-lint-action@v3 with: - version: v1.49 + version: v1.55.2 args: --timeout=5m0s diff --git a/.golangci.yml b/.golangci.yml index d05598c5f..3ef8c8bf4 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,15 +1,103 @@ -linters-settings: +run: + timeout: 5m + go: '1.19' + skip-files: + - ".*\\.pb\\.go$" + - ".*\\.pb\\.gw\\.\\.go$" + - ".*\\.pulsar\\.go$" linters: disable-all: true enable: - bodyclose - - gofmt - - goimports + - whitespace + - errcheck + - exportloopref + - gci + - gocritic + - gofumpt + - gosec + - gosimple + - govet + - ineffassign - misspell + - nolintlint + - revive + - staticcheck + - stylecheck + - unconvert - typecheck - - whitespace -run: - timeout: 5m - go: '1.19' +issues: + exclude-rules: + - text: 'Use of weak random number generator' + linters: + - gosec + - text: 'ST1003:' + linters: + - stylecheck + +linters-settings: + gci: + custom-order: true + sections: + - standard # Standard section: captures all standard packages. + - default # Default section: contains all imports that could not be matched to another section type. + - prefix(github.com/bandprotocol/chain) + gocritic: + disabled-checks: + - regexpMust + - appendAssign + - ifElseChain + maligned: + # print struct with more effective memory layout or not, false by default + suggest-new: true + nolintlint: + allow-unused: false + allow-leading-space: true + require-explanation: false + require-specific: false + revive: + rules: + - name: unused-parameter + disabled: true + gosec: + # To select a subset of rules to run. + # Available rules: https://github.com/securego/gosec#available-rules + # Default: [] - means include all rules + includes: + # - G101 # Look for hard coded credentials + - G102 # Bind to all interfaces + - G103 # Audit the use of unsafe block + - G104 # Audit errors not checked + - G106 # Audit the use of ssh.InsecureIgnoreHostKey + - G107 # Url provided to HTTP request as taint input + - G108 # Profiling endpoint automatically exposed on /debug/pprof + - G109 # Potential Integer overflow made by strconv.Atoi result conversion to int16/32 + - G110 # Potential DoS vulnerability via decompression bomb + - G111 # Potential directory traversal + - G112 # Potential slowloris attack + - G113 # Usage of Rat.SetString in math/big with an overflow (CVE-2022-23772) + - G114 # Use of net/http serve function that has no support for setting timeouts + - G201 # SQL query construction using format string + - G202 # SQL query construction using string concatenation + - G203 # Use of unescaped data in HTML templates + - G204 # Audit use of command execution + - G301 # Poor file permissions used when creating a directory + - G302 # Poor file permissions used with chmod + - G303 # Creating tempfile using a predictable path + - G304 # File path provided as taint input + - G305 # File traversal when extracting zip/tar archive + - G306 # Poor file permissions used when writing to a new file + - G307 # Deferring a method which returns an error + - G401 # Detect the usage of DES, RC4, MD5 or SHA1 + - G402 # Look for bad TLS connection settings + - G403 # Ensure minimum RSA key length of 2048 bits + - G404 # Insecure random number source (rand) + - G501 # Import blocklist: crypto/md5 + - G502 # Import blocklist: crypto/des + - G503 # Import blocklist: crypto/rc4 + - G504 # Import blocklist: net/http/cgi + - G505 # Import blocklist: crypto/sha1 + - G601 # Implicit memory aliasing of items from a range statement + diff --git a/app/app.go b/app/app.go index 9ddf6f3c6..a5ac9c104 100644 --- a/app/app.go +++ b/app/app.go @@ -303,6 +303,7 @@ func NewBandApp( if err != nil { panic(err) } + // Initialize params keeper and module subspaces. app.ParamsKeeper = initParamsKeeper( appCodec, @@ -340,6 +341,7 @@ func NewBandApp( Bech32MainPrefix, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) + // wrappedBankerKeeper overrides burn token behavior to instead transfer to community pool. app.BankKeeper = bandbankkeeper.NewWrappedBankKeeperBurnToCommunityPool( bankkeeper.NewBaseKeeper( @@ -351,6 +353,7 @@ func NewBandApp( ), app.AccountKeeper, ) + app.StakingKeeper = stakingkeeper.NewKeeper( appCodec, keys[stakingtypes.StoreKey], @@ -358,6 +361,7 @@ func NewBandApp( app.BankKeeper, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) + app.MintKeeper = mintkeeper.NewKeeper( appCodec, keys[minttypes.StoreKey], @@ -367,6 +371,7 @@ func NewBandApp( authtypes.FeeCollectorName, authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) + app.DistrKeeper = distrkeeper.NewKeeper( appCodec, keys[distrtypes.StoreKey], @@ -378,6 +383,7 @@ func NewBandApp( ) // DistrKeeper must be set afterward due to the circular reference between banker-staking-distr. app.BankKeeper.SetDistrKeeper(&app.DistrKeeper) + app.SlashingKeeper = slashingkeeper.NewKeeper( appCodec, legacyAmino, @@ -488,7 +494,6 @@ func NewBandApp( scopedICAHostKeeper, app.MsgServiceRouter(), ) - icaModule := ica.NewAppModule(nil, &app.ICAHostKeeper) icaHostIBCModule := icahost.NewIBCModule(app.ICAHostKeeper) @@ -536,7 +541,7 @@ func NewBandApp( /**** Module Options ****/ // 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. @@ -602,11 +607,11 @@ func NewBandApp( oracleModule, globalfee.NewAppModule(app.GlobalfeeKeeper), ) + // NOTE: Oracle module must occur before distr as it takes some fee to distribute to active oracle validators. // NOTE: During begin block slashing happens after distr.BeginBlocker so that there is nothing left // over in the validator fee pool, so as to keep the CanWithdrawInvariant invariant. // NOTE: capability module's beginblocker must come before any modules using capabilities (e.g. IBC) - app.mm.SetOrderBeginBlockers( upgradetypes.ModuleName, capabilitytypes.ModuleName, @@ -632,6 +637,7 @@ func NewBandApp( consensusparamtypes.ModuleName, globalfeetypes.ModuleName, ) + app.mm.SetOrderEndBlockers( crisistypes.ModuleName, govtypes.ModuleName, @@ -765,6 +771,7 @@ func NewBandApp( app.ScopedIBCKeeper = scopedIBCKeeper app.ScopedTransferKeeper = scopedTransferKeeper app.ScopedOracleKeeper = scopedOracleKeeper + app.ScopedICAHostKeeper = scopedICAHostKeeper return app } @@ -961,7 +968,7 @@ func initParamsKeeper( paramsKeeper.Subspace(minttypes.ModuleName) paramsKeeper.Subspace(distrtypes.ModuleName) paramsKeeper.Subspace(slashingtypes.ModuleName) - paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govv1.ParamKeyTable()) + paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govv1.ParamKeyTable()) //nolint:staticcheck paramsKeeper.Subspace(crisistypes.ModuleName) paramsKeeper.Subspace(ibcexported.ModuleName) paramsKeeper.Subspace(ibctransfertypes.ModuleName) @@ -996,9 +1003,9 @@ func (app *BandApp) setupUpgradeStoreLoaders() { return } - for _, upgrade := range Upgrades { + for idx, upgrade := range Upgrades { if upgradeInfo.Name == upgrade.UpgradeName { - app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &upgrade.StoreUpgrades)) + app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &Upgrades[idx].StoreUpgrades)) } } } diff --git a/app/export.go b/app/export.go index 5652ecbdd..958089a66 100644 --- a/app/export.go +++ b/app/export.go @@ -2,10 +2,10 @@ package band import ( "encoding/json" + "fmt" "log" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - servertypes "github.com/cosmos/cosmos-sdk/server/types" sdk "github.com/cosmos/cosmos-sdk/types" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" @@ -109,7 +109,9 @@ func (app *BandApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ feePool.CommunityPool = feePool.CommunityPool.Add(scraps...) app.DistrKeeper.SetFeePool(ctx, feePool) - app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()) + if err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()); err != nil { + panic(err) + } return false }) @@ -123,8 +125,16 @@ func (app *BandApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ if err != nil { panic(err) } - app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr) - app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr) + + if err := app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr); err != nil { + // never called as BeforeDelegationCreated always returns nil + panic(fmt.Errorf("error while incrementing period: %w", err)) + } + + if err := app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr); err != nil { + // never called as AfterDelegationModified always returns nil + panic(fmt.Errorf("error while creating a new delegation period record: %w", err)) + } } // reset context height diff --git a/app/upgrades/v2_4/upgrades.go b/app/upgrades/v2_4/upgrades.go index be937898e..0f9716b47 100644 --- a/app/upgrades/v2_4/upgrades.go +++ b/app/upgrades/v2_4/upgrades.go @@ -86,7 +86,9 @@ func CreateUpgradeHandler( } // Oracle DefaultParams only upgrade BaseRequestGas to 50000 - keepers.OracleKeeper.SetParams(ctx, oracletypes.DefaultParams()) + if err := keepers.OracleKeeper.SetParams(ctx, oracletypes.DefaultParams()); err != nil { + return nil, err + } consensusParam := am.GetConsensusParams(ctx) consensusParam.Block.MaxGas = 50_000_000 diff --git a/app/upgrades/v2_6/upgrades.go b/app/upgrades/v2_6/upgrades.go index fd2e6b236..5f88810a0 100644 --- a/app/upgrades/v2_6/upgrades.go +++ b/app/upgrades/v2_6/upgrades.go @@ -1,7 +1,6 @@ package v2_6 import ( - oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -21,12 +20,13 @@ import ( "github.com/bandprotocol/chain/v2/app/keepers" "github.com/bandprotocol/chain/v2/app/upgrades" globalfeetypes "github.com/bandprotocol/chain/v2/x/globalfee/types" + oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" ) func CreateUpgradeHandler( mm *module.Manager, configurator module.Configurator, - am upgrades.AppManager, + _ upgrades.AppManager, keepers *keepers.AppKeepers, ) upgradetypes.UpgradeHandler { return func(ctx sdk.Context, _ upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { @@ -41,7 +41,7 @@ func CreateUpgradeHandler( case banktypes.ModuleName: keyTable = banktypes.ParamKeyTable() //nolint:staticcheck case stakingtypes.ModuleName: - keyTable = stakingtypes.ParamKeyTable() //nolint:staticcheck + keyTable = stakingtypes.ParamKeyTable() case minttypes.ModuleName: keyTable = minttypes.ParamKeyTable() //nolint:staticcheck case distrtypes.ModuleName: @@ -54,11 +54,11 @@ func CreateUpgradeHandler( keyTable = crisistypes.ParamKeyTable() //nolint:staticcheck // ibc types case ibctransfertypes.ModuleName: - keyTable = ibctransfertypes.ParamKeyTable() //nolint:staticcheck + keyTable = ibctransfertypes.ParamKeyTable() case icahosttypes.SubModuleName: - keyTable = icahosttypes.ParamKeyTable() //nolint:staticcheck + keyTable = icahosttypes.ParamKeyTable() case oracletypes.ModuleName: - keyTable = oracletypes.ParamKeyTable() //nolint:staticcheck + keyTable = oracletypes.ParamKeyTable() default: continue } diff --git a/benchmark/README.md b/benchmark/README.md index 7bcc2ab33..8703a9f87 100644 --- a/benchmark/README.md +++ b/benchmark/README.md @@ -2,7 +2,7 @@ ## Benchmark Oracle Script Spec -This oracle script will act as a proxy. We have to send scenario number and value with it to execute the specified type of code. +This oracle script will act as a proxy. We have to send the scenario number and value with it to execute the specified type of code. ``` Input { @@ -35,42 +35,42 @@ Output { - Value = Size of memory ### Execute scenarios -- Scenario 0: nothing +- Scenario 0: Nothing - Value = - - Scenario 101: infinite_loop - Value = - - Scenario 102: arithmetic_ops - - Value = Number of loop + - Value = Number of loops - Scenario 103: allocate_mem - Value = Size of memory - Scenario 104: find_median - - Value = Number of loop + - Value = Number of loops - Scenario 105: finite_loop - - Value = Number of loop + - Value = Number of loops - Scenario 106: set_local_var - Value = Size of memory - Scenario 201: get_ask_count - - Value = Number of loop + - Value = Number of loops - Scenario 202: get_min_count - - Value = Number of loop + - Value = Number of loops - Scenario 203: get_prepare_time - - Value = Number of loop + - Value = Number of loops - Scenario 204: get_execute_time - - Value = Number of loop + - Value = Number of loops - Scenario 205: get_ans_count - - Value = Number of loop + - Value = Number of loops - Scenario 206: get_calldata - - Value = Number of loop + - Value = Number of loops - Scenario 207: save_return_data - - Value = Number of loop + - Value = Number of loops - Scenario 208: get_external_data - - Value = Number of loop + - Value = Number of loops - Scenario 209: ecvrf_verify - - Value = Number of loop + - Value = Number of loops - Scenario 210: base_import - Value = - -## How to run benchmark +## How to run the benchmark ``` cd benchmark diff --git a/benchmark/app_test.go b/benchmark/app_test.go index 312e2f7dc..b2feeef84 100644 --- a/benchmark/app_test.go +++ b/benchmark/app_test.go @@ -28,7 +28,7 @@ type BenchmarkApp struct { Querier keeper.Querier } -func InitializeBenchmarkApp(b testing.TB, maxGasPerBlock int64) *BenchmarkApp { +func InitializeBenchmarkApp(tb testing.TB, maxGasPerBlock int64) *BenchmarkApp { ba := &BenchmarkApp{ TestingApp: testapp.NewTestApp("", log.NewNopLogger()), Sender: &Account{ @@ -41,7 +41,7 @@ func InitializeBenchmarkApp(b testing.TB, maxGasPerBlock int64) *BenchmarkApp { Num: 5, Seq: 0, }, - TB: b, + TB: tb, } ba.Ctx = ba.NewUncachedContext(false, tmproto.Header{}) ba.Querier = keeper.Querier{ @@ -57,19 +57,19 @@ func InitializeBenchmarkApp(b testing.TB, maxGasPerBlock int64) *BenchmarkApp { // create oracle script oCode, err := GetBenchmarkWasm() - require.NoError(b, err) + require.NoError(tb, err) _, res, err := ba.DeliverMsg(ba.Sender, GenMsgCreateOracleScript(ba.Sender, oCode)) - require.NoError(b, err) + require.NoError(tb, err) oid, err := GetFirstAttributeOfLastEventValue(res.Events) - require.NoError(b, err) + require.NoError(tb, err) ba.Oid = uint64(oid) // create data source dCode := []byte("hello") _, res, err = ba.DeliverMsg(ba.Sender, GenMsgCreateDataSource(ba.Sender, dCode)) - require.NoError(b, err) + require.NoError(tb, err) did, err := GetFirstAttributeOfLastEventValue(res.Events) - require.NoError(b, err) + require.NoError(tb, err) ba.Did = uint64(did) // activate oracle @@ -109,7 +109,7 @@ func (ba *BenchmarkApp) AddMaxMsgRequests(msg []sdk.Msg) { for block := 0; block < 10; block++ { ba.CallBeginBlock() - var totalGas uint64 = 0 + totalGas := uint64(0) for { tx := GenSequenceOfTxs( ba.TxConfig, diff --git a/benchmark/bench_test.go b/benchmark/bench_test.go index 6dbb2e8ce..b4586b314 100644 --- a/benchmark/bench_test.go +++ b/benchmark/bench_test.go @@ -152,11 +152,13 @@ var CacheCases = map[string]uint32{ "cache": 1, } -var PrepareGasLimit uint64 = 7_500_000 -var ExecuteGasLimit uint64 = 7_500_000 -var BlockMaxGas int64 = 50_000_000 -var GasRanges []int = []int{1, 1_000, 10_000, 100_000, 1_000_000, 7_900_000} -var NumRequestRanges []int = []int{0, 1, 5, 10, 20} +var ( + PrepareGasLimit uint64 = 7_500_000 + ExecuteGasLimit uint64 = 7_500_000 + BlockMaxGas int64 = 50_000_000 + GasRanges = []int{1, 1_000, 10_000, 100_000, 1_000_000, 7_900_000} + NumRequestRanges = []int{0, 1, 5, 10, 20} +) // benchmark test for prepare function of owasm vm func BenchmarkOwasmVMPrepare(b *testing.B) { @@ -334,7 +336,7 @@ func BenchmarkRequestDataEndBlock(b *testing.B) { ba.Oid, ba.Did, tc.scenario, - uint64(pm), + pm, strlen, 10000, ExecuteGasLimit, @@ -438,7 +440,7 @@ func benchmarkBlockNormalMsg(b *testing.B) { ba.CallBeginBlock() b.StopTimer() - var totalGas uint64 = 0 + totalGas := uint64(0) for { tx := GenSequenceOfTxs( ba.TxConfig, @@ -503,7 +505,7 @@ func benchmarkBlockReportMsg(b *testing.B) { b.StopTimer() res := ba.GetAllPendingRequests(ba.Validator) - var totalGas uint64 = 0 + totalGas := uint64(0) reqChunks := ChunkSlice(res.RequestIDs, reportSize) for _, reqChunk := range reqChunks { diff --git a/benchmark/helper_test.go b/benchmark/helper_test.go index ca7357658..3ae2a9b8b 100644 --- a/benchmark/helper_test.go +++ b/benchmark/helper_test.go @@ -29,7 +29,7 @@ type Account struct { } type BenchmarkCalldata struct { - DataSourceId uint64 + DataSourceID uint64 Scenario uint64 Value uint64 Text string @@ -42,8 +42,8 @@ func GetBenchmarkWasm() ([]byte, error) { func GenMsgRequestData( sender *Account, - oracleScriptId uint64, - dataSourceId uint64, + oracleScriptID uint64, + dataSourceID uint64, scenario uint64, value uint64, stringLength int, @@ -51,9 +51,9 @@ func GenMsgRequestData( executeGas uint64, ) []sdk.Msg { msg := oracletypes.MsgRequestData{ - OracleScriptID: oracletypes.OracleScriptID(oracleScriptId), + OracleScriptID: oracletypes.OracleScriptID(oracleScriptID), Calldata: obi.MustEncode(BenchmarkCalldata{ - DataSourceId: dataSourceId, + DataSourceID: dataSourceID, Scenario: scenario, Value: value, Text: strings.Repeat("#", stringLength), @@ -138,7 +138,7 @@ func GenSequenceOfTxs( []uint64{account.Seq}, account.PrivKey, ) - account.Seq += 1 + account.Seq++ } return txs @@ -154,7 +154,7 @@ func DecodeEvents(events []types.Event) []Event { for _, event := range events { attrs := make(map[string]string, 0) for _, attributes := range event.Attributes { - attrs[string(attributes.Key)] = string(attributes.Value) + attrs[attributes.Key] = attributes.Value } evs = append(evs, Event{ Type: event.Type, @@ -165,27 +165,16 @@ func DecodeEvents(events []types.Event) []Event { return evs } -func LogEvents(b testing.TB, events []types.Event) { - evs := DecodeEvents(events) - for i, ev := range evs { - b.Logf("Event %d: %+v\n", i, ev) - } - - if len(evs) == 0 { - b.Logf("No Event") - } -} - func GetFirstAttributeOfLastEventValue(events []types.Event) (int, error) { evt := events[len(events)-1] attr := evt.Attributes[0] - value, err := strconv.Atoi(string(attr.Value)) + value, err := strconv.Atoi(attr.Value) return value, err } func InitOwasmTestEnv( - b testing.TB, + tb testing.TB, cacheSize uint32, scenario uint64, parameter uint64, @@ -193,18 +182,18 @@ func InitOwasmTestEnv( ) (*owasm.Vm, []byte, oracletypes.Request) { // prepare owasm vm owasmVM, err := owasm.NewVm(cacheSize) - require.NoError(b, err) + require.NoError(tb, err) // prepare owasm code oCode, err := GetBenchmarkWasm() - require.NoError(b, err) + require.NoError(tb, err) compiledCode, err := owasmVM.Compile(oCode, oracletypes.MaxCompiledWasmCodeSize) - require.NoError(b, err) + require.NoError(tb, err) // prepare request req := oracletypes.NewRequest( 1, obi.MustEncode(BenchmarkCalldata{ - DataSourceId: 1, + DataSourceID: 1, Scenario: scenario, Value: parameter, Text: strings.Repeat("#", stringLength), diff --git a/client/grpc/node/service.go b/client/grpc/node/service.go index 9eda1b68b..5e4e63655 100644 --- a/client/grpc/node/service.go +++ b/client/grpc/node/service.go @@ -5,12 +5,11 @@ import ( "fmt" "github.com/cometbft/cometbft/crypto/secp256k1" + "github.com/cosmos/cosmos-sdk/client" + sdk "github.com/cosmos/cosmos-sdk/types" gogogrpc "github.com/cosmos/gogoproto/grpc" "github.com/ethereum/go-ethereum/crypto" "github.com/grpc-ecosystem/grpc-gateway/runtime" - - "github.com/cosmos/cosmos-sdk/client" - sdk "github.com/cosmos/cosmos-sdk/types" ) // RegisterNodeService registers the node gRPC service on the provided gRPC router. @@ -21,7 +20,7 @@ func RegisterNodeService(clientCtx client.Context, server gogogrpc.Server) { // RegisterGRPCGatewayRoutes mounts the node gRPC service's GRPC-gateway routes // on the given mux object. func RegisterGRPCGatewayRoutes(clientConn gogogrpc.ClientConn, mux *runtime.ServeMux) { - RegisterServiceHandlerClient(context.Background(), mux, NewServiceClient(clientConn)) + _ = RegisterServiceHandlerClient(context.Background(), mux, NewServiceClient(clientConn)) } // to check queryServer implements ServiceServer @@ -59,8 +58,8 @@ func (s queryServer) EVMValidators( } // Get top 100 validators for now - var page int = 1 - var perPage int = 100 + page := 1 + perPage := 100 validators, err := node.Validators(context.Background(), nil, &page, &perPage) if err != nil { return nil, err diff --git a/client/grpc/oracle/proof/result.go b/client/grpc/oracle/proof/result.go index 51e408492..f61f484ce 100644 --- a/client/grpc/oracle/proof/result.go +++ b/client/grpc/oracle/proof/result.go @@ -24,10 +24,10 @@ func transformResult(r oracletypes.Result) ResultEthereum { ClientID: r.ClientID, OracleScriptID: uint64(r.OracleScriptID), Params: r.Calldata, - AskCount: uint64(r.AskCount), - MinCount: uint64(r.MinCount), + AskCount: r.AskCount, + MinCount: r.MinCount, RequestID: uint64(r.RequestID), - AnsCount: uint64(r.AnsCount), + AnsCount: r.AnsCount, RequestTime: uint64(r.RequestTime), ResolveTime: uint64(r.ResolveTime), ResolveStatus: uint8(r.ResolveStatus), diff --git a/client/grpc/oracle/proof/signature.go b/client/grpc/oracle/proof/signature.go index cb8b85ab3..3c9577dd1 100644 --- a/client/grpc/oracle/proof/signature.go +++ b/client/grpc/oracle/proof/signature.go @@ -32,7 +32,7 @@ func (signature *TMSignature) encodeToEthFormat() TMSignatureEthereum { func recoverETHAddress(msg, sig, signer []byte) ([]byte, uint8, error) { for i := uint8(0); i < 2; i++ { - pubuc, err := crypto.SigToPub(tmhash.Sum(msg), append(sig, byte(i))) + pubuc, err := crypto.SigToPub(tmhash.Sum(msg), append(sig, i)) if err != nil { return nil, 0, err } diff --git a/cmd/bandd/cmd/genaccounts.go b/cmd/bandd/cmd/genaccounts.go index 7a917f60d..463e2d618 100644 --- a/cmd/bandd/cmd/genaccounts.go +++ b/cmd/bandd/cmd/genaccounts.go @@ -6,8 +6,6 @@ import ( "errors" "fmt" - "github.com/spf13/cobra" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -18,6 +16,7 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/genutil" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" + "github.com/spf13/cobra" ) const ( diff --git a/cmd/bandd/cmd/gends.go b/cmd/bandd/cmd/gends.go index 70128c2ec..0ba3a395d 100644 --- a/cmd/bandd/cmd/gends.go +++ b/cmd/bandd/cmd/gends.go @@ -62,7 +62,6 @@ func AddGenesisDataSourceCmd(defaultNodeHome string) *cobra.Command { owner, args[0], args[1], filename, fee, treasury, )) oracleGenStateBz, err := cdc.MarshalJSON(oracleGenState) - if err != nil { return fmt.Errorf("failed to marshal auth genesis state: %w", err) } diff --git a/cmd/bandd/cmd/multi_send.go b/cmd/bandd/cmd/multi_send.go index ee364ae80..b624e3c6f 100644 --- a/cmd/bandd/cmd/multi_send.go +++ b/cmd/bandd/cmd/multi_send.go @@ -21,7 +21,7 @@ func MultiSendTxCmd() *cobra.Command { if err != nil { return err } - sender := sdk.AccAddress(clientCtx.GetFromAddress()) + sender := clientCtx.GetFromAddress() // Parse the coins we are trying to send coins, err := sdk.ParseCoinsNormalized(args[0]) diff --git a/cmd/bandd/cmd/root.go b/cmd/bandd/cmd/root.go index b4f091e7f..a6ecebe7f 100644 --- a/cmd/bandd/cmd/root.go +++ b/cmd/bandd/cmd/root.go @@ -201,8 +201,15 @@ func newApp( } func appExport( - logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailAllowedAddrs []string, - appOpts servertypes.AppOptions, modulesToExport []string) (servertypes.ExportedApp, error) { + logger log.Logger, + db dbm.DB, + traceStore io.Writer, + height int64, + forZeroHeight bool, + jailAllowedAddrs []string, + appOpts servertypes.AppOptions, + modulesToExport []string, +) (servertypes.ExportedApp, error) { homePath, ok := appOpts.Get(flags.FlagHome).(string) if !ok || homePath == "" { return servertypes.ExportedApp{}, errors.New("application home not set") diff --git a/pkg/bandrng/sampling.go b/pkg/bandrng/sampling.go index 81cf46adf..f2813bdf6 100644 --- a/pkg/bandrng/sampling.go +++ b/pkg/bandrng/sampling.go @@ -55,8 +55,8 @@ func ChooseSome(rng *Rng, weights []uint64, cnt int) []int { // ChooseSomeMaxWeight performs ChooseSome "tries" times and returns the sampling with the // highest weight sum among all tries. func ChooseSomeMaxWeight(rng *Rng, weights []uint64, cnt int, tries int) []int { - var maxWeightSum uint64 = 0 - var maxWeightResult []int = nil + var maxWeightSum uint64 + var maxWeightResult []int for each := 0; each < tries; each++ { candidate := ChooseSome(rng, weights, cnt) candidateWeightSum := uint64(0) diff --git a/pkg/filecache/filecache.go b/pkg/filecache/filecache.go index 5bee07abb..5772a0827 100644 --- a/pkg/filecache/filecache.go +++ b/pkg/filecache/filecache.go @@ -32,7 +32,7 @@ func GetFilename(data []byte) string { func (c Cache) AddFile(data []byte) string { filename := GetFilename(data) if !c.fileCache.Has(filename) { - c.fileCache.Write(filename, data) + _ = c.fileCache.Write(filename, data) } return filename } diff --git a/pkg/filecache/filecache_test.go b/pkg/filecache/filecache_test.go index 779f6d328..8b2ba8f79 100644 --- a/pkg/filecache/filecache_test.go +++ b/pkg/filecache/filecache_test.go @@ -125,7 +125,7 @@ func TestMustGetFileGoodContent(t *testing.T) { f := filecache.New(dir) filename := "b20727a9b7cc4198d8785b0ef1fa4c774eb9a360e1563dd4f095ddc7af02bd55" // Correct filepath := filepath.Join(dir, filename) - err = os.WriteFile(filepath, []byte("NOT_LIKE_THIS"), 0666) + err = os.WriteFile(filepath, []byte("NOT_LIKE_THIS"), 0o600) require.NoError(t, err) content := f.MustGetFile(filename) @@ -147,7 +147,7 @@ func TestGetFileGoodContent(t *testing.T) { f := filecache.New(dir) filename := "b20727a9b7cc4198d8785b0ef1fa4c774eb9a360e1563dd4f095ddc7af02bd55" // Correct filepath := filepath.Join(dir, filename) - err = os.WriteFile(filepath, []byte("NOT_LIKE_THIS"), 0666) + err = os.WriteFile(filepath, []byte("NOT_LIKE_THIS"), 0o600) require.NoError(t, err) content, err := f.GetFile(filename) @@ -170,7 +170,7 @@ func TestMustGetFileBadContent(t *testing.T) { f := filecache.New(dir) filename := "b20727a9b7cc4198d8785b0ef1fa4c774eb9a360e1563dd4f095ddc7af02bd56" // Not correct filepath := filepath.Join(dir, filename) - err = os.WriteFile(filepath, []byte("NOT_LIKE_THIS"), 0666) + err = os.WriteFile(filepath, []byte("NOT_LIKE_THIS"), 0o600) require.NoError(t, err) require.Panics(t, func() { @@ -193,7 +193,7 @@ func TesGetFileBadContent(t *testing.T) { f := filecache.New(dir) filename := "b20727a9b7cc4198d8785b0ef1fa4c774eb9a360e1563dd4f095ddc7af02bd56" // Not correct filepath := filepath.Join(dir, filename) - err = os.WriteFile(filepath, []byte("NOT_LIKE_THIS"), 0666) + err = os.WriteFile(filepath, []byte("NOT_LIKE_THIS"), 0o600) require.NoError(t, err) _, err = f.GetFile(filename) @@ -215,7 +215,7 @@ func TestMustGetFileInconsistentContent(t *testing.T) { f := filecache.New(dir) filename := "b20727a9b7cc4198d8785b0ef1fa4c774eb9a360e1563dd4f095ddc7af02bd55" filepath := filepath.Join(dir, filename) - err = os.WriteFile(filepath, []byte("INCONSISTENT"), 0666) // Not consistent with name + err = os.WriteFile(filepath, []byte("INCONSISTENT"), 0o600) // Not consistent with name require.NoError(t, err) require.Panics(t, func() { _ = f.MustGetFile(filename) @@ -237,7 +237,7 @@ func TestGetFileInconsistentContent(t *testing.T) { f := filecache.New(dir) filename := "b20727a9b7cc4198d8785b0ef1fa4c774eb9a360e1563dd4f095ddc7af02bd55" filepath := filepath.Join(dir, filename) - err = os.WriteFile(filepath, []byte("INCONSISTENT"), 0666) // Not consistent with name + err = os.WriteFile(filepath, []byte("INCONSISTENT"), 0o600) // Not consistent with name require.NoError(t, err) _, err = f.GetFile(filename) require.Error(t, err) diff --git a/pkg/gzip/gzip_test.go b/pkg/gzip/gzip_test.go index c7890a37d..da721d3ac 100644 --- a/pkg/gzip/gzip_test.go +++ b/pkg/gzip/gzip_test.go @@ -14,7 +14,8 @@ func TestUncompress(t *testing.T) { file1 := []byte("file") var buf bytes.Buffer zw := gz.NewWriter(&buf) - zw.Write(file1) + _, err := zw.Write(file1) + require.NoError(t, err) zw.Close() gzipFile := buf.Bytes() @@ -73,7 +74,8 @@ func TestIsGzip(t *testing.T) { file1 := []byte("file") var buf bytes.Buffer zw := gz.NewWriter(&buf) - zw.Write(file1) + _, err := zw.Write(file1) + require.NoError(t, err) zw.Close() gzipFile := buf.Bytes() require.True(t, gzip.IsGzipped(gzipFile)) diff --git a/pkg/obi/decode.go b/pkg/obi/decode.go index 65880d251..f0753b1e2 100644 --- a/pkg/obi/decode.go +++ b/pkg/obi/decode.go @@ -28,7 +28,7 @@ func decodeImpl(data []byte, v interface{}) ([]byte, error) { return rem, err case reflect.Uint64: val, rem, err := DecodeUnsigned64(data) - ev.SetUint(uint64(val)) + ev.SetUint(val) return rem, err case reflect.Int8: val, rem, err := DecodeSigned8(data) @@ -44,7 +44,7 @@ func decodeImpl(data []byte, v interface{}) ([]byte, error) { return rem, err case reflect.Int64: val, rem, err := DecodeSigned64(data) - ev.SetInt(int64(val)) + ev.SetInt(val) return rem, err case reflect.String: val, rem, err := DecodeString(data) diff --git a/pkg/obi/encode.go b/pkg/obi/encode.go index 88eaaa1d3..c976aba45 100644 --- a/pkg/obi/encode.go +++ b/pkg/obi/encode.go @@ -17,7 +17,7 @@ func encodeImpl(v interface{}) ([]byte, error) { case reflect.Uint32: return EncodeUnsigned32(uint32(rv.Uint())), nil case reflect.Uint64: - return EncodeUnsigned64(uint64(rv.Uint())), nil + return EncodeUnsigned64(rv.Uint()), nil case reflect.Int8: return EncodeSigned8(int8(rv.Int())), nil case reflect.Int16: @@ -25,7 +25,7 @@ func encodeImpl(v interface{}) ([]byte, error) { case reflect.Int32: return EncodeSigned32(int32(rv.Int())), nil case reflect.Int64: - return EncodeSigned64(int64(rv.Int())), nil + return EncodeSigned64(rv.Int()), nil case reflect.String: return EncodeString(rv.String()), nil case reflect.Slice: diff --git a/pkg/obi/encode_test.go b/pkg/obi/encode_test.go index f502d8ef5..2cbee77a3 100644 --- a/pkg/obi/encode_test.go +++ b/pkg/obi/encode_test.go @@ -40,6 +40,7 @@ func TestEncodeBytes(t *testing.T) { Arr: []int16{10, 11}, }), []byte{0x0, 0x0, 0x0, 0x3, 0x42, 0x54, 0x43, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x23, 0x28, 0x1, 0x2, 0x0, 0x0, 0x0, 0x2, 0x0, 0xa, 0x0, 0xb}) } + func TestEncodeBytesMulti(t *testing.T) { require.Equal(t, MustEncode(SimpleData{X: 1, Y: 2}, ExampleData{ Symbol: "BTC", @@ -190,7 +191,7 @@ func TestEncodeString(t *testing.T) { 0x6f, 0x62, } - require.Equal(t, []byte(expectedEncodeBytes), MustEncode(testString)) + require.Equal(t, expectedEncodeBytes, MustEncode(testString)) } func TestEncodeSlice(t *testing.T) { diff --git a/pkg/obi/schema_test.go b/pkg/obi/schema_test.go index 7ba68b5e9..f7d7d5850 100644 --- a/pkg/obi/schema_test.go +++ b/pkg/obi/schema_test.go @@ -9,7 +9,7 @@ import ( type EmptySchema struct{} type NoOBITagStruct struct { - NoOBITag string `"noOBItag"` //missing obi + NoOBITag string `"noOBItag"` //nolint:govet // missing obi } type NotSupportedStruct struct { @@ -28,14 +28,16 @@ type AllData struct { NumInt64 int64 `obi:"numInt64"` } -type Uint8ID uint8 -type Uint16ID uint16 -type Uint32ID uint32 -type Uint64ID uint64 -type Int8ID int8 -type Int16ID int16 -type Int32ID int32 -type Int64ID int64 +type ( + Uint8ID uint8 + Uint16ID uint16 + Uint32ID uint32 + Uint64ID uint64 + Int8ID int8 + Int16ID int16 + Int32ID int32 + Int64ID int64 +) type AllDataAlias struct { NumUint8 Uint8ID `obi:"numUint8"` diff --git a/testing/chain.go b/testing/chain.go index dd5e02e08..4559abae2 100644 --- a/testing/chain.go +++ b/testing/chain.go @@ -37,9 +37,7 @@ import ( "github.com/bandprotocol/chain/v2/x/oracle/types" ) -var ( - valSize uint64 = 2 -) +var valSize uint64 = 2 // TestChain is a testing struct that wraps a TestingApp with the last TM Header, the current ABCI // header and the validators of the TestChain. It also contains a field called ChainID. This @@ -113,7 +111,8 @@ func NewTestChain(t *testing.T, coord *Coordinator, chainID string) *TestChain { ctx := app.NewContext(false, tmproto.Header{Height: app.LastBlockHeight()}) vals := app.StakingKeeper.GetAllValidators(ctx) for _, v := range vals { - app.OracleKeeper.Activate(ctx, v.GetOperator()) + err := app.OracleKeeper.Activate(ctx, v.GetOperator()) + require.NoError(t, err) } // create current header and call begin block @@ -274,7 +273,8 @@ func (chain *TestChain) SendMsgs(msgs ...sdk.Msg) (*sdk.Result, error) { chain.NextBlock() // increment sequence for successful transaction execution - chain.SenderAccount.SetSequence(chain.SenderAccount.GetSequence() + 1) + err = chain.SenderAccount.SetSequence(chain.SenderAccount.GetSequence() + 1) + require.NoError(chain.t, err) chain.Coordinator.IncrementTime() @@ -313,7 +313,7 @@ func (chain *TestChain) SendReport( chain.NextBlock() // increment sequence for successful transaction execution - senderAccount.SetSequence(senderAccount.GetSequence() + 1) + _ = senderAccount.SetSequence(senderAccount.GetSequence() + 1) chain.Coordinator.IncrementTime() @@ -493,7 +493,7 @@ func (chain *TestChain) CreateTMClientHeader( Commit: commit.ToProto(), } - if tmValSet != nil { + if tmValSet != nil { //nolint:staticcheck valSet, err = tmValSet.ToProto() if err != nil { panic(err) @@ -532,8 +532,12 @@ func MakeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) tmtypes.Bl // (including voting power). It returns a signer array of PrivValidators that matches the // sorting of ValidatorSet. // The sorting is first by .VotingPower (descending), with secondary index of .Address (ascending). -func CreateSortedSignerArray(altPrivVal, suitePrivVal tmtypes.PrivValidator, - altVal, suiteVal *tmtypes.Validator) []tmtypes.PrivValidator { +func CreateSortedSignerArray( + altPrivVal, + suitePrivVal tmtypes.PrivValidator, + altVal, + suiteVal *tmtypes.Validator, +) []tmtypes.PrivValidator { switch { case altVal.VotingPower > suiteVal.VotingPower: return []tmtypes.PrivValidator{altPrivVal, suitePrivVal} diff --git a/testing/coordinator.go b/testing/coordinator.go index 29d2b5ba2..704b57853 100644 --- a/testing/coordinator.go +++ b/testing/coordinator.go @@ -118,7 +118,8 @@ func (coord *Coordinator) CreateConnections(path *Path) { require.NoError(coord.t, err) // ensure counterparty is up to date - path.EndpointA.UpdateClient() + err = path.EndpointA.UpdateClient() + require.NoError(coord.t, err) } // CreateMockChannels constructs and executes channel handshake messages to create OPEN @@ -159,7 +160,8 @@ func (coord *Coordinator) CreateChannels(path *Path) { require.NoError(coord.t, err) // ensure counterparty is up to date - path.EndpointA.UpdateClient() + err = path.EndpointA.UpdateClient() + require.NoError(coord.t, err) } // GetChain returns the TestChain using the given chainID and returns an error if it does diff --git a/testing/endpoint.go b/testing/endpoint.go index cfe128048..a9f65447c 100644 --- a/testing/endpoint.go +++ b/testing/endpoint.go @@ -136,9 +136,7 @@ func (endpoint *Endpoint) UpdateClient() (err error) { // ensure counterparty has committed state endpoint.Chain.Coordinator.CommitBlock(endpoint.Counterparty.Chain) - var ( - header *ibctmtypes.Header - ) + var header *ibctmtypes.Header switch endpoint.ClientConfig.GetClientType() { case exported.Tendermint: @@ -182,7 +180,8 @@ func (endpoint *Endpoint) ConnOpenInit() error { // ConnOpenTry will construct and execute a MsgConnectionOpenTry on the associated endpoint. func (endpoint *Endpoint) ConnOpenTry() error { - endpoint.UpdateClient() + err := endpoint.UpdateClient() + require.NoError(endpoint.Chain.t, err) counterpartyClient, proofClient, proofConsensus, consensusHeight, proofInit, proofHeight := endpoint.QueryConnectionHandshakeProof() @@ -216,7 +215,8 @@ func (endpoint *Endpoint) ConnOpenTry() error { // ConnOpenAck will construct and execute a MsgConnectionOpenAck on the associated endpoint. func (endpoint *Endpoint) ConnOpenAck() error { - endpoint.UpdateClient() + err := endpoint.UpdateClient() + require.NoError(endpoint.Chain.t, err) counterpartyClient, proofClient, proofConsensus, consensusHeight, proofTry, proofHeight := endpoint.QueryConnectionHandshakeProof() @@ -237,7 +237,8 @@ func (endpoint *Endpoint) ConnOpenAck() error { // ConnOpenConfirm will construct and execute a MsgConnectionOpenConfirm on the associated endpoint. func (endpoint *Endpoint) ConnOpenConfirm() error { - endpoint.UpdateClient() + err := endpoint.UpdateClient() + require.NoError(endpoint.Chain.t, err) connectionKey := host.ConnectionKey(endpoint.Counterparty.ConnectionID) proof, height := endpoint.Counterparty.Chain.QueryProof(connectionKey) @@ -300,7 +301,8 @@ func (endpoint *Endpoint) ChanOpenInit() error { // ChanOpenTry will construct and execute a MsgChannelOpenTry on the associated endpoint. func (endpoint *Endpoint) ChanOpenTry() error { - endpoint.UpdateClient() + err := endpoint.UpdateClient() + require.NoError(endpoint.Chain.t, err) channelKey := host.ChannelKey(endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID) proof, height := endpoint.Counterparty.Chain.QueryProof(channelKey) @@ -332,7 +334,8 @@ func (endpoint *Endpoint) ChanOpenTry() error { // ChanOpenAck will construct and execute a MsgChannelOpenAck on the associated endpoint. func (endpoint *Endpoint) ChanOpenAck() error { - endpoint.UpdateClient() + err := endpoint.UpdateClient() + require.NoError(endpoint.Chain.t, err) channelKey := host.ChannelKey(endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID) proof, height := endpoint.Counterparty.Chain.QueryProof(channelKey) @@ -351,7 +354,8 @@ func (endpoint *Endpoint) ChanOpenAck() error { // ChanOpenConfirm will construct and execute a MsgChannelOpenConfirm on the associated endpoint. func (endpoint *Endpoint) ChanOpenConfirm() error { - endpoint.UpdateClient() + err := endpoint.UpdateClient() + require.NoError(endpoint.Chain.t, err) channelKey := host.ChannelKey(endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID) proof, height := endpoint.Counterparty.Chain.QueryProof(channelKey) diff --git a/testing/events.go b/testing/events.go index ac1fdd719..7d3a54e96 100644 --- a/testing/events.go +++ b/testing/events.go @@ -5,11 +5,10 @@ import ( "strconv" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" connectiontypes "github.com/cosmos/ibc-go/v7/modules/core/03-connection/types" channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" + "github.com/stretchr/testify/suite" ) type EventsMap map[string]map[string]string diff --git a/testing/testapp/setup.go b/testing/testapp/setup.go index 0f6117f3c..74c2f31ba 100644 --- a/testing/testapp/setup.go +++ b/testing/testapp/setup.go @@ -55,7 +55,6 @@ type Account struct { ValAddress sdk.ValAddress } -// nolint var ( Owner Account Treasury Account @@ -69,7 +68,6 @@ var ( OwasmVM *owasm.Vm ) -// nolint var ( EmptyCoins = sdk.Coins(nil) Coins1uband = sdk.NewCoins(sdk.NewInt64Coin("uband", 1)) @@ -389,9 +387,9 @@ func CreateTestInput(autoActivate bool) (*TestingApp, sdk.Context, keeper.Keeper app := NewTestApp("BANDCHAIN", log.NewNopLogger()) ctx := app.NewContext(false, tmproto.Header{Height: app.LastBlockHeight()}) if autoActivate { - app.OracleKeeper.Activate(ctx, Validators[0].ValAddress) - app.OracleKeeper.Activate(ctx, Validators[1].ValAddress) - app.OracleKeeper.Activate(ctx, Validators[2].ValAddress) + _ = app.OracleKeeper.Activate(ctx, Validators[0].ValAddress) + _ = app.OracleKeeper.Activate(ctx, Validators[1].ValAddress) + _ = app.OracleKeeper.Activate(ctx, Validators[2].ValAddress) } return app, ctx, app.OracleKeeper } diff --git a/testing/testapp/wasm_1_simple.go b/testing/testapp/wasm_1_simple.go index c7e822917..e5347441f 100644 --- a/testing/testapp/wasm_1_simple.go +++ b/testing/testapp/wasm_1_simple.go @@ -1,6 +1,6 @@ package testapp -// A simple Owasm script with the following specification: +// Wasm1 is a simple Owasm script with the following specification: // // PREPARE: // CALL ask_external_data with EID 1 DID 1 CALLDATA "beeb" @@ -8,7 +8,7 @@ package testapp // CALL ask_external_data with EID 3 DID 3 CALLDATA "beeb" // EXECUTE: // CALL set_return_date with RETDATE "beeb" -var Wasm1 []byte = wat2wasm([]byte(` +var Wasm1 = wat2wasm([]byte(` (module (type $t0 (func)) (type $t1 (func (param i64 i64 i64 i64))) diff --git a/testing/testapp/wasm_2_return_in_prepare.go b/testing/testapp/wasm_2_return_in_prepare.go index 96f736e51..a94048635 100644 --- a/testing/testapp/wasm_2_return_in_prepare.go +++ b/testing/testapp/wasm_2_return_in_prepare.go @@ -1,6 +1,6 @@ package testapp -// A bad Owasm script with the following specification: +// Wasm2 is a bad Owasm script with the following specification: // // PREPARE: // CALL set_return_data with RETDATA "beeb" -- Not allowed during prepare diff --git a/testing/testapp/wasm_3_do_nothing.go b/testing/testapp/wasm_3_do_nothing.go index 43f9ca30f..f94d4dfc8 100644 --- a/testing/testapp/wasm_3_do_nothing.go +++ b/testing/testapp/wasm_3_do_nothing.go @@ -1,6 +1,6 @@ package testapp -// A silly oracle script, primarily to test that you must make at least one raw request: +// Wasm3 is a silly oracle script, primarily to test that you must make at least one raw request: // // PREPARE: // DO NOTHING diff --git a/testing/testapp/wasm_4_complex.go b/testing/testapp/wasm_4_complex.go index 8320036e1..29d653926 100644 --- a/testing/testapp/wasm_4_complex.go +++ b/testing/testapp/wasm_4_complex.go @@ -4,7 +4,7 @@ import ( "encoding/hex" ) -// An oracle script for testing complex interactions. +// Wasm4 is an oracle script for testing complex interactions. // // PREPARE: // Call into the given data source ids with the given calldata. diff --git a/testing/testapp/wasm_extras.go b/testing/testapp/wasm_extras.go index 7de803843..3f2c0551e 100644 --- a/testing/testapp/wasm_extras.go +++ b/testing/testapp/wasm_extras.go @@ -5,7 +5,7 @@ import ( "encoding/hex" ) -// An extra Owasm code to test creating or editing oracle scripts. +// WasmExtra1 is an extra Owasm code to test creating or editing oracle scripts. var WasmExtra1 []byte = wat2wasm([]byte(` (module (type $t0 (func)) @@ -17,7 +17,7 @@ var WasmExtra1 []byte = wat2wasm([]byte(` `)) -// Another extra Owasm code to test creating or editing oracle scripts. +// WasmExtra2 is another extra Owasm code to test creating or editing oracle scripts. var WasmExtra2 []byte = wat2wasm([]byte(` (module (type $t0 (func)) @@ -30,8 +30,10 @@ var WasmExtra2 []byte = wat2wasm([]byte(` (memory $memory (export "memory") 17)) `)) -var WasmExtra1FileName string -var WasmExtra2FileName string +var ( + WasmExtra1FileName string + WasmExtra2FileName string +) func init() { wasm1CompiledHash := sha256.Sum256(compile(WasmExtra1)) diff --git a/testing/testapp/wasm_util.go b/testing/testapp/wasm_util.go index f894b967d..1ab6e078e 100644 --- a/testing/testapp/wasm_util.go +++ b/testing/testapp/wasm_util.go @@ -12,6 +12,7 @@ func compile(code []byte) []byte { if err != nil { panic(err) } + return compiled } @@ -21,20 +22,25 @@ func wat2wasm(wat []byte) []byte { panic(err) } defer os.Remove(inputFile.Name()) + outputFile, err := os.CreateTemp("", "output") if err != nil { panic(err) } defer os.Remove(outputFile.Name()) + if _, err := inputFile.Write(wat); err != nil { panic(err) } - if err := exec.Command("wat2wasm", inputFile.Name(), "-o", outputFile.Name()).Run(); err != nil { + + if err := exec.Command("wat2wasm", inputFile.Name(), "-o", outputFile.Name()).Run(); err != nil { //nolint:gosec panic(err) } + output, err := os.ReadFile(outputFile.Name()) if err != nil { panic(err) } + return output } diff --git a/testing/value.go b/testing/value.go index e9eba50ef..e11da44ba 100644 --- a/testing/value.go +++ b/testing/value.go @@ -9,7 +9,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" connectiontypes "github.com/cosmos/ibc-go/v7/modules/core/03-connection/types" - commitmenttypes "github.com/cosmos/ibc-go/v7/modules/core/23-commitment/types" ibctmtypes "github.com/cosmos/ibc-go/v7/modules/light-clients/07-tendermint" "github.com/cosmos/ibc-go/v7/testing/mock" @@ -55,5 +54,5 @@ var ( // MockFailPacketData = []byte("mock failed packet data") // MockCanaryCapabilityName = []byte("mock async packet data") - prefix = commitmenttypes.NewMerklePrefix([]byte("ibc")) + // prefix = commitmenttypes.NewMerklePrefix([]byte("ibc")) ) diff --git a/x/bank/keeper/keeper.go b/x/bank/keeper/keeper.go index d37e6c4a2..3288d7cdd 100644 --- a/x/bank/keeper/keeper.go +++ b/x/bank/keeper/keeper.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/cometbft/cometbft/libs/log" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -71,7 +70,7 @@ func (k WrappedBankKeeper) BurnCoins(ctx sdk.Context, moduleName string, amt sdk } // Instead of burning coins, we send them to the community pool. - k.SendCoinsFromModuleToModule(ctx, moduleName, distrtypes.ModuleName, amt) + _ = k.SendCoinsFromModuleToModule(ctx, moduleName, distrtypes.ModuleName, amt) feePool := k.distrKeeper.GetFeePool(ctx) feePool.CommunityPool = feePool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amt...)...) k.distrKeeper.SetFeePool(ctx, feePool) diff --git a/x/globalfee/feechecker/feechecker_test.go b/x/globalfee/feechecker/feechecker_test.go index b525670b1..bc34cb36c 100644 --- a/x/globalfee/feechecker/feechecker_test.go +++ b/x/globalfee/feechecker/feechecker_test.go @@ -54,7 +54,7 @@ type FeeCheckerTestSuite struct { suite.Suite FeeChecker feechecker.FeeChecker ctx sdk.Context - requestId types.RequestID + requestID types.RequestID } func (suite *FeeCheckerTestSuite) SetupTest() { @@ -63,7 +63,8 @@ func (suite *FeeCheckerTestSuite) SetupTest() { WithIsCheckTx(true). WithMinGasPrices(sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDecWithPrec(1, 4)}}) - oracleKeeper.GrantReporter(suite.ctx, testapp.Validators[0].ValAddress, testapp.Alice.Address) + err := oracleKeeper.GrantReporter(suite.ctx, testapp.Validators[0].ValAddress, testapp.Alice.Address) + suite.Require().NoError(err) req := types.NewRequest( 1, @@ -77,7 +78,7 @@ func (suite *FeeCheckerTestSuite) SetupTest() { nil, 0, ) - suite.requestId = oracleKeeper.AddRequest(suite.ctx, req) + suite.requestID = oracleKeeper.AddRequest(suite.ctx, req) suite.FeeChecker = feechecker.NewFeeChecker( &oracleKeeper, @@ -87,7 +88,7 @@ func (suite *FeeCheckerTestSuite) SetupTest() { } func (suite *FeeCheckerTestSuite) TestValidRawReport() { - msgs := []sdk.Msg{types.NewMsgReportData(suite.requestId, []types.RawReport{}, testapp.Validators[0].ValAddress)} + msgs := []sdk.Msg{types.NewMsgReportData(suite.requestID, []types.RawReport{}, testapp.Validators[0].ValAddress)} stubTx := &StubTx{Msgs: msgs} // test - check report tx @@ -116,7 +117,7 @@ func (suite *FeeCheckerTestSuite) TestNotValidRawReport() { func (suite *FeeCheckerTestSuite) TestValidReport() { reportMsgs := []sdk.Msg{ - types.NewMsgReportData(suite.requestId, []types.RawReport{}, testapp.Validators[0].ValAddress), + types.NewMsgReportData(suite.requestID, []types.RawReport{}, testapp.Validators[0].ValAddress), } authzMsg := authz.NewMsgExec(testapp.Alice.Address, reportMsgs) stubTx := &StubTx{Msgs: []sdk.Msg{&authzMsg}} @@ -134,7 +135,7 @@ func (suite *FeeCheckerTestSuite) TestValidReport() { func (suite *FeeCheckerTestSuite) TestNoAuthzReport() { reportMsgs := []sdk.Msg{ - types.NewMsgReportData(suite.requestId, []types.RawReport{}, testapp.Validators[0].ValAddress), + types.NewMsgReportData(suite.requestID, []types.RawReport{}, testapp.Validators[0].ValAddress), } authzMsg := authz.NewMsgExec(testapp.Bob.Address, reportMsgs) stubTx := &StubTx{Msgs: []sdk.Msg{&authzMsg}, GasPrices: sdk.NewDecCoins(sdk.NewDecCoin("uband", sdk.NewInt(1)))} @@ -150,7 +151,7 @@ func (suite *FeeCheckerTestSuite) TestNoAuthzReport() { func (suite *FeeCheckerTestSuite) TestNotValidReport() { reportMsgs := []sdk.Msg{ - types.NewMsgReportData(suite.requestId+1, []types.RawReport{}, testapp.Validators[0].ValAddress), + types.NewMsgReportData(suite.requestID+1, []types.RawReport{}, testapp.Validators[0].ValAddress), } authzMsg := authz.NewMsgExec(testapp.Alice.Address, reportMsgs) stubTx := &StubTx{Msgs: []sdk.Msg{&authzMsg}} @@ -201,7 +202,7 @@ func (suite *FeeCheckerTestSuite) TestNotReportMsg() { } func (suite *FeeCheckerTestSuite) TestReportMsgAndOthersTypeMsgInTheSameAuthzMsgs() { - reportMsg := types.NewMsgReportData(suite.requestId, []types.RawReport{}, testapp.Validators[0].ValAddress) + reportMsg := types.NewMsgReportData(suite.requestID, []types.RawReport{}, testapp.Validators[0].ValAddress) requestMsg := types.NewMsgRequestData( 1, BasicCalldata, @@ -229,7 +230,7 @@ func (suite *FeeCheckerTestSuite) TestReportMsgAndOthersTypeMsgInTheSameAuthzMsg } func (suite *FeeCheckerTestSuite) TestReportMsgAndOthersTypeMsgInTheSameTx() { - reportMsg := types.NewMsgReportData(suite.requestId, []types.RawReport{}, testapp.Validators[0].ValAddress) + reportMsg := types.NewMsgReportData(suite.requestID, []types.RawReport{}, testapp.Validators[0].ValAddress) requestMsg := types.NewMsgRequestData( 1, BasicCalldata, diff --git a/x/globalfee/keeper/genesis.go b/x/globalfee/keeper/genesis.go index 330402d92..f7188ca17 100644 --- a/x/globalfee/keeper/genesis.go +++ b/x/globalfee/keeper/genesis.go @@ -7,14 +7,14 @@ import ( ) // InitGenesis new globalfee genesis -func (keeper Keeper) InitGenesis(ctx sdk.Context, data *types.GenesisState) { - if err := keeper.SetParams(ctx, data.Params); err != nil { +func (k Keeper) InitGenesis(ctx sdk.Context, data *types.GenesisState) { + if err := k.SetParams(ctx, data.Params); err != nil { panic(err) } } // ExportGenesis returns a GenesisState for a given context. -func (keeper Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { - params := keeper.GetParams(ctx) +func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { + params := k.GetParams(ctx) return types.NewGenesisState(params) } diff --git a/x/globalfee/keeper/genesis_test.go b/x/globalfee/keeper/genesis_test.go index c24285b1d..57c2cfc8b 100644 --- a/x/globalfee/keeper/genesis_test.go +++ b/x/globalfee/keeper/genesis_test.go @@ -68,14 +68,14 @@ func (s *GenesisTestSuite) TestImportExportGenesis() { } for name, spec := range specs { s.Run(name, func() { - genesisState := &spec.exp - s.keeper.InitGenesis(s.sdkCtx, genesisState) + genesisState := spec.exp + s.keeper.InitGenesis(s.sdkCtx, &genesisState) params := s.keeper.GetParams(s.sdkCtx) s.Require().Equal(genesisState.Params, params) genesisState2 := s.keeper.ExportGenesis(s.sdkCtx) - s.Require().Equal(genesisState, genesisState2) + s.Require().Equal(&genesisState, genesisState2) }) } } diff --git a/x/globalfee/keeper/grpc_query_test.go b/x/globalfee/keeper/grpc_query_test.go index 39aa29be7..27546f382 100644 --- a/x/globalfee/keeper/grpc_query_test.go +++ b/x/globalfee/keeper/grpc_query_test.go @@ -22,7 +22,7 @@ func TestQueryParams(t *testing.T) { }{ "one coin": { setupStore: func(ctx sdk.Context, k keeper.Keeper) { - k.SetParams(ctx, types.Params{ + _ = k.SetParams(ctx, types.Params{ MinimumGasPrices: sdk.NewDecCoins(sdk.NewDecCoin("ALX", sdk.OneInt())), }) }, @@ -30,7 +30,7 @@ func TestQueryParams(t *testing.T) { }, "multiple coins": { setupStore: func(ctx sdk.Context, k keeper.Keeper) { - k.SetParams(ctx, types.Params{ + _ = k.SetParams(ctx, types.Params{ MinimumGasPrices: sdk.NewDecCoins( sdk.NewDecCoin("ALX", sdk.OneInt()), sdk.NewDecCoin("BLX", sdk.NewInt(2)), @@ -41,7 +41,7 @@ func TestQueryParams(t *testing.T) { }, "no min gas price set": { setupStore: func(ctx sdk.Context, k keeper.Keeper) { - k.SetParams(ctx, types.Params{}) + _ = k.SetParams(ctx, types.Params{}) }, }, "no param set": { diff --git a/x/globalfee/keeper/keeper_test.go b/x/globalfee/keeper/keeper_test.go index dd6f3b437..7b161048a 100644 --- a/x/globalfee/keeper/keeper_test.go +++ b/x/globalfee/keeper/keeper_test.go @@ -3,13 +3,12 @@ package keeper_test import ( "testing" - "github.com/stretchr/testify/suite" - "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/stretchr/testify/suite" "github.com/bandprotocol/chain/v2/x/globalfee" "github.com/bandprotocol/chain/v2/x/globalfee/keeper" diff --git a/x/globalfee/module.go b/x/globalfee/module.go index 2d98a852a..f257cb487 100644 --- a/x/globalfee/module.go +++ b/x/globalfee/module.go @@ -41,7 +41,7 @@ func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { } // RegisterInterfaces registers the module's interface types -func (b AppModuleBasic) RegisterInterfaces(r codectypes.InterfaceRegistry) { +func (a AppModuleBasic) RegisterInterfaces(r codectypes.InterfaceRegistry) { types.RegisterInterfaces(r) } @@ -68,7 +68,7 @@ func (a AppModuleBasic) ValidateGenesis( } func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) + _ = types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) } func (a AppModuleBasic) GetTxCmd() *cobra.Command { diff --git a/x/globalfee/types/keys.go b/x/globalfee/types/keys.go index 012e31211..b4cc14221 100644 --- a/x/globalfee/types/keys.go +++ b/x/globalfee/types/keys.go @@ -14,6 +14,4 @@ const ( RouterKey = ModuleName ) -var ( - ParamsKeyPrefix = []byte{0x01} -) +var ParamsKeyPrefix = []byte{0x01} diff --git a/x/oracle/abci_test.go b/x/oracle/abci_test.go index 37c6dfa7a..7f1b98ff9 100644 --- a/x/oracle/abci_test.go +++ b/x/oracle/abci_test.go @@ -69,23 +69,29 @@ func TestAllocateTokensCalledOnBeginBlock(t *testing.T) { // Set collected fee to 100uband + 70% oracle reward proportion + disable minting inflation. // NOTE: we intentionally keep ctx.BlockHeight = 0, so distr's AllocateTokens doesn't get called. feeCollector := app.AccountKeeper.GetModuleAccount(ctx, authtypes.FeeCollectorName) - app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, sdk.NewCoins(sdk.NewInt64Coin("uband", 100))) - app.BankKeeper.SendCoinsFromModuleToModule( + err := app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, sdk.NewCoins(sdk.NewInt64Coin("uband", 100))) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToModule( ctx, minttypes.ModuleName, authtypes.FeeCollectorName, sdk.NewCoins(sdk.NewInt64Coin("uband", 100)), ) + require.NoError(t, err) + distModule := app.AccountKeeper.GetModuleAccount(ctx, distrtypes.ModuleName) app.AccountKeeper.SetAccount(ctx, feeCollector) mintParams := app.MintKeeper.GetParams(ctx) mintParams.InflationMin = sdk.ZeroDec() mintParams.InflationMax = sdk.ZeroDec() - app.MintKeeper.SetParams(ctx, mintParams) + err = app.MintKeeper.SetParams(ctx, mintParams) + require.NoError(t, err) + params := k.GetParams(ctx) params.OracleRewardPercentage = 70 - k.SetParams(ctx, params) + err = k.SetParams(ctx, params) + require.NoError(t, err) require.Equal( t, sdk.NewCoins(sdk.NewInt64Coin("uband", 100)), @@ -102,7 +108,8 @@ func TestAllocateTokensCalledOnBeginBlock(t *testing.T) { app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress()), ) // 1 validator active, begin block should take 70% of the fee. 2% of that goes to comm pool. - k.Activate(ctx, testapp.Validators[1].ValAddress) + err = k.Activate(ctx, testapp.Validators[1].ValAddress) + require.NoError(t, err) app.BeginBlocker(ctx, abci.RequestBeginBlock{ Hash: fromHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), LastCommitInfo: abci.CommitInfo{Votes: votes}, @@ -132,7 +139,9 @@ func TestAllocateTokensCalledOnBeginBlock(t *testing.T) { app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[1].ValAddress).Rewards, ) // 2 validators active now. 70% of the remaining fee pool will be split 3 ways (comm pool + val1 + val2). - k.Activate(ctx, testapp.Validators[0].ValAddress) + err = k.Activate(ctx, testapp.Validators[0].ValAddress) + require.NoError(t, err) + app.BeginBlocker(ctx, abci.RequestBeginBlock{ Hash: fromHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), LastCommitInfo: abci.CommitInfo{Votes: votes}, @@ -216,21 +225,25 @@ func TestAllocateTokensWithDistrAllocateTokens(t *testing.T) { distModule := app.AccountKeeper.GetModuleAccount(ctx, distrtypes.ModuleName) // Set collected fee to 100uband + 70% oracle reward proportion + disable minting inflation. - app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, sdk.NewCoins(sdk.NewInt64Coin("uband", 50))) - app.BankKeeper.SendCoinsFromModuleToModule( + err := app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, sdk.NewCoins(sdk.NewInt64Coin("uband", 50))) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToModule( ctx, minttypes.ModuleName, authtypes.FeeCollectorName, sdk.NewCoins(sdk.NewInt64Coin("uband", 50)), ) + require.NoError(t, err) app.AccountKeeper.SetAccount(ctx, feeCollector) mintParams := app.MintKeeper.GetParams(ctx) mintParams.InflationMin = sdk.ZeroDec() mintParams.InflationMax = sdk.ZeroDec() - app.MintKeeper.SetParams(ctx, mintParams) + err = app.MintKeeper.SetParams(ctx, mintParams) + require.NoError(t, err) params := k.GetParams(ctx) params.OracleRewardPercentage = 70 - k.SetParams(ctx, params) + err = k.SetParams(ctx, params) + require.NoError(t, err) // Set block proposer to Validators[1], who will receive 5% bonus. app.DistrKeeper.SetPreviousProposerConsAddr(ctx, testapp.Validators[1].Address.Bytes()) require.Equal( @@ -252,7 +265,8 @@ func TestAllocateTokensWithDistrAllocateTokens(t *testing.T) { // Community pool: 0.7 + 0.3 = 1 // Validators[0]: 34.3 + 8.715 = 43.015 // Validators[1]: 2.25 + 3.735 = 5.985 - k.Activate(ctx, testapp.Validators[0].ValAddress) + err = k.Activate(ctx, testapp.Validators[0].ValAddress) + require.NoError(t, err) app.BeginBlocker(ctx, abci.RequestBeginBlock{ Hash: fromHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), LastCommitInfo: abci.CommitInfo{Votes: votes}, diff --git a/x/oracle/app_test.go b/x/oracle/app_test.go index 1d16c0a14..4b046360c 100644 --- a/x/oracle/app_test.go +++ b/x/oracle/app_test.go @@ -101,7 +101,7 @@ func TestSuccessRequestOracleData(t *testing.T) { result = app.EndBlocker(ctx, abci.RequestEndBlock{Height: 8}) resPacket := types.NewOracleResponsePacketData( - expectRequest.ClientID, types.RequestID(1), 2, int64(expectRequest.RequestTime), 1581589795, + expectRequest.ClientID, types.RequestID(1), 2, expectRequest.RequestTime, 1581589795, types.RESOLVE_STATUS_SUCCESS, []byte("beeb"), ) expectEvents = []abci.Event{{Type: types.EventTypeResolve, Attributes: []abci.EventAttribute{ @@ -172,7 +172,7 @@ func TestExpiredRequestOracleData(t *testing.T) { ctx = ctx.WithBlockHeight(132).WithBlockTime(ctx.BlockTime().Add(time.Minute)) result := app.EndBlocker(ctx, abci.RequestEndBlock{Height: 132}) resPacket := types.NewOracleResponsePacketData( - expectRequest.ClientID, types.RequestID(1), 0, int64(expectRequest.RequestTime), ctx.BlockTime().Unix(), + expectRequest.ClientID, types.RequestID(1), 0, expectRequest.RequestTime, ctx.BlockTime().Unix(), types.RESOLVE_STATUS_EXPIRED, []byte{}, ) expectEvents := []abci.Event{{ diff --git a/x/oracle/genesis.go b/x/oracle/genesis.go index 84c3bfd84..f2e3dd8ce 100644 --- a/x/oracle/genesis.go +++ b/x/oracle/genesis.go @@ -3,6 +3,7 @@ package oracle import ( "fmt" + errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/bandprotocol/chain/v2/x/oracle/keeper" @@ -11,7 +12,10 @@ import ( // InitGenesis performs genesis initialization for the oracle module. func InitGenesis(ctx sdk.Context, k keeper.Keeper, data *types.GenesisState) { - k.SetParams(ctx, data.Params) + if err := k.SetParams(ctx, data.Params); err != nil { + panic(errorsmod.Wrapf(err, "set params")) + } + k.SetDataSourceCount(ctx, 0) k.SetOracleScriptCount(ctx, 0) k.SetRequestCount(ctx, 0) diff --git a/x/oracle/handler_test.go b/x/oracle/handler_test.go index c2af4f582..168345e76 100644 --- a/x/oracle/handler_test.go +++ b/x/oracle/handler_test.go @@ -55,7 +55,7 @@ func TestCreateDataSourceSuccess(t *testing.T) { {Key: types.AttributeKeyID, Value: fmt.Sprintf("%d", dsCount+1)}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) } func TestCreateGzippedExecutableDataSourceFail(t *testing.T) { @@ -67,7 +67,8 @@ func TestCreateGzippedExecutableDataSourceFail(t *testing.T) { executable := []byte("executable") var buf bytes.Buffer zw := gz.NewWriter(&buf) - zw.Write(executable) + _, err := zw.Write(executable) + require.NoError(t, err) zw.Close() sender := testapp.Alice.Address msg := types.NewMsgCreateDataSource( @@ -121,7 +122,7 @@ func TestEditDataSourceSuccess(t *testing.T) { Type: types.EventTypeEditDataSource, Attributes: []abci.EventAttribute{{Key: types.AttributeKeyID, Value: "1"}}, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) } func TestEditDataSourceFail(t *testing.T) { @@ -160,7 +161,8 @@ func TestEditDataSourceFail(t *testing.T) { // Bad Gzip var buf bytes.Buffer zw := gz.NewWriter(&buf) - zw.Write(newExecutable) + _, err = zw.Write(newExecutable) + require.NoError(t, err) zw.Close() msg = types.NewMsgEditDataSource( 1, @@ -210,7 +212,7 @@ func TestCreateOracleScriptSuccess(t *testing.T) { {Key: types.AttributeKeyID, Value: fmt.Sprintf("%d", osCount+1)}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) } func TestCreateGzippedOracleScriptSuccess(t *testing.T) { @@ -222,7 +224,8 @@ func TestCreateGzippedOracleScriptSuccess(t *testing.T) { url := "url" var buf bytes.Buffer zw := gz.NewWriter(&buf) - zw.Write(testapp.WasmExtra1) + _, err := zw.Write(testapp.WasmExtra1) + require.NoError(t, err) zw.Close() msg := types.NewMsgCreateOracleScript( name, @@ -249,7 +252,7 @@ func TestCreateGzippedOracleScriptSuccess(t *testing.T) { {Key: types.AttributeKeyID, Value: fmt.Sprintf("%d", osCount+1)}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) } func TestCreateOracleScriptFail(t *testing.T) { @@ -274,7 +277,8 @@ func TestCreateOracleScriptFail(t *testing.T) { // Bad Gzip var buf bytes.Buffer zw := gz.NewWriter(&buf) - zw.Write(testapp.WasmExtra1) + _, err = zw.Write(testapp.WasmExtra1) + require.NoError(t, err) zw.Close() msg = types.NewMsgCreateOracleScript( name, @@ -328,7 +332,7 @@ func TestEditOracleScriptSuccess(t *testing.T) { Type: types.EventTypeEditOracleScript, Attributes: []abci.EventAttribute{{Key: types.AttributeKeyID, Value: "1"}}, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) } func TestEditOracleScriptFail(t *testing.T) { @@ -383,7 +387,8 @@ func TestEditOracleScriptFail(t *testing.T) { // Bad Gzip var buf bytes.Buffer zw := gz.NewWriter(&buf) - zw.Write(testapp.WasmExtra2) + _, err = zw.Write(testapp.WasmExtra2) + require.NoError(t, err) zw.Close() msg = types.NewMsgEditOracleScript( 1, @@ -430,7 +435,7 @@ func TestRequestDataSuccess(t *testing.T) { types.NewRawRequest(3, 3, []byte("beeb")), }, nil, - uint64(testapp.TestDefaultExecuteGas), + testapp.TestDefaultExecuteGas, ), k.MustGetRequest(ctx, 1)) event := abci.Event{ Type: authtypes.EventTypeCoinSpent, @@ -439,9 +444,9 @@ func TestRequestDataSuccess(t *testing.T) { {Key: sdk.AttributeKeyAmount, Value: "2000000uband"}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) - require.Equal(t, abci.Event(event), res.Events[4]) - require.Equal(t, abci.Event(event), res.Events[8]) + require.Equal(t, event, res.Events[0]) + require.Equal(t, event, res.Events[4]) + require.Equal(t, event, res.Events[8]) event = abci.Event{ Type: authtypes.EventTypeCoinReceived, Attributes: []abci.EventAttribute{ @@ -449,9 +454,9 @@ func TestRequestDataSuccess(t *testing.T) { {Key: sdk.AttributeKeyAmount, Value: "2000000uband"}, }, } - require.Equal(t, abci.Event(event), res.Events[1]) - require.Equal(t, abci.Event(event), res.Events[5]) - require.Equal(t, abci.Event(event), res.Events[9]) + require.Equal(t, event, res.Events[1]) + require.Equal(t, event, res.Events[5]) + require.Equal(t, event, res.Events[9]) event = abci.Event{ Type: authtypes.EventTypeTransfer, Attributes: []abci.EventAttribute{ @@ -460,18 +465,18 @@ func TestRequestDataSuccess(t *testing.T) { {Key: sdk.AttributeKeyAmount, Value: "2000000uband"}, }, } - require.Equal(t, abci.Event(event), res.Events[2]) - require.Equal(t, abci.Event(event), res.Events[6]) - require.Equal(t, abci.Event(event), res.Events[10]) + require.Equal(t, event, res.Events[2]) + require.Equal(t, event, res.Events[6]) + require.Equal(t, event, res.Events[10]) event = abci.Event{ Type: sdk.EventTypeMessage, Attributes: []abci.EventAttribute{ {Key: authtypes.AttributeKeySender, Value: testapp.FeePayer.Address.String()}, }, } - require.Equal(t, abci.Event(event), res.Events[3]) - require.Equal(t, abci.Event(event), res.Events[7]) - require.Equal(t, abci.Event(event), res.Events[11]) + require.Equal(t, event, res.Events[3]) + require.Equal(t, event, res.Events[7]) + require.Equal(t, event, res.Events[11]) event = abci.Event{ Type: types.EventTypeRequest, @@ -488,7 +493,7 @@ func TestRequestDataSuccess(t *testing.T) { {Key: types.AttributeKeyValidator, Value: testapp.Validators[0].ValAddress.String()}, }, } - require.Equal(t, abci.Event(event), res.Events[12]) + require.Equal(t, event, res.Events[12]) event = abci.Event{ Type: types.EventTypeRawRequest, Attributes: []abci.EventAttribute{ @@ -499,7 +504,7 @@ func TestRequestDataSuccess(t *testing.T) { {Key: types.AttributeKeyFee, Value: "1000000uband"}, }, } - require.Equal(t, abci.Event(event), res.Events[13]) + require.Equal(t, event, res.Events[13]) event = abci.Event{ Type: types.EventTypeRawRequest, Attributes: []abci.EventAttribute{ @@ -510,7 +515,7 @@ func TestRequestDataSuccess(t *testing.T) { {Key: types.AttributeKeyFee, Value: "1000000uband"}, }, } - require.Equal(t, abci.Event(event), res.Events[14]) + require.Equal(t, event, res.Events[14]) event = abci.Event{ Type: types.EventTypeRawRequest, Attributes: []abci.EventAttribute{ @@ -521,7 +526,7 @@ func TestRequestDataSuccess(t *testing.T) { {Key: types.AttributeKeyFee, Value: "1000000uband"}, }, } - require.Equal(t, abci.Event(event), res.Events[15]) + require.Equal(t, event, res.Events[15]) } func TestRequestDataFail(t *testing.T) { @@ -545,8 +550,10 @@ func TestRequestDataFail(t *testing.T) { ) testapp.CheckErrorf(t, err, types.ErrInsufficientValidators, "0 < 2") require.Nil(t, res) - k.Activate(ctx, testapp.Validators[0].ValAddress) - k.Activate(ctx, testapp.Validators[1].ValAddress) + err = k.Activate(ctx, testapp.Validators[0].ValAddress) + require.NoError(t, err) + err = k.Activate(ctx, testapp.Validators[1].ValAddress) + require.NoError(t, err) // Too large calldata res, err = oracle.NewHandler( k, @@ -660,7 +667,7 @@ func TestReportSuccess(t *testing.T) { {Key: types.AttributeKeyValidator, Value: testapp.Validators[0].ValAddress.String()}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) // Validators[1] reports data. Now the request should move to pending resolve. res, err = oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, testapp.Validators[1].ValAddress)) require.NoError(t, err) @@ -672,7 +679,7 @@ func TestReportSuccess(t *testing.T) { {Key: types.AttributeKeyValidator, Value: testapp.Validators[1].ValAddress.String()}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) // Even if we resolve the request, Validators[2] should still be able to report. k.SetPendingResolveList(ctx, []types.RequestID{}) k.ResolveSuccess(ctx, 42, []byte("RESOLVE_RESULT!"), 1234) @@ -685,7 +692,7 @@ func TestReportSuccess(t *testing.T) { {Key: types.AttributeKeyValidator, Value: testapp.Validators[2].ValAddress.String()}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) // Check the reports of this request. We should see 3 reports, with report from Validators[2] comes after resolve. finalReport := k.GetReports(ctx, 42) require.Contains(t, finalReport, types.NewReport(testapp.Validators[0].ValAddress, true, reports)) @@ -800,7 +807,7 @@ func TestActivateSuccess(t *testing.T) { {Key: types.AttributeKeyValidator, Value: testapp.Validators[0].ValAddress.String()}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) } func TestActivateFail(t *testing.T) { @@ -848,7 +855,7 @@ func TestUpdateParamsSuccess(t *testing.T) { {Key: types.AttributeKeyParams, Value: expectedParams.String()}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) expectedParams = types.Params{ MaxRawRequestCount: 2, @@ -873,7 +880,7 @@ func TestUpdateParamsSuccess(t *testing.T) { {Key: types.AttributeKeyParams, Value: expectedParams.String()}, }, } - require.Equal(t, abci.Event(event), res.Events[0]) + require.Equal(t, event, res.Events[0]) } func TestUpdateParamsFail(t *testing.T) { diff --git a/x/oracle/ibc_test.go b/x/oracle/ibc_test.go index e83ac189f..74a69ebb8 100644 --- a/x/oracle/ibc_test.go +++ b/x/oracle/ibc_test.go @@ -101,7 +101,7 @@ func (suite *OracleTestSuite) TestHandleIBCRequestSuccess() { types.NewRawReport(2, 0, []byte("data2")), types.NewRawReport(3, 0, []byte("data3")), } - suite.chainB.SendReport(1, raws1, testapp.Validators[0]) + _, err = suite.chainB.SendReport(1, raws1, testapp.Validators[0]) suite.Require().NoError(err) raws2 := []types.RawReport{ @@ -109,7 +109,7 @@ func (suite *OracleTestSuite) TestHandleIBCRequestSuccess() { types.NewRawReport(2, 0, []byte("data2")), types.NewRawReport(3, 0, []byte("data3")), } - suite.chainB.SendReport(1, raws2, testapp.Validators[1]) + _, err = suite.chainB.SendReport(1, raws2, testapp.Validators[1]) suite.Require().NoError(err) oracleResponsePacket := types.NewOracleResponsePacketData( @@ -240,17 +240,19 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestNotEnoughFund() { // Use Carol as a relayer carol := testapp.Carol carolExpectedBalance := sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2492500))) - suite.chainB.SendMsgs(banktypes.NewMsgSend( + _, err := suite.chainB.SendMsgs(banktypes.NewMsgSend( suite.chainB.SenderAccount.GetAddress(), carol.Address, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2500000))), )) + suite.Require().NoError(err) + suite.chainB.SenderPrivKey = carol.PrivKey suite.chainB.SenderAccount = suite.chainB.App.AccountKeeper.GetAccount(suite.chainB.GetContext(), carol.Address) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) - err := path.RelayPacket(packet) + err = path.RelayPacket(packet) suite.Require().NoError(err) // relay committed carolBalance := suite.chainB.App.BankKeeper.GetAllBalances(suite.chainB.GetContext(), carol.Address) @@ -367,7 +369,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestBaseOwasmFeePanic() { params := suite.chainB.App.OracleKeeper.GetParams(suite.chainB.GetContext()) params.BaseOwasmGas = 100000000 params.PerValidatorRequestGas = 0 - suite.chainB.App.OracleKeeper.SetParams(suite.chainB.GetContext(), params) + err := suite.chainB.App.OracleKeeper.SetParams(suite.chainB.GetContext(), params) + suite.Require().NoError(err) // send request from A to B timeoutHeight := clienttypes.NewHeight(0, 110) @@ -384,7 +387,7 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestBaseOwasmFeePanic() { packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) // ConsumeGas panics due to insufficient gas, so ErrAcknowledgement is not created. - err := path.RelayPacket(packet) + err = path.RelayPacket(packet) suite.Require().Contains(err.Error(), "BASE_OWASM_FEE; gasWanted: 1000000") } @@ -393,7 +396,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestPerValidatorRequestFeePanic() params := suite.chainB.App.OracleKeeper.GetParams(suite.chainB.GetContext()) params.PerValidatorRequestGas = 100000000 - suite.chainB.App.OracleKeeper.SetParams(suite.chainB.GetContext(), params) + err := suite.chainB.App.OracleKeeper.SetParams(suite.chainB.GetContext(), params) + suite.Require().NoError(err) // send request from A to B timeoutHeight := clienttypes.NewHeight(0, 110) @@ -410,7 +414,7 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestPerValidatorRequestFeePanic() packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) // ConsumeGas panics due to insufficient gas, so ErrAcknowledgement is not created. - err := path.RelayPacket(packet) + err = path.RelayPacket(packet) suite.Require().Contains(err.Error(), "PER_VALIDATOR_REQUEST_FEE; gasWanted: 1000000") } @@ -503,7 +507,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestInvalidDataSourceCount() { params := suite.chainB.App.OracleKeeper.GetParams(suite.chainB.GetContext()) params.MaxRawRequestCount = 3 - suite.chainB.App.OracleKeeper.SetParams(suite.chainB.GetContext(), params) + err := suite.chainB.App.OracleKeeper.SetParams(suite.chainB.GetContext(), params) + suite.Require().NoError(err) // send request from A to B timeoutHeight := clienttypes.NewHeight(0, 110) @@ -522,7 +527,7 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestInvalidDataSourceCount() { ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) - err := path.RelayPacket(packet) + err = path.RelayPacket(packet) suite.Require().NoError(err) // relay committed } @@ -595,7 +600,8 @@ func (suite *OracleTestSuite) TestIBCResolveRequestOutOfGas() { types.NewRawReport(2, 0, []byte("data2")), types.NewRawReport(3, 0, []byte("data3")), } - suite.chainB.SendReport(1, raws, testapp.Validators[0]) + _, err = suite.chainB.SendReport(1, raws, testapp.Validators[0]) + suite.Require().NoError(err) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( suite.chainB.GetContext(), @@ -651,10 +657,12 @@ func (suite *OracleTestSuite) TestIBCResolveReadNilExternalData() { suite.checkChainBSenderBalances(sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(5970000)))) raws1 := []types.RawReport{types.NewRawReport(0, 0, nil), types.NewRawReport(1, 0, []byte("beebd2v1"))} - suite.chainB.SendReport(1, raws1, testapp.Validators[0]) + _, err = suite.chainB.SendReport(1, raws1, testapp.Validators[0]) + suite.Require().NoError(err) raws2 := []types.RawReport{types.NewRawReport(0, 0, []byte("beebd1v2")), types.NewRawReport(1, 0, nil)} - suite.chainB.SendReport(1, raws2, testapp.Validators[1]) + _, err = suite.chainB.SendReport(1, raws2, testapp.Validators[1]) + suite.Require().NoError(err) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( suite.chainB.GetContext(), @@ -708,7 +716,8 @@ func (suite *OracleTestSuite) TestIBCResolveRequestNoReturnData() { )) raws := []types.RawReport{types.NewRawReport(1, 0, []byte("beeb"))} - suite.chainB.SendReport(1, raws, testapp.Validators[0]) + _, err := suite.chainB.SendReport(1, raws, testapp.Validators[0]) + suite.Require().NoError(err) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( suite.chainB.GetContext(), @@ -762,7 +771,8 @@ func (suite *OracleTestSuite) TestIBCResolveRequestWasmFailure() { )) raws := []types.RawReport{types.NewRawReport(1, 0, []byte("beeb"))} - suite.chainB.SendReport(1, raws, testapp.Validators[0]) + _, err := suite.chainB.SendReport(1, raws, testapp.Validators[0]) + suite.Require().NoError(err) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( suite.chainB.GetContext(), @@ -816,7 +826,8 @@ func (suite *OracleTestSuite) TestIBCResolveRequestCallReturnDataSeveralTimes() )) raws := []types.RawReport{types.NewRawReport(1, 0, []byte("beeb"))} - suite.chainB.SendReport(1, raws, testapp.Validators[0]) + _, err := suite.chainB.SendReport(1, raws, testapp.Validators[0]) + suite.Require().NoError(err) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( suite.chainB.GetContext(), diff --git a/x/oracle/keeper/grpc_query.go b/x/oracle/keeper/grpc_query.go index b8344c312..f83a91258 100644 --- a/x/oracle/keeper/grpc_query.go +++ b/x/oracle/keeper/grpc_query.go @@ -26,10 +26,10 @@ var _ types.QueryServer = Querier{} func (k Querier) Counts(c context.Context, req *types.QueryCountsRequest) (*types.QueryCountsResponse, error) { ctx := sdk.UnwrapSDKContext(c) return &types.QueryCountsResponse{ - DataSourceCount: k.GetDataSourceCount(ctx), - OracleScriptCount: k.GetOracleScriptCount(ctx), - RequestCount: k.GetRequestCount(ctx)}, - nil + DataSourceCount: k.GetDataSourceCount(ctx), + OracleScriptCount: k.GetOracleScriptCount(ctx), + RequestCount: k.GetRequestCount(ctx), + }, nil } // Data queries the data source or oracle script script for given file hash. @@ -343,7 +343,7 @@ func (k Querier) RequestVerification( if err != nil || len(pk) != secp256k1.PubKeySize { return nil, status.Error(codes.InvalidArgument, "unable to get reporter's public key") } - reporterPubKey := secp256k1.PubKey(pk[:]) + reporterPubKey := secp256k1.PubKey(pk) requestVerificationContent := types.NewRequestVerification( req.ChainId, @@ -400,14 +400,14 @@ func (k Querier) RequestVerification( } // Provided external ID should be required by the request determined by oracle script - var dataSourceID *types.DataSourceID + var dataSourceID types.DataSourceID for _, rawRequest := range request.RawRequests { if rawRequest.ExternalID == types.ExternalID(req.ExternalId) { - dataSourceID = &rawRequest.DataSourceID + dataSourceID = rawRequest.DataSourceID break } } - if dataSourceID == nil { + if dataSourceID == 0 { return nil, status.Error( codes.InvalidArgument, fmt.Sprintf( @@ -417,7 +417,7 @@ func (k Querier) RequestVerification( ), ) } - if *dataSourceID != types.DataSourceID(req.DataSourceId) { + if dataSourceID != types.DataSourceID(req.DataSourceId) { return nil, status.Error( codes.InvalidArgument, fmt.Sprintf( @@ -458,7 +458,7 @@ func (k Querier) RequestVerification( Validator: req.Validator, RequestId: req.RequestId, ExternalId: req.ExternalId, - DataSourceId: uint64(*dataSourceID), + DataSourceId: uint64(dataSourceID), IsDelay: false, }, nil } diff --git a/x/oracle/keeper/grpc_query_test.go b/x/oracle/keeper/grpc_query_test.go index 0ed02531f..0f517f704 100644 --- a/x/oracle/keeper/grpc_query_test.go +++ b/x/oracle/keeper/grpc_query_test.go @@ -63,8 +63,10 @@ func (suite *RequestVerificationTestSuite) SetupTest() { k.SetRequest(ctx, types.RequestID(1), suite.request) k.SetRequestCount(ctx, 1) err := k.GrantReporter(ctx, testapp.Validators[0].ValAddress, suite.reporterAddr) + suite.assert.NoError(err) + expiration := ctx.BlockTime().Add(10 * time.Minute) - app.AuthzKeeper.SaveGrant(ctx, suite.granteeAddr, sdk.AccAddress(testapp.Validators[0].ValAddress), + err = app.AuthzKeeper.SaveGrant(ctx, suite.granteeAddr, sdk.AccAddress(testapp.Validators[0].ValAddress), authz.NewGenericAuthorization("some url"), &expiration, ) suite.assert.NoError(err) @@ -547,7 +549,8 @@ func (suite *RequestVerificationTestSuite) TestIsNotReporter() { } func (suite *RequestVerificationTestSuite) TestRevokeReporters() { - suite.querier.Keeper.RevokeReporter(suite.ctx, testapp.Validators[0].ValAddress, suite.reporterAddr) + err := suite.querier.Keeper.RevokeReporter(suite.ctx, testapp.Validators[0].ValAddress, suite.reporterAddr) + suite.assert.NoError(err) req := &types.QueryReportersRequest{ ValidatorAddress: testapp.Validators[0].ValAddress.String(), } diff --git a/x/oracle/keeper/oracle_script_test.go b/x/oracle/keeper/oracle_script_test.go index 80bdeaa0d..87bebbe66 100644 --- a/x/oracle/keeper/oracle_script_test.go +++ b/x/oracle/keeper/oracle_script_test.go @@ -121,7 +121,7 @@ func TestAddOracleScriptMustReturnCorrectID(t *testing.T) { )) require.Equal(t, types.OracleScriptID(genesisCount+2), id2) // Finally we expect the oracle script to increase as well. - require.Equal(t, uint64(genesisCount+2), k.GetOracleScriptCount(ctx)) + require.Equal(t, genesisCount+2, k.GetOracleScriptCount(ctx)) } func TestEditNonExistentOracleScript(t *testing.T) { diff --git a/x/oracle/keeper/owasm.go b/x/oracle/keeper/owasm.go index 44dd03799..a39683c98 100644 --- a/x/oracle/keeper/owasm.go +++ b/x/oracle/keeper/owasm.go @@ -15,7 +15,7 @@ import ( const gasConversionFactor = 20_000_000 func ConvertToOwasmGas(cosmos uint64) uint64 { - return uint64(cosmos * gasConversionFactor) + return cosmos * gasConversionFactor } // GetSpanSize return maximum value between MaxReportDataSize and MaxCallDataSize diff --git a/x/oracle/keeper/owasm_test.go b/x/oracle/keeper/owasm_test.go index 415dcf2b6..6aac3f958 100644 --- a/x/oracle/keeper/owasm_test.go +++ b/x/oracle/keeper/owasm_test.go @@ -95,8 +95,10 @@ func TestGetRandomValidatorsWithActivate(t *testing.T) { _, err := k.GetRandomValidators(ctx, 1, 1) require.ErrorIs(t, err, types.ErrInsufficientValidators) // If we activate 2 validators, we should be able to get at most 2 from the function. - k.Activate(ctx, testapp.Validators[0].ValAddress) - k.Activate(ctx, testapp.Validators[1].ValAddress) + err = k.Activate(ctx, testapp.Validators[0].ValAddress) + require.NoError(t, err) + err = k.Activate(ctx, testapp.Validators[1].ValAddress) + require.NoError(t, err) vals, err := k.GetRandomValidators(ctx, 1, 1) require.NoError(t, err) require.Equal(t, []sdk.ValAddress{testapp.Validators[0].ValAddress}, vals) @@ -387,7 +389,8 @@ func TestPrepareRequestInvalidAskCountFail(t *testing.T) { _, ctx, k := testapp.CreateTestInput(true) params := k.GetParams(ctx) params.MaxAskCount = 5 - k.SetParams(ctx, params) + err := k.SetParams(ctx, params) + require.NoError(t, err) wrappedGasMeter := testapp.NewGasMeterWrapper(ctx.GasMeter()) ctx = ctx.WithGasMeter(wrappedGasMeter) @@ -403,7 +406,7 @@ func TestPrepareRequestInvalidAskCountFail(t *testing.T) { testapp.TestDefaultExecuteGas, testapp.Alice.Address, ) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) require.ErrorIs(t, err, types.ErrInvalidAskCount) require.Equal(t, 0, wrappedGasMeter.CountDescriptor("BASE_OWASM_FEE")) @@ -452,7 +455,8 @@ func TestPrepareRequestBaseOwasmFeePanic(t *testing.T) { params := k.GetParams(ctx) params.BaseOwasmGas = 100000 params.PerValidatorRequestGas = 0 - k.SetParams(ctx, params) + err := k.SetParams(ctx, params) + require.NoError(t, err) m := types.NewMsgRequestData( 1, BasicCalldata, @@ -468,7 +472,7 @@ func TestPrepareRequestBaseOwasmFeePanic(t *testing.T) { require.PanicsWithValue( t, sdk.ErrorOutOfGas{Descriptor: "BASE_OWASM_FEE"}, - func() { k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) }, + func() { _, _ = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) }, ) ctx = ctx.WithGasMeter(sdk.NewGasMeter(1000000)) id, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) @@ -481,7 +485,8 @@ func TestPrepareRequestPerValidatorRequestFeePanic(t *testing.T) { params := k.GetParams(ctx) params.BaseOwasmGas = 100000 params.PerValidatorRequestGas = 50000 - k.SetParams(ctx, params) + err := k.SetParams(ctx, params) + require.NoError(t, err) m := types.NewMsgRequestData( 1, BasicCalldata, @@ -497,7 +502,7 @@ func TestPrepareRequestPerValidatorRequestFeePanic(t *testing.T) { require.PanicsWithValue( t, sdk.ErrorOutOfGas{Descriptor: "PER_VALIDATOR_REQUEST_FEE"}, - func() { k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) }, + func() { _, _ = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) }, ) m = types.NewMsgRequestData( 1, @@ -598,12 +603,13 @@ func TestPrepareRequestInvalidDataSourceCount(t *testing.T) { _, ctx, k := testapp.CreateTestInput(true) params := k.GetParams(ctx) params.MaxRawRequestCount = 3 - k.SetParams(ctx, params) + err := k.SetParams(ctx, params) + require.NoError(t, err) m := types.NewMsgRequestData(4, obi.MustEncode(testapp.Wasm4Input{ IDs: []int64{1, 2, 3, 4}, Calldata: "beeb", }), 1, 1, BasicClientID, testapp.Coins100000000uband, testapp.TestDefaultPrepareGas, testapp.TestDefaultExecuteGas, testapp.Alice.Address) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) require.ErrorIs(t, err, types.ErrBadWasmExecution) m = types.NewMsgRequestData(4, obi.MustEncode(testapp.Wasm4Input{ IDs: []int64{1, 2, 3}, @@ -1075,15 +1081,17 @@ func TestCollectFeeWithWithManyUnitSuccess(t *testing.T) { testapp.EmptyCoins, }) - app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, sdk.NewCoins(sdk.NewCoin("uabc", sdk.NewInt(2000000)))) + err := app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, sdk.NewCoins(sdk.NewCoin("uabc", sdk.NewInt(2000000)))) + require.NoError(t, err) // Carol have not enough uband but have enough uabc - app.BankKeeper.SendCoinsFromModuleToAccount( + err = app.BankKeeper.SendCoinsFromModuleToAccount( ctx, minttypes.ModuleName, testapp.FeePayer.Address, sdk.NewCoins(sdk.NewCoin("uabc", sdk.NewInt(2000000))), ) + require.NoError(t, err) coins, err := k.CollectFee( ctx, @@ -1136,35 +1144,42 @@ func TestCollectFeeWithWithManyUnitFail(t *testing.T) { testapp.EmptyCoins, }) - app.BankKeeper.MintCoins( + err := app.BankKeeper.MintCoins( ctx, minttypes.ModuleName, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(10000000)), sdk.NewCoin("uabc", sdk.NewInt(2000000))), ) + require.NoError(t, err) + // Alice have no enough uband and don't have uabc so don't top up // Bob have enough uband and have some but not enough uabc so add some - app.BankKeeper.SendCoinsFromModuleToAccount( + err = app.BankKeeper.SendCoinsFromModuleToAccount( ctx, minttypes.ModuleName, testapp.Bob.Address, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), ) - app.BankKeeper.SendCoinsFromModuleToAccount( + require.NoError(t, err) + + err = app.BankKeeper.SendCoinsFromModuleToAccount( ctx, minttypes.ModuleName, testapp.Bob.Address, sdk.NewCoins(sdk.NewCoin("uabc", sdk.NewInt(1))), ) + require.NoError(t, err) + // Carol have not enough uband but have enough uabc - app.BankKeeper.SendCoinsFromModuleToAccount( + err = app.BankKeeper.SendCoinsFromModuleToAccount( ctx, minttypes.ModuleName, testapp.Carol.Address, sdk.NewCoins(sdk.NewCoin("uabc", sdk.NewInt(1000000))), ) + require.NoError(t, err) // Alice - _, err := k.CollectFee( + _, err = k.CollectFee( ctx, testapp.Alice.Address, testapp.MustGetBalances(ctx, app.BankKeeper, testapp.Alice.Address), diff --git a/x/oracle/keeper/params_test.go b/x/oracle/keeper/params_test.go index 9b94a8473..58fdb502a 100644 --- a/x/oracle/keeper/params_test.go +++ b/x/oracle/keeper/params_test.go @@ -25,7 +25,8 @@ func TestGetSetParams(t *testing.T) { InactivePenaltyDuration: 1000, IBCRequestEnabled: true, } - k.SetParams(ctx, expectedParams) + err := k.SetParams(ctx, expectedParams) + require.NoError(t, err) require.Equal(t, expectedParams, k.GetParams(ctx)) expectedParams = types.Params{ @@ -41,7 +42,8 @@ func TestGetSetParams(t *testing.T) { InactivePenaltyDuration: 10000, IBCRequestEnabled: false, } - k.SetParams(ctx, expectedParams) + err = k.SetParams(ctx, expectedParams) + require.NoError(t, err) require.Equal(t, expectedParams, k.GetParams(ctx)) expectedParams = types.Params{ @@ -57,7 +59,8 @@ func TestGetSetParams(t *testing.T) { InactivePenaltyDuration: 0, IBCRequestEnabled: false, } - k.SetParams(ctx, expectedParams) + err = k.SetParams(ctx, expectedParams) + require.NoError(t, err) require.Equal(t, expectedParams, k.GetParams(ctx)) expectedParams = types.Params{ @@ -73,6 +76,6 @@ func TestGetSetParams(t *testing.T) { InactivePenaltyDuration: 10000, IBCRequestEnabled: false, } - err := k.SetParams(ctx, expectedParams) + err = k.SetParams(ctx, expectedParams) require.EqualError(t, fmt.Errorf("max raw request count must be positive: 0"), err.Error()) } diff --git a/x/oracle/keeper/request.go b/x/oracle/keeper/request.go index 1629afa10..f293289c0 100644 --- a/x/oracle/keeper/request.go +++ b/x/oracle/keeper/request.go @@ -76,7 +76,7 @@ func (k Keeper) ProcessExpiredRequests(ctx sdk.Context) { for _, val := range req.RequestedValidators { v, _ := sdk.ValAddressFromBech32(val) if !k.HasReport(ctx, currentReqID, v) { - k.MissReport(ctx, v, time.Unix(int64(req.RequestTime), 0)) + k.MissReport(ctx, v, time.Unix(req.RequestTime, 0)) } } diff --git a/x/oracle/keeper/request_test.go b/x/oracle/keeper/request_test.go index 4bf0f533a..fe53cf9af 100644 --- a/x/oracle/keeper/request_test.go +++ b/x/oracle/keeper/request_test.go @@ -132,7 +132,8 @@ func TestProcessExpiredRequests(t *testing.T) { _, ctx, k := testapp.CreateTestInput(true) params := k.GetParams(ctx) params.ExpirationBlockCount = 3 - k.SetParams(ctx, params) + err := k.SetParams(ctx, params) + require.NoError(t, err) // Set some initial requests. All requests are asked to validators 1 & 2. req1 := defaultRequest() @@ -154,13 +155,20 @@ func TestProcessExpiredRequests(t *testing.T) { // Validator 1 reports all requests. Validator 2 misses request#3. rawReports := []types.RawReport{types.NewRawReport(42, 0, BasicReport), types.NewRawReport(43, 0, BasicReport)} - k.AddReport(ctx, 1, testapp.Validators[0].ValAddress, false, rawReports) - k.AddReport(ctx, 2, testapp.Validators[0].ValAddress, true, rawReports) - k.AddReport(ctx, 3, testapp.Validators[0].ValAddress, false, rawReports) - k.AddReport(ctx, 4, testapp.Validators[0].ValAddress, true, rawReports) - k.AddReport(ctx, 1, testapp.Validators[1].ValAddress, true, rawReports) - k.AddReport(ctx, 2, testapp.Validators[1].ValAddress, true, rawReports) - k.AddReport(ctx, 4, testapp.Validators[1].ValAddress, true, rawReports) + err = k.AddReport(ctx, 1, testapp.Validators[0].ValAddress, false, rawReports) + require.NoError(t, err) + err = k.AddReport(ctx, 2, testapp.Validators[0].ValAddress, true, rawReports) + require.NoError(t, err) + err = k.AddReport(ctx, 3, testapp.Validators[0].ValAddress, false, rawReports) + require.NoError(t, err) + err = k.AddReport(ctx, 4, testapp.Validators[0].ValAddress, true, rawReports) + require.NoError(t, err) + err = k.AddReport(ctx, 1, testapp.Validators[1].ValAddress, true, rawReports) + require.NoError(t, err) + err = k.AddReport(ctx, 2, testapp.Validators[1].ValAddress, true, rawReports) + require.NoError(t, err) + err = k.AddReport(ctx, 4, testapp.Validators[1].ValAddress, true, rawReports) + require.NoError(t, err) // Request 1, 2 and 4 gets resolved. Request 3 does not. k.ResolveSuccess(ctx, 1, BasicResult, 1234) @@ -209,7 +217,7 @@ func TestProcessExpiredRequests(t *testing.T) { require.False(t, k.GetValidatorStatus(ctx, testapp.Validators[1].ValAddress).IsActive) require.Equal(t, types.NewResult( BasicClientID, req3.OracleScriptID, req3.Calldata, uint64(len(req3.RequestedValidators)), req3.MinCount, - 3, 1, int64(req3.RequestTime), testapp.ParseTime(9000).Unix(), + 3, 1, req3.RequestTime, testapp.ParseTime(9000).Unix(), types.RESOLVE_STATUS_EXPIRED, nil, ), k.MustGetResult(ctx, 3)) testRequest(t, k, ctx, types.RequestID(1), types.RESOLVE_STATUS_SUCCESS, 0, false) diff --git a/x/oracle/keeper/result.go b/x/oracle/keeper/result.go index 6dd998872..05732751f 100644 --- a/x/oracle/keeper/result.go +++ b/x/oracle/keeper/result.go @@ -93,7 +93,7 @@ func (k Keeper) SaveResult( r.MinCount, // MinCount id, // RequestID reportCount, // AnsCount - int64(r.RequestTime), // RequestTime + r.RequestTime, // RequestTime ctx.BlockTime().Unix(), // ResolveTime status, // ResolveStatus result, // Result @@ -113,7 +113,7 @@ func (k Keeper) SaveResult( } packetData := types.NewOracleResponsePacketData( - r.ClientID, id, reportCount, int64(r.RequestTime), ctx.BlockTime().Unix(), status, result, + r.ClientID, id, reportCount, r.RequestTime, ctx.BlockTime().Unix(), status, result, ) if _, err := k.channelKeeper.SendPacket( diff --git a/x/oracle/keeper/validator_status_test.go b/x/oracle/keeper/validator_status_test.go index 94dbac3f9..8baa5e122 100644 --- a/x/oracle/keeper/validator_status_test.go +++ b/x/oracle/keeper/validator_status_test.go @@ -41,8 +41,8 @@ func defaultVotes() []abci.VoteInfo { func SetupFeeCollector(app *testapp.TestingApp, ctx sdk.Context, k keeper.Keeper) authtypes.ModuleAccountI { // Set collected fee to 1000000uband and 70% oracle reward proportion. feeCollector := app.AccountKeeper.GetModuleAccount(ctx, authtypes.FeeCollectorName) - app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, Coins1000000uband) - app.BankKeeper.SendCoinsFromModuleToModule( + _ = app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, Coins1000000uband) + _ = app.BankKeeper.SendCoinsFromModuleToModule( ctx, minttypes.ModuleName, authtypes.FeeCollectorName, @@ -52,7 +52,7 @@ func SetupFeeCollector(app *testapp.TestingApp, ctx sdk.Context, k keeper.Keeper params := k.GetParams(ctx) params.OracleRewardPercentage = 70 - k.SetParams(ctx, params) + _ = k.SetParams(ctx, params) return feeCollector } @@ -76,7 +76,8 @@ func TestAllocateTokensOneActive(t *testing.T) { require.Equal(t, Coins1000000uband, app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress())) // From 70% of fee, 2% should go to community pool, the rest goes to the only active validator. - k.Activate(ctx, testapp.Validators[1].ValAddress) + err := k.Activate(ctx, testapp.Validators[1].ValAddress) + require.NoError(t, err) k.AllocateTokens(ctx, defaultVotes()) distAccount := app.AccountKeeper.GetModuleAccount(ctx, disttypes.ModuleName) diff --git a/x/oracle/module.go b/x/oracle/module.go index e7729b8a7..29e6bd8fd 100644 --- a/x/oracle/module.go +++ b/x/oracle/module.go @@ -5,9 +5,6 @@ import ( "encoding/json" "fmt" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - abci "github.com/cometbft/cometbft/abci/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" @@ -15,6 +12,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" porttypes "github.com/cosmos/ibc-go/v7/modules/core/05-port/types" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" "github.com/bandprotocol/chain/v2/x/oracle/client/cli" "github.com/bandprotocol/chain/v2/x/oracle/exported" @@ -66,7 +65,7 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncod // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the oracle module. func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) + _ = types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) } // GetTxCmd returns cobra CLI command to send txs for this module (SDK AppModuleBasic interface). diff --git a/x/oracle/types/channel.go b/x/oracle/types/channel.go index 33aa45b30..38fb48171 100644 --- a/x/oracle/types/channel.go +++ b/x/oracle/types/channel.go @@ -1,9 +1,9 @@ package types // NewIBCChannel creates a new IBCChannel instance. -func NewIBCChannel(portId, channelId string) IBCChannel { +func NewIBCChannel(portID, channelID string) IBCChannel { return IBCChannel{ - PortId: portId, - ChannelId: channelId, + PortId: portID, + ChannelId: channelID, } } diff --git a/x/oracle/types/constants.go b/x/oracle/types/constants.go index 2a0d17688..3a87650be 100644 --- a/x/oracle/types/constants.go +++ b/x/oracle/types/constants.go @@ -1,6 +1,5 @@ package types -// nolint const ( DoNotModify = "[do-not-modify]" @@ -17,7 +16,4 @@ const ( MaximumOwasmGas = 8000000 ) -// nolint -var ( - DoNotModifyBytes = []byte(DoNotModify) -) +var DoNotModifyBytes = []byte(DoNotModify) diff --git a/x/oracle/types/events.go b/x/oracle/types/events.go index 65119ee66..62e376429 100644 --- a/x/oracle/types/events.go +++ b/x/oracle/types/events.go @@ -1,6 +1,5 @@ package types -// nolint const ( EventTypeCreateDataSource = "create_data_source" EventTypeEditDataSource = "edit_data_source" diff --git a/x/oracle/types/exec_env.go b/x/oracle/types/exec_env.go index 33a2ce122..a25b736c5 100644 --- a/x/oracle/types/exec_env.go +++ b/x/oracle/types/exec_env.go @@ -44,7 +44,7 @@ func (env *BaseEnv) GetMinCount() int64 { // GetPrepareTime implements Owasm ExecEnv interface. func (env *BaseEnv) GetPrepareTime() int64 { - return int64(env.request.RequestTime) + return env.request.RequestTime } // GetExecuteTime implements Owasm ExecEnv interface. diff --git a/x/oracle/types/exec_env_test.go b/x/oracle/types/exec_env_test.go index c8b8d12cb..340622b2e 100644 --- a/x/oracle/types/exec_env_test.go +++ b/x/oracle/types/exec_env_test.go @@ -4,11 +4,10 @@ import ( "testing" "time" + "github.com/bandprotocol/go-owasm/api" "github.com/cometbft/cometbft/crypto/secp256k1" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - - "github.com/bandprotocol/go-owasm/api" ) var ( @@ -78,9 +77,9 @@ func mockFreshPrepareEnv() *PrepareEnv { func mockAlreadyPreparedEnv() *PrepareEnv { env := mockFreshPrepareEnv() - env.AskExternalData(1, 1, []byte("CALLDATA1")) - env.AskExternalData(2, 2, []byte("CALLDATA2")) - env.AskExternalData(3, 3, []byte("CALLDATA3")) + _ = env.AskExternalData(1, 1, []byte("CALLDATA1")) + _ = env.AskExternalData(2, 2, []byte("CALLDATA2")) + _ = env.AskExternalData(3, 3, []byte("CALLDATA3")) return env } @@ -102,9 +101,11 @@ func TestSetReturnData(t *testing.T) { require.Equal(t, api.ErrWrongPeriodAction, err) eenv := mockExecEnv() - eenv.SetReturnData(result) + err = eenv.SetReturnData(result) + require.NoError(t, err) require.Equal(t, result, eenv.Retdata) } + func TestGetAskCount(t *testing.T) { // Can call on both environment penv := mockFreshPrepareEnv() @@ -200,9 +201,12 @@ func TestFailedGetExternalData(t *testing.T) { func TestAskExternalData(t *testing.T) { env := mockFreshPrepareEnv() - env.AskExternalData(1, 1, []byte("CALLDATA1")) - env.AskExternalData(42, 2, []byte("CALLDATA2")) - env.AskExternalData(3, 4, []byte("CALLDATA3")) + err := env.AskExternalData(1, 1, []byte("CALLDATA1")) + require.NoError(t, err) + err = env.AskExternalData(42, 2, []byte("CALLDATA2")) + require.NoError(t, err) + err = env.AskExternalData(3, 4, []byte("CALLDATA3")) + require.NoError(t, err) rawReq := env.GetRawRequests() expectRawReq := []RawRequest{ @@ -220,6 +224,7 @@ func TestAskExternalDataOnTooSmallSpan(t *testing.T) { require.Equal(t, api.ErrSpanTooSmall, err) require.Equal(t, []RawRequest(nil), penv.GetRawRequests()) } + func TestAskTooManyExternalData(t *testing.T) { penv := mockFreshPrepareEnv() diff --git a/x/oracle/types/msgs.go b/x/oracle/types/msgs.go index 3d83c6731..43c7341b0 100644 --- a/x/oracle/types/msgs.go +++ b/x/oracle/types/msgs.go @@ -503,23 +503,23 @@ func NewMsgUpdateParams(authority string, params Params) *MsgUpdateParams { } // GetSignBytes implements the LegacyMsg interface. -func (m MsgUpdateParams) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) +func (msg MsgUpdateParams) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) } // GetSigners returns the expected signers for a MsgUpdateParams message. -func (m *MsgUpdateParams) GetSigners() []sdk.AccAddress { - addr, _ := sdk.AccAddressFromBech32(m.Authority) +func (msg *MsgUpdateParams) GetSigners() []sdk.AccAddress { + addr, _ := sdk.AccAddressFromBech32(msg.Authority) return []sdk.AccAddress{addr} } // ValidateBasic does a sanity check on the provided data. -func (m *MsgUpdateParams) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.Authority); err != nil { +func (msg *MsgUpdateParams) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { return errorsmod.Wrap(err, "invalid authority address") } - if err := m.Params.Validate(); err != nil { + if err := msg.Params.Validate(); err != nil { return err } diff --git a/x/oracle/types/oracle_script.go b/x/oracle/types/oracle_script.go index 61cd80927..a10d50464 100644 --- a/x/oracle/types/oracle_script.go +++ b/x/oracle/types/oracle_script.go @@ -5,19 +5,19 @@ import ( ) func NewOracleScript( - Owner sdk.AccAddress, - Name string, - Description string, - Filename string, - Schema string, - SourceCodeURL string, + owner sdk.AccAddress, + name string, + description string, + filename string, + schema string, + sourceCodeURL string, ) OracleScript { return OracleScript{ - Owner: Owner.String(), - Name: Name, - Description: Description, - Filename: Filename, - Schema: Schema, - SourceCodeURL: SourceCodeURL, + Owner: owner.String(), + Name: name, + Description: description, + Filename: filename, + Schema: schema, + SourceCodeURL: sourceCodeURL, } } diff --git a/x/oracle/types/params.go b/x/oracle/types/params.go index 4a478dde5..43e2d1b08 100644 --- a/x/oracle/types/params.go +++ b/x/oracle/types/params.go @@ -7,7 +7,6 @@ import ( "gopkg.in/yaml.v2" ) -// nolint const ( // Each value below is the default value for each parameter when generating the default // genesis file. See comments in types.proto for explanation for each parameter. diff --git a/x/oracle/types/params_legacy.go b/x/oracle/types/params_legacy.go index 3ff56a3c1..a34d45c0c 100644 --- a/x/oracle/types/params_legacy.go +++ b/x/oracle/types/params_legacy.go @@ -9,7 +9,6 @@ import ( paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) -// nolint // Parameter store keys var ( // Each value below is the key to store the respective oracle module parameter. See comments diff --git a/x/oracle/types/report.go b/x/oracle/types/report.go index 1bf810e09..f4cc5da8d 100644 --- a/x/oracle/types/report.go +++ b/x/oracle/types/report.go @@ -5,25 +5,25 @@ import ( ) func NewReport( - Validator sdk.ValAddress, - InBeforeResolve bool, - RawReports []RawReport, + validator sdk.ValAddress, + inBeforeResolve bool, + rawReports []RawReport, ) Report { return Report{ - Validator: Validator.String(), - InBeforeResolve: InBeforeResolve, - RawReports: RawReports, + Validator: validator.String(), + InBeforeResolve: inBeforeResolve, + RawReports: rawReports, } } func NewRawReport( - ExternalID ExternalID, - ExitCode uint32, - Data []byte, + externalID ExternalID, + exitCode uint32, + data []byte, ) RawReport { return RawReport{ - ExternalID: ExternalID, - ExitCode: ExitCode, - Data: Data, + ExternalID: externalID, + ExitCode: exitCode, + Data: data, } } diff --git a/x/oracle/types/request.go b/x/oracle/types/request.go index afdb93208..9c8a636e8 100644 --- a/x/oracle/types/request.go +++ b/x/oracle/types/request.go @@ -24,14 +24,14 @@ type RequestSpec interface { } func NewRawRequest( - ExternalID ExternalID, - DataSourceID DataSourceID, - Calldata []byte, + externalID ExternalID, + dataSourceID DataSourceID, + calldata []byte, ) RawRequest { return RawRequest{ - ExternalID: ExternalID, - DataSourceID: DataSourceID, - Calldata: Calldata, + ExternalID: externalID, + DataSourceID: dataSourceID, + Calldata: calldata, } } diff --git a/x/oracle/types/result.go b/x/oracle/types/result.go index f5f81939d..56d1d55c9 100644 --- a/x/oracle/types/result.go +++ b/x/oracle/types/result.go @@ -2,23 +2,23 @@ package types // NewResult creates a new Result instance. func NewResult( - clientId string, + clientID string, oid OracleScriptID, calldata []byte, askCount, minCount uint64, - requestId RequestID, + requestID RequestID, ansCount uint64, requestTime, resolveTime int64, resolveStatus ResolveStatus, result []byte, ) Result { return Result{ - ClientID: clientId, + ClientID: clientID, OracleScriptID: oid, Calldata: calldata, AskCount: askCount, MinCount: minCount, - RequestID: requestId, + RequestID: requestID, AnsCount: ansCount, RequestTime: requestTime, ResolveTime: resolveTime, diff --git a/x/oracle/types/validator_status.go b/x/oracle/types/validator_status.go index 7a204fd1c..71fb7db4c 100644 --- a/x/oracle/types/validator_status.go +++ b/x/oracle/types/validator_status.go @@ -3,11 +3,11 @@ package types import "time" func NewValidatorStatus( - IsActive bool, - Since time.Time, + isActive bool, + since time.Time, ) ValidatorStatus { return ValidatorStatus{ - IsActive: IsActive, - Since: Since, + IsActive: isActive, + Since: since, } } diff --git a/yoda/execute.go b/yoda/execute.go index b1c953e6e..9f753c714 100644 --- a/yoda/execute.go +++ b/yoda/execute.go @@ -21,10 +21,8 @@ import ( "github.com/bandprotocol/chain/v2/x/oracle/types" ) -var ( - // Proto codec for encoding/decoding proto message - cdc = band.MakeEncodingConfig().Marshaler -) +// Proto codec for encoding/decoding proto message +var cdc = band.MakeEncodingConfig().Marshaler func signAndBroadcast( c *Context, key *keyring.Record, msgs []sdk.Msg, gasLimit uint64, memo string, diff --git a/yoda/executor/docker.go b/yoda/executor/docker.go index fdd65961b..5704b8632 100644 --- a/yoda/executor/docker.go +++ b/yoda/executor/docker.go @@ -30,7 +30,7 @@ func (e *DockerExec) Exec(code []byte, arg string, env interface{}) (ExecResult, return ExecResult{}, err } defer os.RemoveAll(dir) - err = os.WriteFile(filepath.Join(dir, "exec"), code, 0777) + err = os.WriteFile(filepath.Join(dir, "exec"), code, 0o600) if err != nil { return ExecResult{}, err } @@ -54,7 +54,7 @@ func (e *DockerExec) Exec(code []byte, arg string, env interface{}) (ExecResult, cmd.Stderr = &buf err = cmd.Run() if ctx.Err() == context.DeadlineExceeded { - exec.Command("docker", "kill", name).Start() + _ = exec.Command("docker", "kill", name).Start() return ExecResult{}, ErrExecutionimeout } exitCode := uint32(0) diff --git a/yoda/executor/executor.go b/yoda/executor/executor.go index 1eddaa24b..e4a7df03f 100644 --- a/yoda/executor/executor.go +++ b/yoda/executor/executor.go @@ -54,7 +54,6 @@ func NewExecutor(executor string) (exec Executor, err error) { "BAND_REPORTER": "test-reporter", "BAND_SIGNATURE": "test-signature", }) - if err != nil { return nil, fmt.Errorf("failed to run test program: %s", err.Error()) } @@ -64,6 +63,7 @@ func NewExecutor(executor string) (exec Executor, err error) { if string(res.Output) != "TEST_ARG test-chain-id\n" { return nil, fmt.Errorf("test program returned wrong output: %s", res.Output) } + return exec, nil } diff --git a/yoda/executor/rest.go b/yoda/executor/rest.go index 5e01bdb1d..a37573fb6 100644 --- a/yoda/executor/rest.go +++ b/yoda/executor/rest.go @@ -41,7 +41,6 @@ func (e *RestExec) Exec(code []byte, arg string, env interface{}) (ExecResult, e RequestTimeout: e.timeout, }, ) - if err != nil { urlErr, ok := err.(*url.Error) if !ok || !urlErr.Timeout() { diff --git a/yoda/executor/rest_test.go b/yoda/executor/rest_test.go index 2be616afa..c4f88c888 100644 --- a/yoda/executor/rest_test.go +++ b/yoda/executor/rest_test.go @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/require" ) -func creatDefaultServer() *httptest.Server { +func createDefaultServer() *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { res.WriteHeader(200) ret := externalExecutionResponse{ @@ -18,7 +18,7 @@ func creatDefaultServer() *httptest.Server { Stdout: "BEEB", Stderr: "Stderr", } - json.NewEncoder(res).Encode(ret) + _ = json.NewEncoder(res).Encode(ret) })) } @@ -28,14 +28,14 @@ func createResponseNotOkSenarioServer() *httptest.Server { })) } -func createCannotDecodeJsonSenarioServer() *httptest.Server { +func createCannotDecodeJSONSenarioServer() *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { res.WriteHeader(200) - res.Write([]byte("invalid bytes")) + _, _ = res.Write([]byte("invalid bytes")) })) } -func creatExecuteFailSenarioServer() *httptest.Server { +func createExecuteFailSenarioServer() *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { res.WriteHeader(200) ret := externalExecutionResponse{ @@ -43,12 +43,12 @@ func creatExecuteFailSenarioServer() *httptest.Server { Stdout: "BEEB", Stderr: "Stderr", } - json.NewEncoder(res).Encode(ret) + _ = json.NewEncoder(res).Encode(ret) })) } func TestExecuteSuccess(t *testing.T) { - testServer := creatDefaultServer() + testServer := createDefaultServer() defer func() { testServer.Close() }() executor := NewRestExec(testServer.URL, 1*time.Second) @@ -59,7 +59,7 @@ func TestExecuteSuccess(t *testing.T) { } func TestExecuteBadUrlFail(t *testing.T) { - testServer := creatDefaultServer() + testServer := createDefaultServer() defer func() { testServer.Close() }() executor := NewRestExec("www.beeb.com", 1*time.Second) // bad url @@ -68,7 +68,7 @@ func TestExecuteBadUrlFail(t *testing.T) { } func TestExecuteDecodeStructFail(t *testing.T) { - testServer := createCannotDecodeJsonSenarioServer() + testServer := createCannotDecodeJSONSenarioServer() defer func() { testServer.Close() }() executor := NewRestExec(testServer.URL, 1*time.Second) @@ -86,7 +86,7 @@ func TestExecuteResponseNotOk(t *testing.T) { } func TestExecuteFail(t *testing.T) { - testServer := creatExecuteFailSenarioServer() + testServer := createExecuteFailSenarioServer() defer func() { testServer.Close() }() executor := NewRestExec(testServer.URL, 1*time.Second) diff --git a/yoda/gas.go b/yoda/gas.go index fbcbcb429..0b4591fcb 100644 --- a/yoda/gas.go +++ b/yoda/gas.go @@ -107,7 +107,7 @@ func estimateReportHandlerGas(msg *types.MsgReportData, f FeeEstimationData) uin } func estimateAuthAnteHandlerGas(c *Context, msgs []sdk.Msg) uint64 { - gas := uint64(baseAuthAnteGas) + gas := baseAuthAnteGas txByteLength := getTxByteLength(msgs) gas += txCostPerByte * txByteLength diff --git a/yoda/handler.go b/yoda/handler.go index 7a72cbc54..6e0182e42 100644 --- a/yoda/handler.go +++ b/yoda/handler.go @@ -112,7 +112,7 @@ func handleRequest(c *Context, l *Logger, id types.RequestID) { reports, execVersions := handleRawRequests(c, l, id, rawRequests, key) c.pendingMsgs <- ReportMsgWithKey{ - msg: types.NewMsgReportData(types.RequestID(id), reports, c.validator), + msg: types.NewMsgReportData(id, reports, c.validator), execVersion: execVersions, keyIndex: keyIndex, feeEstimationData: FeeEstimationData{ @@ -139,7 +139,7 @@ func handleRawRequests( l.With("did", req.dataSourceID, "eid", req.externalID), req, key, - types.RequestID(id), + id, resultsChan, ) } diff --git a/yoda/keys.go b/yoda/keys.go index 958f6892a..b202426c2 100644 --- a/yoda/keys.go +++ b/yoda/keys.go @@ -186,7 +186,7 @@ func keysListCmd(c *Context) *cobra.Command { }, } cmd.Flags().BoolP(flagAddress, "a", false, "Output the address only") - viper.BindPFlag(flagAddress, cmd.Flags().Lookup(flagAddress)) + _ = viper.BindPFlag(flagAddress, cmd.Flags().Lookup(flagAddress)) flags.AddQueryFlagsToCmd(cmd) diff --git a/yoda/metrics.go b/yoda/metrics.go index 5d054f475..0f38118c4 100644 --- a/yoda/metrics.go +++ b/yoda/metrics.go @@ -3,6 +3,7 @@ package yoda import ( "net/http" "sync/atomic" + "time" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" @@ -60,5 +61,13 @@ func metricsListen(listenAddr string, c *Context) { collector := NewYodaCollector(c) prometheus.MustRegister(collector) http.Handle("/metrics", promhttp.Handler()) - panic(http.ListenAndServe(listenAddr, nil)) + + server := &http.Server{ + Addr: listenAddr, + ReadHeaderTimeout: 10 * time.Second, + } + + if err := server.ListenAndServe(); err != nil { + panic(err) + } } diff --git a/yoda/run.go b/yoda/run.go index e21d52f49..2325543a5 100644 --- a/yoda/run.go +++ b/yoda/run.go @@ -31,7 +31,7 @@ func runImpl(c *Context, l *Logger) error { if err != nil { return err } - defer c.client.Stop() + defer c.client.Stop() //nolint:errcheck ctx, cxl := context.WithTimeout(context.Background(), 5*time.Second) defer cxl() @@ -170,15 +170,16 @@ func runCmd(c *Context) *cobra.Command { cmd.Flags().String(flagRPCPollInterval, "1s", "The duration of rpc poll interval") cmd.Flags().Uint64(flagMaxTry, 5, "The maximum number of tries to submit a report transaction") cmd.Flags().Uint64(flagMaxReport, 10, "The maximum number of reports in one transaction") - viper.BindPFlag(flags.FlagChainID, cmd.Flags().Lookup(flags.FlagChainID)) - viper.BindPFlag(flags.FlagNode, cmd.Flags().Lookup(flags.FlagNode)) - viper.BindPFlag(flagValidator, cmd.Flags().Lookup(flagValidator)) - viper.BindPFlag(flags.FlagGasPrices, cmd.Flags().Lookup(flags.FlagGasPrices)) - viper.BindPFlag(flagLogLevel, cmd.Flags().Lookup(flagLogLevel)) - viper.BindPFlag(flagExecutor, cmd.Flags().Lookup(flagExecutor)) - viper.BindPFlag(flagBroadcastTimeout, cmd.Flags().Lookup(flagBroadcastTimeout)) - viper.BindPFlag(flagRPCPollInterval, cmd.Flags().Lookup(flagRPCPollInterval)) - viper.BindPFlag(flagMaxTry, cmd.Flags().Lookup(flagMaxTry)) - viper.BindPFlag(flagMaxReport, cmd.Flags().Lookup(flagMaxReport)) + _ = viper.BindPFlag(flags.FlagChainID, cmd.Flags().Lookup(flags.FlagChainID)) + _ = viper.BindPFlag(flags.FlagNode, cmd.Flags().Lookup(flags.FlagNode)) + _ = viper.BindPFlag(flagValidator, cmd.Flags().Lookup(flagValidator)) + _ = viper.BindPFlag(flags.FlagGasPrices, cmd.Flags().Lookup(flags.FlagGasPrices)) + _ = viper.BindPFlag(flagLogLevel, cmd.Flags().Lookup(flagLogLevel)) + _ = viper.BindPFlag(flagExecutor, cmd.Flags().Lookup(flagExecutor)) + _ = viper.BindPFlag(flagBroadcastTimeout, cmd.Flags().Lookup(flagBroadcastTimeout)) + _ = viper.BindPFlag(flagRPCPollInterval, cmd.Flags().Lookup(flagRPCPollInterval)) + _ = viper.BindPFlag(flagMaxTry, cmd.Flags().Lookup(flagMaxTry)) + _ = viper.BindPFlag(flagMaxReport, cmd.Flags().Lookup(flagMaxReport)) + return cmd }