diff --git a/.golangci.yml b/.golangci.yml index 03958ee0f..53f3833d1 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -60,9 +60,6 @@ issues: - mempool - state/indexer - state/txindex - exclude-rules: - - text: "G115: integer overflow conversion" - linters: [ gosec ] linters-settings: diff --git a/block/block.go b/block/block.go index 521c44465..4b4562794 100644 --- a/block/block.go +++ b/block/block.go @@ -209,7 +209,7 @@ func (m *Manager) isHeightAlreadyApplied(blockHeight uint64) (bool, error) { return false, errorsmod.Wrap(err, "get app info") } - isBlockAlreadyApplied := uint64(proxyAppInfo.LastBlockHeight) == blockHeight + isBlockAlreadyApplied := uint64(proxyAppInfo.LastBlockHeight) == blockHeight //nolint:gosec // LastBlockHeight is always positive // TODO: add switch case to validate better the current app state diff --git a/block/executor.go b/block/executor.go index 9650cb86a..f3a1421c5 100644 --- a/block/executor.go +++ b/block/executor.go @@ -144,8 +144,8 @@ func (e *Executor) CreateBlock( state *types.State, maxBlockDataSizeBytes uint64, ) *types.Block { - maxBlockDataSizeBytes = min(maxBlockDataSizeBytes, uint64(max(minBlockMaxBytes, state.ConsensusParams.Block.MaxBytes))) - mempoolTxs := e.mempool.ReapMaxBytesMaxGas(int64(maxBlockDataSizeBytes), state.ConsensusParams.Block.MaxGas) + maxBlockDataSizeBytes = min(maxBlockDataSizeBytes, uint64(max(minBlockMaxBytes, state.ConsensusParams.Block.MaxBytes))) //nolint:gosec // MaxBytes is always positive + mempoolTxs := e.mempool.ReapMaxBytesMaxGas(int64(maxBlockDataSizeBytes), state.ConsensusParams.Block.MaxGas) //nolint:gosec // size is always positive and falls in int64 block := &types.Block{ Header: types.Header{ @@ -214,7 +214,7 @@ func (e *Executor) commit(state *types.State, block *types.Block, deliverTxs []* maxBytes := state.ConsensusParams.Block.MaxBytes maxGas := state.ConsensusParams.Block.MaxGas - err = e.mempool.Update(int64(block.Header.Height), fromDymintTxs(block.Data.Txs), deliverTxs) + err = e.mempool.Update(int64(block.Header.Height), fromDymintTxs(block.Data.Txs), deliverTxs) //nolint:gosec // height is non-negative and falls in int64 if err != nil { return nil, 0, err } @@ -273,7 +273,7 @@ func (e *Executor) ExecuteBlock(block *types.Block) (*tmstate.ABCIResponses, err } } - abciResponses.EndBlock, err = e.proxyAppConsensusConn.EndBlockSync(abci.RequestEndBlock{Height: int64(block.Header.Height)}) + abciResponses.EndBlock, err = e.proxyAppConsensusConn.EndBlockSync(abci.RequestEndBlock{Height: int64(block.Header.Height)}) //nolint:gosec // height is non-negative and falls in int64 if err != nil { return nil, err } @@ -305,14 +305,14 @@ func (e *Executor) publishEvents(resp *tmstate.ABCIResponses, block *types.Block for _, ev := range abciBlock.Evidence.Evidence { err = multierr.Append(err, e.eventBus.PublishEventNewEvidence(tmtypes.EventDataNewEvidence{ Evidence: ev, - Height: int64(block.Header.Height), + Height: int64(block.Header.Height), //nolint:gosec // height is non-negative and falls in int64 })) } for i, dtx := range resp.DeliverTxs { err = multierr.Append(err, e.eventBus.PublishEventTx(tmtypes.EventDataTx{ TxResult: abci.TxResult{ - Height: int64(block.Header.Height), - Index: uint32(i), + Height: int64(block.Header.Height), //nolint:gosec // block height is within int64 range + Index: uint32(i), //nolint:gosec // num of deliver txs is less than 2^32 Tx: abciBlock.Data.Txs[i], Result: *dtx, }, diff --git a/block/initchain.go b/block/initchain.go index 93b5ee2cc..7368b043f 100644 --- a/block/initchain.go +++ b/block/initchain.go @@ -10,7 +10,7 @@ import ( func (m *Manager) RunInitChain(ctx context.Context) error { // Get the proposer at the initial height. If we're at genesis the height will be 0. - proposer, err := m.SLClient.GetProposerAtHeight(int64(m.State.Height()) + 1) + proposer, err := m.SLClient.GetProposerAtHeight(int64(m.State.Height()) + 1) //nolint:gosec // height is non-negative and falls in int64 if err != nil { return fmt.Errorf("get proposer at height: %w", err) } diff --git a/block/manager.go b/block/manager.go index 378c314b3..b74564625 100644 --- a/block/manager.go +++ b/block/manager.go @@ -308,7 +308,7 @@ func (m *Manager) updateFromLastSettlementState() error { if errors.Is(err, gerrc.ErrNotFound) { // The SL hasn't got any batches for this chain yet. m.logger.Info("No batches for chain found in SL.") - m.LastSettlementHeight.Store(uint64(m.Genesis.InitialHeight - 1)) + m.LastSettlementHeight.Store(uint64(m.Genesis.InitialHeight - 1)) //nolint:gosec // height is non-negative and falls in int64 m.LastBlockTimeInSettlement.Store(m.Genesis.GenesisTime.UTC().UnixNano()) return nil } diff --git a/block/produce.go b/block/produce.go index e206de7bc..83c1d7d5e 100644 --- a/block/produce.go +++ b/block/produce.go @@ -274,7 +274,7 @@ func (m *Manager) createTMSignature(block *types.Block, proposerAddress []byte, headerHash := block.Header.Hash() vote := tmtypes.Vote{ Type: cmtproto.PrecommitType, - Height: int64(block.Header.Height), + Height: int64(block.Header.Height), //nolint:gosec // height is non-negative and falls in int64 Round: 0, Timestamp: voteTimestamp, BlockID: tmtypes.BlockID{Hash: headerHash[:], PartSetHeader: tmtypes.PartSetHeader{ diff --git a/block/pruning.go b/block/pruning.go index 30f44802b..9a92451e9 100644 --- a/block/pruning.go +++ b/block/pruning.go @@ -28,6 +28,7 @@ func (m *Manager) Prune(retainHeight uint64) { logResult(err, "dymint store", retainHeight, pruned) } +//nolint:gosec // height is non-negative and falls in int64 func (m *Manager) PruningLoop(ctx context.Context) error { for { select { diff --git a/block/sequencers.go b/block/sequencers.go index dcbb502a3..ca6155397 100644 --- a/block/sequencers.go +++ b/block/sequencers.go @@ -177,7 +177,7 @@ func (m *Manager) UpdateSequencerSetFromSL() error { // UpdateProposerFromSL queries the hub and updates the local dymint state proposer at the current height func (m *Manager) UpdateProposerFromSL() error { - SLProposer, err := m.SLClient.GetProposerAtHeight(int64(m.State.NextHeight())) + SLProposer, err := m.SLClient.GetProposerAtHeight(int64(m.State.NextHeight())) //nolint:gosec // height is non-negative and falls in int64 if err != nil { return fmt.Errorf("get proposer at height: %w", err) } diff --git a/block/state.go b/block/state.go index 70d5202c2..7b1991bc2 100644 --- a/block/state.go +++ b/block/state.go @@ -59,7 +59,7 @@ func NewStateFromGenesis(genDoc *tmtypes.GenesisDoc) (*types.State, error) { s := types.State{ Version: InitStateVersion, ChainID: genDoc.ChainID, - InitialHeight: uint64(genDoc.InitialHeight), + InitialHeight: uint64(genDoc.InitialHeight), //nolint:gosec // height is non-negative and falls in int64 ConsensusParams: *genDoc.ConsensusParams, } s.SetHeight(0) @@ -80,7 +80,7 @@ func (m *Manager) UpdateStateFromApp(blockHeaderHash [32]byte) error { return errorsmod.Wrap(err, "get app info") } - appHeight := uint64(proxyAppInfo.LastBlockHeight) + appHeight := uint64(proxyAppInfo.LastBlockHeight) //nolint:gosec // height is non-negative and falls in int64 resp, err := m.Store.LoadBlockResponses(appHeight) if err != nil { return errorsmod.Wrap(err, "load block responses") diff --git a/block/submit.go b/block/submit.go index 46c70b101..aeaa6ac2f 100644 --- a/block/submit.go +++ b/block/submit.go @@ -67,7 +67,7 @@ func SubmitLoopInner( case <-ctx.Done(): return nil case n := <-bytesProduced: - pendingBytes.Add(uint64(n)) + pendingBytes.Add(uint64(n)) //nolint:gosec // bytes size is always positive logger.Debug("Added bytes produced to bytes pending submission counter.", "bytes added", n, "pending", pendingBytes.Load()) } @@ -129,7 +129,7 @@ func SubmitLoopInner( return err } ticker.Reset(maxBatchSubmitTime) - pending = uint64(unsubmittedBlocksBytes()) + pending = uint64(unsubmittedBlocksBytes()) //nolint:gosec // bytes size is always positive logger.Info("Submitted a batch to both sub-layers.", "n bytes consumed from pending", nConsumed, "pending after", pending) // TODO: debug level } trigger.Nudge() @@ -147,7 +147,7 @@ func (m *Manager) CreateAndSubmitBatchGetSizeBlocksCommits(maxSize uint64) (uint if b == nil { return 0, err } - return uint64(b.SizeBlockAndCommitBytes()), err + return uint64(b.SizeBlockAndCommitBytes()), err //nolint:gosec // size is always positive and falls in uint64 } // CreateAndSubmitBatch creates and submits a batch to the DA and SL. @@ -212,7 +212,7 @@ func (m *Manager) CreateBatch(maxBatchSize uint64, startHeight uint64, endHeight batch.DRSVersion = append(batch.DRSVersion, drsVersion) totalSize := batch.SizeBytes() - if maxBatchSize < uint64(totalSize) { + if maxBatchSize < uint64(totalSize) { //nolint:gosec // size is always positive and falls in uint64 // Remove the last block and commit from the batch batch.Blocks = batch.Blocks[:len(batch.Blocks)-1] diff --git a/config/flags.go b/config/flags.go index 92d009f60..1f1eaf83e 100644 --- a/config/flags.go +++ b/config/flags.go @@ -58,7 +58,7 @@ func AddNodeFlags(cmd *cobra.Command) { cmd.Flags().String(FlagP2PListenAddress, def.P2PConfig.ListenAddress, "P2P listen address") cmd.Flags().String(FlagP2PBootstrapNodes, def.P2PConfig.BootstrapNodes, "P2P bootstrap nodes") cmd.Flags().Duration(FlagP2PBootstrapRetryTime, def.P2PConfig.BootstrapRetryTime, "P2P bootstrap time") - cmd.Flags().Uint64(FlagP2PGossipCacheSize, uint64(def.P2PConfig.GossipSubCacheSize), "P2P Gossiped blocks cache size") + cmd.Flags().Uint64(FlagP2PGossipCacheSize, uint64(def.P2PConfig.GossipSubCacheSize), "P2P Gossiped blocks cache size") //nolint:gosec // GossipSubCacheSize should be always positive } func BindDymintFlags(cmd *cobra.Command, v *viper.Viper) error { diff --git a/da/avail/avail.go b/da/avail/avail.go index d1a84e64d..81c30b48b 100644 --- a/da/avail/avail.go +++ b/da/avail/avail.go @@ -18,10 +18,11 @@ import ( "github.com/centrifuge/go-substrate-rpc-client/v4/rpc/state" "github.com/centrifuge/go-substrate-rpc-client/v4/signature" availtypes "github.com/centrifuge/go-substrate-rpc-client/v4/types" + "github.com/tendermint/tendermint/libs/pubsub" + "github.com/dymensionxyz/dymint/da" "github.com/dymensionxyz/dymint/store" pb "github.com/dymensionxyz/dymint/types/pb/dymint" - "github.com/tendermint/tendermint/libs/pubsub" ) const ( @@ -363,7 +364,7 @@ func (c *DataAvailabilityLayerClient) broadcastTx(tx []byte) (uint64, error) { SpecVersion: rv.SpecVersion, Tip: availtypes.NewUCompactFromUInt(c.config.Tip), TransactionVersion: rv.TransactionVersion, - AppID: availtypes.NewUCompactFromUInt(uint64(c.config.AppID)), + AppID: availtypes.NewUCompactFromUInt(uint64(c.config.AppID)), //nolint:gosec // AppID should be always positive } // Sign the transaction using Alice's default account diff --git a/da/celestia/celestia.go b/da/celestia/celestia.go index 05d9a827f..2c3b843a8 100644 --- a/da/celestia/celestia.go +++ b/da/celestia/celestia.go @@ -278,7 +278,7 @@ func (c *DataAvailabilityLayerClient) RetrieveBatches(daMetaData *da.DASubmitMet return nil }, - retry.Attempts(uint(*c.config.RetryAttempts)), + retry.Attempts(uint(*c.config.RetryAttempts)), //nolint:gosec // RetryAttempts should be always positive retry.DelayType(retry.FixedDelay), retry.Delay(c.config.RetryDelay), ) @@ -361,17 +361,22 @@ func (c *DataAvailabilityLayerClient) CheckBatchAvailability(daMetaData *da.DASu c.logger.Debug("Context cancelled") return da.ResultCheckBatch{} default: - err := retry.Do(func() error { - result := c.checkBatchAvailability(daMetaData) - availabilityResult = result + err := retry.Do( + func() error { + result := c.checkBatchAvailability(daMetaData) + availabilityResult = result - if result.Code != da.StatusSuccess { - c.logger.Error("Blob submitted not found in DA. Retrying availability check.") - return da.ErrBlobNotFound - } + if result.Code != da.StatusSuccess { + c.logger.Error("Blob submitted not found in DA. Retrying availability check.") + return da.ErrBlobNotFound + } - return nil - }, retry.Attempts(uint(*c.config.RetryAttempts)), retry.DelayType(retry.FixedDelay), retry.Delay(c.config.RetryDelay)) + return nil + }, + retry.Attempts(uint(*c.config.RetryAttempts)), //nolint:gosec // RetryAttempts should be always positive + retry.DelayType(retry.FixedDelay), + retry.Delay(c.config.RetryDelay), + ) if err != nil { c.logger.Error("CheckAvailability process failed.", "error", err) } @@ -496,11 +501,6 @@ func (c *DataAvailabilityLayerClient) submit(daBlob da.Blob) (uint64, da.Commitm return 0, nil, fmt.Errorf("zero commitments: %w: %w", gerrc.ErrNotFound, gerrc.ErrInternal) } - blobSizes := make([]uint32, len(blobs)) - for i, blob := range blobs { - blobSizes[i] = uint32(len(blob.Data)) - } - ctx, cancel := context.WithTimeout(c.ctx, c.config.Timeout) defer cancel() diff --git a/da/celestia/types/types.go b/da/celestia/types/types.go index 817b1a933..9a10f3a0b 100644 --- a/da/celestia/types/types.go +++ b/da/celestia/types/types.go @@ -75,23 +75,3 @@ const ( // Default maximum bytes per blob allowed DefaultMaxBytes = DefaultGovMaxSquareSize * DefaultGovMaxSquareSize * ContinuationSparseShareContentSize ) - -// SparseSharesNeeded returns the number of shares needed to store a sequence of -// length sequenceLen. -func SparseSharesNeeded(sequenceLen uint32) (sharesNeeded int) { - if sequenceLen == 0 { - return 0 - } - - if sequenceLen < FirstSparseShareContentSize { - return 1 - } - - bytesAvailable := FirstSparseShareContentSize - sharesNeeded++ - for uint32(bytesAvailable) < sequenceLen { - bytesAvailable += ContinuationSparseShareContentSize - sharesNeeded++ - } - return sharesNeeded -} diff --git a/da/da.go b/da/da.go index 98bdff5c1..3bde8023f 100644 --- a/da/da.go +++ b/da/da.go @@ -9,16 +9,18 @@ import ( "cosmossdk.io/math" "github.com/celestiaorg/celestia-openrpc/types/blob" "github.com/cometbft/cometbft/crypto/merkle" + "github.com/tendermint/tendermint/libs/pubsub" + "github.com/dymensionxyz/dymint/store" "github.com/dymensionxyz/dymint/types" - "github.com/tendermint/tendermint/libs/pubsub" ) // StatusCode is a type for DA layer return status. // TODO: define an enum of different non-happy-path cases // that might need to be handled by Dymint independent of -// the underlying DA chain. -type StatusCode uint64 +// the underlying DA chain. Use int32 to match the protobuf +// enum representation. +type StatusCode int32 // Commitment should contain serialized cryptographic commitment to Blob value. type Commitment = []byte diff --git a/indexers/blockindexer/kv/kv.go b/indexers/blockindexer/kv/kv.go index e88f24224..bb8ee295c 100644 --- a/indexers/blockindexer/kv/kv.go +++ b/indexers/blockindexer/kv/kv.go @@ -19,9 +19,10 @@ import ( indexer "github.com/dymensionxyz/dymint/indexers/blockindexer" "github.com/dymensionxyz/dymint/store" + tmtypes "github.com/tendermint/tendermint/types" + "github.com/dymensionxyz/dymint/types/pb/dymint" dmtypes "github.com/dymensionxyz/dymint/types/pb/dymint" - tmtypes "github.com/tendermint/tendermint/types" ) var _ indexer.BlockIndexer = (*BlockerIndexer)(nil) @@ -545,7 +546,7 @@ func (idx *BlockerIndexer) pruneBlocks(from, to uint64, logger log.Logger) (uint return nil } - for h := int64(from); h < int64(to); h++ { + for h := int64(from); h < int64(to); h++ { //nolint:gosec // heights (from and to) are always positive and fall in int64 // flush every 1000 blocks to avoid batches becoming too large if toFlush > 1000 { @@ -591,7 +592,7 @@ func (idx *BlockerIndexer) pruneBlocks(from, to uint64, logger log.Logger) (uint } - err := flush(batch, int64(to)) + err := flush(batch, int64(to)) //nolint:gosec // height is non-negative and falls in int64 if err != nil { return 0, err } diff --git a/indexers/txindex/kv/kv.go b/indexers/txindex/kv/kv.go index e7548dc98..e1ea88910 100644 --- a/indexers/txindex/kv/kv.go +++ b/indexers/txindex/kv/kv.go @@ -592,11 +592,11 @@ func (txi *TxIndex) pruneTxsAndEvents(from, to uint64, logger log.Logger) (uint6 return nil } - for h := from; h < to; h++ { + for h := int64(from); h < int64(to); h++ { //nolint:gosec // heights (from and to) are always positive and fall in int64 // flush every 1000 txs to avoid batches becoming too large if toFlush > 1000 { - err := flush(batch, int64(h)) + err := flush(batch, h) if err != nil { return 0, err } @@ -615,7 +615,7 @@ func (txi *TxIndex) pruneTxsAndEvents(from, to uint64, logger log.Logger) (uint6 } // then all txs indexed are iterated by height - it := txi.store.PrefixIterator(prefixForHeight(int64(h))) + it := txi.store.PrefixIterator(prefixForHeight(h)) // and deleted all indexed (by hash and by keyheight) for ; it.Valid(); it.Next() { @@ -635,7 +635,7 @@ func (txi *TxIndex) pruneTxsAndEvents(from, to uint64, logger log.Logger) (uint6 } - err := flush(batch, int64(to)) + err := flush(batch, int64(to)) //nolint:gosec // height is non-negative and falls in int64 if err != nil { return 0, err } @@ -643,9 +643,9 @@ func (txi *TxIndex) pruneTxsAndEvents(from, to uint64, logger log.Logger) (uint6 return pruned, nil } -func (txi *TxIndex) pruneEvents(height uint64, batch store.KVBatch) (uint64, error) { +func (txi *TxIndex) pruneEvents(height int64, batch store.KVBatch) (uint64, error) { pruned := uint64(0) - eventKey, err := eventHeightKey(int64(height)) + eventKey, err := eventHeightKey(height) if err != nil { return pruned, err } diff --git a/rpc/client/client.go b/rpc/client/client.go index 8e192afc8..d697476fb 100644 --- a/rpc/client/client.go +++ b/rpc/client/client.go @@ -298,7 +298,7 @@ func (c *Client) Genesis(_ context.Context) (*ctypes.ResultGenesis, error) { } // GenesisChunked returns given chunk of genesis. -func (c *Client) GenesisChunked(context context.Context, id uint) (*ctypes.ResultGenesisChunk, error) { +func (c *Client) GenesisChunked(_ context.Context, id uint) (*ctypes.ResultGenesisChunk, error) { genChunks, err := c.GetGenesisChunks() if err != nil { return nil, fmt.Errorf("while creating chunks of the genesis document: %w", err) @@ -312,13 +312,14 @@ func (c *Client) GenesisChunked(context context.Context, id uint) (*ctypes.Resul return nil, fmt.Errorf("service configuration error, there are no chunks") } - if int(id) > chunkLen-1 { + // it's safe to do uint(chunkLen)-1 (no overflow) since we always have at least one chunk here + if id > uint(chunkLen)-1 { return nil, fmt.Errorf("there are %d chunks, %d is invalid", chunkLen-1, id) } return &ctypes.ResultGenesisChunk{ TotalChunks: chunkLen, - ChunkNumber: int(id), + ChunkNumber: int(id), //nolint:gosec // id is always positive Data: genChunks[id], }, nil } @@ -335,8 +336,8 @@ func (c *Client) BlockchainInfo(ctx context.Context, minHeight, maxHeight int64) baseHeight = 1 } minHeight, maxHeight, err = filterMinMax( - int64(baseHeight), - int64(c.node.GetBlockManagerHeight()), + int64(baseHeight), //nolint:gosec // height is non-negative and falls in int64 + int64(c.node.GetBlockManagerHeight()), //nolint:gosec // height is non-negative and falls in int64 minHeight, maxHeight, limit) @@ -347,7 +348,7 @@ func (c *Client) BlockchainInfo(ctx context.Context, minHeight, maxHeight int64) blocks := make([]*tmtypes.BlockMeta, 0, maxHeight-minHeight+1) for height := maxHeight; height >= minHeight; height-- { - block, err := c.node.Store.LoadBlock(uint64(height)) + block, err := c.node.Store.LoadBlock(uint64(height)) //nolint:gosec // height is non-negative and falls in int64 if err != nil { return nil, err } @@ -361,7 +362,7 @@ func (c *Client) BlockchainInfo(ctx context.Context, minHeight, maxHeight int64) } return &ctypes.ResultBlockchainInfo{ - LastHeight: int64(c.node.GetBlockManagerHeight()), + LastHeight: int64(c.node.GetBlockManagerHeight()), //nolint:gosec // height is non-negative and falls in int64 BlockMetas: blocks, }, nil } @@ -405,7 +406,7 @@ func (c *Client) ConsensusParams(ctx context.Context, height *int64) (*ctypes.Re // TODO(tzdybal): implement consensus params handling: https://github.com/dymensionxyz/dymint/issues/291 params := c.node.GetGenesis().ConsensusParams return &ctypes.ResultConsensusParams{ - BlockHeight: int64(c.normalizeHeight(height)), + BlockHeight: int64(c.normalizeHeight(height)), //nolint:gosec // height is non-negative and falls in int64 ConsensusParams: tmproto.ConsensusParams{ Block: tmproto.BlockParams{ MaxBytes: params.Block.MaxBytes, @@ -490,7 +491,7 @@ func (c *Client) BlockResults(ctx context.Context, height *int64) (*ctypes.Resul if height == nil { h = c.node.GetBlockManagerHeight() } else { - h = uint64(*height) + h = uint64(*height) //nolint:gosec // height is non-negative and falls in int64 } resp, err := c.node.Store.LoadBlockResponses(h) if err != nil { @@ -498,7 +499,7 @@ func (c *Client) BlockResults(ctx context.Context, height *int64) (*ctypes.Resul } return &ctypes.ResultBlockResults{ - Height: int64(h), + Height: int64(h), //nolint:gosec // height is non-negative and falls in int64 TxsResults: resp.DeliverTxs, BeginBlockEvents: resp.BeginBlock.Events, EndBlockEvents: resp.EndBlock.Events, @@ -528,7 +529,7 @@ func (c *Client) Commit(ctx context.Context, height *int64) (*ctypes.ResultCommi } // Validators returns paginated list of validators at given height. -func (c *Client) Validators(ctx context.Context, heightPtr *int64, pagePtr, perPagePtr *int) (*ctypes.ResultValidators, error) { +func (c *Client) Validators(ctx context.Context, heightPtr *int64, _, _ *int) (*ctypes.ResultValidators, error) { height := c.normalizeHeight(heightPtr) proposer, err := c.node.Store.LoadProposer(height) @@ -537,7 +538,7 @@ func (c *Client) Validators(ctx context.Context, heightPtr *int64, pagePtr, perP } return &ctypes.ResultValidators{ - BlockHeight: int64(height), + BlockHeight: int64(height), //nolint:gosec // height is non-negative and falls in int64 Validators: proposer.TMValidators(), Count: 1, Total: 1, @@ -560,8 +561,8 @@ func (c *Client) Tx(ctx context.Context, hash []byte, prove bool) (*ctypes.Resul var proof tmtypes.TxProof if prove { - block, _ := c.node.Store.LoadBlock(uint64(height)) - blockProof := block.Data.Txs.Proof(int(index)) // XXX: overflow on 32-bit machines + block, _ := c.node.Store.LoadBlock(uint64(height)) //nolint:gosec // height is non-negative and falls in int64 + blockProof := block.Data.Txs.Proof(int(index)) // XXX: overflow on 32-bit machines proof = tmtypes.TxProof{ RootHash: blockProof.RootHash, Data: tmtypes.Tx(blockProof.Data), @@ -689,7 +690,7 @@ func (c *Client) BlockSearch(ctx context.Context, query string, page, perPage *i // Fetch the blocks blocks := make([]*ctypes.ResultBlock, 0, pageSize) for i := skipCount; i < skipCount+pageSize; i++ { - b, err := c.node.Store.LoadBlock(uint64(results[i])) + b, err := c.node.Store.LoadBlock(uint64(results[i])) //nolint:gosec // height is non-negative and falls in int64 if err != nil { return nil, err } @@ -709,7 +710,7 @@ func (c *Client) BlockSearch(ctx context.Context, query string, page, perPage *i } // Status returns detailed information about current status of the node. -func (c *Client) Status(ctx context.Context) (*ctypes.ResultStatus, error) { +func (c *Client) Status(_ context.Context) (*ctypes.ResultStatus, error) { latest, err := c.node.Store.LoadBlock(c.node.GetBlockManagerHeight()) if err != nil { // TODO(tzdybal): extract error @@ -755,7 +756,7 @@ func (c *Client) Status(ctx context.Context) (*ctypes.ResultStatus, error) { SyncInfo: ctypes.SyncInfo{ LatestBlockHash: latestBlockHash[:], LatestAppHash: latestAppHash[:], - LatestBlockHeight: int64(latestHeight), + LatestBlockHeight: int64(latestHeight), //nolint:gosec // height is non-negative and falls in int64 LatestBlockTime: latestBlockTime, // CatchingUp is true if the node is not at the latest height received from p2p or da. CatchingUp: c.node.BlockManager.TargetHeight.Load() > latestHeight, @@ -824,11 +825,11 @@ func (c *Client) BlockValidated(height *int64) (*ResultBlockValidated, error) { return &ResultBlockValidated{Result: -1, ChainID: chainID}, nil } // node has not reached the height yet - if uint64(*height) > c.node.BlockManager.State.Height() { + if uint64(*height) > c.node.BlockManager.State.Height() { //nolint:gosec // height is non-negative and falls in int64 return &ResultBlockValidated{Result: NotValidated, ChainID: chainID}, nil } - if uint64(*height) <= c.node.BlockManager.SettlementValidator.GetLastValidatedHeight() { + if uint64(*height) <= c.node.BlockManager.SettlementValidator.GetLastValidatedHeight() { //nolint:gosec // height is non-negative and falls in int64 return &ResultBlockValidated{Result: SLValidated, ChainID: chainID}, nil } @@ -869,7 +870,7 @@ func (c *Client) eventsRoutine(sub tmtypes.Subscription, subscriber string, q tm // Try to resubscribe with exponential backoff. func (c *Client) resubscribe(subscriber string, q tmpubsub.Query) tmtypes.Subscription { - attempts := 0 + attempts := uint(0) for { if !c.IsRunning() { return nil @@ -881,7 +882,7 @@ func (c *Client) resubscribe(subscriber string, q tmpubsub.Query) tmtypes.Subscr } attempts++ - time.Sleep((10 << uint(attempts)) * time.Millisecond) // 10ms -> 20ms -> 40ms + time.Sleep((10 << attempts) * time.Millisecond) // 10ms -> 20ms -> 40ms } } @@ -906,7 +907,7 @@ func (c *Client) normalizeHeight(height *int64) uint64 { if height == nil || *height == 0 { heightValue = c.node.GetBlockManagerHeight() } else { - heightValue = uint64(*height) + heightValue = uint64(*height) //nolint:gosec // height is non-negative and falls in int64 } return heightValue diff --git a/rpc/json/service.go b/rpc/json/service.go index 5241eaa69..e9c1c8e08 100644 --- a/rpc/json/service.go +++ b/rpc/json/service.go @@ -202,7 +202,7 @@ func (s *service) Genesis(req *http.Request, args *genesisArgs) (*ctypes.ResultG } func (s *service) GenesisChunked(req *http.Request, args *genesisChunkedArgs) (*ctypes.ResultGenesisChunk, error) { - return s.client.GenesisChunked(req.Context(), uint(args.ID)) + return s.client.GenesisChunked(req.Context(), uint(args.ID)) //nolint:gosec // id is always positive } func (s *service) Block(req *http.Request, args *blockArgs) (*ctypes.ResultBlock, error) { diff --git a/settlement/dymension/events.go b/settlement/dymension/events.go index fde8d738a..ba0a2849e 100644 --- a/settlement/dymension/events.go +++ b/settlement/dymension/events.go @@ -111,27 +111,27 @@ func convertToNewBatchEvent(rawEventData ctypes.ResultEvent) (*settlement.EventD return nil, fmt.Errorf("missing expected attributes in event") } - numBlocks, err := strconv.ParseInt(events["state_update.num_blocks"][0], 10, 64) + numBlocks, err := strconv.ParseUint(events["state_update.num_blocks"][0], 10, 64) if err != nil { errs = append(errs, err) } - startHeight, err := strconv.ParseInt(events["state_update.start_height"][0], 10, 64) + startHeight, err := strconv.ParseUint(events["state_update.start_height"][0], 10, 64) if err != nil { errs = append(errs, err) } - stateIndex, err := strconv.ParseInt(events["state_update.state_info_index"][0], 10, 64) + stateIndex, err := strconv.ParseUint(events["state_update.state_info_index"][0], 10, 64) if err != nil { errs = append(errs, err) } if len(errs) > 0 { return nil, errors.Join(errs...) } - endHeight := uint64(startHeight + numBlocks - 1) + endHeight := startHeight + numBlocks - 1 NewBatchEvent := &settlement.EventDataNewBatch{ - StartHeight: uint64(startHeight), + StartHeight: startHeight, EndHeight: endHeight, - StateIndex: uint64(stateIndex), + StateIndex: stateIndex, } return NewBatchEvent, nil } diff --git a/test/loadtime/cmd/load/main.go b/test/loadtime/cmd/load/main.go index cb3f5ff75..456f78b1d 100644 --- a/test/loadtime/cmd/load/main.go +++ b/test/loadtime/cmd/load/main.go @@ -3,10 +3,11 @@ package main import ( "fmt" - "github.com/dymensionxyz/dymint/test/loadtime/payload" - "github.com/dymensionxyz/dymint/test/pb/loadtime" "github.com/google/uuid" "github.com/informalsystems/tm-load-test/pkg/loadtest" + + "github.com/dymensionxyz/dymint/test/loadtime/payload" + "github.com/dymensionxyz/dymint/test/pb/loadtime" ) // Ensure all of the interfaces are correctly satisfied. @@ -56,6 +57,8 @@ func (f *ClientFactory) ValidateConfig(cfg loadtest.Config) error { } // NewClient creates a new client for the load test. +// +//nolint:gosec // params are always positive and fall in uint64 func (f *ClientFactory) NewClient(cfg loadtest.Config) (loadtest.Client, error) { return &TxGenerator{ id: f.ID, diff --git a/test/loadtime/cmd/report/main.go b/test/loadtime/cmd/report/main.go index 6b132ae5d..4fd90ebe3 100644 --- a/test/loadtime/cmd/report/main.go +++ b/test/loadtime/cmd/report/main.go @@ -129,9 +129,9 @@ func toCSVRecords(rs []report.Report) [][]string { offset := 1 for _, r := range rs { idStr := r.ID.String() - connStr := strconv.FormatInt(int64(r.Connections), 10) - rateStr := strconv.FormatInt(int64(r.Rate), 10) - sizeStr := strconv.FormatInt(int64(r.Size), 10) + connStr := strconv.FormatUint(r.Connections, 10) + rateStr := strconv.FormatUint(r.Rate, 10) + sizeStr := strconv.FormatUint(r.Size, 10) for i, v := range r.All { res[offset+i] = []string{idStr, strconv.FormatInt(v.BlockTime.UnixNano(), 10), strconv.FormatInt(int64(v.Duration), 10), fmt.Sprintf("%X", v.Hash), connStr, rateStr, sizeStr} } diff --git a/testutil/types.go b/testutil/types.go index c71c90192..a4fea4ca9 100644 --- a/testutil/types.go +++ b/testutil/types.go @@ -44,7 +44,7 @@ func createRandomHashes() [][32]byte { func GetRandomTx() types.Tx { n, _ := rand.Int(rand.Reader, big.NewInt(100)) - size := uint64(n.Int64()) + 100 + size := n.Uint64() + 100 return types.Tx(GetRandomBytes(size)) } @@ -324,7 +324,7 @@ func GenerateSequencer() types.Sequencer { func GenerateStateWithSequencer(initialHeight int64, lastBlockHeight int64, pubkey tmcrypto.PubKey) *types.State { s := &types.State{ ChainID: "test-chain", - InitialHeight: uint64(initialHeight), + InitialHeight: uint64(initialHeight), //nolint:gosec // height is non-negative and falls in int64 AppHash: [32]byte{}, LastResultsHash: GetEmptyLastResultsHash(), Version: tmstate.Version{ @@ -350,8 +350,7 @@ func GenerateStateWithSequencer(initialHeight int64, lastBlockHeight int64, pubk GenerateSettlementAddress(), []string{GenerateSettlementAddress()}, )) - - s.SetHeight(uint64(lastBlockHeight)) + s.SetHeight(uint64(lastBlockHeight)) //nolint:gosec // height is non-negative and falls in int64 return s } diff --git a/types/conv.go b/types/conv.go index b604b727a..afbfc94a6 100644 --- a/types/conv.go +++ b/types/conv.go @@ -21,7 +21,7 @@ func ToABCIHeader(header *Header) tmtypes.Header { Block: header.Version.Block, App: header.Version.App, }, - Height: int64(header.Height), + Height: int64(header.Height), //nolint:gosec // height is non-negative and falls in int64 Time: header.GetTimestamp(), LastBlockID: tmtypes.BlockID{ Hash: header.LastHeaderHash[:], @@ -96,7 +96,7 @@ func ToABCIBlockMeta(block *Block) (*tmtypes.BlockMeta, error) { func ToABCICommit(commit *Commit, header *Header) *tmtypes.Commit { headerHash := header.Hash() tmCommit := tmtypes.Commit{ - Height: int64(commit.Height), + Height: int64(commit.Height), //nolint:gosec // height is non-negative and falls in int64 Round: 0, BlockID: tmtypes.BlockID{ Hash: headerHash[:], diff --git a/types/pb/dymensionxyz/dymension/rollapp/message_update_state.go b/types/pb/dymensionxyz/dymension/rollapp/message_update_state.go index 34fb6e606..11b1c7f3c 100644 --- a/types/pb/dymensionxyz/dymension/rollapp/message_update_state.go +++ b/types/pb/dymensionxyz/dymension/rollapp/message_update_state.go @@ -35,7 +35,7 @@ func (msg *MsgUpdateState) ValidateBasic() error { } // check to see that update contains all BDs - if len(msg.BDs.BD) != int(msg.NumBlocks) { + if uint64(len(msg.BDs.BD)) != msg.NumBlocks { return errorsmod.Wrapf(ErrInvalidNumBlocks, "number of blocks (%d) != number of block descriptors(%d)", msg.NumBlocks, len(msg.BDs.BD)) } diff --git a/types/serialization.go b/types/serialization.go index 27786dc76..a4e79bb8e 100644 --- a/types/serialization.go +++ b/types/serialization.go @@ -265,15 +265,15 @@ func (s *State) ToProto() (*pb.State, error) { return &pb.State{ Version: &s.Version, ChainId: s.ChainID, - InitialHeight: int64(s.InitialHeight), - LastBlockHeight: int64(s.Height()), + InitialHeight: int64(s.InitialHeight), //nolint:gosec // height is non-negative and falls in int64 + LastBlockHeight: int64(s.Height()), //nolint:gosec // height is non-negative and falls in int64 ConsensusParams: s.ConsensusParams, LastResultsHash: s.LastResultsHash[:], LastHeaderHash: s.LastHeaderHash[:], AppHash: s.AppHash[:], RollappParams: s.RollappParams, Proposer: proposerProto, - RevisionStartHeight: int64(s.RevisionStartHeight), + RevisionStartHeight: int64(s.RevisionStartHeight), //nolint:gosec // height is non-negative and falls in int64 }, nil } @@ -281,9 +281,9 @@ func (s *State) ToProto() (*pb.State, error) { func (s *State) FromProto(other *pb.State) error { s.Version = *other.Version s.ChainID = other.ChainId - s.InitialHeight = uint64(other.InitialHeight) - s.SetHeight(uint64(other.LastBlockHeight)) - s.RevisionStartHeight = uint64(other.RevisionStartHeight) + s.InitialHeight = uint64(other.InitialHeight) //nolint:gosec // height is non-negative and falls in int64 + s.SetHeight(uint64(other.LastBlockHeight)) //nolint:gosec // height is non-negative and falls in int64 + s.RevisionStartHeight = uint64(other.RevisionStartHeight) //nolint:gosec // height is non-negative and falls in int64 if other.Proposer != nil { proposer, err := SequencerFromProto(other.Proposer) if err != nil { diff --git a/version/version.go b/version/version.go index 5b9325ac7..acbae16e8 100644 --- a/version/version.go +++ b/version/version.go @@ -15,5 +15,5 @@ func GetDRSVersion() (uint32, error) { if err != nil { return uint32(0), fmt.Errorf("converting DRS version to int: %v", err) } - return uint32(currentDRS), nil + return uint32(currentDRS), nil //nolint:gosec // DRS is uint32 }