From 7991fad225b106a8cfa5e0e851376257902ad50b Mon Sep 17 00:00:00 2001 From: Lucas Bertrand Date: Mon, 2 Oct 2023 11:39:24 -0700 Subject: [PATCH] fix: address `cosmos-gosec` lint issues (#1153) * add cosmos go sec makefile command * first wave fix * wave 2 * wave 3 * wave 4 * goimports * fix typo * fix error build * fix websocket * fix proof * fix flags * format * conflict 2 * fix arguments * solve remaining * ci test * make generate --- .github/workflows/sast-linters.yml | 7 ++-- Makefile | 3 ++ app/ante/ante.go | 5 ++- app/export.go | 15 ++++++-- cmd/zetaclientd/init.go | 5 ++- cmd/zetaclientd/p2p_diagnostics.go | 6 +++- cmd/zetaclientd/root.go | 6 ++-- cmd/zetaclientd/start.go | 13 +++++-- cmd/zetacore_utils/main.go | 36 ++++++++++++++----- cmd/zetacored/collect_observer_info.go | 10 ++++-- cmd/zetacored/parsers.go | 5 ++- common/ethereum/proof.go | 10 ++++++ .../smoketest/test_deposit_eth.go | 5 +-- .../localnet/orchestrator/smoketest/utils.go | 5 +-- contrib/rpctest/main.go | 17 +++++---- rpc/backend/account_info.go | 6 ++++ rpc/backend/blocks.go | 9 +++++ rpc/backend/call_tx.go | 5 ++- rpc/backend/chain_info.go | 22 ++++++++++-- rpc/backend/node_info.go | 5 ++- rpc/backend/tracing.go | 2 ++ rpc/backend/tx_info.go | 13 +++++++ rpc/backend/utils.go | 2 ++ rpc/namespaces/ethereum/eth/api.go | 1 + rpc/namespaces/ethereum/eth/filters/api.go | 15 ++++++-- rpc/types/block.go | 1 + rpc/types/events.go | 24 ++++++++----- rpc/types/utils.go | 18 ++++++---- rpc/websockets.go | 34 +++++++++++++----- scripts/cosmos-gosec.sh | 7 ++++ server/start.go | 12 +++++-- x/crosschain/client/cli/cli_chain_nonce.go | 4 +-- x/crosschain/client/cli/cli_out_tx_tracker.go | 12 +++---- x/crosschain/client/querytests/cctx.go | 3 ++ .../client/querytests/chain_nonces.go | 4 +++ x/crosschain/client/querytests/gas_price.go | 4 +++ x/crosschain/client/querytests/intx_hash.go | 4 +++ .../client/querytests/last_block_height.go | 4 +++ .../client/querytests/out_tx_tracker.go | 4 +++ x/crosschain/keeper/cctx_utils.go | 1 + x/crosschain/keeper/evm_deposit.go | 1 + x/crosschain/keeper/grpc_zevm.go | 2 ++ x/crosschain/keeper/keeper_cross_chain_tx.go | 4 ++- .../keeper_cross_chain_tx_vote_inbound_tx.go | 1 + .../keeper_cross_chain_tx_vote_outbound_tx.go | 2 ++ x/crosschain/keeper/keeper_gas_price.go | 8 ++++- x/crosschain/keeper/keeper_tss.go | 8 ++++- .../keeper/msg_server_whitelist_erc20.go | 15 ++++++-- x/crosschain/keeper/msg_tss_voter.go | 2 +- x/crosschain/keeper/zeta_conversion_rate.go | 3 +- x/crosschain/migrations/v2/migrate.go | 1 + x/crosschain/types/params.go | 5 ++- x/emissions/types/params.go | 5 ++- .../cli/tx_deploy_fungible_coin_zrc_4.go | 3 +- x/fungible/keeper/evm.go | 10 ++++-- x/fungible/keeper/gas_coin_and_pool.go | 1 + .../msg_server_deploy_fungible_coin_zrc20.go | 11 +++--- x/fungible/keeper/system_contract.go | 15 ++++++-- x/fungible/types/params.go | 5 ++- x/observer/abci.go | 2 ++ x/observer/keeper/keeper_utils.go | 5 ++- x/observer/keeper/observer_mapper.go | 13 +++++-- x/observer/types/params.go | 5 ++- zetaclient/bitcoin_client.go | 18 +++++++--- zetaclient/broadcast.go | 11 +++--- zetaclient/btc_signer.go | 15 ++++++-- zetaclient/config/config.go | 10 ++++-- zetaclient/config/types.go | 5 ++- zetaclient/evm_client.go | 33 ++++++++++++++--- zetaclient/keys.go | 5 ++- zetaclient/query.go | 11 +++--- zetaclient/telemetry.go | 5 ++- zetaclient/tss_signer.go | 30 +++++++++++++--- zetaclient/tx.go | 4 ++- zetaclient/utils.go | 2 ++ zetaclient/zetabridge.go | 6 +++- zetaclient/zetacore_observer.go | 22 +++++++----- 77 files changed, 530 insertions(+), 138 deletions(-) create mode 100644 scripts/cosmos-gosec.sh diff --git a/.github/workflows/sast-linters.yml b/.github/workflows/sast-linters.yml index 79efac1562..6e78d8383f 100644 --- a/.github/workflows/sast-linters.yml +++ b/.github/workflows/sast-linters.yml @@ -56,9 +56,10 @@ jobs: # uses: ./.github/actions/install-dependencies - name: Run Cosmos Gosec Security Scanner - uses: cosmos/gosec@master - with: - args: './... -include=G701,G703,G704' # Disabled G702 as it doesn't seem to be relevant 2023-09-14 + run: make lint-cosmos-gosec +# uses: cosmos/gosec@master +# with: +# args: '-include=G701,G703,G704 ./...' # Disabled G702 as it doesn't seem to be relevant 2023-09-14 git-guardian: diff --git a/Makefile b/Makefile index f6333af275..5fb9f29843 100644 --- a/Makefile +++ b/Makefile @@ -152,6 +152,9 @@ lint-pre: lint: lint-pre @golangci-lint run +lint-cosmos-gosec: + @bash ./scripts/cosmos-gosec.sh + proto: @echo "--> Removing old Go types " @find . -name '*.pb.go' -type f -delete diff --git a/app/ante/ante.go b/app/ante/ante.go index b6029c33c9..e45378b175 100644 --- a/app/ante/ante.go +++ b/app/ante/ante.go @@ -120,7 +120,10 @@ func NewAnteHandler(options ethante.HandlerOptions) (sdk.AnteHandler, error) { func Recover(logger tmlog.Logger, err *error) { if r := recover(); r != nil { - *err = errorsmod.Wrapf(errortypes.ErrPanic, "%v", r) + if err != nil { + // #nosec G703 err is checked non-nil above + *err = errorsmod.Wrapf(errortypes.ErrPanic, "%v", r) + } if e, ok := r.(error); ok { logger.Error( diff --git a/app/export.go b/app/export.go index 066e8dd41b..2ae0db042e 100644 --- a/app/export.go +++ b/app/export.go @@ -111,14 +111,23 @@ func (app *App) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []str feePool.CommunityPool = feePool.CommunityPool.Add(scraps...) app.DistrKeeper.SetFeePool(ctx, feePool) - _ = app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()) + err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()) + if err != nil { + panic(err) + } return false }) // reinitialize all delegations for _, del := range dels { - _ = app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, del.GetDelegatorAddr(), del.GetValidatorAddr()) - _ = app.DistrKeeper.Hooks().AfterDelegationModified(ctx, del.GetDelegatorAddr(), del.GetValidatorAddr()) + err := app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, del.GetDelegatorAddr(), del.GetValidatorAddr()) + if err != nil { + panic(err) + } + err = app.DistrKeeper.Hooks().AfterDelegationModified(ctx, del.GetDelegatorAddr(), del.GetValidatorAddr()) + if err != nil { + panic(err) + } } // reset context height diff --git a/cmd/zetaclientd/init.go b/cmd/zetaclientd/init.go index 79ef1833cb..8db8b18386 100644 --- a/cmd/zetaclientd/init.go +++ b/cmd/zetaclientd/init.go @@ -56,7 +56,10 @@ func init() { } func Initialize(_ *cobra.Command, _ []string) error { - setHomeDir() + err := setHomeDir() + if err != nil { + return err + } //Create new config struct configData := config.New() diff --git a/cmd/zetaclientd/p2p_diagnostics.go b/cmd/zetaclientd/p2p_diagnostics.go index f07441beb5..a33c0257cf 100644 --- a/cmd/zetaclientd/p2p_diagnostics.go +++ b/cmd/zetaclientd/p2p_diagnostics.go @@ -124,7 +124,11 @@ func RunDiagnostics(startLogger zerolog.Logger, peers p2p.AddrList, bridgePk cry var wg sync.WaitGroup for _, peerAddr := range peers { - peerinfo, _ := peer.AddrInfoFromP2pAddr(peerAddr) + peerinfo, err := peer.AddrInfoFromP2pAddr(peerAddr) + if err != nil { + startLogger.Error().Err(err).Msgf("fail to parse peer address %s", peerAddr) + continue + } wg.Add(1) go func() { defer wg.Done() diff --git a/cmd/zetaclientd/root.go b/cmd/zetaclientd/root.go index bc9c02bee1..eb358c0fb5 100644 --- a/cmd/zetaclientd/root.go +++ b/cmd/zetaclientd/root.go @@ -15,6 +15,8 @@ type rootArguments struct { zetaCoreHome string } -func setHomeDir() { - rootArgs.zetaCoreHome, _ = RootCmd.Flags().GetString(tmcli.HomeFlag) +func setHomeDir() error { + var err error + rootArgs.zetaCoreHome, err = RootCmd.Flags().GetString(tmcli.HomeFlag) + return err } diff --git a/cmd/zetaclientd/start.go b/cmd/zetaclientd/start.go index f6fda1b60f..bab4924167 100644 --- a/cmd/zetaclientd/start.go +++ b/cmd/zetaclientd/start.go @@ -39,8 +39,13 @@ func init() { } func start(_ *cobra.Command, _ []string) error { - setHomeDir() + err := setHomeDir() + if err != nil { + return err + } + SetupConfigForTest() + //Load Config file given path cfg, err := config.Load(rootArgs.zetaCoreHome) if err != nil { @@ -213,7 +218,11 @@ func start(_ *cobra.Command, _ []string) error { return err } - userDir, _ := os.UserHomeDir() + userDir, err := os.UserHomeDir() + if err != nil { + log.Error().Err(err).Msg("os.UserHomeDir") + return err + } dbpath := filepath.Join(userDir, ".zetaclient/chainobserver") // CreateChainClientMap : This creates a map of all chain clients . Each chain client is responsible for listening to events on the chain and processing them diff --git a/cmd/zetacore_utils/main.go b/cmd/zetacore_utils/main.go index bcc9bf2302..cee1b46a48 100644 --- a/cmd/zetacore_utils/main.go +++ b/cmd/zetacore_utils/main.go @@ -34,14 +34,23 @@ type TokenDistribution struct { } func main() { - file, _ := filepath.Abs(filepath.Join("cmd", "zetacore_utils", "address-list.json")) + file, err := filepath.Abs(filepath.Join("cmd", "zetacore_utils", "address-list.json")) + if err != nil { + panic(err) + } addresses, err := readLines(file) if err != nil { panic(err) } addresses = removeDuplicates(addresses) - fileS, _ := filepath.Abs(filepath.Join("cmd", "zetacore_utils", "successful_address.json")) - fileF, _ := filepath.Abs(filepath.Join("cmd", "zetacore_utils", "failed_address.json")) + fileS, err := filepath.Abs(filepath.Join("cmd", "zetacore_utils", "successful_address.json")) + if err != nil { + panic(err) + } + fileF, err := filepath.Abs(filepath.Join("cmd", "zetacore_utils", "failed_address.json")) + if err != nil { + panic(err) + } distributionList := make([]TokenDistribution, len(addresses)) for i, address := range addresses { @@ -111,11 +120,22 @@ func main() { failedDistributions = append(failedDistributions, distribution) } } - successFile, _ := json.MarshalIndent(successfullDistributions, "", " ") - _ = os.WriteFile(fileS, successFile, 0600) - failedFile, _ := json.MarshalIndent(failedDistributions, "", " ") - _ = os.WriteFile(fileF, failedFile, 0600) - + successFile, err := json.MarshalIndent(successfullDistributions, "", " ") + if err != nil { + panic(err) + } + err = os.WriteFile(fileS, successFile, 0600) + if err != nil { + panic(err) + } + failedFile, err := json.MarshalIndent(failedDistributions, "", " ") + if err != nil { + panic(err) + } + err = os.WriteFile(fileF, failedFile, 0600) + if err != nil { + panic(err) + } } func readLines(path string) ([]string, error) { diff --git a/cmd/zetacored/collect_observer_info.go b/cmd/zetacored/collect_observer_info.go index 9b74042422..f9c351636c 100644 --- a/cmd/zetacored/collect_observer_info.go +++ b/cmd/zetacored/collect_observer_info.go @@ -46,8 +46,14 @@ func CollectObserverInfoCmd() *cobra.Command { } observerInfoList = append(observerInfoList, observerInfo) } - file, _ := json.MarshalIndent(observerInfoList, "", " ") - _ = os.WriteFile("observer_info.json", file, 0600) + file, err := json.MarshalIndent(observerInfoList, "", " ") + if err != nil { + return err + } + err = os.WriteFile("observer_info.json", file, 0600) + if err != nil { + return err + } return nil }, } diff --git a/cmd/zetacored/parsers.go b/cmd/zetacored/parsers.go index 037f2e80da..008777cec7 100644 --- a/cmd/zetacored/parsers.go +++ b/cmd/zetacored/parsers.go @@ -20,7 +20,10 @@ type ObserverInfoReader struct { } func (o ObserverInfoReader) String() string { - s, _ := json.MarshalIndent(o, "", "\t") + s, err := json.MarshalIndent(o, "", "\t") + if err != nil { + return "" + } return string(s) } diff --git a/common/ethereum/proof.go b/common/ethereum/proof.go index 1ff6f705b4..6d457bc444 100644 --- a/common/ethereum/proof.go +++ b/common/ethereum/proof.go @@ -103,7 +103,11 @@ func (m *Proof) Get(key []byte) ([]byte, error) { // Typically, the rootHash is from a trusted source (e.g. a trusted block header), // and the key is the index of the transaction in the block. func (m *Proof) Verify(rootHash common.Hash, key int) ([]byte, error) { + if key < 0 { + return nil, errors.New("key not found") + } var indexBuf []byte + // #nosec G701 range is valid indexBuf = rlp.AppendUint64(indexBuf[:0], uint64(key)) return trie.VerifyProof(rootHash, indexBuf, m) } @@ -126,7 +130,11 @@ func encodeForDerive(list types.DerivableList, i int, buf *bytes.Buffer) []byte } func (t *Trie) GenerateProof(txIndex int) (*Proof, error) { + if txIndex < 0 { + return nil, errors.New("transaction index out of range") + } var indexBuf []byte + // #nosec G701 checked as non-negative indexBuf = rlp.AppendUint64(indexBuf[:0], uint64(txIndex)) proof := NewProof() err := t.Prove(indexBuf, 0, proof) @@ -150,6 +158,7 @@ func NewTrie(list types.DerivableList) Trie { // order is correct. var indexBuf []byte for i := 1; i < list.Len() && i <= 0x7f; i++ { + // #nosec G701 iterator indexBuf = rlp.AppendUint64(indexBuf[:0], uint64(i)) value := encodeForDerive(list, i, valueBuf) hasher.Update(indexBuf, value) @@ -160,6 +169,7 @@ func NewTrie(list types.DerivableList) Trie { hasher.Update(indexBuf, value) } for i := 0x80; i < list.Len(); i++ { + // #nosec G701 iterator indexBuf = rlp.AppendUint64(indexBuf[:0], uint64(i)) value := encodeForDerive(list, i, valueBuf) hasher.Update(indexBuf, value) diff --git a/contrib/localnet/orchestrator/smoketest/test_deposit_eth.go b/contrib/localnet/orchestrator/smoketest/test_deposit_eth.go index 5f390560e0..cf3e03b4c1 100644 --- a/contrib/localnet/orchestrator/smoketest/test_deposit_eth.go +++ b/contrib/localnet/orchestrator/smoketest/test_deposit_eth.go @@ -6,11 +6,12 @@ package main import ( "context" "fmt" - "github.com/zeta-chain/zetacore/common/ethereum" - observertypes "github.com/zeta-chain/zetacore/x/observer/types" "math/big" "time" + "github.com/zeta-chain/zetacore/common/ethereum" + observertypes "github.com/zeta-chain/zetacore/x/observer/types" + "github.com/ethereum/go-ethereum/accounts/abi/bind" ethcommon "github.com/ethereum/go-ethereum/common" ethtypes "github.com/ethereum/go-ethereum/core/types" diff --git a/contrib/localnet/orchestrator/smoketest/utils.go b/contrib/localnet/orchestrator/smoketest/utils.go index 36afa0d364..be9dd03f5f 100644 --- a/contrib/localnet/orchestrator/smoketest/utils.go +++ b/contrib/localnet/orchestrator/smoketest/utils.go @@ -8,11 +8,12 @@ import ( "encoding/hex" "errors" "fmt" - rpchttp "github.com/tendermint/tendermint/rpc/client/http" - coretypes "github.com/tendermint/tendermint/rpc/core/types" "sync" "time" + rpchttp "github.com/tendermint/tendermint/rpc/client/http" + coretypes "github.com/tendermint/tendermint/rpc/core/types" + "github.com/ethereum/go-ethereum" "github.com/btcsuite/btcd/chaincfg" diff --git a/contrib/rpctest/main.go b/contrib/rpctest/main.go index e909c97bd3..7d314bc888 100644 --- a/contrib/rpctest/main.go +++ b/contrib/rpctest/main.go @@ -51,10 +51,15 @@ func main() { fmt.Printf("Start testing the zEVM ETH JSON-RPC for all txs...\n") fmt.Printf("Test1: simple gas voter tx\n") - bn, err := strconv.Atoi(os.Args[1]) + bn, err := strconv.ParseInt(os.Args[1], 10, 64) if err != nil { panic(err) } + if bn < 0 { + panic("Block number must be non-negative") + } + // #nosec G701 check as positive + bnUint64 := uint64(bn) if false { // THIS WOULD NOT WORK: see https://github.com/zeta-chain/zeta-node/pull/445 @@ -64,7 +69,7 @@ func main() { panic(err) } - block, err := zevmClient.BlockByNumber(context.Background(), big.NewInt(int64(bn))) + block, err := zevmClient.BlockByNumber(context.Background(), big.NewInt(bn)) if err != nil { panic(err) } @@ -76,7 +81,7 @@ func main() { Endpoint: "http://localhost:8545", HTTPClient: &http.Client{}, } - resp := client.EthGetBlockByNumber(uint64(bn), false) + resp := client.EthGetBlockByNumber(bnUint64, false) var jsonObject map[string]interface{} if resp.Error != nil { fmt.Printf("Error: %s (code %d)\n", resp.Error.Message, resp.Error.Code) @@ -118,7 +123,7 @@ func main() { // HeaderByHash works; BlockByHash does not work; // main offending RPC is the transaction type; we have custom type id 56 // which is not recognized by the go-ethereum client. - blockHeader, err := zevmClient.HeaderByNumber(context.Background(), big.NewInt(int64(bn))) + blockHeader, err := zevmClient.HeaderByNumber(context.Background(), big.NewInt(bn)) if err != nil { panic(err) } @@ -209,9 +214,9 @@ func main() { panic(err) } fmt.Printf("Gas price: %s\n", gas.String()) - toBlock := uint64(bn) + toBlock := bnUint64 gasPriceIter, err := sys.FilterSetGasPrice(&bind.FilterOpts{ - Start: uint64(bn), + Start: bnUint64, End: &toBlock, }) if err != nil { diff --git a/rpc/backend/account_info.go b/rpc/backend/account_info.go index c7335e11b7..b6175b5cd1 100644 --- a/rpc/backend/account_info.go +++ b/rpc/backend/account_info.go @@ -77,6 +77,7 @@ func (b *Backend) GetProof(address common.Address, storageKeys []string, blockNr return nil, fmt.Errorf("not able to query block number greater than MaxInt64") } + // #nosec G701 range checked height = int64(bn) } @@ -194,8 +195,13 @@ func (b *Backend) GetTransactionCount(address common.Address, blockNum rpctypes. if err != nil { return &n, err } + if bn > math.MaxInt64 { + return nil, fmt.Errorf("not able to query block number greater than MaxInt64") + } height := blockNum.Int64() + // #nosec G701 range checked currentHeight := int64(bn) + if height > currentHeight { return &n, errorsmod.Wrapf( sdkerrors.ErrInvalidHeight, diff --git a/rpc/backend/blocks.go b/rpc/backend/blocks.go index f659085d51..8fa721ccf0 100644 --- a/rpc/backend/blocks.go +++ b/rpc/backend/blocks.go @@ -18,6 +18,7 @@ package backend import ( "bytes" "fmt" + "math" "math/big" "strconv" @@ -174,6 +175,10 @@ func (b *Backend) TendermintBlockByNumber(blockNum rpctypes.BlockNumber) (*tmrpc if err != nil { return nil, err } + if n > math.MaxInt64 { + return nil, fmt.Errorf("block number %d is greater than max int64", n) + } + // #nosec G701 range checked height = int64(n) } resBlock, err := b.clientCtx.Client.Block(b.ctx, &height) @@ -396,12 +401,15 @@ func (b *Backend) RPCBlockFromTendermintBlock( rpcTx, err = rpctypes.NewRPCTransaction( tx, common.BytesToHash(block.Hash()), + // #nosec G701 non negative value uint64(block.Height), + // #nosec G701 non negative value uint64(txIndex), baseFee, b.chainID, ) } else { + // #nosec G701 non negative value rpcTx, err = rpctypes.NewRPCTransactionFromIncompleteMsg(ethMsg, common.BytesToHash(block.Hash()), uint64(block.Height), uint64(txIndex), baseFee, b.chainID, txsAdditional[txIndex]) } if err != nil { @@ -455,6 +463,7 @@ func (b *Backend) RPCBlockFromTendermintBlock( // block gas limit has exceeded, other txs must have failed with same reason. break } + // #nosec G701 non negative value gasUsed += uint64(txsResult.GetGasUsed()) } diff --git a/rpc/backend/call_tx.go b/rpc/backend/call_tx.go index 0eb9ade41e..fd757d2f04 100644 --- a/rpc/backend/call_tx.go +++ b/rpc/backend/call_tx.go @@ -244,7 +244,10 @@ func (b *Backend) SetTxDefaults(args evmtypes.TransactionArgs) (evmtypes.Transac if args.Nonce == nil { // get the nonce from the account retriever // ignore error in case tge account doesn't exist yet - nonce, _ := b.getAccountNonce(*args.From, true, 0, b.logger) + nonce, err := b.getAccountNonce(*args.From, true, 0, b.logger) + if err != nil { + nonce = 0 + } args.Nonce = (*hexutil.Uint64)(&nonce) } diff --git a/rpc/backend/chain_info.go b/rpc/backend/chain_info.go index 2f12631460..2cc0b1d465 100644 --- a/rpc/backend/chain_info.go +++ b/rpc/backend/chain_info.go @@ -17,6 +17,7 @@ package backend import ( "fmt" + "math" "math/big" "strconv" @@ -104,7 +105,11 @@ func (b *Backend) BaseFee(blockRes *tmrpctypes.ResultBlockResults) (*big.Int, er // CurrentHeader returns the latest block header func (b *Backend) CurrentHeader() *ethtypes.Header { - header, _ := b.HeaderByNumber(rpctypes.EthLatestBlockNumber) + header, err := b.HeaderByNumber(rpctypes.EthLatestBlockNumber) + if err != nil { + b.logger.Debug("failed to fetch latest header", "error", err.Error()) + return nil + } return header } @@ -149,7 +154,10 @@ func (b *Backend) GetCoinbase() (sdk.AccAddress, error) { return nil, err } - address, _ := sdk.AccAddressFromBech32(res.AccountAddress) + address, err := sdk.AccAddressFromBech32(res.AccountAddress) + if err != nil { + return nil, err + } return address, nil } @@ -166,9 +174,17 @@ func (b *Backend) FeeHistory( if err != nil { return nil, err } + if blockNumber > math.MaxInt64 { + return nil, fmt.Errorf("not able to query block number greater than MaxInt64") + } + // #nosec G701 range checked blockEnd = int64(blockNumber) } + if userBlockCount > math.MaxInt64 { + return nil, fmt.Errorf("not able to query block count greater than MaxInt64") + } + // #nosec G701 range checked blocks := int64(userBlockCount) maxBlockCount := int64(b.cfg.JSONRPC.FeeHistoryCap) if blocks > maxBlockCount { @@ -197,6 +213,7 @@ func (b *Backend) FeeHistory( // fetch block for blockID := blockStart; blockID <= blockEnd; blockID++ { + // #nosec G701 range checked index := int32(blockID - blockStart) // tendermint block tendermintblock, err := b.TendermintBlockByNumber(rpctypes.BlockNumber(blockID)) @@ -273,6 +290,7 @@ func (b *Backend) SuggestGasTipCap(baseFee *big.Int) (*big.Int, error) { // MaxDelta = BaseFee * (GasLimit - GasLimit / ElasticityMultiplier) / (GasLimit / ElasticityMultiplier) / Denominator // = BaseFee * (ElasticityMultiplier - 1) / Denominator // ``` + // #nosec G701 range checked maxDelta := baseFee.Int64() * (int64(params.Params.ElasticityMultiplier) - 1) / int64(params.Params.BaseFeeChangeDenominator) if maxDelta < 0 { // impossible if the parameter validation passed. diff --git a/rpc/backend/node_info.go b/rpc/backend/node_info.go index 04ac8eb297..52826bbc60 100644 --- a/rpc/backend/node_info.go +++ b/rpc/backend/node_info.go @@ -213,7 +213,10 @@ func (b *Backend) ImportRawKey(privkey, password string) (common.Address, error) } // ignore error as we only care about the length of the list - list, _ := b.clientCtx.Keyring.List() + list, err := b.clientCtx.Keyring.List() + if err != nil { + list = []*keyring.Record{} + } privKeyName := fmt.Sprintf("personal_%d", len(list)) armor := sdkcrypto.EncryptArmorPrivKey(privKey, password, ethsecp256k1.KeyType) diff --git a/rpc/backend/tracing.go b/rpc/backend/tracing.go index fb961d2c28..145b45ec5e 100644 --- a/rpc/backend/tracing.go +++ b/rpc/backend/tracing.go @@ -50,6 +50,7 @@ func (b *Backend) TraceTransaction(hash common.Hash, config *evmtypes.TraceConfi } // check tx index is not out of bound + // #nosec G701 txs number in block is always less than MaxUint32 if uint32(len(blk.Block.Txs)) < transaction.TxIndex { b.logger.Debug("tx index out of bounds", "index", transaction.TxIndex, "hash", hash.String(), "height", blk.Block.Height) return nil, fmt.Errorf("transaction not included in block %v", blk.Block.Height) @@ -79,6 +80,7 @@ func (b *Backend) TraceTransaction(hash common.Hash, config *evmtypes.TraceConfi } // add predecessor messages in current cosmos tx + // #nosec G701 always in range for i := 0; i < int(transaction.MsgIndex); i++ { ethMsg, ok := tx.GetMsgs()[i].(*evmtypes.MsgEthereumTx) if !ok { diff --git a/rpc/backend/tx_info.go b/rpc/backend/tx_info.go index a53863df2d..c81f289d9e 100644 --- a/rpc/backend/tx_info.go +++ b/rpc/backend/tx_info.go @@ -74,6 +74,7 @@ func (b *Backend) GetTransactionByHash(txHash common.Hash) (*rpctypes.RPCTransac msgs, _ := b.EthMsgsFromTendermintBlock(block, blockRes) for i := range msgs { if msgs[i].Hash == hexTx { + // #nosec G701 always in range res.EthTxIndex = int32(i) break } @@ -96,7 +97,9 @@ func (b *Backend) GetTransactionByHash(txHash common.Hash) (*rpctypes.RPCTransac return rpctypes.NewTransactionFromMsg( msg, common.BytesToHash(block.BlockID.Hash.Bytes()), + // #nosec G701 always positive uint64(res.Height), + // #nosec G701 always positive uint64(res.EthTxIndex), baseFee, b.chainID, @@ -189,6 +192,7 @@ func (b *Backend) GetTransactionReceipt(hash common.Hash) (map[string]interface{ return nil, nil } for _, txResult := range blockRes.TxsResults[0:res.TxIndex] { + // #nosec G701 always positive cumulativeGasUsed += uint64(txResult.GasUsed) } cumulativeGasUsed += res.CumulativeGasUsed @@ -218,6 +222,7 @@ func (b *Backend) GetTransactionReceipt(hash common.Hash) (map[string]interface{ } // parse tx logs from events + // #nosec G701 always in range logs, err := TxLogsFromEvents(blockRes.TxsResults[res.TxIndex].Events, int(res.MsgIndex)) if err != nil { b.logger.Debug("failed to parse logs", "hash", hexTx, "error", err.Error()) @@ -228,6 +233,7 @@ func (b *Backend) GetTransactionReceipt(hash common.Hash) (map[string]interface{ msgs, _ := b.EthMsgsFromTendermintBlock(resBlock, blockRes) for i := range msgs { if msgs[i].Hash == hexTx { + // #nosec G701 always in range res.EthTxIndex = int32(i) break } @@ -245,6 +251,7 @@ func (b *Backend) GetTransactionReceipt(hash common.Hash) (map[string]interface{ var txType uint8 if txData == nil { + // #nosec G701 always in range txType = uint8(additional.Type) *to = additional.Recipient } else { @@ -361,6 +368,7 @@ func (b *Backend) GetTxByEthHash(hash common.Hash) (*ethermint.TxResult, *rpctyp // GetTxByTxIndex uses `/tx_query` to find transaction by tx index of valid ethereum txs func (b *Backend) GetTxByTxIndex(height int64, index uint) (*ethermint.TxResult, *rpctypes.TxResultAdditionalFields, error) { if b.indexer != nil { + // #nosec G701 always in range txRes, err := b.indexer.GetByBlockAndIndex(height, int32(index)) if err == nil { return txRes, nil, nil @@ -373,6 +381,7 @@ func (b *Backend) GetTxByTxIndex(height int64, index uint) (*ethermint.TxResult, evmtypes.AttributeKeyTxIndex, index, ) txResult, txAdditional, err := b.queryTendermintTxIndexer(query, func(txs *rpctypes.ParsedTxs) *rpctypes.ParsedTx { + // #nosec G701 always in range return txs.GetTxByTxIndex(int(index)) }) if err != nil { @@ -416,6 +425,7 @@ func (b *Backend) GetTransactionByBlockAndIndex(block *tmrpctypes.ResultBlock, i var msg *evmtypes.MsgEthereumTx // find in tx indexer + // #nosec G701 always in range res, additional, err := b.GetTxByTxIndex(block.Block.Height, uint(idx)) if err == nil { tx, err := b.clientCtx.TxConfig.TxDecoder()(block.Block.Txs[res.TxIndex]) @@ -438,6 +448,7 @@ func (b *Backend) GetTransactionByBlockAndIndex(block *tmrpctypes.ResultBlock, i } } } else { + // #nosec G701 always in range i := int(idx) ethMsgs, _ := b.EthMsgsFromTendermintBlock(block, blockRes) if i >= len(ethMsgs) { @@ -457,7 +468,9 @@ func (b *Backend) GetTransactionByBlockAndIndex(block *tmrpctypes.ResultBlock, i return rpctypes.NewTransactionFromMsg( msg, common.BytesToHash(block.Block.Hash()), + // #nosec G701 always positive uint64(block.Block.Height), + // #nosec G701 always positive uint64(idx), baseFee, b.chainID, diff --git a/rpc/backend/utils.go b/rpc/backend/utils.go index 334ac408cc..b20d6e068e 100644 --- a/rpc/backend/utils.go +++ b/rpc/backend/utils.go @@ -182,6 +182,7 @@ func (b *Backend) processBlock( b.logger.Debug("failed to decode transaction in block", "height", blockHeight, "error", err.Error()) continue } + // #nosec G701 always positive txGasUsed := uint64(eachTendermintTxResult.GasUsed) for _, msg := range tx.GetMsgs() { ethMsg, ok := msg.(*evmtypes.MsgEthereumTx) @@ -209,6 +210,7 @@ func (b *Backend) processBlock( sumGasUsed := sorter[0].gasUsed for i, p := range rewardPercentiles { + // #nosec G701 always positive thresholdGasUsed := uint64(blockGasUsed * p / 100) for sumGasUsed < thresholdGasUsed && txIndex < ethTxCount-1 { txIndex++ diff --git a/rpc/namespaces/ethereum/eth/api.go b/rpc/namespaces/ethereum/eth/api.go index 7d05848b91..5200e26495 100644 --- a/rpc/namespaces/ethereum/eth/api.go +++ b/rpc/namespaces/ethereum/eth/api.go @@ -429,6 +429,7 @@ func (e *PublicAPI) GetTransactionLogs(txHash common.Hash) ([]*ethtypes.Log, err } // parse tx logs from events + // #nosec G701 always in range return backend.TxLogsFromEvents(resBlockResult.TxsResults[res.TxIndex].Events, int(res.MsgIndex)) } diff --git a/rpc/namespaces/ethereum/eth/filters/api.go b/rpc/namespaces/ethereum/eth/filters/api.go index 0268c7217d..f6a6ca4f1e 100644 --- a/rpc/namespaces/ethereum/eth/filters/api.go +++ b/rpc/namespaces/ethereum/eth/filters/api.go @@ -248,7 +248,10 @@ func (api *PublicFilterAPI) NewPendingTransactions(ctx context.Context) (*rpc.Su for _, msg := range tx.GetMsgs() { ethTx, ok := msg.(*evmtypes.MsgEthereumTx) if ok { - _ = notifier.Notify(rpcSub.ID, ethTx.AsTransaction().Hash()) + err = notifier.Notify(rpcSub.ID, ethTx.AsTransaction().Hash()) + if err != nil { + api.logger.Debug("failed to notify", "error", err.Error()) + } } } case <-rpcSub.Err(): @@ -356,7 +359,10 @@ func (api *PublicFilterAPI) NewHeads(ctx context.Context) (*rpc.Subscription, er // TODO: fetch bloom from events header := types.EthHeaderFromTendermint(data.Header, ethtypes.Bloom{}, baseFee) - _ = notifier.Notify(rpcSub.ID, header) + err = notifier.Notify(rpcSub.ID, header) + if err != nil { + api.logger.Debug("failed to notify", "error", err.Error()) + } case <-rpcSub.Err(): headersSub.Unsubscribe(api.events) return @@ -420,7 +426,10 @@ func (api *PublicFilterAPI) Logs(ctx context.Context, crit filters.FilterCriteri logs := FilterLogs(evmtypes.LogsToEthereum(txResponse.Logs), crit.FromBlock, crit.ToBlock, crit.Addresses, crit.Topics) for _, log := range logs { - _ = notifier.Notify(rpcSub.ID, log) + err = notifier.Notify(rpcSub.ID, log) + if err != nil { + api.logger.Debug("failed to notify", "error", err.Error()) + } } case <-rpcSub.Err(): // client send an unsubscribe request logsSub.Unsubscribe(api.events) diff --git a/rpc/types/block.go b/rpc/types/block.go index 9f4b533950..4079d264de 100644 --- a/rpc/types/block.go +++ b/rpc/types/block.go @@ -107,6 +107,7 @@ func (bn *BlockNumber) UnmarshalJSON(data []byte) error { if blckNum > math.MaxInt64 { return fmt.Errorf("block number larger than int64") } + // #nosec G701 range checked *bn = BlockNumber(blckNum) return nil diff --git a/rpc/types/events.go b/rpc/types/events.go index e760c9b4cb..71fd7a789f 100644 --- a/rpc/types/events.go +++ b/rpc/types/events.go @@ -162,6 +162,7 @@ func ParseTxResult(result *abci.ResponseDeliverTx, tx sdk.Tx) (*ParsedTxs, error // some old versions miss some events, fill it with tx result if len(p.Txs) == 1 { + // #nosec G701 always positive p.Txs[0].GasUsed = uint64(result.GasUsed) } @@ -191,8 +192,9 @@ func ParseTxIndexerResult(txResult *tmrpctypes.ResultTx, tx sdk.Tx, getter func( } if parsedTx.Type == 88 { return ðermint.TxResult{ - Height: txResult.Height, - TxIndex: txResult.Index, + Height: txResult.Height, + TxIndex: txResult.Index, + // #nosec G701 always in range MsgIndex: uint32(parsedTx.MsgIndex), EthTxIndex: parsedTx.EthTxIndex, Failed: parsedTx.Failed, @@ -208,8 +210,9 @@ func ParseTxIndexerResult(txResult *tmrpctypes.ResultTx, tx sdk.Tx, getter func( }, nil } return ðermint.TxResult{ - Height: txResult.Height, - TxIndex: txResult.Index, + Height: txResult.Height, + TxIndex: txResult.Index, + // #nosec G701 always in range MsgIndex: uint32(parsedTx.MsgIndex), EthTxIndex: parsedTx.EthTxIndex, Failed: parsedTx.Failed, @@ -231,8 +234,10 @@ func ParseTxBlockResult(txResult *abci.ResponseDeliverTx, tx sdk.Tx, txIndex int parsedTx := txs.Txs[0] if parsedTx.Type == 88 { return ðermint.TxResult{ - Height: height, - TxIndex: uint32(txIndex), + Height: height, + // #nosec G701 always in range + TxIndex: uint32(txIndex), + // #nosec G701 always in range MsgIndex: uint32(parsedTx.MsgIndex), EthTxIndex: parsedTx.EthTxIndex, Failed: parsedTx.Failed, @@ -249,8 +254,10 @@ func ParseTxBlockResult(txResult *abci.ResponseDeliverTx, tx sdk.Tx, txIndex int }, nil } return ðermint.TxResult{ - Height: height, - TxIndex: uint32(txIndex), + Height: height, + // #nosec G701 always in range + TxIndex: uint32(txIndex), + // #nosec G701 always in range MsgIndex: uint32(parsedTx.MsgIndex), EthTxIndex: parsedTx.EthTxIndex, Failed: parsedTx.Failed, @@ -336,6 +343,7 @@ func fillTxAttribute(tx *ParsedTx, key []byte, value []byte) error { if err != nil { return err } + // #nosec G701 always in range tx.EthTxIndex = int32(txIndex) case evmtypes.AttributeKeyTxGasUsed: gasUsed, err := strconv.ParseUint(string(value), 10, 64) diff --git a/rpc/types/utils.go b/rpc/types/utils.go index c3831deb26..62d947dfe5 100644 --- a/rpc/types/utils.go +++ b/rpc/types/utils.go @@ -82,11 +82,12 @@ func EthHeaderFromTendermint(header tmtypes.Header, bloom ethtypes.Bloom, baseFe Number: big.NewInt(header.Height), GasLimit: 0, GasUsed: 0, - Time: uint64(header.Time.UTC().Unix()), - Extra: []byte{}, - MixDigest: common.Hash{}, - Nonce: ethtypes.BlockNonce{}, - BaseFee: baseFee, + // #nosec G701 always positive + Time: uint64(header.Time.UTC().Unix()), + Extra: []byte{}, + MixDigest: common.Hash{}, + Nonce: ethtypes.BlockNonce{}, + BaseFee: baseFee, } } @@ -94,6 +95,7 @@ func EthHeaderFromTendermint(header tmtypes.Header, bloom ethtypes.Bloom, baseFe func BlockMaxGasFromConsensusParams(goCtx context.Context, clientCtx client.Context, blockHeight int64) (int64, error) { resConsParams, err := clientCtx.Client.ConsensusParams(goCtx, &blockHeight) if err != nil { + // #nosec G701 always in range return int64(^uint32(0)), err } @@ -102,6 +104,7 @@ func BlockMaxGasFromConsensusParams(goCtx context.Context, clientCtx client.Cont // Sets gas limit to max uint32 to not error with javascript dev tooling // This -1 value indicating no block gas limit is set to max uint64 with geth hexutils // which errors certain javascript dev tooling which only supports up to 53 bits + // #nosec G701 always in range gasLimit = int64(^uint32(0)) } @@ -186,7 +189,10 @@ func NewRPCTransaction( } else { signer = ethtypes.HomesteadSigner{} } - from, _ := ethtypes.Sender(signer, tx) + from, err := ethtypes.Sender(signer, tx) + if err != nil { + return nil, err + } v, r, s := tx.RawSignatureValues() result := &RPCTransaction{ Type: hexutil.Uint64(tx.Type()), diff --git a/rpc/websockets.go b/rpc/websockets.go index ba0419efcc..1346aad955 100644 --- a/rpc/websockets.go +++ b/rpc/websockets.go @@ -92,7 +92,10 @@ type websocketsServer struct { func NewWebsocketsServer(clientCtx client.Context, logger log.Logger, tmWSClient *rpcclient.WSClient, cfg *config.Config) WebsocketsServer { logger = logger.With("api", "websocket-server") - _, port, _ := net.SplitHostPort(cfg.JSONRPC.Address) + _, port, err := net.SplitHostPort(cfg.JSONRPC.Address) + if err != nil { + logger.Error("failed to parse rpc address", "error", err.Error()) + } return &websocketsServer{ rpcAddr: "localhost:" + port, // FIXME: this shouldn't be hardcoded to localhost @@ -158,7 +161,10 @@ func (s *websocketsServer) sendErrResponse(wsConn *wsConn, msg string) { ID: nil, } - _ = wsConn.WriteJSON(res) + err := wsConn.WriteJSON(res) + if err != nil { + s.logger.Debug("error writing error response", "error", err.Error()) + } } type wsConn struct { @@ -199,7 +205,10 @@ func (s *websocketsServer) readLoop(wsConn *wsConn) { for { _, mb, err := wsConn.ReadMessage() if err != nil { - _ = wsConn.Close() + err = wsConn.Close() + if err != nil { + s.logger.Debug("error closing websocket connection", "error", err.Error()) + } s.logger.Error("read message error, breaking read loop", "error", err.Error()) return } @@ -430,7 +439,10 @@ func (api *pubSubAPI) subscribeNewHeads(wsConn *wsConn, subID rpc.ID) (pubsub.Un try(func() { if err != websocket.ErrCloseSent { - _ = wsConn.Close() + err = wsConn.Close() + if err != nil { + api.logger.Debug("error closing websocket peer", "error", err.Error()) + } } }, api.logger, "closing websocket peer sub") } @@ -609,8 +621,11 @@ func (api *pubSubAPI) subscribeLogs(wsConn *wsConn, subID rpc.ID, extra interfac err = wsConn.WriteJSON(res) if err != nil { try(func() { - if err != websocket.ErrCloseSent { - _ = wsConn.Close() + if !errors.Is(err, websocket.ErrCloseSent) { + err = wsConn.Close() + if err != nil { + api.logger.Debug("error closing websocket peer", "error", err.Error()) + } } }, api.logger, "closing websocket peer sub") } @@ -667,8 +682,11 @@ func (api *pubSubAPI) subscribePendingTransactions(wsConn *wsConn, subID rpc.ID) api.logger.Debug("error writing header, will drop peer", "error", err.Error()) try(func() { - if err != websocket.ErrCloseSent { - _ = wsConn.Close() + if !errors.Is(err, websocket.ErrCloseSent) { + err = wsConn.Close() + if err != nil { + api.logger.Debug("error closing websocket peer", "error", err.Error()) + } } }, api.logger, "closing websocket peer sub") } diff --git a/scripts/cosmos-gosec.sh b/scripts/cosmos-gosec.sh new file mode 100644 index 0000000000..0863a94cce --- /dev/null +++ b/scripts/cosmos-gosec.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash + +# Install gosec +go install github.com/cosmos/gosec/v2/cmd/gosec@latest + +# Run gosec +gosec -include=G701,G703,G704 ./... \ No newline at end of file diff --git a/server/start.go b/server/start.go index 14a07c0ebd..e490886733 100644 --- a/server/start.go +++ b/server/start.go @@ -135,7 +135,10 @@ which accepts a path for the resulting pprof file. return err } - withTM, _ := cmd.Flags().GetBool(srvflags.WithTendermint) + withTM, err := cmd.Flags().GetBool(srvflags.WithTendermint) + if err != nil { + withTM = false + } if !withTM { serverCtx.Logger.Info("starting ABCI without Tendermint") return startStandAlone(serverCtx, opts) @@ -144,7 +147,10 @@ which accepts a path for the resulting pprof file. serverCtx.Logger.Info("Unlocking keyring") // fire unlock precess for keyring - keyringBackend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend) + keyringBackend, err := cmd.Flags().GetString(flags.FlagKeyringBackend) + if err != nil { + keyringBackend = "" + } if keyringBackend == keyring.BackendFile { _, err = clientCtx.Keyring.List() if err != nil { @@ -393,7 +399,7 @@ func startInProcess(ctx *server.Context, clientCtx client.Context, opts StartOpt defer func() { if tmNode.IsRunning() { - _ = tmNode.Stop() + err = tmNode.Stop() } }() } diff --git a/x/crosschain/client/cli/cli_chain_nonce.go b/x/crosschain/client/cli/cli_chain_nonce.go index e6add33648..dd1ddb2b0d 100644 --- a/x/crosschain/client/cli/cli_chain_nonce.go +++ b/x/crosschain/client/cli/cli_chain_nonce.go @@ -84,7 +84,7 @@ func CmdNonceVoter() *cobra.Command { if err != nil { return err } - argsNonce, err := strconv.Atoi(args[1]) + argsNonce, err := strconv.ParseUint(args[1], 10, 64) if err != nil { return err } @@ -93,7 +93,7 @@ func CmdNonceVoter() *cobra.Command { return err } - msg := types.NewMsgNonceVoter(clientCtx.GetFromAddress().String(), argsChain, uint64(argsNonce)) + msg := types.NewMsgNonceVoter(clientCtx.GetFromAddress().String(), argsChain, argsNonce) if err := msg.ValidateBasic(); err != nil { return err } diff --git a/x/crosschain/client/cli/cli_out_tx_tracker.go b/x/crosschain/client/cli/cli_out_tx_tracker.go index 95432badad..fc87399818 100644 --- a/x/crosschain/client/cli/cli_out_tx_tracker.go +++ b/x/crosschain/client/cli/cli_out_tx_tracker.go @@ -58,14 +58,14 @@ func CmdShowOutTxTracker() *cobra.Command { if err != nil { return err } - argNonce, err := strconv.ParseInt(args[1], 10, 64) + argNonce, err := strconv.ParseUint(args[1], 10, 64) if err != nil { return err } params := &types.QueryGetOutTxTrackerRequest{ ChainID: argChain, - Nonce: uint64(argNonce), + Nonce: argNonce, } res, err := queryClient.OutTxTracker(context.Background(), params) @@ -94,7 +94,7 @@ func CmdAddToWatchList() *cobra.Command { if err != nil { return err } - argNonce, err := strconv.ParseInt(args[1], 10, 64) + argNonce, err := strconv.ParseUint(args[1], 10, 64) if err != nil { return err } @@ -108,7 +108,7 @@ func CmdAddToWatchList() *cobra.Command { msg := types.NewMsgAddToOutTxTracker( clientCtx.GetFromAddress().String(), argChain, - uint64(argNonce), + argNonce, argTxHash, nil, // TODO: add option to provide a proof from CLI arguments https://github.com/zeta-chain/node/issues/1134 "", @@ -136,7 +136,7 @@ func CmdRemoveFromWatchList() *cobra.Command { if err != nil { return err } - argNonce, err := strconv.ParseInt(args[1], 10, 64) + argNonce, err := strconv.ParseUint(args[1], 10, 64) if err != nil { return err } @@ -149,7 +149,7 @@ func CmdRemoveFromWatchList() *cobra.Command { msg := types.NewMsgRemoveFromOutTxTracker( clientCtx.GetFromAddress().String(), argChain, - uint64(argNonce), + argNonce, ) if err := msg.ValidateBasic(); err != nil { return err diff --git a/x/crosschain/client/querytests/cctx.go b/x/crosschain/client/querytests/cctx.go index 7125f9c6af..2cc4ef4d91 100644 --- a/x/crosschain/client/querytests/cctx.go +++ b/x/crosschain/client/querytests/cctx.go @@ -34,6 +34,7 @@ func (s *CliTestSuite) TestListCCTX() { s.Run("ByOffset", func() { step := 2 for i := 0; i < len(objs); i += step { + // #nosec G701 always in range args := request(nil, uint64(i), uint64(step), false) out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListSend(), args) s.Require().NoError(err) @@ -48,6 +49,7 @@ func (s *CliTestSuite) TestListCCTX() { step := 2 var next []byte for i := 0; i < len(objs); i += step { + // #nosec G701 always in range args := request(next, 0, uint64(step), false) out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListSend(), args) s.Require().NoError(err) @@ -66,6 +68,7 @@ func (s *CliTestSuite) TestListCCTX() { var resp types.QueryAllCctxResponse s.Require().NoError(s.network.Config.Codec.UnmarshalJSON(out.Bytes(), &resp)) s.Require().NoError(err) + // #nosec G701 always in range s.Require().Equal(len(objs), int(resp.Pagination.Total)) s.Require().Equal(objs, resp.CrossChainTx) }) diff --git a/x/crosschain/client/querytests/chain_nonces.go b/x/crosschain/client/querytests/chain_nonces.go index a3bab5c4ed..0e42078974 100644 --- a/x/crosschain/client/querytests/chain_nonces.go +++ b/x/crosschain/client/querytests/chain_nonces.go @@ -79,6 +79,7 @@ func (s *CliTestSuite) TestListChainNonces() { s.Run("ByOffset", func() { step := 2 for i := 0; i < len(objs); i += step { + // #nosec G701 always in range args := request(nil, uint64(i), uint64(step), false) out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListChainNonces(), args) s.Require().NoError(err) @@ -93,6 +94,7 @@ func (s *CliTestSuite) TestListChainNonces() { step := 2 var next []byte for i := 0; i < len(objs); i += step { + // #nosec G701 always in range args := request(next, 0, uint64(step), false) out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListChainNonces(), args) s.Require().NoError(err) @@ -105,12 +107,14 @@ func (s *CliTestSuite) TestListChainNonces() { } }) s.Run("Total", func() { + // #nosec G701 always in range args := request(nil, 0, uint64(len(objs)), true) out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListChainNonces(), args) s.Require().NoError(err) var resp types.QueryAllChainNoncesResponse s.Require().NoError(s.network.Config.Codec.UnmarshalJSON(out.Bytes(), &resp)) s.Require().NoError(err) + // #nosec G701 always in range s.Require().Equal(len(objs), int(resp.Pagination.Total)) s.Require().Equal(objs, resp.ChainNonces) }) diff --git a/x/crosschain/client/querytests/gas_price.go b/x/crosschain/client/querytests/gas_price.go index 077733702d..b4ac9ec62f 100644 --- a/x/crosschain/client/querytests/gas_price.go +++ b/x/crosschain/client/querytests/gas_price.go @@ -79,6 +79,7 @@ func (s *CliTestSuite) TestListGasPrice() { s.Run("ByOffset", func() { step := 2 for i := 0; i < len(objs); i += step { + // #nosec G701 always in range args := request(nil, uint64(i), uint64(step), false) out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListGasPrice(), args) s.Require().NoError(err) @@ -93,6 +94,7 @@ func (s *CliTestSuite) TestListGasPrice() { step := 2 var next []byte for i := 0; i < len(objs); i += step { + // #nosec G701 always in range args := request(next, 0, uint64(step), false) out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListGasPrice(), args) s.Require().NoError(err) @@ -105,12 +107,14 @@ func (s *CliTestSuite) TestListGasPrice() { } }) s.Run("Total", func() { + // #nosec G701 always in range args := request(nil, 0, uint64(len(objs)), true) out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListGasPrice(), args) s.Require().NoError(err) var resp types.QueryAllGasPriceResponse s.Require().NoError(s.network.Config.Codec.UnmarshalJSON(out.Bytes(), &resp)) s.Require().NoError(err) + // #nosec G701 always in range s.Require().Equal(len(objs), int(resp.Pagination.Total)) s.Require().Equal(objs, resp.GasPrice) }) diff --git a/x/crosschain/client/querytests/intx_hash.go b/x/crosschain/client/querytests/intx_hash.go index 989822aecc..0c7c4b6321 100644 --- a/x/crosschain/client/querytests/intx_hash.go +++ b/x/crosschain/client/querytests/intx_hash.go @@ -91,6 +91,7 @@ func (s *CliTestSuite) TestListInTxHashToCctx() { s.Run("ByOffset", func() { step := 2 for i := 0; i < len(objs); i += step { + // #nosec G701 always in range args := request(nil, uint64(i), uint64(step), false) out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListInTxHashToCctx(), args) s.Require().NoError(err) @@ -106,6 +107,7 @@ func (s *CliTestSuite) TestListInTxHashToCctx() { step := 2 var next []byte for i := 0; i < len(objs); i += step { + // #nosec G701 always in range args := request(next, 0, uint64(step), false) out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListInTxHashToCctx(), args) s.Require().NoError(err) @@ -119,6 +121,7 @@ func (s *CliTestSuite) TestListInTxHashToCctx() { } }) s.Run("Total", func() { + // #nosec G701 always in range args := request(nil, 0, uint64(len(objs)), true) out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListInTxHashToCctx(), args) s.Require().NoError(err) @@ -126,6 +129,7 @@ func (s *CliTestSuite) TestListInTxHashToCctx() { s.Require().NoError(s.network.Config.Codec.UnmarshalJSON(out.Bytes(), &resp)) s.Require().NoError(err) // saving CCTX also adds a new mapping + // #nosec G701 always in range s.Require().Equal(len(objs)+cctxCount, int(resp.Pagination.Total)) s.Require().ElementsMatch(nullify.Fill(objs), nullify.Fill(resp.InTxHashToCctx), diff --git a/x/crosschain/client/querytests/last_block_height.go b/x/crosschain/client/querytests/last_block_height.go index c6116d268e..d100715048 100644 --- a/x/crosschain/client/querytests/last_block_height.go +++ b/x/crosschain/client/querytests/last_block_height.go @@ -79,6 +79,7 @@ func (s *CliTestSuite) TestListLastBlockHeight() { s.Run("ByOffset", func() { step := 2 for i := 0; i < len(objs); i += step { + // #nosec G701 always in range args := request(nil, uint64(i), uint64(step), false) out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListLastBlockHeight(), args) s.Require().NoError(err) @@ -93,6 +94,7 @@ func (s *CliTestSuite) TestListLastBlockHeight() { step := 2 var next []byte for i := 0; i < len(objs); i += step { + // #nosec G701 always in range args := request(next, 0, uint64(step), false) out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListLastBlockHeight(), args) s.Require().NoError(err) @@ -105,12 +107,14 @@ func (s *CliTestSuite) TestListLastBlockHeight() { } }) s.Run("Total", func() { + // #nosec G701 always in range args := request(nil, 0, uint64(len(objs)), true) out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListLastBlockHeight(), args) s.Require().NoError(err) var resp types.QueryAllLastBlockHeightResponse s.Require().NoError(s.network.Config.Codec.UnmarshalJSON(out.Bytes(), &resp)) s.Require().NoError(err) + // #nosec G701 always in range s.Require().Equal(len(objs), int(resp.Pagination.Total)) s.Require().Equal(objs, resp.LastBlockHeight) }) diff --git a/x/crosschain/client/querytests/out_tx_tracker.go b/x/crosschain/client/querytests/out_tx_tracker.go index 119970612a..85f00522f7 100644 --- a/x/crosschain/client/querytests/out_tx_tracker.go +++ b/x/crosschain/client/querytests/out_tx_tracker.go @@ -32,6 +32,7 @@ func (s *CliTestSuite) TestListOutTxTracker() { s.Run("ByOffset", func() { step := 2 for i := 0; i < len(objs); i += step { + // #nosec G701 always in range args := request(nil, uint64(i), uint64(step), false) out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListOutTxTracker(), args) s.Require().NoError(err) @@ -47,6 +48,7 @@ func (s *CliTestSuite) TestListOutTxTracker() { step := 2 var next []byte for i := 0; i < len(objs); i += step { + // #nosec G701 always in range args := request(next, 0, uint64(step), false) out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListOutTxTracker(), args) s.Require().NoError(err) @@ -61,12 +63,14 @@ func (s *CliTestSuite) TestListOutTxTracker() { } }) s.Run("Total", func() { + // #nosec G701 always in range args := request(nil, 0, uint64(len(objs)), true) out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListOutTxTracker(), args) s.Require().NoError(err) var resp types.QueryAllOutTxTrackerResponse s.Require().NoError(s.network.Config.Codec.UnmarshalJSON(out.Bytes(), &resp)) s.Require().NoError(err) + // #nosec G701 always in range s.Require().Equal(len(objs), int(resp.Pagination.Total)) s.Require().ElementsMatch(nullify.Fill(objs), nullify.Fill(resp.OutTxTracker), diff --git a/x/crosschain/keeper/cctx_utils.go b/x/crosschain/keeper/cctx_utils.go index 70850b948b..b04b79a9b5 100644 --- a/x/crosschain/keeper/cctx_utils.go +++ b/x/crosschain/keeper/cctx_utils.go @@ -39,6 +39,7 @@ func (k Keeper) UpdateNonce(ctx sdk.Context, receiveChainID int64, cctx *types.C return sdkerrors.Wrap(types.ErrCannotFindPendingNonces, fmt.Sprintf("chain_id %d, nonce %d", receiveChainID, nonce.Nonce)) } + // #nosec G701 always in range if p.NonceHigh != int64(nonce.Nonce) { return sdkerrors.Wrap(types.ErrNonceMismatch, fmt.Sprintf("chain_id %d, high nonce %d, current nonce %d", receiveChainID, p.NonceHigh, nonce.Nonce)) } diff --git a/x/crosschain/keeper/evm_deposit.go b/x/crosschain/keeper/evm_deposit.go index 15cc9a8fa4..ee6620c950 100644 --- a/x/crosschain/keeper/evm_deposit.go +++ b/x/crosschain/keeper/evm_deposit.go @@ -24,6 +24,7 @@ func (k msgServer) HandleEVMDeposit(ctx sdk.Context, cctx *types.CrossChainTx, m hash := tmbytes.HexBytes(tmtypes.Tx(ctx.TxBytes()).Hash()) ethTxHash = ethcommon.BytesToHash(hash) cctx.GetCurrentOutTxParam().OutboundTxHash = ethTxHash.String() + // #nosec G701 always positive cctx.GetCurrentOutTxParam().OutboundTxObservedExternalHeight = uint64(ctx.BlockHeight()) } diff --git a/x/crosschain/keeper/grpc_zevm.go b/x/crosschain/keeper/grpc_zevm.go index bccb527496..820ac57dcd 100644 --- a/x/crosschain/keeper/grpc_zevm.go +++ b/x/crosschain/keeper/grpc_zevm.go @@ -42,10 +42,12 @@ func (k Keeper) ZEVMGetBlock(c context.Context, req *types.QueryZEVMGetBlockByNu if height >= math.MaxInt64 { return nil, status.Error(codes.OutOfRange, "invalid height , the height is too large") } + // #nosec G701 range checked blockResults, err := GetTendermintBlockResultsByNumber(ctx, int64(req.Height)) if err != nil { return nil, status.Error(codes.Internal, err.Error()) } + // #nosec G701 range checked block, err := GetTendermintBlockByNumber(ctx, int64(req.Height)) if err != nil { return nil, status.Error(codes.Internal, err.Error()) diff --git a/x/crosschain/keeper/keeper_cross_chain_tx.go b/x/crosschain/keeper/keeper_cross_chain_tx.go index 7fab7d2776..a53c1159c4 100644 --- a/x/crosschain/keeper/keeper_cross_chain_tx.go +++ b/x/crosschain/keeper/keeper_cross_chain_tx.go @@ -44,7 +44,8 @@ func (k Keeper) SetCctxAndNonceToCctxAndInTxHashToCctx(ctx sdk.Context, send typ // set mapping nonce => cctxIndex if send.CctxStatus.Status == types.CctxStatus_PendingOutbound || send.CctxStatus.Status == types.CctxStatus_PendingRevert { k.SetNonceToCctx(ctx, types.NonceToCctx{ - ChainId: send.GetCurrentOutTxParam().ReceiverChainId, + ChainId: send.GetCurrentOutTxParam().ReceiverChainId, + // #nosec G701 always in range Nonce: int64(send.GetCurrentOutTxParam().OutboundTxTssNonce), CctxIndex: send.Index, Tss: tss.TssPubkey, @@ -149,6 +150,7 @@ func (k Keeper) CctxByNonce(c context.Context, req *types.QueryGetCctxByNonceReq if !found { return nil, status.Error(codes.Internal, "tss not found") } + // #nosec G701 always in range res, found := k.GetNonceToCctx(ctx, tss.TssPubkey, req.ChainID, int64(req.Nonce)) if !found { return nil, status.Error(codes.Internal, fmt.Sprintf("nonceToCctx not found: nonce %d, chainid %d", req.Nonce, req.ChainID)) diff --git a/x/crosschain/keeper/keeper_cross_chain_tx_vote_inbound_tx.go b/x/crosschain/keeper/keeper_cross_chain_tx_vote_inbound_tx.go index 01c8e5d822..62c7813976 100644 --- a/x/crosschain/keeper/keeper_cross_chain_tx_vote_inbound_tx.go +++ b/x/crosschain/keeper/keeper_cross_chain_tx_vote_inbound_tx.go @@ -123,6 +123,7 @@ func (k msgServer) VoteOnObservedInboundTx(goCtx context.Context, msg *types.Msg cctx := k.CreateNewCCTX(ctx, msg, index, tssPub, types.CctxStatus_PendingInbound, observationChain, receiverChain) defer func() { EmitEventInboundFinalized(ctx, &cctx) + // #nosec G701 always positive cctx.InboundTxParams.InboundTxFinalizedZetaHeight = uint64(ctx.BlockHeight()) k.SetCctxAndNonceToCctxAndInTxHashToCctx(ctx, cctx) }() diff --git a/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go b/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go index 64783e6eaf..f8b845a925 100644 --- a/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go +++ b/x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go @@ -199,6 +199,7 @@ func (k msgServer) VoteOnObservedOutboundTx(goCtx context.Context, msg *types.Ms // do not commit tmpCtx cctx.CctxStatus.ChangeStatus(types.CctxStatus_Aborted, err.Error()) ctx.Logger().Error(err.Error()) + // #nosec G701 always in range k.RemoveFromPendingNonces(ctx, tss.TssPubkey, msg.OutTxChain, int64(msg.OutTxTssNonce)) k.RemoveOutTxTracker(ctx, msg.OutTxChain, msg.OutTxTssNonce) k.SetCctxAndNonceToCctxAndInTxHashToCctx(ctx, cctx) @@ -207,6 +208,7 @@ func (k msgServer) VoteOnObservedOutboundTx(goCtx context.Context, msg *types.Ms commit() // Set the ballot index to the finalized ballot cctx.GetCurrentOutTxParam().OutboundTxBallotIndex = ballotIndex + // #nosec G701 always in range k.RemoveFromPendingNonces(ctx, tss.TssPubkey, msg.OutTxChain, int64(msg.OutTxTssNonce)) k.RemoveOutTxTracker(ctx, msg.OutTxChain, msg.OutTxTssNonce) k.SetCctxAndNonceToCctxAndInTxHashToCctx(ctx, cctx) diff --git a/x/crosschain/keeper/keeper_gas_price.go b/x/crosschain/keeper/keeper_gas_price.go index 5566336e23..63ea8e527f 100644 --- a/x/crosschain/keeper/keeper_gas_price.go +++ b/x/crosschain/keeper/keeper_gas_price.go @@ -166,11 +166,17 @@ func (k msgServer) GasPriceVoter(goCtx context.Context, msg *types.MsgGasPriceVo } // recompute the median gas price mi := medianOfArray(gasPrice.Prices) + // #nosec G701 always positive gasPrice.MedianIndex = uint64(mi) } k.SetGasPrice(ctx, gasPrice) chainIDBigINT := big.NewInt(chain.ChainId) - gasUsed, err := k.fungibleKeeper.SetGasPrice(ctx, chainIDBigINT, big.NewInt(int64(gasPrice.Prices[gasPrice.MedianIndex]))) + + gasUsed, err := k.fungibleKeeper.SetGasPrice( + ctx, + chainIDBigINT, + math.NewUint(gasPrice.Prices[gasPrice.MedianIndex]).BigInt(), + ) if err != nil { return nil, err } diff --git a/x/crosschain/keeper/keeper_tss.go b/x/crosschain/keeper/keeper_tss.go index fc57e0013a..d1461539f9 100644 --- a/x/crosschain/keeper/keeper_tss.go +++ b/x/crosschain/keeper/keeper_tss.go @@ -23,7 +23,13 @@ func (k Keeper) SetTssAndUpdateNonce(ctx sdk.Context, tss types.TSS) { // initialize the nonces and pending nonces of all enabled chains supportedChains := k.zetaObserverKeeper.GetParams(ctx).GetSupportedChains() for _, chain := range supportedChains { - chainNonce := types.ChainNonces{Index: chain.ChainName.String(), ChainId: chain.ChainId, Nonce: 0, FinalizedHeight: uint64(ctx.BlockHeight())} + chainNonce := types.ChainNonces{ + Index: chain.ChainName.String(), + ChainId: chain.ChainId, + Nonce: 0, + // #nosec G701 always positive + FinalizedHeight: uint64(ctx.BlockHeight()), + } k.SetChainNonces(ctx, chainNonce) p := types.PendingNonces{ diff --git a/x/crosschain/keeper/msg_server_whitelist_erc20.go b/x/crosschain/keeper/msg_server_whitelist_erc20.go index b101d0b059..a4118fc774 100644 --- a/x/crosschain/keeper/msg_server_whitelist_erc20.go +++ b/x/crosschain/keeper/msg_server_whitelist_erc20.go @@ -48,7 +48,17 @@ func (k Keeper) WhitelistERC20(goCtx context.Context, msg *types.MsgWhitelistERC tmpCtx, commit := ctx.CacheContext() // add to the foreign coins. Deploy ZRC20 contract for it. - zrc20Addr, err := k.fungibleKeeper.DeployZRC20Contract(tmpCtx, msg.Name, msg.Symbol, uint8(msg.Decimals), chain.ChainId, common.CoinType_ERC20, msg.Erc20Address, big.NewInt(msg.GasLimit)) + zrc20Addr, err := k.fungibleKeeper.DeployZRC20Contract( + tmpCtx, + msg.Name, + msg.Symbol, + // #nosec G701 always in range + uint8(msg.Decimals), + chain.ChainId, + common.CoinType_ERC20, + msg.Erc20Address, + big.NewInt(msg.GasLimit), + ) if err != nil { return nil, sdkerrors.Wrapf(types.ErrDeployContract, "failed to deploy ZRC20 contract for ERC20 contract address (%s) on chain (%d)", msg.Erc20Address, msg.ChainId) } @@ -122,7 +132,8 @@ func (k Keeper) WhitelistERC20(goCtx context.Context, msg *types.MsgWhitelistERC Name: msg.Name, Symbol: msg.Symbol, CoinType: common.CoinType_ERC20, - GasLimit: uint64(msg.GasLimit), + // #nosec G701 always positive + GasLimit: uint64(msg.GasLimit), } k.fungibleKeeper.SetForeignCoins(ctx, foreignCoin) k.SetCctxAndNonceToCctxAndInTxHashToCctx(ctx, cctx) diff --git a/x/crosschain/keeper/msg_tss_voter.go b/x/crosschain/keeper/msg_tss_voter.go index a5d6603252..f81f43cd7b 100644 --- a/x/crosschain/keeper/msg_tss_voter.go +++ b/x/crosschain/keeper/msg_tss_voter.go @@ -64,7 +64,7 @@ func (k msgServer) CreateTSSVoter(goCtx context.Context, msg *types.MsgCreateTSS } k.zetaObserverKeeper.AddBallotToList(ctx, ballot) } - err := error(nil) + var err error if msg.Status == common.ReceiveStatus_Success { ballot, err = k.zetaObserverKeeper.AddVoteToBallot(ctx, ballot, msg.Creator, observerTypes.VoteType_SuccessObservation) if err != nil { diff --git a/x/crosschain/keeper/zeta_conversion_rate.go b/x/crosschain/keeper/zeta_conversion_rate.go index abb43e02ec..5bfb68a455 100644 --- a/x/crosschain/keeper/zeta_conversion_rate.go +++ b/x/crosschain/keeper/zeta_conversion_rate.go @@ -37,7 +37,8 @@ func (k Keeper) ConvertGasToZeta(context context.Context, request *types.QueryCo return &types.QueryConvertGasToZetaResponse{ OutboundGasInZeta: outTxGasFeeInZeta.String(), ProtocolFeeInZeta: types.GetProtocolFee().String(), - ZetaBlockHeight: uint64(ctx.BlockHeight()), + // #nosec G701 always positive + ZetaBlockHeight: uint64(ctx.BlockHeight()), }, nil } diff --git a/x/crosschain/migrations/v2/migrate.go b/x/crosschain/migrations/v2/migrate.go index 58f803e510..0461ba107a 100644 --- a/x/crosschain/migrations/v2/migrate.go +++ b/x/crosschain/migrations/v2/migrate.go @@ -69,6 +69,7 @@ func MigrateStore( totalObserverCountCurrentBlock += len(observer.ObserverList) } observerKeeper.SetLastObserverCount(ctx, &observerTypes.LastObserverCount{ + // #nosec G701 always positive Count: uint64(totalObserverCountCurrentBlock), LastChangeHeight: ctx.BlockHeight(), }) diff --git a/x/crosschain/types/params.go b/x/crosschain/types/params.go index 45f08e2e10..7dda7b56d5 100644 --- a/x/crosschain/types/params.go +++ b/x/crosschain/types/params.go @@ -36,6 +36,9 @@ func (p Params) Validate() error { // String implements the Stringer interface. func (p Params) String() string { - out, _ := yaml.Marshal(p) + out, err := yaml.Marshal(p) + if err != nil { + return "" + } return string(out) } diff --git a/x/emissions/types/params.go b/x/emissions/types/params.go index 01efc2e17a..a61c4ecfea 100644 --- a/x/emissions/types/params.go +++ b/x/emissions/types/params.go @@ -63,7 +63,10 @@ func (p Params) Validate() error { // String implements the Stringer interface. func (p Params) String() string { - out, _ := yaml.Marshal(p) + out, err := yaml.Marshal(p) + if err != nil { + return "" + } return string(out) } diff --git a/x/fungible/client/cli/tx_deploy_fungible_coin_zrc_4.go b/x/fungible/client/cli/tx_deploy_fungible_coin_zrc_4.go index ff876f71e0..3a82f7c75f 100644 --- a/x/fungible/client/cli/tx_deploy_fungible_coin_zrc_4.go +++ b/x/fungible/client/cli/tx_deploy_fungible_coin_zrc_4.go @@ -24,7 +24,7 @@ func CmdDeployFungibleCoinZRC4() *cobra.Command { if err != nil { return err } - argDecimals, err := strconv.ParseInt(args[2], 10, 32) + argDecimals, err := strconv.ParseUint(args[2], 10, 32) if err != nil { return err } @@ -48,6 +48,7 @@ func CmdDeployFungibleCoinZRC4() *cobra.Command { clientCtx.GetFromAddress().String(), argERC20, argForeignChain, + // #nosec G701 parsed in range uint32(argDecimals), argName, argSymbol, diff --git a/x/fungible/keeper/evm.go b/x/fungible/keeper/evm.go index df739a5157..92a87cc1d3 100644 --- a/x/fungible/keeper/evm.go +++ b/x/fungible/keeper/evm.go @@ -110,8 +110,9 @@ func (k Keeper) DeployZRC20Contract( symbol, // symbol decimals, // decimals big.NewInt(chain.ChainId), // chainID - uint8(coinType), // coinType: 0: Zeta 1: gas 2 ERC20 - gasLimit, //gas limit for transfer; 21k for gas asset; around 70k for ERC20 + // #nosec G701 always in range + uint8(coinType), // coinType: 0: Zeta 1: gas 2 ERC20 + gasLimit, //gas limit for transfer; 21k for gas asset; around 70k for ERC20 common.HexToAddress(system.SystemContract), ) if err != nil { @@ -572,7 +573,10 @@ func (k Keeper) CallEVMWithData( // Emit events and log for the transaction if it is committed if commit { - msgBytes, _ := json.Marshal(msg) + msgBytes, err := json.Marshal(msg) + if err != nil { + return nil, cosmoserrors.Wrap(err, "failed to encode msg") + } ethTxHash := common.BytesToHash(crypto.Keccak256(msgBytes)) // NOTE(pwu): this is a fake txhash attrs := []sdk.Attribute{} if len(ctx.TxBytes()) > 0 { diff --git a/x/fungible/keeper/gas_coin_and_pool.go b/x/fungible/keeper/gas_coin_and_pool.go index b90731f86d..493977a879 100644 --- a/x/fungible/keeper/gas_coin_and_pool.go +++ b/x/fungible/keeper/gas_coin_and_pool.go @@ -44,6 +44,7 @@ func (k Keeper) SetupChainGasCoinAndPool(ctx sdk.Context, chainID int64, gasAsse return ethcommon.Address{}, err } amount := big.NewInt(10) + // #nosec G701 always in range amount.Exp(amount, big.NewInt(int64(decimals-1)), nil) amountAZeta := big.NewInt(1e17) diff --git a/x/fungible/keeper/msg_server_deploy_fungible_coin_zrc20.go b/x/fungible/keeper/msg_server_deploy_fungible_coin_zrc20.go index b1debf076a..4784f3f3f6 100644 --- a/x/fungible/keeper/msg_server_deploy_fungible_coin_zrc20.go +++ b/x/fungible/keeper/msg_server_deploy_fungible_coin_zrc20.go @@ -44,11 +44,13 @@ func (k msgServer) DeployFungibleCoinZRC20(goCtx context.Context, msg *types.Msg return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "decimals must be less than 256") } if msg.CoinType == zetacommon.CoinType_Gas { + // #nosec G701 always in range address, err = k.SetupChainGasCoinAndPool(ctx, msg.ForeignChainId, msg.Name, msg.Symbol, uint8(msg.Decimals)) if err != nil { return nil, sdkerrors.Wrapf(err, "failed to setupChainGasCoinAndPool") } } else { + // #nosec G701 always in range address, err = k.DeployZRC20Contract(ctx, msg.Name, msg.Symbol, uint8(msg.Decimals), msg.ForeignChainId, msg.CoinType, msg.ERC20, big.NewInt(msg.GasLimit)) if err != nil { return nil, err @@ -62,10 +64,11 @@ func (k msgServer) DeployFungibleCoinZRC20(goCtx context.Context, msg *types.Msg Contract: address.String(), Name: msg.Name, Symbol: msg.Symbol, - Decimals: int64(msg.Decimals), - CoinType: msg.CoinType, - Erc20: msg.ERC20, - GasLimit: msg.GasLimit, + // #nosec G701 always in range + Decimals: int64(msg.Decimals), + CoinType: msg.CoinType, + Erc20: msg.ERC20, + GasLimit: msg.GasLimit, }, ) if err != nil { diff --git a/x/fungible/keeper/system_contract.go b/x/fungible/keeper/system_contract.go index b49141b031..a6e1ae8e03 100644 --- a/x/fungible/keeper/system_contract.go +++ b/x/fungible/keeper/system_contract.go @@ -60,7 +60,10 @@ func (k *Keeper) GetWZetaContractAddress(ctx sdk.Context) (ethcommon.Address, er return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrStateVariableNotFound, "failed to get system contract variable") } systemAddress := ethcommon.HexToAddress(system.SystemContract) - sysABI, _ := systemcontract.SystemContractMetaData.GetAbi() + sysABI, err := systemcontract.SystemContractMetaData.GetAbi() + if err != nil { + return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to get system contract abi") + } res, err := k.CallEVM( ctx, @@ -93,7 +96,10 @@ func (k *Keeper) GetUniswapV2FactoryAddress(ctx sdk.Context) (ethcommon.Address, return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrStateVariableNotFound, "failed to get system contract variable") } systemAddress := ethcommon.HexToAddress(system.SystemContract) - sysABI, _ := systemcontract.SystemContractMetaData.GetAbi() + sysABI, err := systemcontract.SystemContractMetaData.GetAbi() + if err != nil { + return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to get system contract abi") + } res, err := k.CallEVM( ctx, @@ -126,7 +132,10 @@ func (k *Keeper) GetUniswapV2Router02Address(ctx sdk.Context) (ethcommon.Address return ethcommon.Address{}, cosmoserrors.Wrapf(types.ErrStateVariableNotFound, "failed to get system contract variable") } systemAddress := ethcommon.HexToAddress(system.SystemContract) - sysABI, _ := systemcontract.SystemContractMetaData.GetAbi() + sysABI, err := systemcontract.SystemContractMetaData.GetAbi() + if err != nil { + return ethcommon.Address{}, cosmoserrors.Wrapf(err, "failed to get system contract abi") + } res, err := k.CallEVM( ctx, diff --git a/x/fungible/types/params.go b/x/fungible/types/params.go index 357196ad6a..4b348397da 100644 --- a/x/fungible/types/params.go +++ b/x/fungible/types/params.go @@ -34,6 +34,9 @@ func (p Params) Validate() error { // String implements the Stringer interface. func (p Params) String() string { - out, _ := yaml.Marshal(p) + out, err := yaml.Marshal(p) + if err != nil { + return "" + } return string(out) } diff --git a/x/observer/abci.go b/x/observer/abci.go index b69c4a9bec..f253819d6a 100644 --- a/x/observer/abci.go +++ b/x/observer/abci.go @@ -24,6 +24,7 @@ func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { ctx.Logger().Error("TotalObserverCount is negative at height", ctx.BlockHeight()) return } + // #nosec G701 always in range if totalObserverCountCurrentBlock == int(lastBlockObserverCount.Count) { return } @@ -33,5 +34,6 @@ func BeginBlocker(ctx sdk.Context, k keeper.Keeper) { } k.DisableInboundOnly(ctx) k.SetKeygen(ctx, types.Keygen{BlockNumber: math.MaxInt64}) + // #nosec G701 always positive k.SetLastObserverCount(ctx, &types.LastObserverCount{Count: uint64(totalObserverCountCurrentBlock), LastChangeHeight: ctx.BlockHeight()}) } diff --git a/x/observer/keeper/keeper_utils.go b/x/observer/keeper/keeper_utils.go index f654a97b33..e36cd8e934 100644 --- a/x/observer/keeper/keeper_utils.go +++ b/x/observer/keeper/keeper_utils.go @@ -89,7 +89,10 @@ func (k Keeper) IsValidator(ctx sdk.Context, creator string) error { } func (k Keeper) CheckObserverDelegation(ctx sdk.Context, accAddress string, chain *common.Chain) error { - selfdelAddr, _ := sdk.AccAddressFromBech32(accAddress) + selfdelAddr, err := sdk.AccAddressFromBech32(accAddress) + if err != nil { + return err + } valAddress, err := types.GetOperatorAddressFromAccAddress(accAddress) if err != nil { return err diff --git a/x/observer/keeper/observer_mapper.go b/x/observer/keeper/observer_mapper.go index 35119516c6..e3c2e58d06 100644 --- a/x/observer/keeper/observer_mapper.go +++ b/x/observer/keeper/observer_mapper.go @@ -5,8 +5,11 @@ import ( "fmt" "math" + cosmoserrors "cosmossdk.io/errors" + "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/zeta-chain/zetacore/common" "github.com/zeta-chain/zetacore/x/observer/types" "google.golang.org/grpc/codes" @@ -93,8 +96,14 @@ func (k msgServer) AddObserver(goCtx context.Context, msg *types.MsgAddObserver) if msg.Creator != k.GetParams(ctx).GetAdminPolicyAccount(types.Policy_Type_group2) { return &types.MsgAddObserverResponse{}, types.ErrNotAuthorizedPolicy } - pubkey, _ := common.NewPubKey(msg.ZetaclientGranteePubkey) - granteeAddress, _ := common.GetAddressFromPubkeyString(msg.ZetaclientGranteePubkey) + pubkey, err := common.NewPubKey(msg.ZetaclientGranteePubkey) + if err != nil { + return &types.MsgAddObserverResponse{}, cosmoserrors.Wrap(sdkerrors.ErrInvalidPubKey, err.Error()) + } + granteeAddress, err := common.GetAddressFromPubkeyString(msg.ZetaclientGranteePubkey) + if err != nil { + return &types.MsgAddObserverResponse{}, cosmoserrors.Wrap(sdkerrors.ErrInvalidPubKey, err.Error()) + } k.DisableInboundOnly(ctx) // AddNodeAccountOnly flag usage // True: adds observer into the Node Account list but returns without adding to the observer list diff --git a/x/observer/types/params.go b/x/observer/types/params.go index 765846a32a..bff524b297 100644 --- a/x/observer/types/params.go +++ b/x/observer/types/params.go @@ -63,7 +63,10 @@ func (p Params) Validate() error { // String implements the Stringer interface. func (p Params) String() string { - out, _ := yaml.Marshal(p) + out, err := yaml.Marshal(p) + if err != nil { + return "" + } return string(out) } diff --git a/zetaclient/bitcoin_client.go b/zetaclient/bitcoin_client.go index c2a306ff32..72bce508cb 100644 --- a/zetaclient/bitcoin_client.go +++ b/zetaclient/bitcoin_client.go @@ -245,6 +245,7 @@ func (ob *BitcoinChainClient) observeInTx() error { } // "confirmed" current block number + // #nosec G701 always in range confirmedBlockNum := cnt - int64(ob.GetCoreParams().ConfirmationCount) if confirmedBlockNum < 0 || confirmedBlockNum > math2.MaxInt64 { return fmt.Errorf("skipping observer , confirmedBlockNum is negative or too large ") @@ -286,6 +287,7 @@ func (ob *BitcoinChainClient) observeInTx() error { } tssAddress := ob.Tss.BTCAddress() + // #nosec G701 always positive inTxs := FilterAndParseIncomingTx(block.Tx, uint64(block.Height), tssAddress, &ob.logger.WatchInTx) for _, inTx := range inTxs { @@ -396,6 +398,7 @@ func (ob *BitcoinChainClient) IsSendOutTxProcessed(sendHash string, nonce uint64 zetaHash, err := ob.zetaClient.PostReceiveConfirmation( sendHash, res.TxID, + // #nosec G701 always positive uint64(res.BlockIndex), 0, // gas used not used with Bitcoin nil, // gas price not used with Bitcoin @@ -438,6 +441,7 @@ func (ob *BitcoinChainClient) PostGasPrice() error { if err != nil { return err } + // #nosec G701 always in range zetaHash, err := ob.zetaClient.PostGasPrice(ob.chain, 1000, "100", uint64(bn)) if err != nil { ob.logger.WatchGasPrice.Err(err).Msg("PostGasPrice:") @@ -461,6 +465,7 @@ func (ob *BitcoinChainClient) PostGasPrice() error { if err != nil { return err } + // #nosec G701 always positive zetaHash, err := ob.zetaClient.PostGasPrice(ob.chain, gasPriceU64, "100", uint64(bn)) if err != nil { ob.logger.WatchGasPrice.Err(err).Msg("PostGasPrice:") @@ -657,9 +662,12 @@ func (ob *BitcoinChainClient) refreshPendingNonce() { pendingNonce := ob.pendingNonce ob.mu.Unlock() - if p.NonceLow > 0 && uint64(p.NonceLow) >= pendingNonce { + // #nosec G701 always positive + nonceLow := uint64(p.NonceLow) + + if nonceLow > 0 && nonceLow >= pendingNonce { // get the last included outTx hash - txid, err := ob.getOutTxidByNonce(uint64(p.NonceLow)-1, false) + txid, err := ob.getOutTxidByNonce(nonceLow-1, false) if err != nil { ob.logger.ChainLogger.Error().Err(err).Msg("refreshPendingNonce: error getting last outTx txid") } @@ -667,7 +675,7 @@ func (ob *BitcoinChainClient) refreshPendingNonce() { // set 'NonceLow' as the new pending nonce ob.mu.Lock() defer ob.mu.Unlock() - ob.pendingNonce = uint64(p.NonceLow) + ob.pendingNonce = nonceLow ob.logger.ChainLogger.Info().Msgf("refreshPendingNonce: increase pending nonce to %d with txid %s", ob.pendingNonce, txid) } } @@ -1042,7 +1050,8 @@ func (ob *BitcoinChainClient) checkTSSVout(vouts []btcjson.Vout, params types.Ou if recvAddress != params.Receiver { return fmt.Errorf("checkTSSVout: output address %s not match params receiver %s", recvAddress, params.Receiver) } - if amount != int64(params.Amount.Uint64()) { + // #nosec G701 always positive + if uint64(amount) != params.Amount.Uint64() { return fmt.Errorf("checkTSSVout: output amount %d not match params amount %d", amount, params.Amount) } } @@ -1137,5 +1146,6 @@ func (ob *BitcoinChainClient) GetTxID(nonce uint64) string { // A very special value to mark current nonce in UTXO func NonceMarkAmount(nonce uint64) int64 { + // #nosec G701 always in range return int64(nonce) + dustOffset // +2000 to avoid being a dust rejection } diff --git a/zetaclient/broadcast.go b/zetaclient/broadcast.go index 70f1ce0739..c41333811e 100644 --- a/zetaclient/broadcast.go +++ b/zetaclient/broadcast.go @@ -80,7 +80,7 @@ func (b *ZetaCoreBridge) Broadcast(gaslimit uint64, authzWrappedMsg sdktypes.Msg if len(matches) != 3 { return "", err } - expectedSeq, err := strconv.Atoi(matches[1]) + expectedSeq, err := strconv.ParseUint(matches[1], 10, 64) if err != nil { b.logger.Warn().Msgf("cannot parse expected seq %s", matches[1]) return "", err @@ -90,7 +90,7 @@ func (b *ZetaCoreBridge) Broadcast(gaslimit uint64, authzWrappedMsg sdktypes.Msg b.logger.Warn().Msgf("cannot parse got seq %s", matches[2]) return "", err } - b.seqNumber[authzSigner.KeyType] = uint64(expectedSeq) + b.seqNumber[authzSigner.KeyType] = expectedSeq b.logger.Warn().Msgf("Reset seq number to %d (from err msg) from %d", b.seqNumber[authzSigner.KeyType], gotSeq) } return commit.TxHash, fmt.Errorf("fail to broadcast to zetachain,code:%d, log:%s", commit.Code, commit.RawLog) @@ -109,8 +109,11 @@ func (b *ZetaCoreBridge) Broadcast(gaslimit uint64, authzWrappedMsg sdktypes.Msg // GetContext return a valid context with all relevant values set func (b *ZetaCoreBridge) GetContext() client.Context { ctx := client.Context{} - addr, _ := b.keys.GetSignerInfo().GetAddress() - // TODO : Handle error + addr, err := b.keys.GetSignerInfo().GetAddress() + if err != nil { + // TODO : Handle error + b.logger.Error().Err(err).Msg("fail to get address from key") + } ctx = ctx.WithKeyring(b.keys.GetKeybase()) ctx = ctx.WithChainID(b.zetaChainID) ctx = ctx.WithHomeDir(b.cfg.ChainHomeFolder) diff --git a/zetaclient/btc_signer.go b/zetaclient/btc_signer.go index 52197cb7b6..a31f77bc85 100644 --- a/zetaclient/btc_signer.go +++ b/zetaclient/btc_signer.go @@ -96,8 +96,10 @@ func (signer *BTCSigner) SignWithdrawTx(to *btcutil.AddressWitnessPubKeyHash, am // fee checking fees := new(big.Int).Mul(big.NewInt(int64(tx.SerializeSize())), gasPrice) fees.Div(fees, big.NewInt(1000)) //FIXME: feeRate KB is 1000B or 1024B? + // #nosec G701 always in range if fees.Int64() < int64(minFee*1e8) { fmt.Printf("fees %d is less than minFee %f; use minFee", fees, minFee*1e8) + // #nosec G701 always in range fees = big.NewInt(int64(minFee * 1e8)) } @@ -188,7 +190,10 @@ func (signer *BTCSigner) Broadcast(signedTx *wire.MsgTx) error { fmt.Printf("BTCSigner: Broadcasting: %s\n", signedTx.TxHash().String()) var outBuff bytes.Buffer - _ = signedTx.Serialize(&outBuff) + err := signedTx.Serialize(&outBuff) + if err != nil { + return err + } str := hex.EncodeToString(outBuff.Bytes()) fmt.Printf("BTCSigner: Transaction Data: %s\n", str) @@ -197,7 +202,7 @@ func (signer *BTCSigner) Broadcast(signedTx *wire.MsgTx) error { return err } signer.logger.Info().Msgf("Broadcasting BTC tx , hash %s ", hash) - return err + return nil } func (signer *BTCSigner) TryProcessOutTx(send *types.CrossChainTx, outTxMan *OutTxProcessorManager, outTxID string, chainclient ChainClient, zetaBridge *ZetaCoreBridge, height uint64) { @@ -238,7 +243,11 @@ func (signer *BTCSigner) TryProcessOutTx(send *types.CrossChainTx, outTxMan *Out // Early return if the send is already processed // FIXME: handle revert case outboundTxTssNonce := params.OutboundTxTssNonce - included, confirmed, _ := btcClient.IsSendOutTxProcessed(send.Index, outboundTxTssNonce, common.CoinType_Gas, logger) + included, confirmed, err := btcClient.IsSendOutTxProcessed(send.Index, outboundTxTssNonce, common.CoinType_Gas, logger) + if err != nil { + logger.Error().Err(err).Msgf("cannot check if send %s is processed", send.Index) + return + } if included || confirmed { logger.Info().Msgf("CCTX %s already processed; exit signer", outTxID) return diff --git a/zetaclient/config/config.go b/zetaclient/config/config.go index 3e57feae58..9c2b36790c 100644 --- a/zetaclient/config/config.go +++ b/zetaclient/config/config.go @@ -19,7 +19,10 @@ func Save(config *Config, path string) error { file := filepath.Join(path, folder, filename) file = filepath.Clean(file) - jsonFile, _ := json.MarshalIndent(config, "", " ") + jsonFile, err := json.MarshalIndent(config, "", " ") + if err != nil { + return err + } err = os.WriteFile(file, jsonFile, 0600) if err != nil { return err @@ -55,7 +58,10 @@ func GetPath(inputPath string) string { path := strings.Split(inputPath, "/") if len(path) > 0 { if path[0] == "~" { - home, _ := os.UserHomeDir() + home, err := os.UserHomeDir() + if err != nil { + return "" + } path[0] = home } } diff --git a/zetaclient/config/types.go b/zetaclient/config/types.go index 851acda22f..8b731d49b5 100644 --- a/zetaclient/config/types.go +++ b/zetaclient/config/types.go @@ -75,7 +75,10 @@ func NewConfig() *Config { func (c *Config) String() string { c.cfgLock.RLock() defer c.cfgLock.RUnlock() - s, _ := json.MarshalIndent(c, "", "\t") + s, err := json.MarshalIndent(c, "", "\t") + if err != nil { + return "" + } return string(s) } diff --git a/zetaclient/evm_client.go b/zetaclient/evm_client.go index d023aadbaa..6f0058a2c0 100644 --- a/zetaclient/evm_client.go +++ b/zetaclient/evm_client.go @@ -317,6 +317,7 @@ func (ob *EVMChainClient) IsSendOutTxProcessed(sendHash string, nonce uint64, co receivedLog, err := connector.ZetaConnectorNonEthFilterer.ParseZetaReceived(*vLog) if err == nil { logger.Info().Msgf("Found (outTx) sendHash %s on chain %s txhash %s", sendHash, ob.chain.String(), vLog.TxHash.Hex()) + // #nosec G701 checked in range if int64(confHeight) < ob.GetLastBlockHeight() { logger.Info().Msg("Confirmed! Sending PostConfirmation to zetacore...") if len(vLog.Topics) != 4 { @@ -346,12 +347,14 @@ func (ob *EVMChainClient) IsSendOutTxProcessed(sendHash string, nonce uint64, co logger.Info().Msgf("Zeta tx hash: %s\n", zetaHash) return true, true, nil } + // #nosec G701 always in range logger.Info().Msgf("Included; %d blocks before confirmed! chain %s nonce %d", int(vLog.BlockNumber+params.ConfirmationCount)-int(ob.GetLastBlockHeight()), ob.chain.String(), nonce) return true, false, nil } revertedLog, err := connector.ZetaConnectorNonEthFilterer.ParseZetaReverted(*vLog) if err == nil { logger.Info().Msgf("Found (revertTx) sendHash %s on chain %s txhash %s", sendHash, ob.chain.String(), vLog.TxHash.Hex()) + // #nosec G701 checked in range if int64(confHeight) < ob.GetLastBlockHeight() { logger.Info().Msg("Confirmed! Sending PostConfirmation to zetacore...") if len(vLog.Topics) != 3 { @@ -380,6 +383,7 @@ func (ob *EVMChainClient) IsSendOutTxProcessed(sendHash string, nonce uint64, co logger.Info().Msgf("Zeta tx hash: %s", metaHash) return true, true, nil } + // #nosec G701 always in range logger.Info().Msgf("Included; %d blocks before confirmed! chain %s nonce %d", int(vLog.BlockNumber+params.ConfirmationCount)-int(ob.GetLastBlockHeight()), ob.chain.String(), nonce) return true, false, nil } @@ -421,6 +425,7 @@ func (ob *EVMChainClient) IsSendOutTxProcessed(sendHash string, nonce uint64, co } if err == nil { logger.Info().Msgf("Found (ERC20Custody.Withdrawn Event) sendHash %s on chain %s txhash %s", sendHash, ob.chain.String(), vLog.TxHash.Hex()) + // #nosec G701 checked in range if int64(confHeight) < ob.GetLastBlockHeight() { logger.Info().Msg("Confirmed! Sending PostConfirmation to zetacore...") @@ -444,6 +449,7 @@ func (ob *EVMChainClient) IsSendOutTxProcessed(sendHash string, nonce uint64, co logger.Info().Msgf("Zeta tx hash: %s\n", zetaHash) return true, true, nil } + // #nosec G701 always in range logger.Info().Msgf("Included; %d blocks before confirmed! chain %s nonce %d", int(vLog.BlockNumber+params.ConfirmationCount)-int(ob.GetLastBlockHeight()), ob.chain.String(), nonce) return true, false, nil } @@ -566,6 +572,7 @@ func (ob *EVMChainClient) queryTxByHash(txHash string, nonce uint64) (*ethtypes. return nil, nil, fmt.Errorf("confHeight is out of range") } + // #nosec G701 checked in range if int64(confHeight) > ob.GetLastBlockHeight() { log.Warn().Msgf("included but not confirmed: receipt block %d, current block %d", receipt.BlockNumber, ob.GetLastBlockHeight()) return nil, nil, fmt.Errorf("included but not confirmed") @@ -647,6 +654,7 @@ func (ob *EVMChainClient) observeInTX() error { } // "confirmed" current block number confirmedBlockNum := header.Number.Uint64() - ob.GetCoreParams().ConfirmationCount + // #nosec G701 always in range ob.SetLastBlockHeight(int64(confirmedBlockNum)) crosschainFlags, err := ob.zetaClient.GetCrosschainFlags() @@ -668,6 +676,7 @@ func (ob *EVMChainClient) observeInTX() error { sampledLogger.Error().Msg("Skipping observer , confirmedBlockNum is negative or too large ") return nil } + // #nosec G701 checked in range if confirmedBlockNum <= uint64(ob.GetLastBlockHeightScanned()) { sampledLogger.Debug().Msg("Skipping observer , No new block is produced ") return nil @@ -675,7 +684,9 @@ func (ob *EVMChainClient) observeInTX() error { lastBlock := ob.GetLastBlockHeightScanned() startBlock := lastBlock + 1 toBlock := lastBlock + config.MaxBlocksPerPeriod // read at most 10 blocks in one go + // #nosec G701 always positive if uint64(toBlock) >= confirmedBlockNum { + // #nosec G701 checked in range toBlock = int64(confirmedBlockNum) } if startBlock < 0 || startBlock >= math2.MaxInt64 { @@ -687,6 +698,7 @@ func (ob *EVMChainClient) observeInTX() error { ob.logger.ExternalChainWatcher.Info().Msgf("Checking for all inTX : startBlock %d, toBlock %d", startBlock, toBlock) //task 1: Query evm chain for zeta sent logs func() { + // #nosec G701 always positive tb := uint64(toBlock) connector, err := ob.GetConnectorContract() if err != nil { @@ -700,6 +712,7 @@ func (ob *EVMChainClient) observeInTX() error { cnt.Inc() } logs, err := connector.FilterZetaSent(&bind.FilterOpts{ + // #nosec G701 always positive Start: uint64(startBlock), End: &tb, Context: context.TODO(), @@ -754,6 +767,7 @@ func (ob *EVMChainClient) observeInTX() error { // task 2: Query evm chain for deposited logs func() { + // #nosec G701 always positive toB := uint64(toBlock) erc20custody, err := ob.GetERC20CustodyContract() if err != nil { @@ -761,6 +775,7 @@ func (ob *EVMChainClient) observeInTX() error { return } depositedLogs, err := erc20custody.FilterDeposited(&bind.FilterOpts{ + // #nosec G701 always positive Start: uint64(startBlock), End: &toB, Context: context.TODO(), @@ -973,8 +988,12 @@ func (ob *EVMChainClient) WatchGasPrice() { err := ob.PostGasPrice() if err != nil { - height, _ := ob.zetaClient.GetBlockHeight() - ob.logger.WatchGasPrice.Error().Err(err).Msgf("PostGasPrice error at zeta block : %d ", height) + height, err := ob.zetaClient.GetBlockHeight() + if err != nil { + ob.logger.WatchGasPrice.Error().Err(err).Msg("GetBlockHeight error") + } else { + ob.logger.WatchGasPrice.Error().Err(err).Msgf("PostGasPrice error at zeta block : %d ", height) + } } ticker := NewDynamicTicker(fmt.Sprintf("EVM_WatchGasPrice_%d", ob.chain.ChainId), ob.GetCoreParams().GasPriceTicker) defer ticker.Stop() @@ -983,8 +1002,12 @@ func (ob *EVMChainClient) WatchGasPrice() { case <-ticker.C(): err := ob.PostGasPrice() if err != nil { - height, _ := ob.zetaClient.GetBlockHeight() - ob.logger.WatchGasPrice.Error().Err(err).Msgf("PostGasPrice error at zeta block : %d ", height) + height, err := ob.zetaClient.GetBlockHeight() + if err != nil { + ob.logger.WatchGasPrice.Error().Err(err).Msg("GetBlockHeight error") + } else { + ob.logger.WatchGasPrice.Error().Err(err).Msgf("PostGasPrice error at zeta block : %d ", height) + } } ticker.UpdateInterval(ob.GetCoreParams().GasPriceTicker, ob.logger.WatchGasPrice) case <-ob.stop: @@ -1029,6 +1052,7 @@ func (ob *EVMChainClient) getLastHeight() (int64, error) { if err != nil { return 0, errors.Wrap(err, "getLastHeight") } + // #nosec G701 always in range return int64(lastheight.LastSendHeight), nil } @@ -1160,6 +1184,7 @@ func (ob *EVMChainClient) SetMinAndMaxNonce(trackers []types.OutTxTracker) error minNonce, maxNonce := int64(-1), int64(0) for _, tracker := range trackers { conv := tracker.Nonce + // #nosec G701 always in range intNonce := int64(conv) if minNonce == -1 { minNonce = intNonce diff --git a/zetaclient/keys.go b/zetaclient/keys.go index cb09e11ba1..5519e0b884 100644 --- a/zetaclient/keys.go +++ b/zetaclient/keys.go @@ -115,7 +115,10 @@ func (k *Keys) GetAddress() sdk.AccAddress { if err != nil { panic(err) } - addr, _ := info.GetAddress() + addr, err := info.GetAddress() + if err != nil { + return nil + } return addr } diff --git a/zetaclient/query.go b/zetaclient/query.go index 18d09f1362..7b813600ce 100644 --- a/zetaclient/query.go +++ b/zetaclient/query.go @@ -45,7 +45,7 @@ func (b *ZetaCoreBridge) GetCoreParamsForChainID(externalChainID int64) (*zetaOb func (b *ZetaCoreBridge) GetCoreParams() ([]*zetaObserverTypes.CoreParams, error) { client := zetaObserverTypes.NewQueryClient(b.grpcConn) - err := error(nil) + var err error resp := &zetaObserverTypes.QueryGetCoreParamsResponse{} for i := 0; i <= DefaultRetryCount; i++ { resp, err = client.GetCoreParams(context.Background(), &zetaObserverTypes.QueryGetCoreParamsRequest{}) @@ -122,8 +122,9 @@ func (b *ZetaCoreBridge) GetCctxByNonce(chainID int64, nonce uint64) (*types.Cro } func (b *ZetaCoreBridge) GetObserverList(chain common.Chain) ([]string, error) { + var err error + client := zetaObserverTypes.NewQueryClient(b.grpcConn) - err := error(nil) for i := 0; i <= DefaultRetryCount; i++ { resp, err := client.ObserversByChain(context.Background(), &zetaObserverTypes.QueryObserversByChainRequest{ObservationChain: chain.ChainName.String()}) if err == nil { @@ -164,8 +165,9 @@ func (b *ZetaCoreBridge) GetLatestZetaBlock() (*tmtypes.Block, error) { } func (b *ZetaCoreBridge) GetNodeInfo() (*tmservice.GetNodeInfoResponse, error) { + var err error + client := tmservice.NewServiceClient(b.grpcConn) - err := error(nil) for i := 0; i <= DefaultRetryCount; i++ { res, err := client.GetNodeInfo(context.Background(), &tmservice.GetNodeInfoRequest{}) if err == nil { @@ -214,8 +216,9 @@ func (b *ZetaCoreBridge) GetAllNodeAccounts() ([]*zetaObserverTypes.NodeAccount, } func (b *ZetaCoreBridge) GetKeyGen() (*zetaObserverTypes.Keygen, error) { + var err error + client := zetaObserverTypes.NewQueryClient(b.grpcConn) - err := error(nil) for i := 0; i <= ExtendedRetryCount; i++ { resp, err := client.Keygen(context.Background(), &zetaObserverTypes.QueryGetKeygenRequest{}) if err == nil { diff --git a/zetaclient/telemetry.go b/zetaclient/telemetry.go index baa51e4a50..7bd124dbc0 100644 --- a/zetaclient/telemetry.go +++ b/zetaclient/telemetry.go @@ -215,7 +215,10 @@ func (t *TelemetryServer) statusHandler(w http.ResponseWriter, _ *http.Request) w.WriteHeader(http.StatusOK) t.mu.Lock() defer t.mu.Unlock() - s, _ := json.MarshalIndent(t.status, "", "\t") + s, err := json.MarshalIndent(t.status, "", "\t") + if err != nil { + t.logger.Error().Err(err).Msg("Failed to marshal status") + } fmt.Fprintf(w, "%s", s) } diff --git a/zetaclient/tss_signer.go b/zetaclient/tss_signer.go index b3369007c0..a52ea4adad 100644 --- a/zetaclient/tss_signer.go +++ b/zetaclient/tss_signer.go @@ -102,6 +102,7 @@ func (tss *TSS) Sign(digest []byte, height uint64, chain *common.Chain, optional if optionalPubKey != "" { tssPubkey = optionalPubKey } + // #nosec G701 always in range keysignReq := keysign.NewRequest(tssPubkey, []string{base64.StdEncoding.EncodeToString(H)}, int64(height), nil, "0.14.0") ksRes, err := tss.Server.KeySign(keysignReq) if err != nil { @@ -172,6 +173,7 @@ func (tss *TSS) SignBatch(digests [][]byte, height uint64, chain *common.Chain) for i, digest := range digests { digestBase64[i] = base64.StdEncoding.EncodeToString(digest) } + // #nosec G701 always in range keysignReq := keysign.NewRequest(tssPubkey, digestBase64, int64(height), nil, "0.14.0") ksRes, err := tss.Server.KeySign(keysignReq) @@ -433,8 +435,14 @@ func (tss *TSS) LoadTssFilesFromDirectory(tssPath string) error { } if len(sharefiles) > 0 { sort.SliceStable(sharefiles, func(i, j int) bool { - fi, _ := sharefiles[i].Info() - fj, _ := sharefiles[j].Info() + fi, err := sharefiles[i].Info() + if err != nil { + return false + } + fj, err := sharefiles[j].Info() + if err != nil { + return false + } return fi.ModTime().After(fj.ModTime()) }) tss.logger.Info().Msgf("found %d localstate files", len(sharefiles)) @@ -555,9 +563,21 @@ func verifySignature(tssPubkey string, signature []keysign.Signature, H []byte) } // verify the signature of msg. var sigbyte [65]byte - _, _ = base64.StdEncoding.Decode(sigbyte[:32], []byte(signature[0].R)) - _, _ = base64.StdEncoding.Decode(sigbyte[32:64], []byte(signature[0].S)) - _, _ = base64.StdEncoding.Decode(sigbyte[64:65], []byte(signature[0].RecoveryID)) + _, err = base64.StdEncoding.Decode(sigbyte[:32], []byte(signature[0].R)) + if err != nil { + log.Error().Err(err).Msg("decoding signature R") + return false + } + _, err = base64.StdEncoding.Decode(sigbyte[32:64], []byte(signature[0].S)) + if err != nil { + log.Error().Err(err).Msg("decoding signature S") + return false + } + _, err = base64.StdEncoding.Decode(sigbyte[64:65], []byte(signature[0].RecoveryID)) + if err != nil { + log.Error().Err(err).Msg("decoding signature RecoveryID") + return false + } sigPublicKey, err := crypto.SigToPub(H, sigbyte[:]) if err != nil { log.Error().Err(err).Msg("SigToPub error in verify_signature") diff --git a/zetaclient/tx.go b/zetaclient/tx.go index 467aa868e6..cfe306cf9d 100644 --- a/zetaclient/tx.go +++ b/zetaclient/tx.go @@ -139,7 +139,8 @@ func (b *ZetaCoreBridge) SetTSS(tssPubkey string, keyGenZetaHeight int64, status signerAddress := b.keys.GetOperatorAddress().String() msg := types.NewMsgCreateTSSVoter(signerAddress, tssPubkey, keyGenZetaHeight, status) authzMsg, authzSigner := b.WrapMessageWithAuthz(msg) - err := error(nil) + + var err error zetaTxHash := "" for i := 0; i <= DefaultRetryCount; i++ { zetaTxHash, err = b.Broadcast(DefaultGasLimit, authzMsg, authzSigner) @@ -149,6 +150,7 @@ func (b *ZetaCoreBridge) SetTSS(tssPubkey string, keyGenZetaHeight int64, status b.logger.Debug().Err(err).Msgf("SetTSS broadcast fail | Retry count : %d", i+1) time.Sleep(DefaultRetryInterval * time.Second) } + return "", fmt.Errorf("set tss failed | err %s", err.Error()) } diff --git a/zetaclient/utils.go b/zetaclient/utils.go index cb508c43a5..56ba3000d9 100644 --- a/zetaclient/utils.go +++ b/zetaclient/utils.go @@ -34,8 +34,10 @@ func getSatoshis(btc float64) (int64, error) { func round(f float64) int64 { if f < 0 { + // #nosec G701 always in range return int64(f - 0.5) } + // #nosec G701 always in range return int64(f + 0.5) } diff --git a/zetaclient/zetabridge.go b/zetaclient/zetabridge.go index 8dfd11afa9..4e29e0d9cf 100644 --- a/zetaclient/zetabridge.go +++ b/zetaclient/zetabridge.go @@ -137,7 +137,11 @@ func (b *ZetaCoreBridge) GetAccountNumberAndSequenceNumber(_ common.KeyType) (ui func (b *ZetaCoreBridge) SetAccountNumber(keyType common.KeyType) { ctx := b.GetContext() address := b.keys.GetAddress() - accN, seq, _ := ctx.AccountRetriever.GetAccountNumberSequence(ctx, address) + accN, seq, err := ctx.AccountRetriever.GetAccountNumberSequence(ctx, address) + if err != nil { + b.logger.Error().Err(err).Msg("fail to get account number and sequence number") + return + } b.accountNumber[keyType] = accN b.seqNumber[keyType] = seq } diff --git a/zetaclient/zetacore_observer.go b/zetaclient/zetacore_observer.go index 060c641cf8..343228004a 100644 --- a/zetaclient/zetacore_observer.go +++ b/zetaclient/zetacore_observer.go @@ -6,14 +6,13 @@ import ( "time" "github.com/pkg/errors" + prom "github.com/prometheus/client_golang/prometheus" "github.com/rs/zerolog" "github.com/rs/zerolog/log" "github.com/zeta-chain/zetacore/common" "github.com/zeta-chain/zetacore/x/crosschain/types" "github.com/zeta-chain/zetacore/zetaclient/config" "github.com/zeta-chain/zetacore/zetaclient/metrics" - - prom "github.com/prometheus/client_golang/prometheus" ) const ( @@ -128,6 +127,7 @@ func (co *CoreObserver) startSendScheduler() { continue } signer := co.signerMap[*c] + cctxList, err := co.bridge.GetAllPendingCctx(c.ChainId) if err != nil { co.logger.ZetaChainWatcher.Error().Err(err).Msgf("failed to GetAllPendingCctx for chain %s", c.ChainName.String()) @@ -173,7 +173,8 @@ func (co *CoreObserver) startSendScheduler() { // Process Bitcoin OutTx if common.IsBitcoinChain(c.ChainId) && !outTxMan.IsOutTxActive(outTxID) { - if stop := co.processBitcoinOutTx(outTxMan, idx, cctx, signer, ob, currentHeight); stop { + // #nosec G701 positive + if stop := co.processBitcoinOutTx(outTxMan, uint64(idx), cctx, signer, ob, currentHeight); stop { break } continue @@ -189,8 +190,10 @@ func (co *CoreObserver) startSendScheduler() { co.logger.ZetaChainWatcher.Info().Msgf("send outTx already included; do not schedule") continue } + + // #nosec G701 positive interval := uint64(ob.GetCoreParams().OutboundTxScheduleInterval) - lookahead := uint64(ob.GetCoreParams().OutboundTxScheduleLookahead) + lookahead := ob.GetCoreParams().OutboundTxScheduleLookahead // determining critical outtx; if it satisfies following criteria // 1. it's the first pending outtx for this chain @@ -219,7 +222,9 @@ func (co *CoreObserver) startSendScheduler() { co.logger.ZetaChainWatcher.Debug().Msgf("chain %s: Sign outtx %s with value %d\n", chain, outTxID, cctx.GetCurrentOutTxParam().Amount) go signer.TryProcessOutTx(cctx, outTxMan, outTxID, ob, co.bridge, currentHeight) } - if idx >= int(lookahead)-1 { // only look at 30 sends per chain + + // #nosec G701 always in range + if int64(idx) >= lookahead-1 { // only look at 30 sends per chain break } } @@ -240,10 +245,10 @@ func (co *CoreObserver) startSendScheduler() { // 3. stop processing when pendingNonce/lookahead is reached // // Returns whether to stop processing -func (co *CoreObserver) processBitcoinOutTx(outTxMan *OutTxProcessorManager, idx int, send *types.CrossChainTx, signer ChainSigner, ob ChainClient, currentHeight uint64) bool { +func (co *CoreObserver) processBitcoinOutTx(outTxMan *OutTxProcessorManager, idx uint64, send *types.CrossChainTx, signer ChainSigner, ob ChainClient, currentHeight uint64) bool { params := send.GetCurrentOutTxParam() nonce := params.OutboundTxTssNonce - lookahead := uint64(ob.GetCoreParams().OutboundTxScheduleLookahead) + lookahead := ob.GetCoreParams().OutboundTxScheduleLookahead outTxID := fmt.Sprintf("%s-%d-%d", send.Index, params.ReceiverChainId, nonce) // start go routine to process outtx @@ -262,7 +267,8 @@ func (co *CoreObserver) processBitcoinOutTx(outTxMan *OutTxProcessorManager, idx return true } // stop if lookahead is reached. 2 bitcoin confirmations span is 20 minutes on average. We look ahead up to 100 pending cctx to target TPM of 5. - if idx >= int(lookahead)-1 { + // #nosec G701 always in range + if int64(idx) >= lookahead-1 { return true } return false // otherwise, continue