From 97f8272eca720ef447559cd918d91de46b977870 Mon Sep 17 00:00:00 2001 From: leonz789 Date: Mon, 13 Jan 2025 09:31:33 +0800 Subject: [PATCH] fix lint --- app/ante/cosmos/sigverify.go | 3 ++ app/ante/cosmos/txsize_gas.go | 2 + precompiles/avs/events.go | 2 + tests/e2e/oracle/helper_nstconvert.go | 8 +++- x/avs/client/cli/tx.go | 2 +- x/avs/keeper/keeper.go | 3 ++ x/delegation/keeper/abci.go | 2 + x/delegation/keeper/delegation.go | 13 +++--- x/evm/keeper/grpc_query.go | 2 + x/operator/keeper/slash.go | 1 + x/operator/types/keys.go | 5 ++- x/oracle/keeper/cache/caches.go | 5 +++ .../keeper/feedermanagement/aggregator.go | 2 +- x/oracle/keeper/feedermanagement/algo.go | 42 +++++++++---------- x/oracle/keeper/feedermanagement/caches.go | 11 +++-- .../keeper/feedermanagement/feedermanager.go | 32 ++++++++++---- x/oracle/keeper/feedermanagement/prices.go | 36 +++------------- x/oracle/keeper/feedermanagement/round.go | 25 +++++++---- x/oracle/keeper/feedermanagement/types.go | 7 +++- x/oracle/keeper/msg_server_create_price.go | 5 +-- x/oracle/keeper/nonce.go | 1 + x/oracle/keeper/params.go | 8 +++- x/oracle/keeper/prices.go | 5 +++ x/oracle/keeper/recent_msg.go | 1 + x/oracle/keeper/recent_params.go | 3 +- x/oracle/keeper/tokens.go | 1 + x/oracle/types/params.go | 5 +++ 27 files changed, 142 insertions(+), 90 deletions(-) diff --git a/app/ante/cosmos/sigverify.go b/app/ante/cosmos/sigverify.go index 3d91e1cdd..92986fe28 100644 --- a/app/ante/cosmos/sigverify.go +++ b/app/ante/cosmos/sigverify.go @@ -391,6 +391,8 @@ func (isd IncrementSequenceDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, sim msg := msg.(*oracletypes.MsgCreatePrice) if accAddress, err := sdk.AccAddressFromBech32(msg.Creator); err != nil { return ctx, errors.New("invalid address") + // #nosec G115 // safe conversion + // TODO: define msg.Nonce as uint32 to avoid conversion } else if _, err := isd.oracleKeeper.CheckAndIncreaseNonce(ctx, sdk.ConsAddress(accAddress).String(), msg.FeederID, uint32(msg.Nonce)); err != nil { return ctx, err } @@ -445,6 +447,7 @@ func (vscd ValidateSigCountDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, sim sigCount := 0 for _, pk := range pubKeys { sigCount += CountSubKeys(pk) + // #nosec G115 if uint64(sigCount) > params.TxSigLimit { return ctx, sdkerrors.ErrTooManySignatures.Wrapf("signatures: %d, limit: %d", sigCount, params.TxSigLimit) } diff --git a/app/ante/cosmos/txsize_gas.go b/app/ante/cosmos/txsize_gas.go index b9684cd11..db448c75a 100644 --- a/app/ante/cosmos/txsize_gas.go +++ b/app/ante/cosmos/txsize_gas.go @@ -76,12 +76,14 @@ func (cgts ConsumeTxSizeGasDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, sim } // use stdsignature to mock the size of a full signature + // #nosec G115 simSig := legacytx.StdSignature{ // nolint:staticcheck // this will be removed when proto is ready Signature: simSecp256k1Sig[:], PubKey: pubkey, } sigBz := legacy.Cdc.MustMarshal(simSig) + // #nosec G115 cost := sdk.Gas(len(sigBz) + 6) // If the pubkey is a multi-signature pubkey, then we estimate for the maximum diff --git a/precompiles/avs/events.go b/precompiles/avs/events.go index 0bf1a5234..8eac48bf3 100644 --- a/precompiles/avs/events.go +++ b/precompiles/avs/events.go @@ -271,6 +271,8 @@ func (p Precompile) EmitTaskSubmittedByOperator(ctx sdk.Context, stateDB vm.Stat } // Prepare the event data:sender,TaskResponse, BlsSignature, Phase arguments := abi.Arguments{event.Inputs[2], event.Inputs[3], event.Inputs[4], event.Inputs[5]} + // #nosec G115 + // TODO: consider modify define of Phase to uint8 packed, err := arguments.Pack(params.CallerAddress.String(), params.TaskResponse, params.BlsSignature, uint8(params.Phase)) if err != nil { return err diff --git a/tests/e2e/oracle/helper_nstconvert.go b/tests/e2e/oracle/helper_nstconvert.go index 57dcb6910..10873b9ae 100644 --- a/tests/e2e/oracle/helper_nstconvert.go +++ b/tests/e2e/oracle/helper_nstconvert.go @@ -2,6 +2,7 @@ package oracle import ( "encoding/binary" + "math" "strings" "github.com/imroc/biu" @@ -10,8 +11,7 @@ import ( func convertBalanceChangeToBytes(stakerChanges [][]int) []byte { if len(stakerChanges) == 0 { // length equals to 0 means that alls takers have efb of 32 with 0 changes - ret := make([]byte, 32) - return ret + return make([]byte, 32) } str := "" index := 0 @@ -23,6 +23,9 @@ func convertBalanceChangeToBytes(stakerChanges [][]int) []byte { // change amount -> bytes change := stakerChange[1] + if change > math.MaxUint16 || change < 0 { + return make([]byte, 32) + } var changeBytes []byte symbol := 1 if change < 0 { @@ -47,6 +50,7 @@ func convertBalanceChangeToBytes(stakerChanges [][]int) []byte { } else { // 2 byte changeBytes = make([]byte, 2) + // #nosec G115 // change has been checked to make sure no overflow binary.BigEndian.PutUint16(changeBytes, uint16(change)) moveLength := 16 - bits changeBytes[0] <<= moveLength diff --git a/x/avs/client/cli/tx.go b/x/avs/client/cli/tx.go index b73524a26..7623857b7 100644 --- a/x/avs/client/cli/tx.go +++ b/x/avs/client/cli/tx.go @@ -116,7 +116,7 @@ func newBuildMsg( taskContractAddress, _ := fs.GetString(FlagTaskContractAddress) taskID, _ := fs.GetUint64(FlagTaskID) - phase, _ := fs.GetUint32(FlagPhase) + phase, _ := fs.GetInt32(FlagPhase) if err := types.ValidatePhase(types.Phase(phase)); err != nil { return nil, err } diff --git a/x/avs/keeper/keeper.go b/x/avs/keeper/keeper.go index 4e0e0fce4..3b5d449f3 100644 --- a/x/avs/keeper/keeper.go +++ b/x/avs/keeper/keeper.go @@ -442,12 +442,14 @@ func (k Keeper) RaiseAndResolveChallenge(ctx sdk.Context, params *types.Challeng return errorsmod.Wrap(types.ErrEpochNotFound, fmt.Sprintf("epoch info not found %s", avsInfo.EpochIdentifier)) } + // #nosec G115 if epoch.CurrentEpoch <= int64(taskInfo.StartingEpoch)+int64(taskInfo.TaskResponsePeriod)+int64(taskInfo.TaskStatisticalPeriod) { return errorsmod.Wrap( types.ErrSubmitTooSoonError, fmt.Sprintf("SetTaskResultInfo:the challenge period has not started , CurrentEpoch:%d", epoch.CurrentEpoch), ) } + // #nosec G115 if epoch.CurrentEpoch > int64(taskInfo.StartingEpoch)+int64(taskInfo.TaskResponsePeriod)+int64(taskInfo.TaskStatisticalPeriod)+int64(taskInfo.TaskChallengePeriod) { return errorsmod.Wrap( types.ErrSubmitTooLateError, @@ -584,6 +586,7 @@ func (k Keeper) SubmitTaskResult(ctx sdk.Context, addr string, info *types.TaskR fmt.Sprintf("SetTaskResultInfo:the TaskResponse period has not started , CurrentEpoch:%d", epoch.CurrentEpoch), ) } + // #nosec G115 if epoch.CurrentEpoch > int64(task.StartingEpoch)+int64(task.TaskResponsePeriod)+int64(task.TaskStatisticalPeriod) { return errorsmod.Wrap( types.ErrSubmitTooLateError, diff --git a/x/delegation/keeper/abci.go b/x/delegation/keeper/abci.go index d89be5616..e0ce751ad 100644 --- a/x/delegation/keeper/abci.go +++ b/x/delegation/keeper/abci.go @@ -16,6 +16,7 @@ func (k *Keeper) EndBlock( ) []abci.ValidatorUpdate { logger := k.Logger(originalCtx) records, err := k.GetPendingUndelegationRecords( + // #nosec G115 // blockHeight is not negative originalCtx, uint64(originalCtx.BlockHeight()), ) if err != nil { @@ -43,6 +44,7 @@ func (k *Keeper) EndBlock( } // add back to all 3 states, with the new block height // #nosec G701 + // #nodese G115 // blockHeight is not negative record.CompleteBlockNumber = uint64(cc.BlockHeight()) + 1 if err := k.SetUndelegationRecords( cc, []types.UndelegationRecord{*record}, diff --git a/x/delegation/keeper/delegation.go b/x/delegation/keeper/delegation.go index a91c43d4c..2ebd87634 100644 --- a/x/delegation/keeper/delegation.go +++ b/x/delegation/keeper/delegation.go @@ -133,12 +133,13 @@ func (k *Keeper) UndelegateFrom(ctx sdk.Context, params *delegationtype.Delegati } // record Undelegation event r := delegationtype.UndelegationRecord{ - StakerID: stakerID, - AssetID: assetID, - OperatorAddr: params.OperatorAddress.String(), - TxHash: params.TxHash.String(), - IsPending: true, - LzTxNonce: params.LzNonce, + StakerID: stakerID, + AssetID: assetID, + OperatorAddr: params.OperatorAddress.String(), + TxHash: params.TxHash.String(), + IsPending: true, + LzTxNonce: params.LzNonce, + // #nosec G115 // blockHeight is not negative BlockNumber: uint64(ctx.BlockHeight()), Amount: removeToken, ActualCompletedAmount: removeToken, diff --git a/x/evm/keeper/grpc_query.go b/x/evm/keeper/grpc_query.go index 851ce1dd0..518611326 100644 --- a/x/evm/keeper/grpc_query.go +++ b/x/evm/keeper/grpc_query.go @@ -472,6 +472,7 @@ func (k Keeper) TraceTx(c context.Context, req *types.QueryTraceTxRequest) (*typ continue } txConfig.TxHash = ethTx.Hash() + // #nosec G115 txConfig.TxIndex = uint(i) // reset gas meter for each transaction ctx = ctx.WithGasMeter(evmostypes.NewInfiniteGasMeterWithLimit(msg.Gas())) @@ -565,6 +566,7 @@ func (k Keeper) TraceBlock(c context.Context, req *types.QueryTraceBlockRequest) result := types.TxTraceResult{} ethTx := tx.AsTransaction() txConfig.TxHash = ethTx.Hash() + // #nosec G115 txConfig.TxIndex = uint(i) traceResult, logIndex, err := k.traceTx(ctx, cfg, txConfig, signer, ethTx, req.TraceConfig, true, nil) if err != nil { diff --git a/x/operator/keeper/slash.go b/x/operator/keeper/slash.go index 3393fc166..e234a4f4b 100644 --- a/x/operator/keeper/slash.go +++ b/x/operator/keeper/slash.go @@ -19,6 +19,7 @@ import ( // GetSlashIDForDogfood It use infractionType+'_'+'infractionHeight' as the slashID, because /* the slash */event occurs in dogfood doesn't have a TxID. It isn't submitted through an external transaction. func GetSlashIDForDogfood(infraction stakingtypes.Infraction, infractionHeight int64) string { // #nosec G701 + // #nosec G115 return strings.Join([]string{hexutil.EncodeUint64(uint64(infraction)), hexutil.EncodeUint64(uint64(infractionHeight))}, utils.DelimiterForID) } diff --git a/x/operator/types/keys.go b/x/operator/types/keys.go index 1239ff735..59827ab81 100644 --- a/x/operator/types/keys.go +++ b/x/operator/types/keys.go @@ -163,7 +163,7 @@ func KeyForVotingPowerSnapshot(avs common.Address, height int64) []byte { return AppendMany( avs.Bytes(), // Append the height - sdk.Uint64ToBigEndian(uint64(height)), + sdk.Uint64ToBigEndian(uint64(height)), // #nosec G115 // height is not negative ) } @@ -189,6 +189,7 @@ func ParseKeyForOperatorAndChainIDToConsKey(key []byte) (addr sdk.AccAddress, ch // Extract the chainID length chainIDLen := sdk.BigEndianToUint64(key[AccAddressLength : AccAddressLength+ByteLengthForUint64]) + // #nosec G115 // safe conversion if len(key) != int(AccAddressLength+ByteLengthForUint64+chainIDLen) { return nil, "", xerrors.Errorf("invalid key length,expected:%d,got:%d", AccAddressLength+ByteLengthForUint64+chainIDLen, len(key)) } @@ -215,6 +216,7 @@ func ParsePrevConsKey(key []byte) (chainID string, addr sdk.AccAddress, err erro // Extract the chainID length chainIDLen := sdk.BigEndianToUint64(key[0:ByteLengthForUint64]) + // #nosec G115 if len(key) < int(ByteLengthForUint64+chainIDLen) { return "", nil, xerrors.New("key too short for chainID length") } @@ -268,6 +270,7 @@ func ParseKeyForOperatorKeyRemoval(key []byte) (addr sdk.AccAddress, chainID str // Extract the chainID length chainIDLen := sdk.BigEndianToUint64(key[AccAddressLength : AccAddressLength+ByteLengthForUint64]) + // #nosec G115 if len(key) != int(AccAddressLength+ByteLengthForUint64+chainIDLen) { return nil, "", xerrors.Errorf("invalid key length,expected:%d,got:%d", AccAddressLength+ByteLengthForUint64+chainIDLen, len(key)) } diff --git a/x/oracle/keeper/cache/caches.go b/x/oracle/keeper/cache/caches.go index 47db24b53..ce8b83081 100644 --- a/x/oracle/keeper/cache/caches.go +++ b/x/oracle/keeper/cache/caches.go @@ -53,6 +53,7 @@ func (c *cacheMsgs) remove(item *ItemM) { } func (c cacheMsgs) commit(ctx sdk.Context, k common.KeeperOracle) { + // #nosec G115 // block height is not negative block := uint64(ctx.BlockHeight()) recentMsgs := types.RecentMsg{ @@ -69,6 +70,7 @@ func (c cacheMsgs) commit(ctx sdk.Context, k common.KeeperOracle) { i := 0 for ; i < len(index.Index); i++ { b := index.Index[i] + // #nosec G115 // maxNonce must not be negative if b > block-uint64(common.MaxNonce) { break } @@ -101,6 +103,7 @@ func (c *cacheValidator) add(validators map[string]*big.Int) { } func (c *cacheValidator) commit(ctx sdk.Context, k common.KeeperOracle) { + // #nosec G115 // block height is not negative block := uint64(ctx.BlockHeight()) k.SetValidatorUpdateBlock(ctx, types.ValidatorUpdateBlock{Block: block}) } @@ -113,11 +116,13 @@ func (c *cacheParams) add(p ItemP) { } func (c *cacheParams) commit(ctx sdk.Context, k common.KeeperOracle) { + // #nosec G115 // block height is not negative block := uint64(ctx.BlockHeight()) index, _ := k.GetIndexRecentParams(ctx) i := 0 for ; i < len(index.Index); i++ { b := index.Index[i] + // #nosec G115 // maxNonce must not be negative if b >= block-uint64(common.MaxNonce) { break } diff --git a/x/oracle/keeper/feedermanagement/aggregator.go b/x/oracle/keeper/feedermanagement/aggregator.go index 79e5e68e9..8dc5eadd3 100644 --- a/x/oracle/keeper/feedermanagement/aggregator.go +++ b/x/oracle/keeper/feedermanagement/aggregator.go @@ -239,7 +239,7 @@ func (rv *recordsValidators) GetFinalPrice() (*PriceResult, bool) { } func (rv *recordsValidators) GetFinalPriceForValidators() (map[string]*PriceResult, bool) { - if rv.finalPrices != nil && len(rv.finalPrices) > 0 { + if len(rv.finalPrices) > 0 { return rv.finalPrices, true } ret := make(map[string]*PriceResult) diff --git a/x/oracle/keeper/feedermanagement/algo.go b/x/oracle/keeper/feedermanagement/algo.go index a73fbd91b..f12eddc95 100644 --- a/x/oracle/keeper/feedermanagement/algo.go +++ b/x/oracle/keeper/feedermanagement/algo.go @@ -47,7 +47,7 @@ type AggMedian struct { t priceType finalString string list []*big.Int - decimal int + decimal int32 } func NewAggMedian() *AggMedian { @@ -65,39 +65,38 @@ func (a *AggMedian) Add(price *PriceResult) bool { if a.t == notSet { a.t = number a.list = append(a.list, priceInt) - a.decimal = int(price.Decimal) + a.decimal = price.Decimal return true } - if a.decimal != int(price.Decimal) { - if a.decimal > int(price.Decimal) { - price.Price = price.Price + strings.Repeat("0", a.decimal-int(price.Decimal)) + if a.decimal != price.Decimal { + if a.decimal > price.Decimal { + price.Price += strings.Repeat("0", int(a.decimal-price.Decimal)) priceInt, _ = new(big.Int).SetString(price.Price, 10) } else { - delta := big.NewInt(int64(int(price.Decimal) - a.decimal)) + delta := big.NewInt(int64(price.Decimal - a.decimal)) for _, v := range a.list { nv := new(big.Int).Mul(v, new(big.Int).Exp(big.NewInt(10), delta, nil)) *v = *nv } - a.decimal = int(price.Decimal) + a.decimal = price.Decimal } } a.list = append(a.list, priceInt) return true - } else { - // input is a string, not a number - if a.t == number { - return false - } - if a.t == notSet { - a.t = notNumber - a.finalString = price.Price - return true - } - if a.finalString != price.Price { - return false - } + } + // input is a string, not a number + if a.t == number { + return false + } + if a.t == notSet { + a.t = notNumber + a.finalString = price.Price return true } + if a.finalString != price.Price { + return false + } + return true } func (a *AggMedian) GetResult() *PriceResult { @@ -107,7 +106,8 @@ func (a *AggMedian) GetResult() *PriceResult { } if a.t == number { result := BigIntList(a.list).Median().String() - decimal := int32(a.decimal) + // + decimal := a.decimal return &PriceResult{ Price: result, Decimal: decimal, diff --git a/x/oracle/keeper/feedermanagement/caches.go b/x/oracle/keeper/feedermanagement/caches.go index b1611d3f3..8e6300ac4 100644 --- a/x/oracle/keeper/feedermanagement/caches.go +++ b/x/oracle/keeper/feedermanagement/caches.go @@ -51,7 +51,7 @@ func (c *caches) Equals(c2 *caches) bool { return true } -func (c *caches) Init(ctx sdk.Context, k Submitter, params *oracletypes.Params, validators map[string]*big.Int) { +func (c *caches) Init(k Submitter, params *oracletypes.Params, validators map[string]*big.Int) { c.ResetCaches() c.k = k @@ -80,6 +80,7 @@ func (c *caches) GetTokenIDForFeederID(feederID int64) (int64, bool) { if !ok { return 0, false } + // #nosec G115 // tokenID is index of slice return int64(tf.TokenID), true } @@ -122,6 +123,7 @@ func (cm *cacheMsgs) commit(ctx sdk.Context, k Submitter) { return } recentMsgs := oracletypes.RecentMsg{ + // #nosec G115 // height is not negative Block: uint64(ctx.BlockHeight()), Msgs: *cm, } @@ -176,6 +178,8 @@ func (cv *cacheValidator) commit(ctx sdk.Context, k Submitter) { if !cv.update { return } + // #nosec blockHeight is not negative + // TODO: consider change the define of all height types in proto to int64(since cosmossdk defined block height as int64) to get avoid all these conversion k.SetValidatorUpdateForCache(ctx, oracletypes.ValidatorUpdateBlock{Block: uint64(ctx.BlockHeight())}) cv.update = false } @@ -206,8 +210,8 @@ func (cp *cacheParams) Equals(cp2 *cacheParams) bool { if cp.update != cp2.update { return false } - p1 := (*oracletypes.Params)(cp.params) - p2 := (*oracletypes.Params)(cp2.params) + p1 := cp.params + p2 := cp2.params return reflect.DeepEqual(p1, p2) } @@ -221,6 +225,7 @@ func (cp *cacheParams) commit(ctx sdk.Context, k Submitter) { return } k.SetParamsForCache(ctx, oracletypes.RecentParams{ + // #nosec G115 blockheight is not negative Block: uint64(ctx.BlockHeight()), Params: cp.params, }) diff --git a/x/oracle/keeper/feedermanagement/feedermanager.go b/x/oracle/keeper/feedermanagement/feedermanager.go index 8057015eb..9c913727c 100644 --- a/x/oracle/keeper/feedermanagement/feedermanager.go +++ b/x/oracle/keeper/feedermanagement/feedermanager.go @@ -9,7 +9,6 @@ import ( sdkerrors "cosmossdk.io/errors" "github.com/ExocoreNetwork/exocore/x/oracle/keeper/common" - "github.com/ExocoreNetwork/exocore/x/oracle/types" oracletypes "github.com/ExocoreNetwork/exocore/x/oracle/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -25,6 +24,7 @@ func NewFeederManager(k common.KeeperOracle) *FeederManager { } } +//nolint:revive func (f *FeederManager) GetCaches() *caches { return f.cs } @@ -107,12 +107,14 @@ func (f *FeederManager) setupNonces(ctx sdk.Context, feederIDs []int64) { height := ctx.BlockHeight() if f.forceSeal { for _, r := range f.rounds { + // #nosec G115 // feederID is index of slice f.k.RemoveNonceWithFeederIDForAll(ctx, uint64(r.feederID)) } } else { for _, r := range f.rounds { if r.IsQuotingWindowEnd(height) { logger.Debug("clear nonces for closing quoting window", "feederID", r.feederID, "roundID", r.roundID, "basedBlock", r.roundBaseBlock, "height", height) + // #nosec G115 // feederID is index of slice f.k.RemoveNonceWithFeederIDForAll(ctx, uint64(r.feederID)) } } @@ -125,6 +127,7 @@ func (f *FeederManager) setupNonces(ctx sdk.Context, feederIDs []int64) { for _, feederID := range feederIDs { r := f.rounds[feederID] logger.Debug("init nonces for new quoting window", "feederID", feederID, "roundID", r.roundID, "basedBlock", r.roundBaseBlock, "height", height) + // #nosec G115 // feederID is index of slice f.k.AddZeroNonceItemWithFeederIDForValidators(ctx, uint64(feederID), validators) } } @@ -271,9 +274,9 @@ func (f *FeederManager) commitRounds(ctx sdk.Context) { if len(successFeederIDs) > 0 { feederIDsStr := strings.Join(successFeederIDs, "_") ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeCreatePrice, - sdk.NewAttribute(types.AttributeKeyPriceUpdated, types.AttributeValuePriceUpdatedSuccess), - sdk.NewAttribute(types.AttributeKeyFeederIDs, feederIDsStr), + oracletypes.EventTypeCreatePrice, + sdk.NewAttribute(oracletypes.AttributeKeyPriceUpdated, oracletypes.AttributeValuePriceUpdatedSuccess), + sdk.NewAttribute(oracletypes.AttributeKeyFeederIDs, feederIDsStr), )) } } @@ -550,6 +553,7 @@ func (f *FeederManager) SetForceSeal() { f.forceSeal = true } +//nolint:revive func (f *FeederManager) ValidateMsg(msg *oracletypes.MsgCreatePrice) error { // TODO: implement me return nil @@ -561,12 +565,14 @@ func (f *FeederManager) ProcessQuote(ctx sdk.Context, msg *oracletypes.MsgCreate } msgItem := getProtoMsgItemFromQuote(msg) + // #nosec G115 // feederID is index of slice r, ok := f.rounds[int64(msgItem.FeederID)] if !ok { // This should not happened since we do check the nonce in anthHandle return nil, fmt.Errorf("round not exists for feederID:%d, porposer:%s", msgItem.FeederID, msgItem.Validator) } + // #nosec G115 // baseBlock is block height which is not negative if valid := r.ValidQuotingBaseBlock(int64(msg.BasedBlock)); !valid { return nil, fmt.Errorf("failed to process price-feed msg for feederID:%d, round is quoting:%t,quotingWindow is open:%t, expected baseBlock:%d, got baseBlock:%d", msgItem.FeederID, r.IsQuoting(), r.IsQuotingWindowOpen(), r.roundBaseBlock, msg.BasedBlock) } @@ -629,11 +635,13 @@ func (f *FeederManager) updateCheckTx() { func (f *FeederManager) ProcessQuoteInRecovery(msgItems []*oracletypes.MsgItem) { for _, msgItem := range msgItems { + // #nosec G115 // feederID is index of slice r, ok := f.rounds[int64(msgItem.FeederID)] if !ok { continue } // error deos not need to be handled in recovery mode + //nolint:all r.Tally(msgItem) } } @@ -647,7 +655,7 @@ func (f *FeederManager) initCaches(ctx sdk.Context) { for _, v := range validatorSet { validatorPowers[sdk.ConsAddress(v.Address).String()] = big.NewInt(v.Power) } - f.cs.Init(ctx, f.k, ¶ms, validatorPowers) + f.cs.Init(f.k, ¶ms, validatorPowers) } func (f *FeederManager) recovery(ctx sdk.Context) bool { @@ -662,6 +670,7 @@ func (f *FeederManager) recovery(ctx sdk.Context) bool { // it's safe to panic since this will only happen when the node is starting with something wrong in the store panic("validator update block not found in recovery mode for feeder manager") } + // #nosec G115 // validatorUpdateBlock.Block represents blockheight startHeight, replayRecentParamsList := getRecoveryStartPoint(height, recentParamsList, &prevRecentParams, &latestRecentParams, int64(validatorUpdateBlock.Block)) f.cs = newCaches() @@ -674,7 +683,7 @@ func (f *FeederManager) recovery(ctx sdk.Context) bool { validatorPowers[sdk.ConsAddress(v.Address).String()] = big.NewInt(v.Power) } - f.cs.Init(ctx, f.k, params, validatorPowers) + f.cs.Init(f.k, params, validatorPowers) replayHeight := startHeight - 1 @@ -683,7 +692,7 @@ func (f *FeederManager) recovery(ctx sdk.Context) bool { if tfID == 0 { continue } - // safe conversion + // #nosec G115 // safe conversion if tf.EndBlock > 0 && int64(tf.EndBlock) <= replayHeight { continue } @@ -700,9 +709,11 @@ func (f *FeederManager) recovery(ctx sdk.Context) bool { // only execute msgItems corresponding to rounds opened on or after replayHeight, since any rounds opened before replay height must be closed on or before height-1 // which means no memory state need to be updated for thoes rounds // and we don't need to take care of 'close quoting-window' since the size of replay window t most equals to maxNonce + // #nosec G115 // block is not negative if len(recentMsgs) > 0 && int64(recentMsgs[0].Block) <= startHeight { i := 0 for idx, recentMsg := range recentMsgs { + // #nosec G115 // block height is defined as int64 in cosmossdk if int64(recentMsg.Block) > startHeight { break } @@ -714,6 +725,7 @@ func (f *FeederManager) recovery(ctx sdk.Context) bool { } recentMsgs = recentMsgs[i+1:] } + // #nosec G115 if len(replayRecentParamsList) > 0 && int64(replayRecentParamsList[0].Block) == startHeight { params = replayRecentParamsList[0].Params replayRecentParamsList = replayRecentParamsList[1:] @@ -780,15 +792,17 @@ func getRecoveryStartPoint(currentHeight int64, recentParamsList []*oracletypes. // for empty recetParamsList, use latestrecentParams as the start point replayRecentParamsList = append(replayRecentParamsList, latestRecentParams) height++ - return + return height, replayRecentParamsList } if prevRecentParams.Block > 0 && prevRecentParams.Params.IsForceSealingUpdate(recentParamsList[0].Params) { + // #nosec G115 height = int64(recentParamsList[0].Block) } idx := 0 for i := 1; i < len(recentParamsList); i++ { if recentParamsList[i-1].Params.IsForceSealingUpdate(recentParamsList[i].Params) { + // #nosec G115 height = int64(recentParamsList[i].Block) idx = i } @@ -799,7 +813,7 @@ func getRecoveryStartPoint(currentHeight int64, recentParamsList []*oracletypes. height = validatorUpdateHeight } height++ - return + return height, replayRecentParamsList } func getProtoMsgItemFromQuote(msg *oracletypes.MsgCreatePrice) *oracletypes.MsgItem { diff --git a/x/oracle/keeper/feedermanagement/prices.go b/x/oracle/keeper/feedermanagement/prices.go index 912254a16..ec515d995 100644 --- a/x/oracle/keeper/feedermanagement/prices.go +++ b/x/oracle/keeper/feedermanagement/prices.go @@ -39,15 +39,17 @@ func (p *PriceResult) ProtoPriceTimeRound(roundID int64, timestamp string) *orac } } -func GetPriceSourceFromProto(ps *oracletypes.PriceSource, checker sourceChecker) *priceSource { +func getPriceSourceFromProto(ps *oracletypes.PriceSource, checker sourceChecker) *priceSource { prices := make([]*PriceInfo, 0, len(ps.Prices)) for _, p := range ps.Prices { prices = append(prices, GetPriceInfoFromProtoPriceTimeDetID(p)) } return &priceSource{ + // #nosec G115 deterministic: checker.IsDeterministic(int64(ps.SourceID)), - sourceID: int64(ps.SourceID), - prices: prices, + // #nosec G115 + sourceID: int64(ps.SourceID), + prices: prices, } } @@ -81,14 +83,6 @@ func (pv *priceValidator) Cpy() *priceValidator { } } -// type priceValidator struct { -// finalPrice *PriceResult -// validator string -// power *big.Int -// // each source will get a single final price independetly, the order of sources does not matter, map is safe -// priceSources map[int64]*priceSource -// } - func (pv *priceValidator) Equals(pv2 *priceValidator) bool { if pv == nil && pv2 == nil { return true @@ -151,25 +145,6 @@ func (pv *priceValidator) ApplyAddedPriceSources(psMap map[int64]*priceSource) { } } -// AddPriceSource adds prices of a source -// func (pv *priceValidator) AddPriceSource(psNew *priceSource, check bool) (*priceSource, error) { -// sourceID := psNew.sourceID -// ps, ok := pv.priceSources[sourceID] -// if !ok { -// ps = newPriceSource(sourceID, psNew.deterministic) -// } else if check { -// ps = ps.Cpy() -// } -// ret, err := ps.Add(psNew) -// if err != nil { -// return nil, fmt.Errorf("failed to add priceSource for priceValidator, sourceID:%d, error:%w", sourceID, err) -// } -// if !ok && !check { -// pv.priceSources[sourceID] = ps -// } -// return ret, nil -// } - // TODO: V2: check valdiator has provided all sources required by rules(defined in oracle.params) func (pv *priceValidator) GetFinalPrice() (*PriceResult, bool) { if pv.finalPrice != nil { @@ -191,6 +166,7 @@ func (pv *priceValidator) GetFinalPrice() (*PriceResult, bool) { pv.finalPrice = defaultAggMedian.GetResult() return pv.finalPrice, true } + func (pv *priceValidator) UpdateFinalPriceForDS(sourceID int64, finalPrice *PriceResult) bool { if finalPrice == nil { return false diff --git a/x/oracle/keeper/feedermanagement/round.go b/x/oracle/keeper/feedermanagement/round.go index e6d776c48..8f45b6bb1 100644 --- a/x/oracle/keeper/feedermanagement/round.go +++ b/x/oracle/keeper/feedermanagement/round.go @@ -8,15 +8,19 @@ import ( func newRound(feederID int64, tokenFeeder *oracletypes.TokenFeeder, quoteWindowSize int64, cache CacheReader) *round { return &round{ - startBaseBlock: int64(tokenFeeder.StartBaseBlock), - startRoundID: int64(tokenFeeder.StartRoundID), - endBlock: int64(tokenFeeder.EndBlock), + // #nosec G115 + startBaseBlock: int64(tokenFeeder.StartBaseBlock), + // #nosec G115 + startRoundID: int64(tokenFeeder.StartRoundID), + // #nosec G115 + endBlock: int64(tokenFeeder.EndBlock), + // #nosec G115 interval: int64(tokenFeeder.Interval), quoteWindowSize: quoteWindowSize, - - feederID: feederID, - tokenID: int64(tokenFeeder.TokenID), - cache: cache, + feederID: feederID, + // #nosec G115 + tokenID: int64(tokenFeeder.TokenID), + cache: cache, // default value status: roundStatusClosed, @@ -65,9 +69,10 @@ func (r *round) getMsgItemFromProto(msg *oracletypes.MsgItem) *MsgItem { power, _ := r.cache.GetPowerForValidator(msg.Validator) priceSources := make([]*priceSource, 0, len(msg.PSources)) for _, ps := range msg.PSources { - priceSources = append(priceSources, GetPriceSourceFromProto(ps, r.cache)) + priceSources = append(priceSources, getPriceSourceFromProto(ps, r.cache)) } return &MsgItem{ + // #nosec G115 FeederID: int64(msg.FeederID), Validator: msg.Validator, Power: power, @@ -117,8 +122,11 @@ func (r *round) Tally(protoMsg *oracletypes.MsgItem) (*PriceResult, *oracletypes } func (r *round) UpdateParams(tokenFeeder *oracletypes.TokenFeeder, quoteWindowSize int64) { + // #nosec G115 r.startBaseBlock = int64(tokenFeeder.StartBaseBlock) + // #nosec G115 r.endBlock = int64(tokenFeeder.EndBlock) + // #nosec G115 r.interval = int64(tokenFeeder.Interval) r.quoteWindowSize = quoteWindowSize } @@ -216,6 +224,7 @@ func (r *round) PerformanceReview(validator string) (miss, malicious bool) { return } +//nolint:unparam func (r *round) getFinalDetIDForSourceID(sourceID int64) string { return r.a.ds.GetFinalDetIDForSourceID(sourceID) } diff --git a/x/oracle/keeper/feedermanagement/types.go b/x/oracle/keeper/feedermanagement/types.go index e664d78dd..396d2ebd1 100644 --- a/x/oracle/keeper/feedermanagement/types.go +++ b/x/oracle/keeper/feedermanagement/types.go @@ -77,14 +77,14 @@ type priceValidator struct { finalPrice *PriceResult validator string power *big.Int - // each source will get a single final price independetly, the order of sources does not matter, map is safe + // each source will get a single final price independently, the order of sources does not matter, map is safe priceSources map[int64]*priceSource } type recordsValidators struct { finalPrice *PriceResult finalPrices map[string]*PriceResult - // TODO: V2: accumulatedValidPower only includes validators who prividing all sources requred by rules(defined in oracle.Params) + // TODO: V2: accumulatedValidPower only includes validators who prividing all sources required by rules(defined in oracle.Params) // accumulatedValidVpower: map[string]*big.Int accumulatedPower *big.Int // each validator will get a single final price independently, the order of validators does not matter, map is safe @@ -193,6 +193,7 @@ func (osi *orderedSliceInt64) add(i int64) { }) *osi = result } + func (osi *orderedSliceInt64) remove(i int64) { for idx, v := range *osi { if v == i { @@ -201,11 +202,13 @@ func (osi *orderedSliceInt64) remove(i int64) { } } } + func (osi *orderedSliceInt64) sort() { sort.Slice(*osi, func(i, j int) bool { return (*osi)[i] < (*osi)[j] }) } + func (osi orderedSliceInt64) Equal(o orderedSliceInt64) bool { if len(osi) != len(o) { return false diff --git a/x/oracle/keeper/msg_server_create_price.go b/x/oracle/keeper/msg_server_create_price.go index 6773410b2..b83487f06 100644 --- a/x/oracle/keeper/msg_server_create_price.go +++ b/x/oracle/keeper/msg_server_create_price.go @@ -44,7 +44,6 @@ func (ms msgServer) CreatePrice(goCtx context.Context, msg *types.MsgCreatePrice } // core logic and functionality of Price Aggregation finalPrice, err := ms.ProcessQuote(ctx, msg, ctx.IsCheckTx()) - if err != nil { if sdkerrors.IsOf(err, types.ErrQuoteRecorded) { // quote is recorded only, this happens when a quoting-window is not availalbe before that window end due to final price aggregated successfully in advance @@ -67,8 +66,8 @@ func (ms msgServer) CreatePrice(goCtx context.Context, msg *types.MsgCreatePrice if finalPrice != nil { logger.Info("final price successfully aggregated", "price", finalPrice, "feederID", msg.FeederID, "height", ctx.BlockHeight()) - decimalStr := strconv.FormatInt(int64(finalPrice.Decimal), 10) + // #nosec G115 tokenID, _ := ms.GetTokenIDForFeederID(int64(msg.FeederID)) tokenIDStr := strconv.FormatInt(tokenID, 10) roundIDStr := strconv.FormatUint(finalPrice.RoundID, 10) @@ -80,7 +79,7 @@ func (ms msgServer) CreatePrice(goCtx context.Context, msg *types.MsgCreatePrice priceStr = base64.StdEncoding.EncodeToString(hash.Sum(nil)) } - // emit event to tell price is udpated for current round of corresponding feederID + // emit event to tell price is updated for current round of corresponding feederID ctx.EventManager().EmitEvent(sdk.NewEvent( types.EventTypeCreatePrice, sdk.NewAttribute(types.AttributeKeyRoundID, roundIDStr), diff --git a/x/oracle/keeper/nonce.go b/x/oracle/keeper/nonce.go index 447d8133b..ddd1509f6 100644 --- a/x/oracle/keeper/nonce.go +++ b/x/oracle/keeper/nonce.go @@ -110,6 +110,7 @@ func (k Keeper) RemoveNonceWithFeederIDForAll(ctx sdk.Context, feederID uint64) // CheckAndIncreaseNonce check and increase the nonce for a specific validator and feederID func (k Keeper) CheckAndIncreaseNonce(ctx sdk.Context, validator string, feederID uint64, nonce uint32) (prevNonce uint32, err error) { + // #nosec G115 // safe conversion if nonce > uint32(common.MaxNonce) { return 0, fmt.Errorf("nonce_check_failed: max_exceeded: limit=%d received=%d", common.MaxNonce, nonce) } diff --git a/x/oracle/keeper/params.go b/x/oracle/keeper/params.go index baed61200..6a189b9db 100644 --- a/x/oracle/keeper/params.go +++ b/x/oracle/keeper/params.go @@ -39,6 +39,7 @@ func (k Keeper) RegisterNewTokenAndSetTokenFeeder(ctx sdk.Context, oInfo *types. chainID := uint64(0) for id, c := range p.Chains { if c.Name == oInfo.Chain.Name { + // #nosec G115 chainID = uint64(id) break } @@ -49,6 +50,7 @@ func (k Keeper) RegisterNewTokenAndSetTokenFeeder(ctx sdk.Context, oInfo *types. Name: oInfo.Chain.Name, Desc: oInfo.Chain.Desc, }) + // #nosec G115 chainID = uint64(len(p.Chains) - 1) } decimalInt, err := strconv.ParseInt(oInfo.Token.Decimal, 10, 32) @@ -95,10 +97,12 @@ func (k Keeper) RegisterNewTokenAndSetTokenFeeder(ctx sdk.Context, oInfo *types. // set a tokenFeeder for the new token p.TokenFeeders = append(p.TokenFeeders, &types.TokenFeeder{ + // #nosec G115 // len(p.Tokens) must be positive since we just append an element for it TokenID: uint64(len(p.Tokens) - 1), // we only support rule_1 for v1 - RuleID: 1, - StartRoundID: 1, + RuleID: 1, + StartRoundID: 1, + // #nosec G115 StartBaseBlock: uint64(ctx.BlockHeight() + startAfterBlocks), Interval: intervalInt, // we don't end feeders for v1 diff --git a/x/oracle/keeper/prices.go b/x/oracle/keeper/prices.go index 0e3b6c36f..26a80e52d 100644 --- a/x/oracle/keeper/prices.go +++ b/x/oracle/keeper/prices.go @@ -34,10 +34,12 @@ func (k Keeper) GetPrices( val.TokenID = tokenID val.NextRoundID = nextRoundID var i uint64 + // #nosec G11 if nextRoundID <= uint64(common.MaxSizePrices) { i = 1 val.PriceList = make([]*types.PriceTimeRound, 0, nextRoundID) } else { + // #nosec G11 i = nextRoundID - uint64(common.MaxSizePrices) val.PriceList = make([]*types.PriceTimeRound, 0, common.MaxSizePrices) } @@ -69,6 +71,7 @@ func (k Keeper) GetSpecifiedAssetsPrice(ctx sdk.Context, assetID string) (types. if tokenID == 0 { return types.Price{}, types.ErrGetPriceAssetNotFound.Wrapf("assetID does not exist in oracle %s", assetID) } + // #nosec G115 price, found := k.GetPriceTRLatest(ctx, uint64(tokenID)) if !found { return types.Price{ @@ -112,6 +115,7 @@ func (k Keeper) GetMultipleAssetsPrices(ctx sdk.Context, assets map[string]inter prices = nil break } + // #nosec G115 price, found := k.GetPriceTRLatest(ctx, uint64(tokenID)) if !found { info = info + assetID + " " @@ -200,6 +204,7 @@ func (k Keeper) AppendPriceTR(ctx sdk.Context, tokenID uint64, priceTR types.Pri b := k.cdc.MustMarshal(&priceTR) store.Set(types.PricesRoundKey(nextRoundID), b) p := *k.GetParamsFromCache() + // #nosec G115 // maxSizePrices is not negative if expiredRoundID := nextRoundID - uint64(p.MaxSizePrices); expiredRoundID > 0 { store.Delete(types.PricesRoundKey(expiredRoundID)) } diff --git a/x/oracle/keeper/recent_msg.go b/x/oracle/keeper/recent_msg.go index a9f56e722..3c15d0f9b 100644 --- a/x/oracle/keeper/recent_msg.go +++ b/x/oracle/keeper/recent_msg.go @@ -15,6 +15,7 @@ func (k Keeper) SetMsgItemsForCache(ctx sdk.Context, recentMsg types.RecentMsg) maxNonce := k.GetParams(ctx).MaxNonce for ; i < len(index.Index); i++ { b := index.Index[i] + // #nosec G115 // maxNonce is not negative if b > block-uint64(maxNonce) { break } diff --git a/x/oracle/keeper/recent_params.go b/x/oracle/keeper/recent_params.go index ae3724908..231e29df6 100644 --- a/x/oracle/keeper/recent_params.go +++ b/x/oracle/keeper/recent_params.go @@ -15,6 +15,7 @@ func (k Keeper) SetParamsForCache(ctx sdk.Context, params types.RecentParams) { maxNonce := k.GetParams(ctx).MaxNonce for ; i < len(index.Index); i++ { b := index.Index[i] + // #nosec G115 // maxNonce is not negative if b > block-uint64(maxNonce) { break } @@ -136,5 +137,5 @@ func (k Keeper) GetRecentParamsWithinMaxNonce(ctx sdk.Context) (recentParamsList prev = types.RecentParams{} } } - return + return recentParamsList, prev, latest } diff --git a/x/oracle/keeper/tokens.go b/x/oracle/keeper/tokens.go index 6b97e8733..3221af141 100644 --- a/x/oracle/keeper/tokens.go +++ b/x/oracle/keeper/tokens.go @@ -12,6 +12,7 @@ func (k Keeper) GetTokens(ctx sdk.Context) []*types.TokenIndex { for idx, token := range params.Tokens { ret = append(ret, &types.TokenIndex{ Token: token.Name, + // #nosec G115 Index: uint64(idx), }) } diff --git a/x/oracle/types/params.go b/x/oracle/types/params.go index 1455f46c5..db9070d42 100644 --- a/x/oracle/types/params.go +++ b/x/oracle/types/params.go @@ -322,6 +322,8 @@ func (p Params) UpdateTokens(currentHeight uint64, tokens ...*Token) (Params, er if len(t.AssetID) > 0 { token.AssetID = t.AssetID } + // tokenID is actually uint since it's index of array + //nolint:gosec if !p.TokenStarted(uint64(tokenID), currentHeight) { // contractAddres is mainly used as a description information if len(t.ContractAddress) > 0 { @@ -553,6 +555,7 @@ func (p Params) IsValidSource(sourceID uint64) bool { func (p Params) GetTokenFeeder(feederID uint64) *TokenFeeder { for k, v := range p.TokenFeeders { + // #nosec G115 // index of array is uint if uint64(k) == feederID { return v } @@ -562,6 +565,7 @@ func (p Params) GetTokenFeeder(feederID uint64) *TokenFeeder { func (p Params) GetTokenInfo(feederID uint64) *Token { for k, v := range p.TokenFeeders { + // #nosec G115 // index of arry is uint if uint64(k) == feederID { return p.Tokens[v.TokenID] } @@ -587,6 +591,7 @@ func (p Params) CheckRules(feederID uint64, prices []*PriceSource) (bool, error) if source.Valid { notFound = true for _, p := range prices { + // #nosec G115 // index of array is uint if p.SourceID == uint64(sID) { notFound = false break