Skip to content

Commit

Permalink
fix lint
Browse files Browse the repository at this point in the history
  • Loading branch information
leonz789 committed Jan 13, 2025
1 parent 30be7b6 commit 97f8272
Show file tree
Hide file tree
Showing 27 changed files with 142 additions and 90 deletions.
3 changes: 3 additions & 0 deletions app/ante/cosmos/sigverify.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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)
}
Expand Down
2 changes: 2 additions & 0 deletions app/ante/cosmos/txsize_gas.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions precompiles/avs/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 6 additions & 2 deletions tests/e2e/oracle/helper_nstconvert.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package oracle

import (
"encoding/binary"
"math"
"strings"

"github.com/imroc/biu"
Expand All @@ -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
Expand All @@ -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 {
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion x/avs/client/cli/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
3 changes: 3 additions & 0 deletions x/avs/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions x/delegation/keeper/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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},
Expand Down
13 changes: 7 additions & 6 deletions x/delegation/keeper/delegation.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions x/evm/keeper/grpc_query.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()))
Expand Down Expand Up @@ -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 {
Expand Down
1 change: 1 addition & 0 deletions x/operator/keeper/slash.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
5 changes: 4 additions & 1 deletion x/operator/types/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
}

Expand All @@ -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))
}
Expand All @@ -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")
}
Expand Down Expand Up @@ -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))
}
Expand Down
5 changes: 5 additions & 0 deletions x/oracle/keeper/cache/caches.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand All @@ -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
}
Expand Down Expand Up @@ -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})
}
Expand All @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion x/oracle/keeper/feedermanagement/aggregator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
42 changes: 21 additions & 21 deletions x/oracle/keeper/feedermanagement/algo.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ type AggMedian struct {
t priceType
finalString string
list []*big.Int
decimal int
decimal int32
}

func NewAggMedian() *AggMedian {
Expand All @@ -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 {
Expand All @@ -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,
Expand Down
11 changes: 8 additions & 3 deletions x/oracle/keeper/feedermanagement/caches.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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,
}
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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)
}

Expand All @@ -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,
})
Expand Down
Loading

0 comments on commit 97f8272

Please sign in to comment.