diff --git a/auth/ante.go b/auth/ante.go index f4371a970..b32c929b7 100644 --- a/auth/ante.go +++ b/auth/ante.go @@ -134,7 +134,7 @@ func NewAnteHandler( return newCtx, err.Result(), true } - if res := ValidateMemo(stdTx, params); !res.IsOK() { + if res = ValidateMemo(stdTx, params); !res.IsOK() { return newCtx, res, true } @@ -218,7 +218,7 @@ func ValidateMemo(stdTx authTypes.StdTx, params authTypes.Params) sdk.Result { } // verify the signature and increment the sequence. If the account doesn't have -// a pubkey, set it. +// a pubKey, set it. func processSig( ctx sdk.Context, acc authTypes.Account, @@ -228,7 +228,7 @@ func processSig( params authTypes.Params, sigGasConsumer SignatureVerificationGasConsumer, ) (updatedAcc authTypes.Account, res sdk.Result) { - if res := sigGasConsumer(ctx.GasMeter(), sig, params); !res.IsOK() { + if res = sigGasConsumer(ctx.GasMeter(), sig, params); !res.IsOK() { return nil, res } diff --git a/bor/client/cli/query.go b/bor/client/cli/query.go index c9433df91..3ab21ba40 100644 --- a/bor/client/cli/query.go +++ b/bor/client/cli/query.go @@ -327,7 +327,7 @@ func GetPreparedProposeSpan(cdc *codec.Codec) *cobra.Command { } var spanDuration uint64 - if err := jsoniter.Unmarshal(res, &spanDuration); err != nil { + if err = jsoniter.Unmarshal(res, &spanDuration); err != nil { return err } @@ -346,7 +346,7 @@ func GetPreparedProposeSpan(cdc *codec.Codec) *cobra.Command { } var seed common.Hash - if err := jsoniter.Unmarshal(res, &seed); err != nil { + if err = jsoniter.Unmarshal(res, &seed); err != nil { return err } diff --git a/bor/client/cli/tx.go b/bor/client/cli/tx.go index 46aba4c7b..6c6ca9e4c 100644 --- a/bor/client/cli/tx.go +++ b/bor/client/cli/tx.go @@ -98,7 +98,7 @@ func PostSendProposeSpanTx(cdc *codec.Codec) *cobra.Command { } var spanDuration uint64 - if err := jsoniter.ConfigFastest.Unmarshal(res, &spanDuration); err != nil { + if err = jsoniter.ConfigFastest.Unmarshal(res, &spanDuration); err != nil { return err } diff --git a/bor/keeper.go b/bor/keeper.go index 348b1ef75..3d6b3ca15 100644 --- a/bor/keeper.go +++ b/bor/keeper.go @@ -371,11 +371,11 @@ func (k *Keeper) GetNextSpanSeed(ctx sdk.Context, id uint64) (common.Hash, error k.Logger(ctx).Debug("newEthBlock to generate seed", "newEthBlock", newEthBlock) // fetch block header from mainchain - var err error - blockHeader, err = k.contractCaller.GetMainChainBlock(newEthBlock) - if err != nil { - k.Logger(ctx).Error("Error fetching block header from mainchain while calculating next span seed", "error", err) - return common.Hash{}, err + var e error + blockHeader, e = k.contractCaller.GetMainChainBlock(newEthBlock) + if e != nil { + k.Logger(ctx).Error("Error fetching block header from mainchain while calculating next span seed", "error", e) + return common.Hash{}, e } } else { var seedSpanID uint64 @@ -519,7 +519,7 @@ func (k *Keeper) getBorBlockForSpanSeed(ctx sdk.Context, seedSpan *hmTypes.Span, break } - author, err := k.GetSeedProducer(ctx, spanID) + author, err = k.GetSeedProducer(ctx, spanID) if err != nil { logger.Error("Error fetching span seed producer", "error", err, "span id", spanID) return 0, nil, err @@ -566,6 +566,10 @@ func (k *Keeper) getBorBlockForSpanSeed(ctx sdk.Context, seedSpan *hmTypes.Span, borBlock = seedSpan.EndBlock } + if borBlock > math.MaxInt64 { + return 0, nil, fmt.Errorf("bor block value out of range for int64: %d", borBlock) + } + author, err = k.contractCaller.GetBorChainBlockAuthor(big.NewInt(int64(borBlock))) if err != nil { logger.Error("Error fetching end block author from bor chain while calculating next span seed", "error", err, "block", borBlock) diff --git a/bor/selection.go b/bor/selection.go index 78c2aaa72..57ea9d69c 100644 --- a/bor/selection.go +++ b/bor/selection.go @@ -128,12 +128,12 @@ func binarySearch(array []uint64, search uint64) int { } // randomRangeInclusive produces unbiased pseudo random in the range [min, max]. Uses rand.Uint64() and can be seeded beforehand. -func randomRangeInclusive(min uint64, max uint64) uint64 { - if max <= min { - return max +func randomRangeInclusive(minV uint64, maxV uint64) uint64 { + if maxV <= minV { + return maxV } - rangeLength := max - min + 1 + rangeLength := maxV - minV + 1 maxAllowedValue := math.MaxUint64 - math.MaxUint64%rangeLength - 1 randomValue := rand.Uint64() //nolint @@ -142,7 +142,7 @@ func randomRangeInclusive(min uint64, max uint64) uint64 { randomValue = rand.Uint64() //nolint } - return min + randomValue%rangeLength + return minV + randomValue%rangeLength } // createWeightedRanges converts array [1, 2, 3] into cumulative form [1, 3, 6] diff --git a/bor/shuffle.go b/bor/shuffle.go index 84fb6a7ed..c4af38714 100644 --- a/bor/shuffle.go +++ b/bor/shuffle.go @@ -78,6 +78,7 @@ func innerShuffleList(input []uint64, seed [32]byte, shuffle bool) ([]uint64, er if pivot>>8 > math.MaxUint32 { return nil, fmt.Errorf("pivot value out of range for uint32: %d", pivot>>8) } + //nolint:gosec binary.LittleEndian.PutUint32(buf[pivotViewSize:], uint32(pivot>>8)) source := sha256Hash(buf) @@ -92,6 +93,7 @@ func innerShuffleList(input []uint64, seed [32]byte, shuffle bool) ([]uint64, er if end>>8 > math.MaxUint32 { return nil, fmt.Errorf("end value out of range for uint32: %d", end>>8) } + //nolint:gosec binary.LittleEndian.PutUint32(buf[pivotViewSize:], uint32(end>>8)) source = sha256Hash(buf) diff --git a/bor/shuffle_test.go b/bor/shuffle_test.go index c4ad6e2c2..e67877083 100644 --- a/bor/shuffle_test.go +++ b/bor/shuffle_test.go @@ -81,8 +81,8 @@ func GenRandomVal(count int, startBlock uint64, power int64, timeAlive uint64, r return } -func generateRandNumber(max int64) uint64 { - nBig, err := rand.Int(rand.Reader, big.NewInt(max)) +func generateRandNumber(maxV int64) uint64 { + nBig, err := rand.Int(rand.Reader, big.NewInt(maxV)) if err != nil { return 1 } diff --git a/bridge/setu/listener/heimdall.go b/bridge/setu/listener/heimdall.go index 5a1580c2b..df5afde33 100644 --- a/bridge/setu/listener/heimdall.go +++ b/bridge/setu/listener/heimdall.go @@ -168,10 +168,10 @@ func (hl *HeimdallListener) fetchFromAndToBlock() (uint64, uint64, error) { // fromBlock - get last block from storage hasLastBlock, _ := hl.storageClient.Has([]byte(heimdallLastBlockKey), nil) if hasLastBlock { - lastBlockBytes, err := hl.storageClient.Get([]byte(heimdallLastBlockKey), nil) - if err != nil { - hl.Logger.Info("Error while fetching last block bytes from storage", "error", err) - return fromBlock, toBlock, err + lastBlockBytes, e := hl.storageClient.Get([]byte(heimdallLastBlockKey), nil) + if e != nil { + hl.Logger.Info("Error while fetching last block bytes from storage", "error", e) + return fromBlock, toBlock, e } if result, err := strconv.ParseUint(string(lastBlockBytes), 10, 64); err == nil { diff --git a/bridge/setu/listener/rootchain.go b/bridge/setu/listener/rootchain.go index 0bb1e446b..37717f664 100644 --- a/bridge/setu/listener/rootchain.go +++ b/bridge/setu/listener/rootchain.go @@ -124,9 +124,9 @@ func (rl *RootChainListener) ProcessHeader(newHeader *blockHeader) { // get last block from storage hasLastBlock, _ := rl.storageClient.Has([]byte(lastRootBlockKey), nil) if hasLastBlock { - lastBlockBytes, err := rl.storageClient.Get([]byte(lastRootBlockKey), nil) - if err != nil { - rl.Logger.Info("Error while fetching last block bytes from storage", "error", err) + lastBlockBytes, e := rl.storageClient.Get([]byte(lastRootBlockKey), nil) + if e != nil { + rl.Logger.Info("Error while fetching last block bytes from storage", "error", e) return } diff --git a/bridge/setu/listener/rootchain_selfheal_graph.go b/bridge/setu/listener/rootchain_selfheal_graph.go index 29498535c..4dd7cf6e4 100644 --- a/bridge/setu/listener/rootchain_selfheal_graph.go +++ b/bridge/setu/listener/rootchain_selfheal_graph.go @@ -223,6 +223,12 @@ func (rl *RootChainListener) getLatestNonce(ctx context.Context, validatorId uin // getStakeUpdate returns StakeUpdate event based on the given validator ID and nonce func (rl *RootChainListener) getStakeUpdate(ctx context.Context, validatorId, nonce uint64) (*types.Log, error) { + if validatorId > math.MaxInt { + return nil, fmt.Errorf("validator ID value out of range for int: %d", validatorId) + } + if nonce > math.MaxInt { + return nil, fmt.Errorf("nonce value out of range for int: %d", nonce) + } query := map[string]string{ "query": ` { diff --git a/bridge/setu/processor/checkpoint.go b/bridge/setu/processor/checkpoint.go index c4107e556..61c1d5802 100644 --- a/bridge/setu/processor/checkpoint.go +++ b/bridge/setu/processor/checkpoint.go @@ -110,7 +110,7 @@ func (cp *CheckpointProcessor) startPollingForNoAck(ctx context.Context, interva // 3. if so, propose checkpoint to heimdall. func (cp *CheckpointProcessor) sendCheckpointToHeimdall(headerBlockStr string) (err error) { var header = types.Header{} - if err := header.UnmarshalJSON([]byte(headerBlockStr)); err != nil { + if err = header.UnmarshalJSON([]byte(headerBlockStr)); err != nil { cp.Logger.Error("Error while unmarshalling the header block", "error", err) return err } @@ -150,9 +150,8 @@ func (cp *CheckpointProcessor) sendCheckpointToHeimdall(headerBlockStr string) ( start := expectedCheckpointState.newStart end := expectedCheckpointState.newEnd - // // Check checkpoint buffer - // + //nolint:gosec timeStamp := uint64(time.Now().Unix()) checkpointBufferTime := uint64(checkpointContext.CheckpointParams.CheckpointBufferTime.Seconds()) @@ -420,6 +419,9 @@ func (cp *CheckpointProcessor) nextExpectedCheckpoint(checkpointContext *Checkpo currentTime := time.Now().UTC().Unix() defaultForcePushInterval := checkpointParams.MaxCheckpointLength * 2 // in seconds (1024 * 2 seconds) + if lastCheckpointTime < 0 || lastCheckpointTime > math.MaxInt64 { + return nil, fmt.Errorf("last checkpoint time is invalid") + } if currentTime-int64(lastCheckpointTime) > int64(defaultForcePushInterval) { end = latestChildBlock cp.Logger.Info("Force push checkpoint", @@ -611,7 +613,9 @@ func (cp *CheckpointProcessor) getLatestCheckpointTime(checkpointContext *Checkp cp.Logger.Error("Error while fetching header block object", "error", err) return 0, err } - + if createdAt < 0 || createdAt > math.MaxInt64 { + return 0, fmt.Errorf("createdAt is invalid") + } return int64(createdAt), nil } diff --git a/bridge/setu/processor/clerk_test.go b/bridge/setu/processor/clerk_test.go index 5db298d5b..c80f566d7 100644 --- a/bridge/setu/processor/clerk_test.go +++ b/bridge/setu/processor/clerk_test.go @@ -672,8 +672,8 @@ func getTestServer() (*machinery.Server, error) { }) } -func generateRandNumber(max int64) uint64 { - nBig, err := rand.Int(rand.Reader, big.NewInt(max)) +func generateRandNumber(maxV int64) uint64 { + nBig, err := rand.Int(rand.Reader, big.NewInt(maxV)) if err != nil { return 1 } diff --git a/bridge/setu/processor/staking.go b/bridge/setu/processor/staking.go index a19498f03..aa6cad9e2 100644 --- a/bridge/setu/processor/staking.go +++ b/bridge/setu/processor/staking.go @@ -1,7 +1,9 @@ package processor import ( + "errors" "fmt" + "math" "time" "github.com/RichardKnop/machinery/v1/tasks" @@ -180,6 +182,10 @@ func (sp *StakingProcessor) sendUnstakeInitToHeimdall(eventName string, logBytes return err } + if nonceDelay < 0 || nonceDelay > math.MaxInt64 { + return errors.New("nonceDelay is invalid") + } + if !validNonce { sp.Logger.Info("Ignoring task to send unstake-init to heimdall as nonce is out of order") return tasks.NewErrRetryTaskLater("Nonce out of order", defaultDelayDuration*time.Duration(nonceDelay)) @@ -256,6 +262,10 @@ func (sp *StakingProcessor) sendStakeUpdateToHeimdall(eventName string, logBytes return err } + if nonceDelay < 0 || nonceDelay > math.MaxInt64 { + return errors.New("nonceDelay is invalid") + } + if !validNonce { sp.Logger.Info("Ignoring task to send stake-update to heimdall as nonce is out of order") return tasks.NewErrRetryTaskLater("Nonce out of order", defaultDelayDuration*time.Duration(nonceDelay)) @@ -336,6 +346,10 @@ func (sp *StakingProcessor) sendSignerChangeToHeimdall(eventName string, logByte return err } + if nonceDelay < 0 || nonceDelay > math.MaxInt64 { + return errors.New("nonceDelay is invalid") + } + if !validNonce { sp.Logger.Info("Ignoring task to send signer-change to heimdall as nonce is out of order") return tasks.NewErrRetryTaskLater("Nonce out of order", defaultDelayDuration*time.Duration(nonceDelay)) diff --git a/checkpoint/client/cli/query.go b/checkpoint/client/cli/query.go index a015a7b23..98a4680de 100644 --- a/checkpoint/client/cli/query.go +++ b/checkpoint/client/cli/query.go @@ -243,7 +243,7 @@ func GetCheckpointLatest(cdc *codec.Codec) *cobra.Command { } var ackCount uint64 - if err := jsoniter.Unmarshal(ackcountBytes, &ackCount); err != nil { + if err = jsoniter.Unmarshal(ackcountBytes, &ackCount); err != nil { return err } @@ -423,7 +423,7 @@ func GetOverview(cdc *codec.Codec) *cobra.Command { validatorSetBytes, _, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", stakingTypes.QuerierRoute, stakingTypes.QueryCurrentValidatorSet), nil) if err == nil { - if err := jsoniter.Unmarshal(validatorSetBytes, &validatorSet); err != nil { + if err = jsoniter.Unmarshal(validatorSetBytes, &validatorSet); err != nil { // log and ignore cliLogger.Error("Error while unmarshing validator set", "error", err.Error()) } diff --git a/checkpoint/client/cli/tx.go b/checkpoint/client/cli/tx.go index 8a23144c1..7fae13799 100644 --- a/checkpoint/client/cli/tx.go +++ b/checkpoint/client/cli/tx.go @@ -161,7 +161,7 @@ func SendCheckpointTx(cdc *codec.Codec) *cobra.Command { return err } - if err := jsoniter.ConfigFastest.Unmarshal(proposerBytes, &checkpointProposer); err != nil { + if err = jsoniter.ConfigFastest.Unmarshal(proposerBytes, &checkpointProposer); err != nil { return err } diff --git a/checkpoint/client/rest/query_milestone.go b/checkpoint/client/rest/query_milestone.go index 8b71d56f4..3339d062b 100644 --- a/checkpoint/client/rest/query_milestone.go +++ b/checkpoint/client/rest/query_milestone.go @@ -23,9 +23,9 @@ func registerQueryMilestoneRoutes(cliCtx context.CLIContext, r *mux.Router) { r.HandleFunc("/milestone/ID/{id}", milestoneByIDHandlerFn(cliCtx)).Methods("GET") } -func milestoneLatestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func milestoneLatestHandlerFn(ctx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, ctx, r) if !ok { return } @@ -57,9 +57,9 @@ func milestoneLatestHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { // responses: // // 200: milestoneCountResponse -func milestoneCountHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func milestoneCountHandlerFn(ctx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, ctx, r) if !ok { return } @@ -84,7 +84,7 @@ func milestoneCountHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } var count uint64 - if err := jsoniter.Unmarshal(countBytes, &count); err != nil { + if err = jsoniter.Unmarshal(countBytes, &count); err != nil { hmRest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } @@ -102,11 +102,11 @@ func milestoneCountHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } } -func milestoneByNumberHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func milestoneByNumberHandlerFn(ctx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, ctx, r) if !ok { return } @@ -144,9 +144,9 @@ func milestoneByNumberHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } } -func latestNoAckMilestoneHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func latestNoAckMilestoneHandlerFn(ctx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, ctx, r) if !ok { return } @@ -171,7 +171,7 @@ func latestNoAckMilestoneHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } var milestoneID string - if err := jsoniter.Unmarshal(result, &milestoneID); err != nil { + if err = jsoniter.Unmarshal(result, &milestoneID); err != nil { hmRest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } @@ -189,11 +189,11 @@ func latestNoAckMilestoneHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } } -func noAckMilestoneByIDHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func noAckMilestoneByIDHandlerFn(ctx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, ctx, r) if !ok { return } @@ -222,7 +222,7 @@ func noAckMilestoneByIDHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } var val bool - if err := jsoniter.Unmarshal(result, &val); err != nil { + if err = jsoniter.Unmarshal(result, &val); err != nil { hmRest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } @@ -241,11 +241,11 @@ func noAckMilestoneByIDHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } } -func milestoneByIDHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func milestoneByIDHandlerFn(ctx context.CLIContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) + cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, ctx, r) if !ok { return } diff --git a/checkpoint/genesis.go b/checkpoint/genesis.go index cd0c50d74..a4560bc20 100644 --- a/checkpoint/genesis.go +++ b/checkpoint/genesis.go @@ -2,6 +2,7 @@ package checkpoint import ( "errors" + "math" sdk "github.com/cosmos/cosmos-sdk/types" @@ -20,6 +21,9 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) { // Add finalised checkpoints to state if len(data.Checkpoints) != 0 { + if data.AckCount > math.MaxInt { + panic(errors.New("AckCount value out of range for int")) + } // check if we are provided all the headers if int(data.AckCount) != len(data.Checkpoints) { panic(errors.New("Incorrect state in state-dump , Please Check ")) @@ -28,6 +32,7 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) { data.Checkpoints = hmTypes.SortHeaders(data.Checkpoints) // load checkpoints to state for i, checkpoint := range data.Checkpoints { + //nolint:gosec checkpointIndex := uint64(i) + 1 if err := keeper.AddCheckpoint(ctx, checkpointIndex, checkpoint); err != nil { keeper.Logger(ctx).Error("InitGenesis | AddCheckpoint", diff --git a/checkpoint/handler.go b/checkpoint/handler.go index a343517ea..c78870aeb 100644 --- a/checkpoint/handler.go +++ b/checkpoint/handler.go @@ -79,13 +79,10 @@ func handleMsgCheckpointAdjust(ctx sdk.Context, msg types.MsgCheckpointAdjust, k func handleMsgCheckpoint(ctx sdk.Context, msg types.MsgCheckpoint, k Keeper, _ helper.IContractCaller) sdk.Result { logger := k.Logger(ctx) + //nolint:gosec timeStamp := uint64(ctx.BlockTime().Unix()) params := k.GetParams(ctx) - // - // Check checkpoint buffer - // - checkpointBuffer, err := k.GetCheckpointFromBuffer(ctx) if err == nil { checkpointBufferTime := uint64(params.CheckpointBufferTime.Seconds()) @@ -105,7 +102,7 @@ func handleMsgCheckpoint(ctx sdk.Context, msg types.MsgCheckpoint, k Keeper, _ h // // fetch last checkpoint from store - if lastCheckpoint, err := k.GetLastCheckpoint(ctx); err == nil { + if lastCheckpoint, e := k.GetLastCheckpoint(ctx); e == nil { // make sure new checkpoint is after tip if lastCheckpoint.EndBlock > msg.StartBlock { logger.Error("Checkpoint already exists", @@ -253,6 +250,9 @@ func handleMsgCheckpointNoAck(ctx sdk.Context, msg types.MsgCheckpointNoAck, k K // Fetch last checkpoint from store // TODO figure out how to handle this error lastCheckpoint, _ := k.GetLastCheckpoint(ctx) + if lastCheckpoint.TimeStamp > math.MaxInt64 { + return sdk.ErrInternal("Checkpoint timestamp exceeds int64 max value").Result() + } lastCheckpointTime := time.Unix(int64(lastCheckpoint.TimeStamp), 0) // If last checkpoint is not present or last checkpoint happens before checkpoint buffer time -- thrown an error @@ -293,6 +293,9 @@ func handleMsgCheckpointNoAck(ctx sdk.Context, msg types.MsgCheckpointNoAck, k K // Check last no ack - prevents repetitive no-ack lastNoAck := k.GetLastNoAck(ctx) + if lastNoAck > math.MaxInt64 { + return sdk.ErrInternal("NoAck timestamp exceeds int64 max value").Result() + } lastNoAckTime := time.Unix(int64(lastNoAck), 0) if lastNoAckTime.After(currentTime) || (currentTime.Sub(lastNoAckTime) < bufferTime) { diff --git a/checkpoint/handler_milestone.go b/checkpoint/handler_milestone.go index 65425d0d5..c9d259fd4 100644 --- a/checkpoint/handler_milestone.go +++ b/checkpoint/handler_milestone.go @@ -2,6 +2,7 @@ package checkpoint import ( "bytes" + "math" "strconv" "time" @@ -56,14 +57,13 @@ func handleMsgMilestone(ctx sdk.Context, msg types.MsgMilestone, k Keeper) sdk.R //Increment the priority in the milestone validator set k.sk.MilestoneIncrementAccum(ctx, 1) - // - //Check for the msg milestone - // - - //Calculate the milestone length + // Calculate the milestone length + if msg.EndBlock > math.MaxInt64 || msg.StartBlock > math.MaxInt64 { + return common.ErrMilestoneInvalid("Block number exceeds int64 max value").Result() + } msgMilestoneLength := int64(msg.EndBlock) - int64(msg.StartBlock) + 1 - //check for the minimum length of milestone + // Check for the minimum length of milestone if msgMilestoneLength < int64(milestoneLength) { logger.Error("Length of the milestone should be greater than configured minimum milestone length", "StartBlock", msg.StartBlock, @@ -131,6 +131,9 @@ func handleMsgMilestoneTimeout(ctx sdk.Context, _ types.MsgMilestoneTimeout, k K return common.ErrNoMilestoneFound(k.Codespace()).Result() } + if lastMilestone.TimeStamp > math.MaxInt64 { + return common.ErrMilestoneInvalid("Milestone timestamp exceeds int64 max value").Result() + } lastMilestoneTime := time.Unix(int64(lastMilestone.TimeStamp), 0) // If last milestone happens before milestone buffer time -- thrown an error @@ -144,6 +147,9 @@ func handleMsgMilestoneTimeout(ctx sdk.Context, _ types.MsgMilestoneTimeout, k K // Check last no ack - prevents repetitive no-ack lastMilestoneTimeout := k.GetLastMilestoneTimeout(ctx) + if lastMilestoneTimeout > math.MaxInt64 { + return common.ErrMilestoneInvalid("Milestone timeout exceeds int64 max value").Result() + } lastMilestoneTimeoutTime := time.Unix(int64(lastMilestoneTimeout), 0) if lastMilestoneTimeoutTime.After(currentTime) || (currentTime.Sub(lastMilestoneTimeoutTime) < bufferTime) { @@ -154,6 +160,7 @@ func handleMsgMilestoneTimeout(ctx sdk.Context, _ types.MsgMilestoneTimeout, k K } // Set new last milestone-timeout + //nolint:gosec newLastMilestoneTimeout := uint64(currentTime.Unix()) k.SetLastMilestoneTimeout(ctx, newLastMilestoneTimeout) logger.Debug("Last milestone-timeout set", "lastMilestoneTimeout", newLastMilestoneTimeout) diff --git a/checkpoint/handler_milestone_test.go b/checkpoint/handler_milestone_test.go index dccf462cc..1e01d60cb 100644 --- a/checkpoint/handler_milestone_test.go +++ b/checkpoint/handler_milestone_test.go @@ -156,7 +156,7 @@ func (suite *HandlerTestSuite) TestHandleMsgMilestone() { //Test5- When milestone is not in continuity suite.Run("Milestone not in countinuity", func() { - err := keeper.AddMilestone(ctx, header) + err = keeper.AddMilestone(ctx, header) require.NoError(t, err) _, err = keeper.GetLastMilestone(ctx) diff --git a/checkpoint/module.go b/checkpoint/module.go index 1f7eb4c9a..3c19d4432 100644 --- a/checkpoint/module.go +++ b/checkpoint/module.go @@ -245,6 +245,7 @@ func verifyGenesis(state types.GenesisState, chainManagerState chainmanagerTypes // check all headers for i, header := range state.Checkpoints { + //nolint:gosec ackCount := uint64(i + 1) root, start, end, _, _, err := contractCaller.GetHeaderInfo(ackCount, rootChainInstance, childBlockInterval) diff --git a/checkpoint/side_handler.go b/checkpoint/side_handler.go index bffe8a8a8..b5a2125ca 100644 --- a/checkpoint/side_handler.go +++ b/checkpoint/side_handler.go @@ -328,6 +328,7 @@ func PostHandleMsgCheckpoint(ctx sdk.Context, k Keeper, msg types.MsgCheckpoint, return common.ErrNoACK(k.Codespace(), expiryTime).Result() } + //nolint:gosec timeStamp := uint64(ctx.BlockTime().Unix()) // Add checkpoint to buffer with root hash and account hash diff --git a/checkpoint/side_milestone_handler.go b/checkpoint/side_milestone_handler.go index 1d49a7ee7..e042677f1 100644 --- a/checkpoint/side_milestone_handler.go +++ b/checkpoint/side_milestone_handler.go @@ -73,7 +73,9 @@ func SideHandleMsgMilestone(ctx sdk.Context, k Keeper, msg types.MsgMilestone, c // PostHandleMsgMilestone handles msg milestone func PostHandleMsgMilestone(ctx sdk.Context, k Keeper, msg types.MsgMilestone, sideTxResult abci.SideTxResultType) sdk.Result { logger := k.MilestoneLogger(ctx) - timeStamp := uint64(ctx.BlockTime().Unix()) + time := ctx.BlockTime().Unix() + //nolint:gosec + timeStamp := uint64(time) // TX bytes txBytes := ctx.TxBytes() diff --git a/clerk/keeper.go b/clerk/keeper.go index 47451c42c..957d73551 100644 --- a/clerk/keeper.go +++ b/clerk/keeper.go @@ -321,7 +321,7 @@ func (k *Keeper) HasRecordSequence(ctx sdk.Context, sequence string) bool { // IterateRecordsAndCollect iterates over EventRecords, collects up to 'max' entries, // and returns a slice containing the collected records. // It continues from the last key processed in the previous batch. -func (k *Keeper) IterateRecordsAndCollect(ctx sdk.Context, nextKey []byte, max int) ([]*types.EventRecord, []byte, error) { +func (k *Keeper) IterateRecordsAndCollect(ctx sdk.Context, nextKey []byte, maxV int) ([]*types.EventRecord, []byte, error) { store := ctx.KVStore(k.storeKey) var startKey []byte @@ -336,10 +336,10 @@ func (k *Keeper) IterateRecordsAndCollect(ctx sdk.Context, nextKey []byte, max i iterator := store.Iterator(startKey, endKey) defer iterator.Close() - collectedRecords := make([]*types.EventRecord, 0, max) + collectedRecords := make([]*types.EventRecord, 0, maxV) entriesCollected := 0 - for ; iterator.Valid() && entriesCollected < max; iterator.Next() { + for ; iterator.Valid() && entriesCollected < maxV; iterator.Next() { var record types.EventRecord if err := k.cdc.UnmarshalBinaryBare(iterator.Value(), &record); err != nil { k.Logger(ctx).Error("IterateRecordsAndCollect | UnmarshalBinaryBare", "error", err) diff --git a/clerk/module.go b/clerk/module.go index 1e6189fa2..0cb49ca1b 100644 --- a/clerk/module.go +++ b/clerk/module.go @@ -154,8 +154,8 @@ func (am AppModule) ExportPartialGenesis(ctx sdk.Context) (json.RawMessage, erro } // NextGenesisData returns the next chunk of genesis data. -func (am AppModule) NextGenesisData(ctx sdk.Context, nextKey []byte, max int) (*hmModule.ModuleGenesisData, error) { - data, nextKey, err := am.keeper.IterateRecordsAndCollect(ctx, nextKey, max) +func (am AppModule) NextGenesisData(ctx sdk.Context, nextKey []byte, maxV int) (*hmModule.ModuleGenesisData, error) { + data, nextKey, err := am.keeper.IterateRecordsAndCollect(ctx, nextKey, maxV) if err != nil { return nil, err } diff --git a/cmd/heimdallcli/main_test.go b/cmd/heimdallcli/main_test.go index 347338cba..8c9e980b5 100644 --- a/cmd/heimdallcli/main_test.go +++ b/cmd/heimdallcli/main_test.go @@ -1,3 +1,4 @@ +//nolint:govet package main import ( diff --git a/cmd/heimdalld/service/init.go b/cmd/heimdalld/service/init.go index 55343d8e4..ed2ed4015 100644 --- a/cmd/heimdalld/service/init.go +++ b/cmd/heimdalld/service/init.go @@ -51,7 +51,7 @@ func heimdallInit(_ *server.Context, cdc *codec.Codec, initConfig *initHeimdallC if !writeGenesis { // When not forcing, check if genesis file exists - _, err := os.Stat(config.GenesisFile()) + _, err = os.Stat(config.GenesisFile()) if err != nil && errors.Is(err, os.ErrNotExist) { logger.Info(fmt.Sprintf("Genesis file %v not found, writing genesis file\n", config.GenesisFile())) @@ -67,9 +67,9 @@ func heimdallInit(_ *server.Context, cdc *codec.Codec, initConfig *initHeimdallC } if writeGenesis { - genesisCreated, err := helper.WriteGenesisFile(initConfig.chain, config.GenesisFile(), cdc) - if err != nil { - return err + genesisCreated, e := helper.WriteGenesisFile(initConfig.chain, config.GenesisFile(), cdc) + if e != nil { + return e } else if genesisCreated { return nil } @@ -83,13 +83,16 @@ func heimdallInit(_ *server.Context, cdc *codec.Codec, initConfig *initHeimdallC chainID = fmt.Sprintf("heimdall-%v", common.RandStr(6)) } - // get pubkey - newPubkey := CryptoKeyToPubkey(valPubKey) + // get pubKey + newPubKey := CryptoKeyToPubkey(valPubKey) // create validator account - validator := hmTypes.NewValidator(hmTypes.NewValidatorID(uint64(initConfig.validatorID)), - 0, 0, 1, 1, newPubkey, - hmTypes.BytesToHeimdallAddress(valPubKey.Address().Bytes())) + validator := hmTypes.NewValidator( + //nolint:gosec + hmTypes.NewValidatorID(uint64(initConfig.validatorID)), + 0, 0, 1, 1, newPubKey, + hmTypes.BytesToHeimdallAddress(valPubKey.Address().Bytes()), + ) // create dividend account for validator dividendAccount := hmTypes.NewDividendAccount(validator.Signer, ZeroIntString) @@ -159,7 +162,7 @@ func heimdallInit(_ *server.Context, cdc *codec.Codec, initConfig *initHeimdallC return err } - fmt.Fprintf(os.Stderr, "%s\n", string(out)) + _, _ = fmt.Fprintf(os.Stderr, "%s\n", string(out)) return writeGenesisFile(tmtime.Now(), config.GenesisFile(), chainID, appStateJSON) } diff --git a/cmd/heimdalld/service/service.go b/cmd/heimdalld/service/service.go index be1932dbc..96edb7d5f 100644 --- a/cmd/heimdalld/service/service.go +++ b/cmd/heimdalld/service/service.go @@ -260,13 +260,12 @@ which accepts a path for the resulting pprof file. if LogsWriterFile != "" { logWriter := helper.GetLogsWriter(LogsWriterFile) - logger, err := SetupCtxLogger(logWriter, ctx.Config.LogLevel) + lg, err := SetupCtxLogger(logWriter, ctx.Config.LogLevel) if err != nil { - logger.Error("Unable to setup logger", "err", err) return err } - ctx.Logger = logger + ctx.Logger = lg } ctx.Logger.Info("starting ABCI with Tendermint") @@ -359,7 +358,7 @@ func startOpenTracing(cmd *cobra.Command) (*sdktrace.TracerProvider, *context.Co traceExporterReady := make(chan *otlptrace.Exporter, 1) go func() { - traceExporter, _ := otlptracegrpc.New( + traceExporter, _ = otlptracegrpc.New( ctx, otlptracegrpc.WithInsecure(), otlptracegrpc.WithEndpoint(openCollectorEndpoint), @@ -546,6 +545,7 @@ func openDB(rootDir string) (dbm.DB, error) { func openTraceWriter(traceWriterFile string) (io.Writer, error) { if traceWriterFile == "" { + //nolint:nilnil return nil, nil } diff --git a/cmd/heimdalld/service/testnet.go b/cmd/heimdalld/service/testnet.go index 33341a570..57dbc265f 100644 --- a/cmd/heimdalld/service/testnet.go +++ b/cmd/heimdalld/service/testnet.go @@ -97,7 +97,7 @@ testnet --v 4 --n 8 --output-dir ./output --starting-ip-address 192.168.10.2 config.SetRoot(nodeDir) // create config folder - err := os.MkdirAll(filepath.Join(nodeDir, "config"), nodeDirPerm) + err = os.MkdirAll(filepath.Join(nodeDir, "config"), nodeDirPerm) if err != nil { _ = os.RemoveAll(outDir) return err @@ -115,17 +115,18 @@ testnet --v 4 --n 8 --output-dir ./output --starting-ip-address 192.168.10.2 } genFiles[i] = config.GenesisFile() - newPubkey := CryptoKeyToPubkey(valPubKeys[i]) + newPubKey := CryptoKeyToPubkey(valPubKeys[i]) if i < numValidators { // create validator account validators[i] = hmTypes.NewValidator( + //nolint:gosec hmTypes.NewValidatorID(uint64(startID+int64(i))), 0, 0, 1, 10000, - newPubkey, + newPubKey, hmTypes.BytesToHeimdallAddress(valPubKeys[i].Address().Bytes()), ) diff --git a/helper/backoff.go b/helper/backoff.go index faf34f608..e908983fb 100644 --- a/helper/backoff.go +++ b/helper/backoff.go @@ -5,9 +5,9 @@ import ( ) // ExponentialBackoff performs exponential backoff attempts on a given action -func ExponentialBackoff(action func() error, max uint, wait time.Duration) error { +func ExponentialBackoff(action func() error, maxV uint, wait time.Duration) error { var err error - for i := uint(0); i < max; i++ { + for i := uint(0); i < maxV; i++ { if err = action(); err == nil { break } diff --git a/helper/call.go b/helper/call.go index 07dc061a2..b19bb749d 100644 --- a/helper/call.go +++ b/helper/call.go @@ -991,7 +991,7 @@ func (c *ContractCaller) GetCheckpointSign(txHash common.Hash) ([]byte, []byte, ctx, cancel := context.WithTimeout(context.Background(), c.MainChainTimeout) defer cancel() - mainChainClient := GetMainClient() + mainChainClient = GetMainClient() transaction, isPending, err := mainChainClient.TransactionByHash(ctx, txHash) if err != nil { diff --git a/helper/query.go b/helper/query.go index 3434586da..65f232df1 100644 --- a/helper/query.go +++ b/helper/query.go @@ -67,7 +67,7 @@ func QueryTxsByEvents(cliCtx cosmosContext.CLIContext, tags []string, page, limi if prove { for _, tx := range resTxs.Txs { - err := ValidateTxResult(cliCtx, tx) + err = ValidateTxResult(cliCtx, tx) if err != nil { return nil, err } diff --git a/helper/tx.go b/helper/tx.go index a8dd25ba5..6267303a9 100644 --- a/helper/tx.go +++ b/helper/tx.go @@ -10,7 +10,7 @@ import ( "math/big" "strings" - ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" @@ -85,7 +85,7 @@ func GenerateAuthObj(client *ethclient.Client, address common.Address, data []by if nonce > uint64(math.MaxInt64) { return nil, fmt.Errorf("nonce value too large to convert to int64: %d", nonce) } - + auth.Nonce = big.NewInt(int64(nonce)) auth.GasPrice = gasprice auth.GasLimit = gasLimit diff --git a/helper/util.go b/helper/util.go index 0cc9bcb55..6adf7e6e6 100644 --- a/helper/util.go +++ b/helper/util.go @@ -385,9 +385,9 @@ func GetSignedTxBytes(cliCtx context.CLIContext, } if !cliCtx.SkipConfirm { - stdSignMsg, err := txBldr.BuildSignMsg(msgs) - if err != nil { - return nil, err + stdSignMsg, e := txBldr.BuildSignMsg(msgs) + if e != nil { + return nil, e } var json []byte @@ -436,9 +436,9 @@ func GetSignedTxBytesWithCLI(cliCtx context.CLIContext, txBldr authTypes.TxBuild } if !cliCtx.SkipConfirm { - stdSignMsg, err := txBldr.BuildSignMsg(msgs) - if err != nil { - return nil, err + stdSignMsg, e := txBldr.BuildSignMsg(msgs) + if e != nil { + return nil, e } var json []byte diff --git a/server/gRPC/gRPC.go b/server/gRPC/gRPC.go index 6b4ef5a4e..83c79359b 100644 --- a/server/gRPC/gRPC.go +++ b/server/gRPC/gRPC.go @@ -70,7 +70,7 @@ func loggingServerInterceptor(ctx context.Context, req interface{}, info *grpc.U h, err := handler(ctx, req) if err != nil { - err = status.Errorf(codes.Internal, err.Error()) + err = status.Error(codes.Internal, err.Error()) } logger.Info("Request", "method", info.FullMethod, "duration", time.Since(start), "error", err) diff --git a/server/gRPC/state_sync.go b/server/gRPC/state_sync.go index ae22c6b7f..fc5b49890 100644 --- a/server/gRPC/state_sync.go +++ b/server/gRPC/state_sync.go @@ -38,13 +38,13 @@ func (h *HeimdallGRPCServer) StateSyncEvents(req *proto.StateSyncEventsRequest, result, err := helper.FetchFromAPI(cliCtx, addParamsToEndpoint(helper.GetHeimdallServerEndpoint(eventRecordList), params)) if err != nil { logger.Error("Error while fetching event records", "error", err) - return status.Errorf(codes.Internal, err.Error()) + return status.Error(codes.Internal, err.Error()) } eventRecords, err := parseEvents(result.Result) if err != nil { logger.Error("Error while parsing event records", "error", err) - return status.Errorf(codes.Internal, err.Error()) + return status.Error(codes.Internal, err.Error()) } if len(eventRecords) == 0 { @@ -57,7 +57,7 @@ func (h *HeimdallGRPCServer) StateSyncEvents(req *proto.StateSyncEventsRequest, }) if err != nil { logger.Error("Error while sending event record", "error", err) - return status.Errorf(codes.Internal, err.Error()) + return status.Error(codes.Internal, err.Error()) } fromId += req.Limit diff --git a/server/root.go b/server/root.go index ee46e354e..e802aba14 100644 --- a/server/root.go +++ b/server/root.go @@ -3,6 +3,7 @@ package server import ( ctx "context" "fmt" + "math" "net" "net/http" "runtime/debug" @@ -53,12 +54,18 @@ func StartRestServer(mainCtx ctx.Context, cdc *codec.Codec, registerRoutesFn fun if viper.GetUint(client.FlagRPCReadTimeout) != 0 { readTimeOut := viper.GetUint(client.FlagRPCReadTimeout) - cfg.ReadTimeout = time.Duration(readTimeOut) * time.Second + if readTimeOut > math.MaxInt64 { + return fmt.Errorf("read timeout exceeds int64 max value") + } + cfg.ReadTimeout = time.Duration(int64(readTimeOut)) * time.Second } if viper.GetUint(client.FlagRPCWriteTimeout) != 0 { writeTimeOut := viper.GetUint(client.FlagRPCWriteTimeout) - cfg.WriteTimeout = time.Duration(writeTimeOut) * time.Second + if writeTimeOut > math.MaxInt64 { + return fmt.Errorf("write timeout exceeds int64 max value") + } + cfg.WriteTimeout = time.Duration(int64(writeTimeOut)) * time.Second } listenAddr := viper.GetString(client.FlagListenAddr) @@ -173,16 +180,19 @@ func startRPCServer(shutdownCtx ctx.Context, listener net.Listener, handler http recoverHandler := recoverAndLog(maxBytesHandler{h: handler, n: cfg.MaxBodyBytes}, logger) readHeaderTimeout := viper.GetUint(FlagRPCReadHeaderTimeout) + if readHeaderTimeout < 0 || readHeaderTimeout > math.MaxUint { + return fmt.Errorf("read header timeout exceeds uint max value or is negative") + } if readHeaderTimeout == 0 { readHeaderTimeout = uint(cfg.ReadTimeout) } s := &http.Server{ Handler: http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - ctx := r.Context() + ctxt := r.Context() select { - case <-ctx.Done(): + case <-ctxt.Done(): fmt.Println("graceful handler exit") rw.WriteHeader(http.StatusOK) return @@ -209,11 +219,11 @@ func startRPCServer(shutdownCtx ctx.Context, listener net.Listener, handler http // wait for interrupt signal coming from mainCtx // and then go to server shutdown <-shutdownCtx.Done() - ctx, cancel := ctx.WithTimeout(ctx.Background(), shutdownTimeout) + ctxt, cancel := ctx.WithTimeout(ctx.Background(), shutdownTimeout) defer cancel() // nolint: contextcheck - return s.Shutdown(ctx) + return s.Shutdown(ctxt) }) if err := g.Wait(); err != nil { diff --git a/staking/client/cli/query.go b/staking/client/cli/query.go index 0184fedd7..f8bea1934 100644 --- a/staking/client/cli/query.go +++ b/staking/client/cli/query.go @@ -136,7 +136,7 @@ func GetTotalStakingPower(cdc *codec.Codec) *cobra.Command { } var totalPower uint64 - if err := json.Unmarshal(totalPowerBytes, &totalPower); err != nil { + if err = json.Unmarshal(totalPowerBytes, &totalPower); err != nil { return err } diff --git a/staking/keeper.go b/staking/keeper.go index 601e0237d..df8c7e0a2 100644 --- a/staking/keeper.go +++ b/staking/keeper.go @@ -261,7 +261,7 @@ func (k *Keeper) UpdateSigner(ctx sdk.Context, newSigner hmTypes.HeimdallAddress validator.VotingPower = 0 // update validator - if err := k.AddValidator(ctx, validator); err != nil { + if err = k.AddValidator(ctx, validator); err != nil { k.Logger(ctx).Error("UpdateSigner | AddValidator", "error", err) } diff --git a/staking/querier.go b/staking/querier.go index 43e71098c..58d1d00c8 100644 --- a/staking/querier.go +++ b/staking/querier.go @@ -174,7 +174,7 @@ func handleQueryMilestoneProposer(ctx sdk.Context, req abci.RequestQuery, keeper if params.Times > math.MaxInt { return nil, sdk.ErrInternal(fmt.Sprintf("times value out of range for int: %d", params.Times)) } - + times := int(params.Times) if times > len(validatorSet.Validators) { times = len(validatorSet.Validators) diff --git a/staking/side_handler_test.go b/staking/side_handler_test.go index abb4443d6..c234cbcd6 100644 --- a/staking/side_handler_test.go +++ b/staking/side_handler_test.go @@ -1158,7 +1158,7 @@ func (suite *SideHandlerTestSuite) TestPostHandleMsgValidatorJoin() { }) suite.Run("Replay", func() { - blockNumber := big.NewInt(11) + blockNumber = big.NewInt(11) msgValJoin := types.NewMsgValidatorJoin( hmTypes.BytesToHeimdallAddress(address.Bytes()), diff --git a/staking/simulation/utils.go b/staking/simulation/utils.go index 4b11cb2ff..eaeb9e50a 100644 --- a/staking/simulation/utils.go +++ b/staking/simulation/utils.go @@ -36,8 +36,8 @@ func GenRandomVal(count int, startBlock uint64, power int64, timeAlive uint64, r return } -func generateRandNumber(max int64) uint64 { - nBig, err := rand.Int(rand.Reader, big.NewInt(max)) +func generateRandNumber(maxV int64) uint64 { + nBig, err := rand.Int(rand.Reader, big.NewInt(maxV)) if err != nil { return 1 } diff --git a/topup/querier.go b/topup/querier.go index 42e770691..9eba5b1ef 100644 --- a/topup/querier.go +++ b/topup/querier.go @@ -127,17 +127,17 @@ func handleQueryAccountProof(ctx sdk.Context, req abci.RequestQuery, keeper Keep if bytes.Equal(accountRootOnChain[:], currentStateAccountRoot) { // Calculate new account root hash - merkleProof, index, err := checkpointTypes.GetAccountProof(dividendAccounts, params.UserAddress) - if err != nil { - return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could fetch account proof", err.Error())) + merkleProof, index, e := checkpointTypes.GetAccountProof(dividendAccounts, params.UserAddress) + if e != nil { + return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could fetch account proof", e.Error())) } accountProof := hmTypes.NewDividendAccountProof(params.UserAddress, merkleProof, index) // json record - bz, err := jsoniter.ConfigFastest.Marshal(accountProof) - if err != nil { - return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", err.Error())) + bz, e := jsoniter.ConfigFastest.Marshal(accountProof) + if e != nil { + return nil, sdk.ErrInternal(sdk.AppendMsgToErr("could not marshal result to JSON", e.Error())) } return bz, nil diff --git a/types/module/module.go b/types/module/module.go index 2c01f113b..b7b6896b9 100644 --- a/types/module/module.go +++ b/types/module/module.go @@ -41,5 +41,5 @@ type StreamedGenesisExporter interface { ExportPartialGenesis(ctx sdk.Context) (json.RawMessage, error) // NextGenesisData returns the next chunk of genesis data. // Returns nil NextKey when no more data is available. - NextGenesisData(ctx sdk.Context, nextKey []byte, max int) (*ModuleGenesisData, error) + NextGenesisData(ctx sdk.Context, nextKey []byte, maxV int) (*ModuleGenesisData, error) } diff --git a/types/simulation/rand_util.go b/types/simulation/rand_util.go index d3a3fa8e2..0097a36a7 100644 --- a/types/simulation/rand_util.go +++ b/types/simulation/rand_util.go @@ -45,14 +45,14 @@ func RandStringOfLength(r *rand.Rand, n int) string { } // RandPositiveInt get a rand positive sdk.Int -func RandPositiveInt(r *rand.Rand, max sdk.Int) (sdk.Int, error) { - if !max.GTE(sdk.OneInt()) { +func RandPositiveInt(r *rand.Rand, maxV sdk.Int) (sdk.Int, error) { + if !maxV.GTE(sdk.OneInt()) { return sdk.Int{}, errors.New("max too small") } - max = max.Sub(sdk.OneInt()) + maxV = maxV.Sub(sdk.OneInt()) - return sdk.NewIntFromBigInt(new(big.Int).Rand(r, max.BigInt())).Add(sdk.OneInt()), nil + return sdk.NewIntFromBigInt(new(big.Int).Rand(r, maxV.BigInt())).Add(sdk.OneInt()), nil } // RandTimestamp generates a random timestamp @@ -63,8 +63,8 @@ func RandTimestamp(r *rand.Rand) time.Time { } // RandIntBetween returns a random int between two numbers inclusively. -func RandIntBetween(r *rand.Rand, min, max int) int { - return r.Intn(max-min) + min +func RandIntBetween(r *rand.Rand, minV, maxV int) int { + return r.Intn(maxV-minV) + minV } // RandSubsetCoins returns random subset of the provided coins diff --git a/types/validator-set.go b/types/validator-set.go index e2f90f492..4681d8368 100644 --- a/types/validator-set.go +++ b/types/validator-set.go @@ -167,20 +167,20 @@ func computeMaxMinPriorityDiff(vals *ValidatorSet) int64 { panic("empty validator set") } - max := int64(math.MinInt64) - min := int64(math.MaxInt64) + maxV := int64(math.MinInt64) + minV := int64(math.MaxInt64) for _, v := range vals.Validators { - if v.ProposerPriority < min { - min = v.ProposerPriority + if v.ProposerPriority < minV { + minV = v.ProposerPriority } - if v.ProposerPriority > max { - max = v.ProposerPriority + if v.ProposerPriority > maxV { + maxV = v.ProposerPriority } } - diff := max - min + diff := maxV - minV if diff < 0 { return -1 * diff }