From 688b8492180fd7fe073d8b2cf8061ec217ea34c7 Mon Sep 17 00:00:00 2001 From: lumtis Date: Tue, 19 Sep 2023 18:08:04 +0200 Subject: [PATCH 01/17] add cosmos go sec makefile command --- Makefile | 3 +++ scripts/cosmos-gosec.sh | 7 +++++++ 2 files changed, 10 insertions(+) create mode 100644 scripts/cosmos-gosec.sh diff --git a/Makefile b/Makefile index ec328166c6..6f623b37e9 100644 --- a/Makefile +++ b/Makefile @@ -136,6 +136,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/scripts/cosmos-gosec.sh b/scripts/cosmos-gosec.sh new file mode 100644 index 0000000000..e802bdb6d6 --- /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 From 73450e8b511ec2c8cc92de41c3bd9fc87e3f6b7d Mon Sep 17 00:00:00 2001 From: lumtis Date: Wed, 20 Sep 2023 09:29:29 +0200 Subject: [PATCH 02/17] first wave fix --- app/ante/ante.go | 4 +++- 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 | 21 ++++++++++++++++----- cmd/zetacored/collect_observer_info.go | 10 ++++++++-- cmd/zetacored/parsers.go | 5 ++++- rpc/backend/call_tx.go | 5 ++++- rpc/backend/chain_info.go | 11 +++++++++-- rpc/backend/node_info.go | 5 ++++- rpc/namespaces/ethereum/eth/filters/api.go | 15 ++++++++++++--- 13 files changed, 96 insertions(+), 25 deletions(-) diff --git a/app/ante/ante.go b/app/ante/ante.go index b6029c33c9..9fb87fef29 100644 --- a/app/ante/ante.go +++ b/app/ante/ante.go @@ -120,7 +120,9 @@ 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 { + *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 303ce02e90..22d1392d7d 100644 --- a/cmd/zetaclientd/init.go +++ b/cmd/zetaclientd/init.go @@ -58,7 +58,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 2cfb8d4a0a..01aa2a9e0a 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 { @@ -211,7 +216,11 @@ func start(_ *cobra.Command, _ []string) error { } metrics.Start() - 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") // Register zetaclient.TSS prometheus metrics diff --git a/cmd/zetacore_utils/main.go b/cmd/zetacore_utils/main.go index bcc9bf2302..4cc824a219 100644 --- a/cmd/zetacore_utils/main.go +++ b/cmd/zetacore_utils/main.go @@ -40,8 +40,14 @@ func main() { 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 { @@ -112,10 +118,15 @@ func main() { } } successFile, _ := json.MarshalIndent(successfullDistributions, "", " ") - _ = os.WriteFile(fileS, successFile, 0600) + err = os.WriteFile(fileS, successFile, 0600) + if err != nil { + panic(err) + } failedFile, _ := json.MarshalIndent(failedDistributions, "", " ") - _ = os.WriteFile(fileF, failedFile, 0600) - + 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/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..06748b829f 100644 --- a/rpc/backend/chain_info.go +++ b/rpc/backend/chain_info.go @@ -104,7 +104,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 +153,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 } 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/namespaces/ethereum/eth/filters/api.go b/rpc/namespaces/ethereum/eth/filters/api.go index f6a9135a16..4f38095ce5 100644 --- a/rpc/namespaces/ethereum/eth/filters/api.go +++ b/rpc/namespaces/ethereum/eth/filters/api.go @@ -252,7 +252,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(): @@ -360,7 +363,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 @@ -424,7 +430,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) From fedfd11e1566f2c783b4ad1edf67d9a74322af8f Mon Sep 17 00:00:00 2001 From: lumtis Date: Wed, 20 Sep 2023 11:14:58 +0200 Subject: [PATCH 03/17] wave 2 --- app/ante/ante.go | 1 + cmd/zetacore_utils/main.go | 15 +++++++++--- common/ethereum/proof.go | 10 ++++++++ contrib/rpctest/main.go | 17 +++++++++----- rpc/backend/account_info.go | 6 +++++ rpc/backend/blocks.go | 9 +++++++ rpc/backend/chain_info.go | 11 +++++++++ rpc/backend/tracing.go | 1 + rpc/backend/tx_info.go | 10 ++++++++ rpc/backend/utils.go | 2 ++ rpc/namespaces/ethereum/eth/api.go | 1 + rpc/types/block.go | 1 + rpc/types/events.go | 24 ++++++++++++------- rpc/types/utils.go | 5 +++- rpc/websockets.go | 35 +++++++++++++++++++++------- server/start.go | 12 +++++++--- x/crosschain/types/params.go | 5 +++- x/emissions/types/params.go | 5 +++- x/fungible/keeper/evm.go | 10 ++++++-- x/fungible/keeper/system_contract.go | 25 ++++++++++++++++---- x/fungible/types/params.go | 5 +++- x/observer/keeper/keeper_utils.go | 5 +++- x/observer/keeper/observer_mapper.go | 11 +++++++-- x/observer/types/params.go | 5 +++- zetaclient/broadcast.go | 7 ++++-- zetaclient/btc_signer.go | 13 ++++++++--- zetaclient/config/config.go | 10 ++++++-- zetaclient/config/types.go | 5 +++- zetaclient/evm_client.go | 16 +++++++++---- zetaclient/keys.go | 5 +++- zetaclient/telemetry.go | 5 +++- zetaclient/tss_signer.go | 28 ++++++++++++++++++---- zetaclient/zetabridge.go | 6 ++++- 33 files changed, 263 insertions(+), 63 deletions(-) diff --git a/app/ante/ante.go b/app/ante/ante.go index 9fb87fef29..e45378b175 100644 --- a/app/ante/ante.go +++ b/app/ante/ante.go @@ -121,6 +121,7 @@ func NewAnteHandler(options ethante.HandlerOptions) (sdk.AnteHandler, error) { func Recover(logger tmlog.Logger, err *error) { if r := recover(); r != nil { if err != nil { + // #nosec G703 err is checked non-nil above *err = errorsmod.Wrapf(errortypes.ErrPanic, "%v", r) } diff --git a/cmd/zetacore_utils/main.go b/cmd/zetacore_utils/main.go index 4cc824a219..cee1b46a48 100644 --- a/cmd/zetacore_utils/main.go +++ b/cmd/zetacore_utils/main.go @@ -34,7 +34,10 @@ 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) @@ -117,12 +120,18 @@ func main() { failedDistributions = append(failedDistributions, distribution) } } - successFile, _ := json.MarshalIndent(successfullDistributions, "", " ") + successFile, err := json.MarshalIndent(successfullDistributions, "", " ") + if err != nil { + panic(err) + } err = os.WriteFile(fileS, successFile, 0600) if err != nil { panic(err) } - failedFile, _ := json.MarshalIndent(failedDistributions, "", " ") + failedFile, err := json.MarshalIndent(failedDistributions, "", " ") + if err != nil { + panic(err) + } err = os.WriteFile(fileF, failedFile, 0600) if err != nil { panic(err) diff --git a/common/ethereum/proof.go b/common/ethereum/proof.go index 1ff6f705b4..918718d93a 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 || key >= len(m.Keys) { + return nil, errors.New("key not found") + } var indexBuf []byte + // #nosec G701 key range is checked above 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/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/chain_info.go b/rpc/backend/chain_info.go index 06748b829f..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" @@ -173,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 { @@ -204,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)) @@ -280,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/tracing.go b/rpc/backend/tracing.go index fb961d2c28..f1e49ac48b 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) diff --git a/rpc/backend/tx_info.go b/rpc/backend/tx_info.go index a53863df2d..89c43eb0d8 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 @@ -416,6 +424,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 +447,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) { 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 d62ddbe18c..0e0d23d792 100644 --- a/rpc/namespaces/ethereum/eth/api.go +++ b/rpc/namespaces/ethereum/eth/api.go @@ -445,6 +445,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/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..6feeff6185 100644 --- a/rpc/types/utils.go +++ b/rpc/types/utils.go @@ -186,7 +186,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 c76a028ea3..f125e5e794 100644 --- a/rpc/websockets.go +++ b/rpc/websockets.go @@ -91,7 +91,11 @@ 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 nil + } return &websocketsServer{ rpcAddr: "localhost:" + port, // FIXME: this shouldn't be hardcoded to localhost @@ -155,7 +159,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 { @@ -196,7 +203,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 } @@ -427,7 +437,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") } @@ -606,8 +619,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") } @@ -664,8 +680,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/server/start.go b/server/start.go index 14a07c0ebd..4ebc9587ff 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 { + return err + } 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 { + return err + } 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/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/keeper/evm.go b/x/fungible/keeper/evm.go index 9911c81adf..f9f2d8909d 100644 --- a/x/fungible/keeper/evm.go +++ b/x/fungible/keeper/evm.go @@ -275,7 +275,10 @@ func (k Keeper) QueryZRC20Data( decimalRes types.ZRC20Uint8Response ) - zrc4, _ := zrc20.ZRC20MetaData.GetAbi() + zrc4, err := zrc20.ZRC20MetaData.GetAbi() + if err != nil { + return types.ZRC20Data{}, err + } // Name res, err := k.CallEVM(ctx, *zrc4, types.ModuleAddressEVM, contract, BigIntZero, nil, false, false, "name") @@ -439,7 +442,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/system_contract.go b/x/fungible/keeper/system_contract.go index 5c2c888b74..875a4f0b3e 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, *sysABI, types.ModuleAddressEVM, systemAddress, BigIntZero, nil, false, false, "wZetaContractAddress") if err != nil { @@ -82,7 +85,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, *sysABI, types.ModuleAddressEVM, systemAddress, BigIntZero, nil, false, false, "uniswapv2FactoryAddress") if err != nil { @@ -104,7 +110,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, *sysABI, types.ModuleAddressEVM, systemAddress, BigIntZero, nil, false, false, "uniswapv2Router02Address") if err != nil { @@ -142,7 +151,10 @@ func (k *Keeper) QueryWZetaBalanceOf(ctx sdk.Context, addr ethcommon.Address) (* if err != nil { return nil, cosmoserrors.Wrapf(err, "failed to get wzeta contract address") } - wzetaABI, _ := connectorzevm.WZETAMetaData.GetAbi() + wzetaABI, err := connectorzevm.WZETAMetaData.GetAbi() + if err != nil { + return nil, cosmoserrors.Wrapf(err, "failed to get wzeta abi") + } res, err := k.CallEVM(ctx, *wzetaABI, addr, wzetaAddress, big.NewInt(0), nil, false, false, "balanceOf", addr) if err != nil { return nil, cosmoserrors.Wrapf(err, "failed to call balanceOf") @@ -163,7 +175,10 @@ func (k *Keeper) QuerySystemContractGasCoinZRC20(ctx sdk.Context, chainid *big.I 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, *sysABI, types.ModuleAddressEVM, systemAddress, BigIntZero, nil, false, false, "gasCoinZRC20ByChainId", chainid) if err != nil { 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/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 dcf63c11df..aa8625cd35 100644 --- a/x/observer/keeper/observer_mapper.go +++ b/x/observer/keeper/observer_mapper.go @@ -2,6 +2,7 @@ package keeper import ( "context" + cosmoserrors "cosmossdk.io/errors" "fmt" "math" @@ -93,8 +94,14 @@ func (k msgServer) AddObserver(goCtx context.Context, msg *types.MsgAddObserver) if msg.Creator != k.GetParams(ctx).GetAdminPolicyAccount(types.Policy_Type_add_observer) { 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(types.ErrInvalidPubKey, err.Error()) + } + granteeAddress, err := common.GetAddressFromPubkeyString(msg.ZetaclientGranteePubkey) + if err != nil { + return &types.MsgAddObserverResponse{}, cosmoserrors.Wrap(types.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 92ba0d5e0b..32373408c5 100644 --- a/x/observer/types/params.go +++ b/x/observer/types/params.go @@ -81,7 +81,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/broadcast.go b/zetaclient/broadcast.go index a9c9c91b3c..d43aa3fb89 100644 --- a/zetaclient/broadcast.go +++ b/zetaclient/broadcast.go @@ -110,8 +110,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 6f9f53c6a7..63687e749b 100644 --- a/zetaclient/btc_signer.go +++ b/zetaclient/btc_signer.go @@ -182,7 +182,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) @@ -191,7 +194,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) { @@ -234,7 +237,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 already processed; exit signer") 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 0e95cb3bea..25fe68425e 100644 --- a/zetaclient/evm_client.go +++ b/zetaclient/evm_client.go @@ -951,8 +951,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() @@ -961,8 +965,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: 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/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 d0e540017d..6a642237cf 100644 --- a/zetaclient/tss_signer.go +++ b/zetaclient/tss_signer.go @@ -426,8 +426,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)) @@ -548,9 +554,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/zetabridge.go b/zetaclient/zetabridge.go index 64a7a565bd..a02c61bf56 100644 --- a/zetaclient/zetabridge.go +++ b/zetaclient/zetabridge.go @@ -126,7 +126,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 } From 5c637f5aac3ea02e8a0dbc0b7ae07854e48692a2 Mon Sep 17 00:00:00 2001 From: lumtis Date: Wed, 20 Sep 2023 11:45:01 +0200 Subject: [PATCH 04/17] wave 3 --- rpc/backend/tracing.go | 1 + rpc/backend/tx_info.go | 3 +++ rpc/types/utils.go | 13 ++++++++----- 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 +++ x/crosschain/client/querytests/chain_nonces.go | 3 +++ x/crosschain/client/querytests/gas_price.go | 3 +++ x/crosschain/client/querytests/intx_hash.go | 3 +++ .../client/querytests/last_block_height.go | 3 +++ x/crosschain/client/querytests/out_tx_tracker.go | 3 +++ x/crosschain/keeper/abci.go | 1 + x/crosschain/keeper/evm_deposit.go | 1 + x/crosschain/keeper/grpc_zevm.go | 2 ++ x/crosschain/keeper/keeper_cross_chain_tx.go | 6 +++++- .../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_pending_nonces.go | 1 + x/crosschain/keeper/keeper_tss.go | 8 +++++++- x/crosschain/keeper/keeper_tss_voter.go | 2 +- x/crosschain/keeper/keeper_utils.go | 2 ++ x/crosschain/keeper/msg_server_whitelist_erc20.go | 15 +++++++++++++-- x/crosschain/keeper/zeta_conversion_rate.go | 3 ++- x/crosschain/migrations/v2/migrate.go | 1 + .../client/cli/tx_deploy_fungible_coin_zrc_4.go | 3 ++- x/fungible/keeper/evm.go | 5 +++-- x/fungible/keeper/gas_coin_and_pool.go | 1 + .../msg_server_deploy_fungible_coin_zrc20.go | 11 +++++++---- x/observer/abci.go | 1 + zetaclient/bitcoin_client.go | 9 ++++++++- 31 files changed, 106 insertions(+), 28 deletions(-) diff --git a/rpc/backend/tracing.go b/rpc/backend/tracing.go index f1e49ac48b..145b45ec5e 100644 --- a/rpc/backend/tracing.go +++ b/rpc/backend/tracing.go @@ -80,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 89c43eb0d8..c81f289d9e 100644 --- a/rpc/backend/tx_info.go +++ b/rpc/backend/tx_info.go @@ -381,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 { @@ -467,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/types/utils.go b/rpc/types/utils.go index 6feeff6185..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)) } 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..0d8dd766a6 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,6 +107,7 @@ 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) diff --git a/x/crosschain/client/querytests/gas_price.go b/x/crosschain/client/querytests/gas_price.go index 077733702d..b506f3e06c 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,6 +107,7 @@ 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) diff --git a/x/crosschain/client/querytests/intx_hash.go b/x/crosschain/client/querytests/intx_hash.go index 989822aecc..6d0c6c6788 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) diff --git a/x/crosschain/client/querytests/last_block_height.go b/x/crosschain/client/querytests/last_block_height.go index c6116d268e..342af8e108 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,6 +107,7 @@ 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) diff --git a/x/crosschain/client/querytests/out_tx_tracker.go b/x/crosschain/client/querytests/out_tx_tracker.go index 119970612a..d7f1fffd56 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,6 +63,7 @@ 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) diff --git a/x/crosschain/keeper/abci.go b/x/crosschain/keeper/abci.go index b40b0f1838..c1be6eee7d 100644 --- a/x/crosschain/keeper/abci.go +++ b/x/crosschain/keeper/abci.go @@ -42,6 +42,7 @@ func (k Keeper) IterateAndUpdateCctxGasPrice(ctx sdk.Context) error { chains := common.DefaultChainsList() for _, chain := range chains { res, err := k.CctxAllPending(sdk.UnwrapSDKContext(ctx), &types.QueryAllCctxPendingRequest{ + // #nosec G701 always positive ChainId: uint64(chain.ChainId), }) if err != nil { 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 8fd5fdc2da..08b05c6cbc 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)) @@ -184,6 +186,7 @@ func (k Keeper) CctxAllPending(c context.Context, req *types.QueryAllCctxPending startNonce = 0 } for i := startNonce; i < p.NonceLow; i++ { + // #nosec G701 always in range res, found := k.GetNonceToCctx(ctx, tss.TssPubkey, int64(req.ChainId), i) if !found { return nil, status.Error(codes.Internal, fmt.Sprintf("nonceToCctx not found: nonce %d, chainid %d", i, req.ChainId)) @@ -199,6 +202,7 @@ func (k Keeper) CctxAllPending(c context.Context, req *types.QueryAllCctxPending // now query the pending nonces that we know are pending for i := p.NonceLow; i < p.NonceHigh; i++ { + // #nosec G701 always in range ntc, found := k.GetNonceToCctx(ctx, tss.TssPubkey, int64(req.ChainId), i) if !found { return nil, status.Error(codes.Internal, "nonceToCctx not found") 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 fac94ec7f4..cf4fd348dc 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 @@ -120,6 +120,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 a72bc84a07..921d59b045 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 @@ -187,6 +187,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) @@ -195,6 +196,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_pending_nonces.go b/x/crosschain/keeper/keeper_pending_nonces.go index da1648b104..2ab527958a 100644 --- a/x/crosschain/keeper/keeper_pending_nonces.go +++ b/x/crosschain/keeper/keeper_pending_nonces.go @@ -74,6 +74,7 @@ func (k Keeper) RemovePendingNonces(ctx sdk.Context, pendingNonces types.Pending // utility func (k Keeper) RemoveFromPendingNonces(ctx sdk.Context, tssPubkey string, chainID int64, nonce int64) { + // #nosec G701 always positive p, found := k.GetPendingNonces(ctx, tssPubkey, uint64(chainID)) if found && nonce >= p.NonceLow && nonce <= p.NonceHigh { p.NonceLow = nonce + 1 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/keeper_tss_voter.go b/x/crosschain/keeper/keeper_tss_voter.go index f28904ba66..f9809a0b80 100644 --- a/x/crosschain/keeper/keeper_tss_voter.go +++ b/x/crosschain/keeper/keeper_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/keeper_utils.go b/x/crosschain/keeper/keeper_utils.go index 77882f6a2b..eb7ad3680c 100644 --- a/x/crosschain/keeper/keeper_utils.go +++ b/x/crosschain/keeper/keeper_utils.go @@ -126,11 +126,13 @@ func (k Keeper) UpdateNonce(ctx sdk.Context, receiveChainID int64, cctx *types.C return sdkerrors.Wrap(types.ErrCannotFindTSSKeys, fmt.Sprintf("Chain(%s) | Identifiers : %s ", chain.ChainName.String(), cctx.LogIdentifierForCCTX())) } + // #nosec G701 always positive p, found := k.GetPendingNonces(ctx, tss.TssPubkey, uint64(receiveChainID)) if !found { 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/msg_server_whitelist_erc20.go b/x/crosschain/keeper/msg_server_whitelist_erc20.go index 5075ee69d4..cee19d1fb9 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/zeta_conversion_rate.go b/x/crosschain/keeper/zeta_conversion_rate.go index b1c0e4df61..cc26e7db78 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 eb788042b6..678d8a34d2 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/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 f9f2d8909d..fb4512250f 100644 --- a/x/fungible/keeper/evm.go +++ b/x/fungible/keeper/evm.go @@ -109,8 +109,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 { 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 41b678e349..3b91f4dc56 100644 --- a/x/fungible/keeper/msg_server_deploy_fungible_coin_zrc20.go +++ b/x/fungible/keeper/msg_server_deploy_fungible_coin_zrc20.go @@ -38,11 +38,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 _, 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 addr, 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 @@ -55,10 +57,11 @@ func (k msgServer) DeployFungibleCoinZRC20(goCtx context.Context, msg *types.Msg Contract: addr.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/observer/abci.go b/x/observer/abci.go index b69c4a9bec..99f1b634fd 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 } diff --git a/zetaclient/bitcoin_client.go b/zetaclient/bitcoin_client.go index c9aa882991..06272d325c 100644 --- a/zetaclient/bitcoin_client.go +++ b/zetaclient/bitcoin_client.go @@ -240,6 +240,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 ") @@ -281,6 +282,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 { @@ -382,6 +384,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 @@ -424,6 +427,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:") @@ -447,6 +451,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:") @@ -970,7 +975,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) } } @@ -1065,5 +1071,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 } From ec1922b0ec62b1d058c29403edde1d9b0571f6d3 Mon Sep 17 00:00:00 2001 From: lumtis Date: Wed, 20 Sep 2023 13:26:58 +0200 Subject: [PATCH 05/17] wave 4 --- x/crosschain/client/querytests/chain_nonces.go | 1 + x/crosschain/client/querytests/gas_price.go | 1 + x/crosschain/client/querytests/intx_hash.go | 1 + .../client/querytests/last_block_height.go | 1 + .../client/querytests/out_tx_tracker.go | 1 + x/observer/abci.go | 1 + zetaclient/broadcast.go | 4 ++-- zetaclient/btc_signer.go | 2 ++ zetaclient/evm_client.go | 17 +++++++++++++++++ zetaclient/query.go | 2 +- zetaclient/tss_signer.go | 2 ++ zetaclient/tx.go | 4 +++- zetaclient/utils.go | 2 ++ zetaclient/zetacore_observer.go | 7 +++++-- 14 files changed, 40 insertions(+), 6 deletions(-) diff --git a/x/crosschain/client/querytests/chain_nonces.go b/x/crosschain/client/querytests/chain_nonces.go index 0d8dd766a6..0e42078974 100644 --- a/x/crosschain/client/querytests/chain_nonces.go +++ b/x/crosschain/client/querytests/chain_nonces.go @@ -114,6 +114,7 @@ func (s *CliTestSuite) TestListChainNonces() { 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 b506f3e06c..b4ac9ec62f 100644 --- a/x/crosschain/client/querytests/gas_price.go +++ b/x/crosschain/client/querytests/gas_price.go @@ -114,6 +114,7 @@ func (s *CliTestSuite) TestListGasPrice() { 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 6d0c6c6788..0c7c4b6321 100644 --- a/x/crosschain/client/querytests/intx_hash.go +++ b/x/crosschain/client/querytests/intx_hash.go @@ -129,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 342af8e108..d100715048 100644 --- a/x/crosschain/client/querytests/last_block_height.go +++ b/x/crosschain/client/querytests/last_block_height.go @@ -114,6 +114,7 @@ func (s *CliTestSuite) TestListLastBlockHeight() { 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 d7f1fffd56..85f00522f7 100644 --- a/x/crosschain/client/querytests/out_tx_tracker.go +++ b/x/crosschain/client/querytests/out_tx_tracker.go @@ -70,6 +70,7 @@ func (s *CliTestSuite) TestListOutTxTracker() { 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/observer/abci.go b/x/observer/abci.go index 99f1b634fd..f253819d6a 100644 --- a/x/observer/abci.go +++ b/x/observer/abci.go @@ -34,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/zetaclient/broadcast.go b/zetaclient/broadcast.go index d43aa3fb89..66d07b3900 100644 --- a/zetaclient/broadcast.go +++ b/zetaclient/broadcast.go @@ -81,7 +81,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 @@ -91,7 +91,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) diff --git a/zetaclient/btc_signer.go b/zetaclient/btc_signer.go index 63687e749b..383c389bbf 100644 --- a/zetaclient/btc_signer.go +++ b/zetaclient/btc_signer.go @@ -90,8 +90,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)) } diff --git a/zetaclient/evm_client.go b/zetaclient/evm_client.go index 25fe68425e..2de6028cf9 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)) permissions, err := ob.zetaClient.GetPermissionFlags() @@ -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 postive Start: uint64(startBlock), End: &tb, Context: context.TODO(), @@ -752,6 +765,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 { @@ -759,6 +773,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(), @@ -1015,6 +1030,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 } @@ -1146,6 +1162,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/query.go b/zetaclient/query.go index a93c52c5e4..42a5569833 100644 --- a/zetaclient/query.go +++ b/zetaclient/query.go @@ -46,7 +46,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{}) diff --git a/zetaclient/tss_signer.go b/zetaclient/tss_signer.go index 6a642237cf..ec39bba2b8 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) if err != nil { diff --git a/zetaclient/tx.go b/zetaclient/tx.go index 5b23ef5a73..83b9e78c34 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 108ce4239c..d91388d2e6 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/zetacore_observer.go b/zetaclient/zetacore_observer.go index 83b0b5dcb3..1db5f5ce8a 100644 --- a/zetaclient/zetacore_observer.go +++ b/zetaclient/zetacore_observer.go @@ -125,6 +125,7 @@ func (co *CoreObserver) startSendScheduler() { } signer := co.signerMap[*c] chainClient := co.clientMap[*c] + // #nosec G701 always positive sendList, err := co.bridge.GetAllPendingCctx(uint64(c.ChainId)) if err != nil { co.logger.ZetaChainWatcher.Error().Err(err).Msgf("failed to GetAllPendingCctx for chain %s", c.ChainName.String()) @@ -181,9 +182,11 @@ func (co *CoreObserver) startSendScheduler() { if bn >= math.MaxInt64 { continue } + // #nosec G701 checked in range currentHeight := uint64(bn) + // #nosec G701 always 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 @@ -212,7 +215,7 @@ func (co *CoreObserver) startSendScheduler() { co.logger.ZetaChainWatcher.Debug().Msgf("chain %s: Sign outtx %s with value %d\n", chain, send.Index, send.GetCurrentOutTxParam().Amount) go signer.TryProcessOutTx(send, outTxMan, outTxID, chainClient, co.bridge, currentHeight) } - if idx > int(lookahead) { // only look at 50 sends per chain + if int64(idx) > lookahead { // only look at 50 sends per chain break } } From a25c7019141fa4cb88a5cc104e7144a25751c19f Mon Sep 17 00:00:00 2001 From: lumtis Date: Wed, 20 Sep 2023 13:27:47 +0200 Subject: [PATCH 06/17] goimports --- x/observer/keeper/observer_mapper.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x/observer/keeper/observer_mapper.go b/x/observer/keeper/observer_mapper.go index aa8625cd35..e14c89ceec 100644 --- a/x/observer/keeper/observer_mapper.go +++ b/x/observer/keeper/observer_mapper.go @@ -2,10 +2,11 @@ package keeper import ( "context" - cosmoserrors "cosmossdk.io/errors" "fmt" "math" + cosmoserrors "cosmossdk.io/errors" + "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/zeta-chain/zetacore/common" From 8947877f31e78504ffbf03dc9d5db77cbbf77460 Mon Sep 17 00:00:00 2001 From: lumtis Date: Wed, 20 Sep 2023 16:24:33 +0200 Subject: [PATCH 07/17] fix typo --- zetaclient/evm_client.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zetaclient/evm_client.go b/zetaclient/evm_client.go index 2de6028cf9..1a573eada5 100644 --- a/zetaclient/evm_client.go +++ b/zetaclient/evm_client.go @@ -712,7 +712,7 @@ func (ob *EVMChainClient) observeInTX() error { cnt.Inc() } logs, err := connector.FilterZetaSent(&bind.FilterOpts{ - // #nosec G701 always postive + // #nosec G701 always positive Start: uint64(startBlock), End: &tb, Context: context.TODO(), From 3a34086bd85fb3055d3cb47ba443224d08608537 Mon Sep 17 00:00:00 2001 From: lumtis Date: Thu, 21 Sep 2023 09:34:59 +0200 Subject: [PATCH 08/17] fix error build --- x/observer/keeper/observer_mapper.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/x/observer/keeper/observer_mapper.go b/x/observer/keeper/observer_mapper.go index e14c89ceec..785998b77a 100644 --- a/x/observer/keeper/observer_mapper.go +++ b/x/observer/keeper/observer_mapper.go @@ -9,6 +9,7 @@ import ( "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" @@ -97,11 +98,11 @@ func (k msgServer) AddObserver(goCtx context.Context, msg *types.MsgAddObserver) } pubkey, err := common.NewPubKey(msg.ZetaclientGranteePubkey) if err != nil { - return &types.MsgAddObserverResponse{}, cosmoserrors.Wrap(types.ErrInvalidPubKey, err.Error()) + return &types.MsgAddObserverResponse{}, cosmoserrors.Wrap(sdkerrors.ErrInvalidPubKey, err.Error()) } granteeAddress, err := common.GetAddressFromPubkeyString(msg.ZetaclientGranteePubkey) if err != nil { - return &types.MsgAddObserverResponse{}, cosmoserrors.Wrap(types.ErrInvalidPubKey, err.Error()) + return &types.MsgAddObserverResponse{}, cosmoserrors.Wrap(sdkerrors.ErrInvalidPubKey, err.Error()) } k.DisableInboundOnly(ctx) // AddNodeAccountOnly flag usage From 653d48e54e8085a60d4fd071eaa100e680caa763 Mon Sep 17 00:00:00 2001 From: lumtis Date: Thu, 21 Sep 2023 10:01:33 +0200 Subject: [PATCH 09/17] fix websocket --- rpc/websockets.go | 1 - 1 file changed, 1 deletion(-) diff --git a/rpc/websockets.go b/rpc/websockets.go index cad025ca57..1346aad955 100644 --- a/rpc/websockets.go +++ b/rpc/websockets.go @@ -95,7 +95,6 @@ func NewWebsocketsServer(clientCtx client.Context, logger log.Logger, tmWSClient _, port, err := net.SplitHostPort(cfg.JSONRPC.Address) if err != nil { logger.Error("failed to parse rpc address", "error", err.Error()) - return nil } return &websocketsServer{ From 3394c9d139feb5064f0994e0c95955197ea6b9cf Mon Sep 17 00:00:00 2001 From: lumtis Date: Thu, 21 Sep 2023 10:17:38 +0200 Subject: [PATCH 10/17] fix proof --- common/ethereum/proof.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/common/ethereum/proof.go b/common/ethereum/proof.go index 918718d93a..6d457bc444 100644 --- a/common/ethereum/proof.go +++ b/common/ethereum/proof.go @@ -103,11 +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 || key >= len(m.Keys) { + if key < 0 { return nil, errors.New("key not found") } var indexBuf []byte - // #nosec G701 key range is checked above + // #nosec G701 range is valid indexBuf = rlp.AppendUint64(indexBuf[:0], uint64(key)) return trie.VerifyProof(rootHash, indexBuf, m) } From 4d05bd5df42b0d4cd001e23bfb6b25ed74f83804 Mon Sep 17 00:00:00 2001 From: lumtis Date: Thu, 21 Sep 2023 10:39:50 +0200 Subject: [PATCH 11/17] fix flags --- server/start.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/start.go b/server/start.go index 4ebc9587ff..e490886733 100644 --- a/server/start.go +++ b/server/start.go @@ -137,7 +137,7 @@ which accepts a path for the resulting pprof file. withTM, err := cmd.Flags().GetBool(srvflags.WithTendermint) if err != nil { - return err + withTM = false } if !withTM { serverCtx.Logger.Info("starting ABCI without Tendermint") @@ -149,7 +149,7 @@ which accepts a path for the resulting pprof file. // fire unlock precess for keyring keyringBackend, err := cmd.Flags().GetString(flags.FlagKeyringBackend) if err != nil { - return err + keyringBackend = "" } if keyringBackend == keyring.BackendFile { _, err = clientCtx.Keyring.List() From 3d384757f0b6ac1851a0df85602367c86a38fc7f Mon Sep 17 00:00:00 2001 From: lumtis Date: Thu, 21 Sep 2023 14:18:55 +0200 Subject: [PATCH 12/17] format --- x/fungible/keeper/system_contract.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/fungible/keeper/system_contract.go b/x/fungible/keeper/system_contract.go index 649cc15367..696371a1e5 100644 --- a/x/fungible/keeper/system_contract.go +++ b/x/fungible/keeper/system_contract.go @@ -201,7 +201,7 @@ func (k *Keeper) QueryWZetaBalanceOf(ctx sdk.Context, addr ethcommon.Address) (* if err != nil { return nil, cosmoserrors.Wrapf(err, "failed to get wzeta abi") } - + res, err := k.CallEVM( ctx, *wzetaABI, From 4a5cbc7af02f957200f6165ff026e39d077001f5 Mon Sep 17 00:00:00 2001 From: lumtis Date: Mon, 25 Sep 2023 16:14:20 +0200 Subject: [PATCH 13/17] conflict 2 --- zetaclient/zetacore_observer.go | 29 ++++------------------------- 1 file changed, 4 insertions(+), 25 deletions(-) diff --git a/zetaclient/zetacore_observer.go b/zetaclient/zetacore_observer.go index f79bd96dd5..4a193a37b1 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,13 +127,8 @@ func (co *CoreObserver) startSendScheduler() { continue } signer := co.signerMap[*c] -<<<<<<< HEAD - chainClient := co.clientMap[*c] - // #nosec G701 always positive - sendList, err := co.bridge.GetAllPendingCctx(uint64(c.ChainId)) -======= + cctxList, err := co.bridge.GetAllPendingCctx(c.ChainId) ->>>>>>> develop if err != nil { co.logger.ZetaChainWatcher.Error().Err(err).Msgf("failed to GetAllPendingCctx for chain %s", c.ChainName.String()) continue @@ -195,19 +189,7 @@ func (co *CoreObserver) startSendScheduler() { co.logger.ZetaChainWatcher.Info().Msgf("send outTx already included; do not schedule") continue } -<<<<<<< HEAD - nonce := params.OutboundTxTssNonce - outTxID := fmt.Sprintf("%s-%d-%d", send.Index, params.ReceiverChainId, nonce) // should be the outTxID? - // FIXME: config this schedule; this value is for localnet fast testing - if bn >= math.MaxInt64 { - continue - } - // #nosec G701 checked in range - currentHeight := uint64(bn) - // #nosec G701 always positive -======= ->>>>>>> develop interval := uint64(ob.GetCoreParams().OutboundTxScheduleInterval) lookahead := ob.GetCoreParams().OutboundTxScheduleLookahead @@ -238,11 +220,8 @@ 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) } -<<<<<<< HEAD - if int64(idx) > lookahead { // only look at 50 sends per chain -======= - if idx >= int(lookahead)-1 { // only look at 30 sends per chain ->>>>>>> develop + + if int64(idx) >= lookahead-1 { // only look at 30 sends per chain break } } From fcbc3d67c7f728fbdfa1ddcd37c536f991fc7113 Mon Sep 17 00:00:00 2001 From: lumtis Date: Mon, 25 Sep 2023 16:25:28 +0200 Subject: [PATCH 14/17] fix arguments --- .github/workflows/sast-linters.yml | 2 +- scripts/cosmos-gosec.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/sast-linters.yml b/.github/workflows/sast-linters.yml index 79efac1562..b7eee53c5f 100644 --- a/.github/workflows/sast-linters.yml +++ b/.github/workflows/sast-linters.yml @@ -58,7 +58,7 @@ jobs: - 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 + args: '-include=G701,G703,G704 ./...' # Disabled G702 as it doesn't seem to be relevant 2023-09-14 git-guardian: diff --git a/scripts/cosmos-gosec.sh b/scripts/cosmos-gosec.sh index e802bdb6d6..0863a94cce 100644 --- a/scripts/cosmos-gosec.sh +++ b/scripts/cosmos-gosec.sh @@ -4,4 +4,4 @@ go install github.com/cosmos/gosec/v2/cmd/gosec@latest # Run gosec -gosec ./... -include=G701,G703,G704 \ No newline at end of file +gosec -include=G701,G703,G704 ./... \ No newline at end of file From 35b4812db0d5b320f5f41eb5ddcf4e5997121030 Mon Sep 17 00:00:00 2001 From: lumtis Date: Mon, 25 Sep 2023 16:41:09 +0200 Subject: [PATCH 15/17] solve remaining --- zetaclient/bitcoin_client.go | 9 ++++++--- zetaclient/query.go | 9 ++++++--- zetaclient/zetacore_observer.go | 12 ++++++++---- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/zetaclient/bitcoin_client.go b/zetaclient/bitcoin_client.go index a2e1f9252b..72bce508cb 100644 --- a/zetaclient/bitcoin_client.go +++ b/zetaclient/bitcoin_client.go @@ -662,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") } @@ -672,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) } } diff --git a/zetaclient/query.go b/zetaclient/query.go index d665e6d1bc..7b813600ce 100644 --- a/zetaclient/query.go +++ b/zetaclient/query.go @@ -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/zetacore_observer.go b/zetaclient/zetacore_observer.go index 4a193a37b1..343228004a 100644 --- a/zetaclient/zetacore_observer.go +++ b/zetaclient/zetacore_observer.go @@ -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 @@ -190,6 +191,7 @@ func (co *CoreObserver) startSendScheduler() { continue } + // #nosec G701 positive interval := uint64(ob.GetCoreParams().OutboundTxScheduleInterval) lookahead := ob.GetCoreParams().OutboundTxScheduleLookahead @@ -221,6 +223,7 @@ func (co *CoreObserver) startSendScheduler() { go signer.TryProcessOutTx(cctx, outTxMan, outTxID, ob, co.bridge, currentHeight) } + // #nosec G701 always in range if int64(idx) >= lookahead-1 { // only look at 30 sends per chain break } @@ -242,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 @@ -264,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 From 60a7dff8d80289653a0806037854bc1af72b760c Mon Sep 17 00:00:00 2001 From: lumtis Date: Mon, 25 Sep 2023 17:19:03 +0200 Subject: [PATCH 16/17] ci test --- .github/workflows/sast-linters.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/sast-linters.yml b/.github/workflows/sast-linters.yml index b7eee53c5f..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: From cf0ff1c2f368aa6101f81f70e5343dee474bc78d Mon Sep 17 00:00:00 2001 From: lumtis Date: Mon, 2 Oct 2023 11:19:42 -0700 Subject: [PATCH 17/17] make generate --- contrib/localnet/orchestrator/smoketest/test_deposit_eth.go | 5 +++-- contrib/localnet/orchestrator/smoketest/utils.go | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) 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"