From 7f50618c16cfba541056bd3fe41129ce1835746d Mon Sep 17 00:00:00 2001 From: Lucas Bertrand Date: Tue, 1 Aug 2023 16:45:17 +0200 Subject: [PATCH 1/5] refactor: simplify code generated by Ignite CLI (#850) * remove var _ = strconv.Itoa(0 * remove var _ = binary.ByteOrder * group add command * group codec register implementation * remove unused variables in module_simulation --------- Co-authored-by: Denis Fadeev Co-authored-by: brewmaster012 <88689859+brewmaster012@users.noreply.github.com> --- x/crosschain/client/cli/cli_cctx.go | 2 -- .../client/cli/cli_out_tx_tracker_test.go | 6 +--- x/crosschain/client/cli/cli_zeta_height.go | 6 +--- x/crosschain/client/cli/query.go | 34 ++++++++++--------- .../client/cli/query_get_tss_address.go | 4 --- x/crosschain/client/cli/tx.go | 32 +++++++---------- x/crosschain/module_simulation.go | 14 -------- x/crosschain/types/codec.go | 15 -------- x/crosschain/types/key_in_tx_hash_to_cctx.go | 4 --- x/emissions/client/cli/query.go | 6 ++-- x/emissions/client/cli/query_list_balances.go | 4 --- x/fungible/client/cli/query.go | 8 +++-- x/fungible/client/cli/tx.go | 14 +++----- .../cli/tx_deploy_fungible_coin_zrc_4.go | 2 -- .../client/cli/tx_remove_foreign_coin.go | 4 --- x/fungible/module_simulation.go | 14 -------- x/fungible/types/codec.go | 5 +-- x/fungible/types/key_foreign_coins.go | 4 --- x/observer/client/cli/query.go | 34 +++++++++---------- x/observer/client/cli/query_ballot.go | 4 --- x/observer/client/cli/query_blame.go | 3 -- x/observer/client/cli/query_core_params.go | 2 -- x/observer/client/cli/query_observers.go | 4 --- .../client/cli/query_show_observer_count.go | 4 --- x/observer/client/cli/tx.go | 17 ++++++---- x/observer/client/cli/tx_add_blame_vote.go | 9 +++-- x/observer/client/cli/tx_add_observer.go | 2 -- .../client/cli/tx_update_core_params.go | 3 -- x/observer/client/cli/tx_update_keygen.go | 4 +-- x/observer/module_simulation.go | 14 -------- x/observer/types/codec.go | 4 --- 31 files changed, 78 insertions(+), 204 deletions(-) diff --git a/x/crosschain/client/cli/cli_cctx.go b/x/crosschain/client/cli/cli_cctx.go index f4b7dc0e9c..398108765a 100644 --- a/x/crosschain/client/cli/cli_cctx.go +++ b/x/crosschain/client/cli/cli_cctx.go @@ -14,8 +14,6 @@ import ( "github.com/zeta-chain/zetacore/x/crosschain/types" ) -var _ = strconv.Itoa(0) - func CmdListSend() *cobra.Command { cmd := &cobra.Command{ Use: "list-cctx", diff --git a/x/crosschain/client/cli/cli_out_tx_tracker_test.go b/x/crosschain/client/cli/cli_out_tx_tracker_test.go index 4cfb17b6e1..01976193dc 100644 --- a/x/crosschain/client/cli/cli_out_tx_tracker_test.go +++ b/x/crosschain/client/cli/cli_out_tx_tracker_test.go @@ -2,19 +2,15 @@ package cli_test import ( "fmt" - "github.com/zeta-chain/zetacore/app" - "strconv" "testing" "github.com/stretchr/testify/require" + "github.com/zeta-chain/zetacore/app" "github.com/zeta-chain/zetacore/testutil/network" "github.com/zeta-chain/zetacore/testutil/nullify" "github.com/zeta-chain/zetacore/x/crosschain/types" ) -// Prevent strconv unused error -var _ = strconv.IntSize - func networkWithOutTxTrackerObjects(t *testing.T, n int) (*network.Network, []types.OutTxTracker) { t.Helper() cfg := network.DefaultConfig() diff --git a/x/crosschain/client/cli/cli_zeta_height.go b/x/crosschain/client/cli/cli_zeta_height.go index 24b698eff9..8f855cd46e 100644 --- a/x/crosschain/client/cli/cli_zeta_height.go +++ b/x/crosschain/client/cli/cli_zeta_height.go @@ -1,16 +1,12 @@ package cli import ( - "github.com/spf13/cobra" - "strconv" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/spf13/cobra" "github.com/zeta-chain/zetacore/x/crosschain/types" ) -var _ = strconv.Itoa(0) - func CmdLastZetaHeight() *cobra.Command { cmd := &cobra.Command{ Use: "last-zeta-height", diff --git a/x/crosschain/client/cli/query.go b/x/crosschain/client/cli/query.go index 5f896a9f20..2618a7e794 100644 --- a/x/crosschain/client/cli/query.go +++ b/x/crosschain/client/cli/query.go @@ -26,22 +26,24 @@ func GetQueryCmd(queryRoute string) *cobra.Command { RunE: client.ValidateCmd, } - cmd.AddCommand(CmdListOutTxTracker()) - cmd.AddCommand(CmdShowOutTxTracker()) - cmd.AddCommand(cli.CmdShowKeygen()) - cmd.AddCommand(CmdShowTSS()) - cmd.AddCommand(CmdListGasPrice()) - cmd.AddCommand(CmdShowGasPrice()) - cmd.AddCommand(CmdListChainNonces()) - cmd.AddCommand(CmdShowChainNonces()) - cmd.AddCommand(CmdListSend()) - cmd.AddCommand(CmdShowSend()) - cmd.AddCommand(CmdLastZetaHeight()) - cmd.AddCommand(CmdListInTxHashToCctx()) - cmd.AddCommand(CmdShowInTxHashToCctx()) - cmd.AddCommand(CmdQueryParams()) - cmd.AddCommand(cli.CmdShowPermissionFlags()) - cmd.AddCommand(CmdGetTssAddress()) + cmd.AddCommand( + CmdListOutTxTracker(), + CmdShowOutTxTracker(), + cli.CmdShowKeygen(), + CmdShowTSS(), + CmdListGasPrice(), + CmdShowGasPrice(), + CmdListChainNonces(), + CmdShowChainNonces(), + CmdListSend(), + CmdShowSend(), + CmdLastZetaHeight(), + CmdListInTxHashToCctx(), + CmdShowInTxHashToCctx(), + CmdQueryParams(), + cli.CmdShowPermissionFlags(), + CmdGetTssAddress(), + ) // this line is used by starport scaffolding # 1 diff --git a/x/crosschain/client/cli/query_get_tss_address.go b/x/crosschain/client/cli/query_get_tss_address.go index b10a1df02d..b6322d84bc 100644 --- a/x/crosschain/client/cli/query_get_tss_address.go +++ b/x/crosschain/client/cli/query_get_tss_address.go @@ -1,16 +1,12 @@ package cli import ( - "strconv" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" "github.com/zeta-chain/zetacore/x/crosschain/types" ) -var _ = strconv.Itoa(0) - func CmdGetTssAddress() *cobra.Command { cmd := &cobra.Command{ Use: "get-tss-address", diff --git a/x/crosschain/client/cli/tx.go b/x/crosschain/client/cli/tx.go index bd885dadf5..571b468bf1 100644 --- a/x/crosschain/client/cli/tx.go +++ b/x/crosschain/client/cli/tx.go @@ -2,24 +2,14 @@ package cli import ( "fmt" - "github.com/zeta-chain/zetacore/x/observer/client/cli" - "time" - "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" + "github.com/zeta-chain/zetacore/x/observer/client/cli" // "github.com/cosmos/cosmos-sdk/client/flags" "github.com/zeta-chain/zetacore/x/crosschain/types" ) -var ( - DefaultRelativePacketTimeoutTimestamp = uint64((time.Duration(10) * time.Minute).Nanoseconds()) -) - -const ( -// flagPacketTimeoutTimestamp = "packet-timeout-timestamp" -) - // GetTxCmd returns the transaction commands for this module func GetTxCmd() *cobra.Command { cmd := &cobra.Command{ @@ -30,15 +20,17 @@ func GetTxCmd() *cobra.Command { RunE: client.ValidateCmd, } - cmd.AddCommand(CmdAddToWatchList()) - cmd.AddCommand(CmdCreateTSSVoter()) - cmd.AddCommand(CmdGasPriceVoter()) - cmd.AddCommand(CmdNonceVoter()) - cmd.AddCommand(CmdCCTXOutboundVoter()) - cmd.AddCommand(CmdCCTXInboundVoter()) - cmd.AddCommand(CmdRemoveFromWatchList()) - cmd.AddCommand(cli.CmdUpdatePermissionFlags()) - cmd.AddCommand(cli.CmdUpdateKeygen()) + cmd.AddCommand( + CmdAddToWatchList(), + CmdCreateTSSVoter(), + CmdGasPriceVoter(), + CmdNonceVoter(), + CmdCCTXOutboundVoter(), + CmdCCTXInboundVoter(), + CmdRemoveFromWatchList(), + cli.CmdUpdatePermissionFlags(), + cli.CmdUpdateKeygen(), + ) // this line is used by starport scaffolding # 1 return cmd diff --git a/x/crosschain/module_simulation.go b/x/crosschain/module_simulation.go index 1ba988d1bc..26118e09aa 100644 --- a/x/crosschain/module_simulation.go +++ b/x/crosschain/module_simulation.go @@ -3,26 +3,12 @@ package crosschain import ( "math/rand" - "github.com/cosmos/cosmos-sdk/baseapp" - simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/simulation" - "github.com/zeta-chain/zetacore/testutil/sample" - crosschainsimulation "github.com/zeta-chain/zetacore/x/crosschain/simulation" "github.com/zeta-chain/zetacore/x/crosschain/types" ) -// avoid unused import issue -var ( - _ = sample.AccAddress - _ = crosschainsimulation.FindAccount - _ = simappparams.StakePerAccount - _ = simulation.MsgEntryKind - _ = baseapp.Paramspace -) - const ( // this line is used by starport scaffolding # simapp/module/const ) diff --git a/x/crosschain/types/codec.go b/x/crosschain/types/codec.go index 94b63b67f0..1dbd981cfd 100644 --- a/x/crosschain/types/codec.go +++ b/x/crosschain/types/codec.go @@ -23,27 +23,12 @@ func RegisterCodec(cdc *codec.LegacyAmino) { func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { registry.RegisterImplementations((*sdk.Msg)(nil), &MsgAddToOutTxTracker{}, - ) - registry.RegisterImplementations((*sdk.Msg)(nil), &MsgRemoveFromOutTxTracker{}, - ) - registry.RegisterImplementations((*sdk.Msg)(nil), &MsgCreateTSSVoter{}, - ) - - registry.RegisterImplementations((*sdk.Msg)(nil), &MsgGasPriceVoter{}, - ) - registry.RegisterImplementations((*sdk.Msg)(nil), &MsgNonceVoter{}, - ) - registry.RegisterImplementations((*sdk.Msg)(nil), &MsgVoteOnObservedOutboundTx{}, - ) - registry.RegisterImplementations((*sdk.Msg)(nil), &MsgVoteOnObservedInboundTx{}, - ) - registry.RegisterImplementations((*sdk.Msg)(nil), &MsgSetNodeKeys{}, ) diff --git a/x/crosschain/types/key_in_tx_hash_to_cctx.go b/x/crosschain/types/key_in_tx_hash_to_cctx.go index b5366e1294..43f0bf8a33 100644 --- a/x/crosschain/types/key_in_tx_hash_to_cctx.go +++ b/x/crosschain/types/key_in_tx_hash_to_cctx.go @@ -1,9 +1,5 @@ package types -import "encoding/binary" - -var _ binary.ByteOrder - const ( // InTxHashToCctxKeyPrefix is the prefix to retrieve all InTxHashToCctx InTxHashToCctxKeyPrefix = "InTxHashToCctx/value/" diff --git a/x/emissions/client/cli/query.go b/x/emissions/client/cli/query.go index 771307efd7..efd2cfad5c 100644 --- a/x/emissions/client/cli/query.go +++ b/x/emissions/client/cli/query.go @@ -24,8 +24,10 @@ func GetQueryCmd(queryRoute string) *cobra.Command { RunE: client.ValidateCmd, } - cmd.AddCommand(CmdQueryParams()) - cmd.AddCommand(CmdListPoolAddresses()) + cmd.AddCommand( + CmdQueryParams(), + CmdListPoolAddresses(), + ) // this line is used by starport scaffolding # 1 diff --git a/x/emissions/client/cli/query_list_balances.go b/x/emissions/client/cli/query_list_balances.go index ccb9efaed4..c20ca85500 100644 --- a/x/emissions/client/cli/query_list_balances.go +++ b/x/emissions/client/cli/query_list_balances.go @@ -1,16 +1,12 @@ package cli import ( - "strconv" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" "github.com/zeta-chain/zetacore/x/emissions/types" ) -var _ = strconv.Itoa(0) - func CmdListPoolAddresses() *cobra.Command { cmd := &cobra.Command{ Use: "list-pool-addresses", diff --git a/x/fungible/client/cli/query.go b/x/fungible/client/cli/query.go index fb7dc6c9f9..0a0ce40cd0 100644 --- a/x/fungible/client/cli/query.go +++ b/x/fungible/client/cli/query.go @@ -24,9 +24,11 @@ func GetQueryCmd(queryRoute string) *cobra.Command { RunE: client.ValidateCmd, } - cmd.AddCommand(CmdQueryParams()) - cmd.AddCommand(CmdListForeignCoins()) - cmd.AddCommand(CmdShowForeignCoins()) + cmd.AddCommand( + CmdQueryParams(), + CmdListForeignCoins(), + CmdShowForeignCoins(), + ) // this line is used by starport scaffolding # 1 return cmd diff --git a/x/fungible/client/cli/tx.go b/x/fungible/client/cli/tx.go index df32f4d9bb..827ec0851e 100644 --- a/x/fungible/client/cli/tx.go +++ b/x/fungible/client/cli/tx.go @@ -2,19 +2,13 @@ package cli import ( "fmt" - "time" - - "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" + "github.com/spf13/cobra" // "github.com/cosmos/cosmos-sdk/client/flags" "github.com/zeta-chain/zetacore/x/fungible/types" ) -var ( - DefaultRelativePacketTimeoutTimestamp = uint64((time.Duration(10) * time.Minute).Nanoseconds()) -) - // GetTxCmd returns the transaction commands for this module func GetTxCmd() *cobra.Command { cmd := &cobra.Command{ @@ -25,8 +19,10 @@ func GetTxCmd() *cobra.Command { RunE: client.ValidateCmd, } - cmd.AddCommand(CmdDeployFungibleCoinZRC4()) - cmd.AddCommand(CmdRemoveForeignCoin()) + cmd.AddCommand( + CmdDeployFungibleCoinZRC4(), + CmdRemoveForeignCoin(), + ) // this line is used by starport scaffolding # 1 return cmd 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 3d5557e052..f4bf1696c2 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 @@ -13,8 +13,6 @@ import ( "github.com/zeta-chain/zetacore/x/fungible/types" ) -var _ = strconv.Itoa(0) - func CmdDeployFungibleCoinZRC4() *cobra.Command { cmd := &cobra.Command{ Use: "deploy-fungible-coin-zrc-4 [erc-20] [foreign-chain] [decimals] [name] [symbol] [coin-type] [gas-limit]", diff --git a/x/fungible/client/cli/tx_remove_foreign_coin.go b/x/fungible/client/cli/tx_remove_foreign_coin.go index b5b891297d..00c6a32352 100644 --- a/x/fungible/client/cli/tx_remove_foreign_coin.go +++ b/x/fungible/client/cli/tx_remove_foreign_coin.go @@ -1,8 +1,6 @@ package cli import ( - "strconv" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" @@ -10,8 +8,6 @@ import ( "github.com/zeta-chain/zetacore/x/fungible/types" ) -var _ = strconv.Itoa(0) - func CmdRemoveForeignCoin() *cobra.Command { cmd := &cobra.Command{ Use: "remove-foreign-coin [name]", diff --git a/x/fungible/module_simulation.go b/x/fungible/module_simulation.go index bea5ddd952..b757c60a6b 100644 --- a/x/fungible/module_simulation.go +++ b/x/fungible/module_simulation.go @@ -3,26 +3,12 @@ package fungible import ( "math/rand" - "github.com/cosmos/cosmos-sdk/baseapp" - simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/simulation" - "github.com/zeta-chain/zetacore/testutil/sample" - fungiblesimulation "github.com/zeta-chain/zetacore/x/fungible/simulation" "github.com/zeta-chain/zetacore/x/fungible/types" ) -// avoid unused import issue -var ( - _ = sample.AccAddress - _ = fungiblesimulation.FindAccount - _ = simappparams.StakePerAccount - _ = simulation.MsgEntryKind - _ = baseapp.Paramspace -) - const ( // this line is used by starport scaffolding # simapp/module/const ) diff --git a/x/fungible/types/codec.go b/x/fungible/types/codec.go index 87a1573de0..8343265cbb 100644 --- a/x/fungible/types/codec.go +++ b/x/fungible/types/codec.go @@ -14,14 +14,11 @@ func RegisterCodec(cdc *codec.LegacyAmino) { } func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), &MsgDeployFungibleCoinZRC20{}, - ) - - registry.RegisterImplementations((*sdk.Msg)(nil), &MsgRemoveForeignCoin{}, ) + // this line is used by starport scaffolding # 3 msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) diff --git a/x/fungible/types/key_foreign_coins.go b/x/fungible/types/key_foreign_coins.go index 395b529ef1..fc13f38486 100644 --- a/x/fungible/types/key_foreign_coins.go +++ b/x/fungible/types/key_foreign_coins.go @@ -1,9 +1,5 @@ package types -import "encoding/binary" - -var _ binary.ByteOrder - const ( // ForeignCoinsKeyPrefix is the prefix to retrieve all ForeignCoins ForeignCoinsKeyPrefix = "ForeignCoins/value/" diff --git a/x/observer/client/cli/query.go b/x/observer/client/cli/query.go index 8d58e79802..d67a0be176 100644 --- a/x/observer/client/cli/query.go +++ b/x/observer/client/cli/query.go @@ -24,24 +24,22 @@ func GetQueryCmd(queryRoute string) *cobra.Command { RunE: client.ValidateCmd, } - cmd.AddCommand(CmdQueryParams()) - cmd.AddCommand(CmdBallotByIdentifier()) - - cmd.AddCommand(CmdObserversByChainAndType()) - cmd.AddCommand(CmdAllObserverMappers()) - cmd.AddCommand(CmdGetSupportedChains()) - - cmd.AddCommand(CmdGetCoreParamsForChain()) - - cmd.AddCommand(CmdGetCoreParams()) - cmd.AddCommand(CmdListNodeAccount()) - cmd.AddCommand(CmdShowNodeAccount()) - cmd.AddCommand(CmdShowPermissionFlags()) - cmd.AddCommand(CmdShowKeygen()) - - cmd.AddCommand(CmdShowObserverCount()) - cmd.AddCommand(CmdBlameByIdentifier()) - cmd.AddCommand(CmdGetAllBlameRecords()) + cmd.AddCommand( + CmdQueryParams(), + CmdBallotByIdentifier(), + CmdObserversByChainAndType(), + CmdAllObserverMappers(), + CmdGetSupportedChains(), + CmdGetCoreParamsForChain(), + CmdGetCoreParams(), + CmdListNodeAccount(), + CmdShowNodeAccount(), + CmdShowPermissionFlags(), + CmdShowKeygen(), + CmdShowObserverCount(), + CmdBlameByIdentifier(), + CmdGetAllBlameRecords(), + ) // this line is used by starport scaffolding # 1 diff --git a/x/observer/client/cli/query_ballot.go b/x/observer/client/cli/query_ballot.go index 72468e7759..a686736b61 100644 --- a/x/observer/client/cli/query_ballot.go +++ b/x/observer/client/cli/query_ballot.go @@ -1,16 +1,12 @@ package cli import ( - "strconv" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" "github.com/zeta-chain/zetacore/x/observer/types" ) -var _ = strconv.Itoa(0) - func CmdBallotByIdentifier() *cobra.Command { cmd := &cobra.Command{ Use: "show-ballot [ballot-identifier]", diff --git a/x/observer/client/cli/query_blame.go b/x/observer/client/cli/query_blame.go index 39ec0e1be8..aee13732b4 100644 --- a/x/observer/client/cli/query_blame.go +++ b/x/observer/client/cli/query_blame.go @@ -5,11 +5,8 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" "github.com/zeta-chain/zetacore/x/observer/types" - "strconv" ) -var _ = strconv.Itoa(0) - func CmdBlameByIdentifier() *cobra.Command { cmd := &cobra.Command{ Use: "show-blame [blame-identifier]", diff --git a/x/observer/client/cli/query_core_params.go b/x/observer/client/cli/query_core_params.go index 0534ab5579..cf64eb7d6a 100644 --- a/x/observer/client/cli/query_core_params.go +++ b/x/observer/client/cli/query_core_params.go @@ -9,8 +9,6 @@ import ( "github.com/zeta-chain/zetacore/x/observer/types" ) -var _ = strconv.Itoa(0) - func CmdGetCoreParamsForChain() *cobra.Command { cmd := &cobra.Command{ Use: "show-core-params [chain-id]", diff --git a/x/observer/client/cli/query_observers.go b/x/observer/client/cli/query_observers.go index 013b761559..edca162189 100644 --- a/x/observer/client/cli/query_observers.go +++ b/x/observer/client/cli/query_observers.go @@ -1,16 +1,12 @@ package cli import ( - "strconv" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" "github.com/zeta-chain/zetacore/x/observer/types" ) -var _ = strconv.Itoa(0) - func CmdAllObserverMappers() *cobra.Command { cmd := &cobra.Command{ Use: "list-observer", diff --git a/x/observer/client/cli/query_show_observer_count.go b/x/observer/client/cli/query_show_observer_count.go index afa714943f..84ad22dde1 100644 --- a/x/observer/client/cli/query_show_observer_count.go +++ b/x/observer/client/cli/query_show_observer_count.go @@ -1,16 +1,12 @@ package cli import ( - "strconv" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/spf13/cobra" "github.com/zeta-chain/zetacore/x/observer/types" ) -var _ = strconv.Itoa(0) - func CmdShowObserverCount() *cobra.Command { cmd := &cobra.Command{ Use: "show-observer-count", diff --git a/x/observer/client/cli/tx.go b/x/observer/client/cli/tx.go index ca8a05ff66..f81743030b 100644 --- a/x/observer/client/cli/tx.go +++ b/x/observer/client/cli/tx.go @@ -17,14 +17,17 @@ func GetTxCmd() *cobra.Command { SuggestionsMinimumDistance: 2, RunE: client.ValidateCmd, } - //cmd.AddCommand(CmdSetSupportedChains()) - //cmd.AddCommand(CmdAddObserver()) - cmd.AddCommand(CmdUpdateCoreParams()) - cmd.AddCommand(CmdUpdatePermissionFlags()) - cmd.AddCommand(CmdUpdateKeygen()) - cmd.AddCommand(CmdAddBlameVote()) - cmd.AddCommand(CmdEncode()) + cmd.AddCommand( + //CmdSetSupportedChains(), + //CmdAddObserver(), + CmdUpdateCoreParams(), + CmdUpdatePermissionFlags(), + CmdUpdateKeygen(), + CmdAddBlameVote(), + CmdEncode(), + ) + // this line is used by starport scaffolding # 1 return cmd diff --git a/x/observer/client/cli/tx_add_blame_vote.go b/x/observer/client/cli/tx_add_blame_vote.go index 74d62ce5d6..e9597d26f0 100644 --- a/x/observer/client/cli/tx_add_blame_vote.go +++ b/x/observer/client/cli/tx_add_blame_vote.go @@ -4,19 +4,18 @@ import ( "encoding/hex" "encoding/json" "fmt" + "os" + "path/filepath" + "strconv" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" "github.com/zeta-chain/zetacore/x/observer/types" "gitlab.com/thorchain/tss/go-tss/blame" - "os" - "path/filepath" - "strconv" ) -var _ = strconv.Itoa(0) - func CmdAddBlameVote() *cobra.Command { cmd := &cobra.Command{ Use: "add-blame-vote [chain-id] [index] [failure-reason] [node-list]", diff --git a/x/observer/client/cli/tx_add_observer.go b/x/observer/client/cli/tx_add_observer.go index f6ded60a8a..b4bf059352 100644 --- a/x/observer/client/cli/tx_add_observer.go +++ b/x/observer/client/cli/tx_add_observer.go @@ -10,8 +10,6 @@ import ( "github.com/zeta-chain/zetacore/x/observer/types" ) -var _ = strconv.Itoa(0) - func CmdAddObserver() *cobra.Command { cmd := &cobra.Command{ Use: "add-observer [observer-chain-id] [observation-type]", diff --git a/x/observer/client/cli/tx_update_core_params.go b/x/observer/client/cli/tx_update_core_params.go index efc4f849b2..e506edeec9 100644 --- a/x/observer/client/cli/tx_update_core_params.go +++ b/x/observer/client/cli/tx_update_core_params.go @@ -4,7 +4,6 @@ import ( "encoding/json" "os" "path/filepath" - "strconv" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" @@ -13,8 +12,6 @@ import ( "github.com/zeta-chain/zetacore/x/observer/types" ) -var _ = strconv.Itoa(0) - func CmdUpdateCoreParams() *cobra.Command { cmd := &cobra.Command{ Use: "update-client-params [chain-id] [client-params.json]", diff --git a/x/observer/client/cli/tx_update_keygen.go b/x/observer/client/cli/tx_update_keygen.go index 3c9408d0d7..776389369c 100644 --- a/x/observer/client/cli/tx_update_keygen.go +++ b/x/observer/client/cli/tx_update_keygen.go @@ -1,17 +1,15 @@ package cli import ( - "github.com/zeta-chain/zetacore/x/observer/types" "strconv" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" "github.com/spf13/cobra" + "github.com/zeta-chain/zetacore/x/observer/types" ) -var _ = strconv.Itoa(0) - func CmdUpdateKeygen() *cobra.Command { cmd := &cobra.Command{ Use: "update-keygen [block]", diff --git a/x/observer/module_simulation.go b/x/observer/module_simulation.go index 6be931e2ec..6ee008cb23 100644 --- a/x/observer/module_simulation.go +++ b/x/observer/module_simulation.go @@ -3,26 +3,12 @@ package observer import ( "math/rand" - "github.com/cosmos/cosmos-sdk/baseapp" - simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/simulation" - "github.com/zeta-chain/zetacore/testutil/sample" - observersimulation "github.com/zeta-chain/zetacore/x/observer/simulation" "github.com/zeta-chain/zetacore/x/observer/types" ) -// avoid unused import issue -var ( - _ = sample.AccAddress - _ = observersimulation.FindAccount - _ = simappparams.StakePerAccount - _ = simulation.MsgEntryKind - _ = baseapp.Paramspace -) - /* #nosec */ const ( opWeightMsgUpdateClientParams = "op_weight_msg_update_client_params" diff --git a/x/observer/types/codec.go b/x/observer/types/codec.go index 81572dfc9d..7fe3c684dd 100644 --- a/x/observer/types/codec.go +++ b/x/observer/types/codec.go @@ -17,11 +17,7 @@ func RegisterCodec(cdc *codec.LegacyAmino) { func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { registry.RegisterImplementations((*sdk.Msg)(nil), &MsgUpdateCoreParams{}, - ) - registry.RegisterImplementations((*sdk.Msg)(nil), &MsgUpdatePermissionFlags{}, - ) - registry.RegisterImplementations((*sdk.Msg)(nil), &MsgUpdateKeygen{}, ) // this line is used by starport scaffolding # 3 From 31cb19492c2a48e00024ffc91de9a18dfecba184 Mon Sep 17 00:00:00 2001 From: Tanmay Date: Tue, 1 Aug 2023 12:02:17 -0400 Subject: [PATCH 2/5] set CCTX inbound finalized height irrespective of receiver chain (#886) --- x/crosschain/keeper/keeper_cross_chain_tx_vote_inbound_tx.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 8b3a35f38c..c0eef13893 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 @@ -88,6 +88,7 @@ func (k msgServer) VoteOnObservedInboundTx(goCtx context.Context, msg *types.Msg cctx := k.CreateNewCCTX(ctx, msg, index, types.CctxStatus_PendingInbound, observationChain, receiverChain) defer func() { EmitEventInboundFinalized(ctx, &cctx) + cctx.InboundTxParams.InboundTxFinalizedZetaHeight = uint64(ctx.BlockHeight()) k.SetCctxAndNonceToCctxAndInTxHashToCctx(ctx, cctx) }() // FinalizeInbound updates CCTX Prices and Nonce @@ -134,7 +135,6 @@ func (k msgServer) VoteOnObservedInboundTx(goCtx context.Context, msg *types.Msg } else { // Cross Chain SWAP tmpCtx, commit := ctx.CacheContext() err = func() error { - cctx.InboundTxParams.InboundTxFinalizedZetaHeight = uint64(ctx.BlockHeader().Height) err := k.PayGasInZetaAndUpdateCctx(tmpCtx, receiverChain.ChainId, &cctx) if err != nil { return err From 17524f19b3039450594d672b5480c5b9a345be63 Mon Sep 17 00:00:00 2001 From: Tanmay Date: Tue, 1 Aug 2023 13:39:30 -0400 Subject: [PATCH 3/5] SetLastObserverCount during genesis (#885) --- x/observer/genesis.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/x/observer/genesis.go b/x/observer/genesis.go index 1f5ffe2b4a..d4b3717ad3 100644 --- a/x/observer/genesis.go +++ b/x/observer/genesis.go @@ -11,8 +11,10 @@ import ( func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) { genesisObservers := genState.Observers types.VerifyObserverMapper(genesisObservers) + observerCount := uint64(0) for _, mapper := range genesisObservers { k.SetObserverMapper(ctx, mapper) + observerCount += uint64(len(mapper.ObserverList)) } k.SetCoreParams(ctx, types.GetCoreParams()) // Set all the nodeAccount @@ -30,6 +32,10 @@ func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) if genState.Keygen != nil { k.SetKeygen(ctx, *genState.Keygen) } + k.SetLastObserverCount(ctx, &types.LastObserverCount{ + Count: observerCount, + LastChangeHeight: 0, + }) } From 723616cb6c3b4a4aaebb1d5277743d1840ada7f0 Mon Sep 17 00:00:00 2001 From: Charlie Chen <34498985+ws4charlie@users.noreply.github.com> Date: Tue, 1 Aug 2023 13:52:32 -0500 Subject: [PATCH 4/5] feat: enable nonce-mark UTXO check and outTx Vin check (#847) * enable nonce-mark UTXO check and outTx Vin check * enable txID check * repurposed the nextNonce variable and some cleanup work * fixed unit test * give a better variable name nextTxNonce2Broadcast * added a bit more function doc * replaced require.Equal with require.Zero in tests * move all Vin checks to a same function --------- Co-authored-by: charliec --- zetaclient/bitcoin_client.go | 177 ++++++++++++++++++++++++---------- zetaclient/btc_signer.go | 35 +++---- zetaclient/btc_signer_test.go | 50 +++++----- 3 files changed, 164 insertions(+), 98 deletions(-) diff --git a/zetaclient/bitcoin_client.go b/zetaclient/bitcoin_client.go index a109c84933..3aae8a8ac2 100644 --- a/zetaclient/bitcoin_client.go +++ b/zetaclient/bitcoin_client.go @@ -46,22 +46,22 @@ type BTCLog struct { type BitcoinChainClient struct { *ChainMetrics - chain common.Chain - rpcClient *rpcclient.Client - zetaClient *ZetaCoreBridge - Tss TSSSigner - lastBlock int64 - BlockTime uint64 // block time in seconds - minedTx map[string]btcjson.GetTransactionResult // key: chain-nonce - broadcastedTx map[string]chainhash.Hash - nextNonce int - mu *sync.Mutex - utxos []btcjson.ListUnspentResult - db *gorm.DB - stop chan struct{} - logger BTCLog - cfg *config.Config - ts *TelemetryServer + chain common.Chain + rpcClient *rpcclient.Client + zetaClient *ZetaCoreBridge + Tss TSSSigner + lastBlock int64 + BlockTime uint64 // block time in seconds + includedTx map[string]btcjson.GetTransactionResult // key: chain-nonce + broadcastedTx map[string]chainhash.Hash + nextTxNonce2Broadcast int + mu *sync.Mutex + utxos []btcjson.ListUnspentResult + db *gorm.DB + stop chan struct{} + logger BTCLog + cfg *config.Config + ts *TelemetryServer } const ( @@ -103,7 +103,7 @@ func NewBitcoinClient(chain common.Chain, bridge *ZetaCoreBridge, tss TSSSigner, ob.zetaClient = bridge ob.Tss = tss - ob.minedTx = make(map[string]btcjson.GetTransactionResult) + ob.includedTx = make(map[string]btcjson.GetTransactionResult) ob.broadcastedTx = make(map[string]chainhash.Hash) // initialize the Client @@ -132,8 +132,8 @@ func NewBitcoinClient(chain common.Chain, bridge *ZetaCoreBridge, tss TSSSigner, return nil, err } - //Set Next Nonce - err = ob.SetNextNonce() + //Set Next Nonce for broadcasted tx + err = ob.SetNextNonceBroadcast() if err != nil { return nil, err } @@ -304,10 +304,10 @@ func (ob *BitcoinChainClient) IsSendOutTxProcessed(sendHash string, nonce int, _ ob.mu.Lock() txnHash, broadcasted := ob.broadcastedTx[outTxID] - res, mined := ob.minedTx[outTxID] + res, included := ob.includedTx[outTxID] ob.mu.Unlock() - if !mined { + if !included { if !broadcasted { return false, false, nil } @@ -325,7 +325,7 @@ func (ob *BitcoinChainClient) IsSendOutTxProcessed(sendHash string, nonce int, _ // Save result to avoid unnecessary query ob.mu.Lock() - ob.minedTx[outTxID] = res + ob.includedTx[outTxID] = res ob.mu.Unlock() } var amount float64 @@ -354,11 +354,6 @@ func (ob *BitcoinChainClient) IsSendOutTxProcessed(sendHash string, nonce int, _ logger.Error().Err(err).Msgf("error posting to zeta core") } else { logger.Info().Msgf("Bitcoin outTx confirmed: PostReceiveConfirmation zeta tx: %s", zetaHash) - - ob.mu.Lock() - ob.nextNonce++ - ob.ts.SetNextNonce(ob.nextNonce) - ob.mu.Unlock() } return true, true, nil } @@ -591,12 +586,11 @@ func (ob *BitcoinChainClient) fetchUTXOS() error { } func (ob *BitcoinChainClient) findNonceMarkUTXO(nonce uint64, tssAddress string) (int, error) { - // TODO: uncomment below checking after bootstrap - // outTxID := ob.GetTxID(nonce) - // _, mined := ob.minedTx[outTxID] - // if !mined { - // return -1, fmt.Errorf("findNonceMarkUTXO: transaction %s not mined yet", outTxID) - // } + outTxID := ob.GetTxID(nonce) + res, mined := ob.includedTx[outTxID] + if !mined { + return -1, fmt.Errorf("findNonceMarkUTXO: outTx %s not included yet", outTxID) + } amount := NonceMarkAmount(nonce) for i, utxo := range ob.utxos { @@ -604,8 +598,7 @@ func (ob *BitcoinChainClient) findNonceMarkUTXO(nonce uint64, tssAddress string) if err != nil { ob.logger.ObserveOutTx.Error().Err(err).Msgf("findNonceMarkUTXO: error getting satoshis for utxo %v", utxo) } - // TODO: uncomment txid check after bootstrap (manually send 0.00002 BTC tss address) - if utxo.Address == tssAddress && sats == amount /*&& utxo.TxID == res.TxID*/ { + if utxo.Address == tssAddress && sats == amount && utxo.TxID == res.TxID { ob.logger.ObserveOutTx.Info().Msgf("findNonceMarkUTXO: found nonce-mark utxo with txid %s, amount %v", utxo.TxID, utxo.Amount) return i, nil } @@ -630,11 +623,10 @@ func (ob *BitcoinChainClient) SelectUTXOs(amount float64, utxoCap uint8, nonce u // for nonce = 0; make exception; no need to include nonce-mark utxo idx := -1 if nonce > 0 { - index, _ := ob.findNonceMarkUTXO(nonce-1, tssAddress) - // TODO: uncomment below checking after bootstrap - // if err != nil { - // return nil, 0, err - // } + index, err := ob.findNonceMarkUTXO(nonce-1, tssAddress) + if err != nil { + return nil, 0, err + } idx = index } @@ -672,6 +664,21 @@ func (ob *BitcoinChainClient) SelectUTXOs(amount float64, utxoCap uint8, nonce u return results, total, nil } +// Save successfully broadcasted transaction +func (ob *BitcoinChainClient) SaveBroadcastedTx(txHash chainhash.Hash, nonce uint64) { + outTxID := ob.GetTxID(nonce) + ob.mu.Lock() + ob.broadcastedTx[outTxID] = txHash + ob.nextTxNonce2Broadcast++ + ob.ts.SetNextNonce(ob.nextTxNonce2Broadcast) + ob.mu.Unlock() + + broadcastEntry := clienttypes.ToTransactionHashSQLType(txHash, outTxID) + if err := ob.db.Create(&broadcastEntry).Error; err != nil { + ob.logger.ObserveOutTx.Error().Err(err).Msg("observeOutTx: error saving broadcasted tx") + } +} + func (ob *BitcoinChainClient) observeOutTx() { ticker := time.NewTicker(time.Duration(ob.GetChainConfig().CoreParams.OutTxTicker) * time.Second) for { @@ -691,19 +698,28 @@ func (ob *BitcoinChainClient) observeOutTx() { ob.logger.ObserveOutTx.Error().Err(err).Msg("error NewHashFromStr") continue } + // The Bitcoin node has to be configured to watch TSS address getTxResult, err := ob.rpcClient.GetTransaction(hash) if err != nil { - ob.logger.ObserveOutTx.Warn().Err(err).Msg("error GetTransaction") + ob.logger.ObserveOutTx.Warn().Err(err).Msgf("error GetTransaction: %s", txHash.TxHash) + continue + } + // Check TSS outTx + err = ob.checkTssOutTxResult(hash, getTxResult) + if err != nil { + ob.logger.ObserveOutTx.Warn().Err(err).Msgf("error checkTssOutTxResult: %s", txHash.TxHash) continue } + ob.logger.ObserveOutTx.Info().Msgf("outTx %s has passed checkTssOutTxResult", txHash.TxHash) if getTxResult.Confirmations >= 0 { ob.mu.Lock() - ob.minedTx[outTxID] = *getTxResult + ob.includedTx[outTxID] = *getTxResult ob.mu.Unlock() //Save to db tx, err := clienttypes.ToTransactionResultSQLType(*getTxResult, outTxID) if err != nil { + ob.logger.ObserveOutTx.Error().Err(err).Msg("observeOutTx: error converting to TransactionResultSQLType") continue } if err := ob.db.Create(&tx).Error; err != nil { @@ -719,7 +735,59 @@ func (ob *BitcoinChainClient) observeOutTx() { } } -func (ob *BitcoinChainClient) BuildSubmittedTxMap() error { +// Basic TSS outTX checks: +// - locate the raw tx and find the Vin +// - check if all inputs are segwit && TSS inputs +// +// Returns: true if outTx passes basic checks. +func (ob *BitcoinChainClient) checkTssOutTxResult(hash *chainhash.Hash, res *btcjson.GetTransactionResult) error { + if res.Confirmations == 0 { + rawtx, err := ob.rpcClient.GetRawTransactionVerbose(hash) // for pending tx, we query the raw tx + if err != nil { + return errors.Wrapf(err, "checkTssOutTxResult: error GetRawTransactionVerbose %s", res.TxID) + } + if !ob.isValidTSSVin(rawtx.Vin) { + return errors.Wrapf(err, "checkTssOutTxResult: invalid outTx with non-TSS vin %s", res.TxID) + } + } else if res.Confirmations > 0 { + blkHash, err := chainhash.NewHashFromStr(res.BlockHash) + if err != nil { + return errors.Wrapf(err, "checkTssOutTxResult: error NewHashFromStr %s", res.BlockHash) + } + block, err := ob.rpcClient.GetBlockVerboseTx(blkHash) // for confirmed tx, we query the block + if err != nil { + return errors.Wrapf(err, "checkTssOutTxResult: error GetBlockVerboseTx %s", res.BlockHash) + } + if res.BlockIndex < 0 || res.BlockIndex >= int64(len(block.Tx)) { + return errors.Wrapf(err, "checkTssOutTxResult: invalid outTx with invalid block index, TxID %s, BlockIndex %d", res.TxID, res.BlockIndex) + } + tx := block.Tx[res.BlockIndex] + if !ob.isValidTSSVin(tx.Vin) { + return errors.Wrapf(err, "checkTssOutTxResult: invalid outTx with non-TSS vin %s", res.TxID) + } + } + return nil // ignore res.Confirmations < 0 (meaning not included) +} + +// Returns true only if all inputs are TSS vins +func (ob *BitcoinChainClient) isValidTSSVin(vins []btcjson.Vin) bool { + if len(vins) == 0 { + return false + } + pubKeyTss := hex.EncodeToString(ob.Tss.PubKeyCompressedBytes()) + for _, vin := range vins { + // The length of the Witness should be always 2 for P2WPKH SegWit inputs. + if len(vin.Witness) != 2 { + return false + } + if vin.Witness[1] != pubKeyTss { + return false + } + } + return true +} + +func (ob *BitcoinChainClient) BuildIncludedTxMap() error { var submittedTransactions []clienttypes.TransactionResultSQLType if err := ob.db.Find(&submittedTransactions).Error; err != nil { ob.logger.ChainLogger.Error().Err(err).Msg("error iterating over db") @@ -730,7 +798,7 @@ func (ob *BitcoinChainClient) BuildSubmittedTxMap() error { if err != nil { return err } - ob.minedTx[txResult.Key] = r + ob.includedTx[txResult.Key] = r } return nil } @@ -747,7 +815,7 @@ func (ob *BitcoinChainClient) BuildBroadcastedTxMap() error { return nil } -func (ob *BitcoinChainClient) SetNextNonce() error { +func (ob *BitcoinChainClient) SetNextNonceBroadcast() error { nonces, err := ob.zetaClient.GetPendingNonces() if err != nil { return err @@ -763,13 +831,22 @@ func (ob *BitcoinChainClient) SetNextNonce() error { continue } if ob.chain.ChainId == nonce.ChainId && bytes.Equal(tssKey.PubkeyInBytes, ob.Tss.Pubkey()) { - ob.nextNonce = int(nonce.NonceLow) - ob.ts.SetNextNonce(ob.nextNonce) + // find lowest nonce that had not been broadcasted + next2Broadcast := int(nonce.NonceLow) + for nc := nonce.NonceLow; nc < nonce.NonceHigh; nc++ { + if _, exist := ob.broadcastedTx[ob.GetTxID(uint64(nc))]; exist { + next2Broadcast++ + continue + } + break + } + ob.nextTxNonce2Broadcast = next2Broadcast + ob.ts.SetNextNonce(ob.nextTxNonce2Broadcast) found = true } } if !found { - return fmt.Errorf("initial nonce for Chain ID: %d not found", ob.chain.ChainId) + ob.logger.ChainLogger.Error().Msgf("initial nonce for Chain ID: %d not found", ob.chain.ChainId) } return nil @@ -825,8 +902,8 @@ func (ob *BitcoinChainClient) loadDB(dbpath string) error { return err } - //Load submitted transactions - err = ob.BuildSubmittedTxMap() + //Load included transactions + err = ob.BuildIncludedTxMap() if err != nil { return err } diff --git a/zetaclient/btc_signer.go b/zetaclient/btc_signer.go index 78d78429a3..4c2afbcd90 100644 --- a/zetaclient/btc_signer.go +++ b/zetaclient/btc_signer.go @@ -19,7 +19,6 @@ import ( "github.com/zeta-chain/zetacore/x/crosschain/types" zetaObserverModuleTypes "github.com/zeta-chain/zetacore/x/observer/types" "github.com/zeta-chain/zetacore/zetaclient/config" - clienttypes "github.com/zeta-chain/zetacore/zetaclient/types" ) const ( @@ -138,7 +137,6 @@ func (signer *BTCSigner) SignWithdrawTx(to *btcutil.AddressWitnessPubKeyHash, am if err != nil { return nil, err } - } tss, ok := signer.tssSigner.(*TSS) if !ok { @@ -157,9 +155,6 @@ func (signer *BTCSigner) SignWithdrawTx(to *btcutil.AddressWitnessPubKeyHash, am R: R, S: S, } - if err != nil { - return nil, err - } pkCompressed := signer.tssSigner.PubKeyCompressedBytes() hashType := txscript.SigHashAll @@ -215,7 +210,8 @@ func (signer *BTCSigner) TryProcessOutTx(send *types.CrossChainTx, outTxMan *Out myid := zetaBridge.keys.GetAddress() // Early return if the send is already processed // FIXME: handle revert case - included, confirmed, _ := btcClient.IsSendOutTxProcessed(send.Index, int(send.GetCurrentOutTxParam().OutboundTxTssNonce), common.CoinType_Gas, logger) + outboundTxTssNonce := send.GetCurrentOutTxParam().OutboundTxTssNonce + included, confirmed, _ := btcClient.IsSendOutTxProcessed(send.Index, int(outboundTxTssNonce), common.CoinType_Gas, logger) if included || confirmed { logger.Info().Msgf("CCTX already processed; exit signer") return @@ -241,20 +237,20 @@ func (signer *BTCSigner) TryProcessOutTx(send *types.CrossChainTx, outTxMan *Out logger.Info().Msgf("SignWithdrawTx: to %s, value %d sats", addr.EncodeAddress(), send.GetCurrentOutTxParam().Amount.Uint64()) logger.Info().Msgf("using utxos: %v", btcClient.utxos) - tx, err := signer.SignWithdrawTx(to, float64(send.GetCurrentOutTxParam().Amount.Uint64())/1e8, gasprice, btcClient, height, send.GetCurrentOutTxParam().OutboundTxTssNonce, &btcClient.chain) + tx, err := signer.SignWithdrawTx(to, float64(send.GetCurrentOutTxParam().Amount.Uint64())/1e8, gasprice, btcClient, height, outboundTxTssNonce, &btcClient.chain) if err != nil { - logger.Warn().Err(err).Msgf("SignOutboundTx error: nonce %d chain %d", send.GetCurrentOutTxParam().OutboundTxTssNonce, send.GetCurrentOutTxParam().ReceiverChainId) + logger.Warn().Err(err).Msgf("SignOutboundTx error: nonce %d chain %d", outboundTxTssNonce, send.GetCurrentOutTxParam().ReceiverChainId) return } - logger.Info().Msgf("Key-sign success: %d => %s, nonce %d", send.InboundTxParams.SenderChainId, btcClient.chain.ChainName, send.GetCurrentOutTxParam().OutboundTxTssNonce) + logger.Info().Msgf("Key-sign success: %d => %s, nonce %d", send.InboundTxParams.SenderChainId, btcClient.chain.ChainName, outboundTxTssNonce) // FIXME: add prometheus metrics _, err = zetaBridge.GetObserverList(btcClient.chain) if err != nil { - logger.Warn().Err(err).Msgf("unable to get observer list: chain %d observation %s", send.GetCurrentOutTxParam().OutboundTxTssNonce, zetaObserverModuleTypes.ObservationType_OutBoundTx.String()) + logger.Warn().Err(err).Msgf("unable to get observer list: chain %d observation %s", outboundTxTssNonce, zetaObserverModuleTypes.ObservationType_OutBoundTx.String()) } if tx != nil { outTxHash := tx.TxHash().String() - logger.Info().Msgf("on chain %s nonce %d, outTxHash %s signer %s", btcClient.chain.ChainName, send.GetCurrentOutTxParam().OutboundTxTssNonce, outTxHash, myid) + logger.Info().Msgf("on chain %s nonce %d, outTxHash %s signer %s", btcClient.chain.ChainName, outboundTxTssNonce, outTxHash, myid) // TODO: pick a few broadcasters. //if len(signers) == 0 || myid == signers[send.OutboundTxParams.Broadcaster] || myid == signers[int(send.OutboundTxParams.Broadcaster+1)%len(signers)] { // retry loop: 1s, 2s, 4s, 8s, 16s in case of RPC error @@ -263,25 +259,18 @@ func (signer *BTCSigner) TryProcessOutTx(send *types.CrossChainTx, outTxMan *Out time.Sleep(time.Duration(rand.Intn(1500)) * time.Millisecond) //random delay to avoid sychronized broadcast err := signer.Broadcast(tx) if err != nil { - logger.Warn().Err(err).Msgf("broadcasting tx %s to chain %s: nonce %d, retry %d", outTxHash, btcClient.chain.ChainName, send.GetCurrentOutTxParam().OutboundTxTssNonce, i) + logger.Warn().Err(err).Msgf("broadcasting tx %s to chain %s: nonce %d, retry %d", outTxHash, btcClient.chain.ChainName, outboundTxTssNonce, i) continue } - logger.Info().Msgf("Broadcast success: nonce %d to chain %s outTxHash %s", send.GetCurrentOutTxParam().OutboundTxTssNonce, btcClient.chain.String(), outTxHash) - zetaHash, err := zetaBridge.AddTxHashToOutTxTracker(btcClient.chain.ChainId, send.GetCurrentOutTxParam().OutboundTxTssNonce, outTxHash) + logger.Info().Msgf("Broadcast success: nonce %d to chain %s outTxHash %s", outboundTxTssNonce, btcClient.chain.String(), outTxHash) + zetaHash, err := zetaBridge.AddTxHashToOutTxTracker(btcClient.chain.ChainId, outboundTxTssNonce, outTxHash) if err != nil { - logger.Err(err).Msgf("Unable to add to tracker on ZetaCore: nonce %d chain %s outTxHash %s", send.GetCurrentOutTxParam().OutboundTxTssNonce, btcClient.chain.ChainName, outTxHash) + logger.Err(err).Msgf("Unable to add to tracker on ZetaCore: nonce %d chain %s outTxHash %s", outboundTxTssNonce, btcClient.chain.ChainName, outTxHash) } logger.Info().Msgf("Broadcast to core successful %s", zetaHash) - outTxID := btcClient.GetTxID(send.GetCurrentOutTxParam().OutboundTxTssNonce) // Save successfully broadcasted transaction to btc chain client - btcClient.mu.Lock() - btcClient.broadcastedTx[outTxID] = tx.TxHash() - btcClient.mu.Unlock() - broadcastEntry := clienttypes.ToTransactionHashSQLType(tx.TxHash(), outTxID) - if err := btcClient.db.Create(&broadcastEntry).Error; err != nil { - btcClient.logger.ObserveOutTx.Error().Err(err).Msg("observeOutTx: error saving broadcasted tx") - } + btcClient.SaveBroadcastedTx(tx.TxHash(), outboundTxTssNonce) break // successful broadcast; no need to retry } diff --git a/zetaclient/btc_signer_test.go b/zetaclient/btc_signer_test.go index e838c49b1a..f4ea56c793 100644 --- a/zetaclient/btc_signer_test.go +++ b/zetaclient/btc_signer_test.go @@ -210,9 +210,9 @@ func createTestClient(t *testing.T) *BitcoinChainClient { // Create BitcoinChainClient client := &BitcoinChainClient{ - Tss: tss, - mu: &sync.Mutex{}, - minedTx: make(map[string]btcjson.GetTransactionResult), + Tss: tss, + mu: &sync.Mutex{}, + includedTx: make(map[string]btcjson.GetTransactionResult), } // Create 10 dummy UTXOs (22.44 BTC in total) @@ -227,12 +227,12 @@ func createTestClient(t *testing.T) *BitcoinChainClient { func mineTxNSetNonceMark(ob *BitcoinChainClient, nonce uint64, txid string, preMarkIndex int) { // Mine transaction outTxID := ob.GetTxID(nonce) - ob.minedTx[outTxID] = btcjson.GetTransactionResult{TxID: txid} + ob.includedTx[outTxID] = btcjson.GetTransactionResult{TxID: txid} // Set nonce mark if preMarkIndex >= 0 { tssAddress := ob.Tss.BTCAddressWitnessPubkeyHash().EncodeAddress() - nonceMark := btcjson.ListUnspentResult{Address: tssAddress, Amount: float64(NonceMarkAmount(nonce)) * 1e-8} + nonceMark := btcjson.ListUnspentResult{TxID: txid, Address: tssAddress, Amount: float64(NonceMarkAmount(nonce)) * 1e-8} ob.utxos[preMarkIndex] = nonceMark sort.SliceStable(ob.utxos, func(i, j int) bool { return ob.utxos[i].Amount < ob.utxos[j].Amount @@ -253,27 +253,27 @@ func TestSelectUTXOs(t *testing.T) { require.Equal(t, 0.01, amount) require.Equal(t, ob.utxos[0:1], result) - // // Case2: nonce = 1, must FAIL and wait for previous transaction to be mined - // // input: utxoCap = 5, amount = 0.5, nonce = 1 - // // output: error - // result, amount, err = ob.SelectUTXOs(0.5, 5, 1, tssAddress) - // require.NotNil(t, err) - // require.Nil(t, result) - // require.Equal(t, 0.0, amount) - // require.Equal(t, "findNonceMarkUTXO: transaction 0-mgaRVNhouhVaiKx8xVtLNHBbSUe1o36qZJ-0 not mined yet", err.Error()) - // mineTxNSetNonceMark(ob, 0, dummyTxID, -1) // mine a transaction for nonce 0 - - // // Case3: nonce = 1, must FAIL without nonce mark utxo - // // input: utxoCap = 5, amount = 0.5, nonce = 1 - // // output: error - // result, amount, err = ob.SelectUTXOs(0.5, 5, 1, tssAddress) - // require.NotNil(t, err) - // require.Nil(t, result) - // require.Equal(t, 0.0, amount) - // require.Equal(t, "findNonceMarkUTXO: cannot find nonce-mark utxo with nonce 0", err.Error()) + // Case2: nonce = 1, must FAIL and wait for previous transaction to be mined + // input: utxoCap = 5, amount = 0.5, nonce = 1 + // output: error + result, amount, err = ob.SelectUTXOs(0.5, 5, 1, tssAddress) + require.NotNil(t, err) + require.Nil(t, result) + require.Zero(t, amount) + require.Equal(t, "findNonceMarkUTXO: outTx 0-mgaRVNhouhVaiKx8xVtLNHBbSUe1o36qZJ-0 not included yet", err.Error()) + mineTxNSetNonceMark(ob, 0, dummyTxID, -1) // mine a transaction for nonce 0 + + // Case3: nonce = 1, must FAIL without nonce mark utxo + // input: utxoCap = 5, amount = 0.5, nonce = 1 + // output: error + result, amount, err = ob.SelectUTXOs(0.5, 5, 1, tssAddress) + require.NotNil(t, err) + require.Nil(t, result) + require.Zero(t, amount) + require.Equal(t, "findNonceMarkUTXO: cannot find nonce-mark utxo with nonce 0", err.Error()) // add nonce-mark utxo for nonce 0 - nonceMark0 := btcjson.ListUnspentResult{Address: tssAddress, Amount: float64(NonceMarkAmount(0)) * 1e-8} + nonceMark0 := btcjson.ListUnspentResult{TxID: dummyTxID, Address: tssAddress, Amount: float64(NonceMarkAmount(0)) * 1e-8} ob.utxos = append([]btcjson.ListUnspentResult{nonceMark0}, ob.utxos...) // Case4: nonce = 1, should pass now @@ -336,6 +336,6 @@ func TestSelectUTXOs(t *testing.T) { result, amount, err = ob.SelectUTXOs(21.64, 5, 24105433, tssAddress) require.NotNil(t, err) require.Nil(t, result) - require.Equal(t, 0.0, amount) + require.Zero(t, amount) require.Equal(t, "SelectUTXOs: not enough btc in reserve - available : 21.63107432 , tx amount : 21.64", err.Error()) } From c3051bb128dbc1296047f35fe42086d4d570c482 Mon Sep 17 00:00:00 2001 From: Charlie Chen <34498985+ws4charlie@users.noreply.github.com> Date: Tue, 1 Aug 2023 15:52:04 -0500 Subject: [PATCH 5/5] removed nonce and persistence of includedTx (#893) Co-authored-by: charliec --- zetaclient/bitcoin_client.go | 108 ++++------------------------ zetaclient/telemetry.go | 12 ---- zetaclient/types/telemetry_types.go | 1 - 3 files changed, 15 insertions(+), 106 deletions(-) diff --git a/zetaclient/bitcoin_client.go b/zetaclient/bitcoin_client.go index 3aae8a8ac2..c36a8343bd 100644 --- a/zetaclient/bitcoin_client.go +++ b/zetaclient/bitcoin_client.go @@ -46,22 +46,21 @@ type BTCLog struct { type BitcoinChainClient struct { *ChainMetrics - chain common.Chain - rpcClient *rpcclient.Client - zetaClient *ZetaCoreBridge - Tss TSSSigner - lastBlock int64 - BlockTime uint64 // block time in seconds - includedTx map[string]btcjson.GetTransactionResult // key: chain-nonce - broadcastedTx map[string]chainhash.Hash - nextTxNonce2Broadcast int - mu *sync.Mutex - utxos []btcjson.ListUnspentResult - db *gorm.DB - stop chan struct{} - logger BTCLog - cfg *config.Config - ts *TelemetryServer + chain common.Chain + rpcClient *rpcclient.Client + zetaClient *ZetaCoreBridge + Tss TSSSigner + lastBlock int64 + BlockTime uint64 // block time in seconds + includedTx map[string]btcjson.GetTransactionResult // key: chain-nonce + broadcastedTx map[string]chainhash.Hash + mu *sync.Mutex + utxos []btcjson.ListUnspentResult + db *gorm.DB + stop chan struct{} + logger BTCLog + cfg *config.Config + ts *TelemetryServer } const ( @@ -132,12 +131,6 @@ func NewBitcoinClient(chain common.Chain, bridge *ZetaCoreBridge, tss TSSSigner, return nil, err } - //Set Next Nonce for broadcasted tx - err = ob.SetNextNonceBroadcast() - if err != nil { - return nil, err - } - return &ob, nil } @@ -669,8 +662,6 @@ func (ob *BitcoinChainClient) SaveBroadcastedTx(txHash chainhash.Hash, nonce uin outTxID := ob.GetTxID(nonce) ob.mu.Lock() ob.broadcastedTx[outTxID] = txHash - ob.nextTxNonce2Broadcast++ - ob.ts.SetNextNonce(ob.nextTxNonce2Broadcast) ob.mu.Unlock() broadcastEntry := clienttypes.ToTransactionHashSQLType(txHash, outTxID) @@ -715,16 +706,6 @@ func (ob *BitcoinChainClient) observeOutTx() { ob.mu.Lock() ob.includedTx[outTxID] = *getTxResult ob.mu.Unlock() - - //Save to db - tx, err := clienttypes.ToTransactionResultSQLType(*getTxResult, outTxID) - if err != nil { - ob.logger.ObserveOutTx.Error().Err(err).Msg("observeOutTx: error converting to TransactionResultSQLType") - continue - } - if err := ob.db.Create(&tx).Error; err != nil { - ob.logger.ObserveOutTx.Error().Err(err).Msg("observeOutTx: error saving submitted tx") - } } } } @@ -787,22 +768,6 @@ func (ob *BitcoinChainClient) isValidTSSVin(vins []btcjson.Vin) bool { return true } -func (ob *BitcoinChainClient) BuildIncludedTxMap() error { - var submittedTransactions []clienttypes.TransactionResultSQLType - if err := ob.db.Find(&submittedTransactions).Error; err != nil { - ob.logger.ChainLogger.Error().Err(err).Msg("error iterating over db") - return err - } - for _, txResult := range submittedTransactions { - r, err := clienttypes.FromTransactionResultSQLType(txResult) - if err != nil { - return err - } - ob.includedTx[txResult.Key] = r - } - return nil -} - func (ob *BitcoinChainClient) BuildBroadcastedTxMap() error { var broadcastedTransactions []clienttypes.TransactionHashSQLType if err := ob.db.Find(&broadcastedTransactions).Error; err != nil { @@ -815,43 +780,6 @@ func (ob *BitcoinChainClient) BuildBroadcastedTxMap() error { return nil } -func (ob *BitcoinChainClient) SetNextNonceBroadcast() error { - nonces, err := ob.zetaClient.GetPendingNonces() - if err != nil { - return err - } - - found := false - for _, nonce := range nonces.PendingNonces { - if len(nonce.Tss) == 0 { - continue - } - tssKey, err := NewTSSKey(nonce.Tss) - if err != nil { - continue - } - if ob.chain.ChainId == nonce.ChainId && bytes.Equal(tssKey.PubkeyInBytes, ob.Tss.Pubkey()) { - // find lowest nonce that had not been broadcasted - next2Broadcast := int(nonce.NonceLow) - for nc := nonce.NonceLow; nc < nonce.NonceHigh; nc++ { - if _, exist := ob.broadcastedTx[ob.GetTxID(uint64(nc))]; exist { - next2Broadcast++ - continue - } - break - } - ob.nextTxNonce2Broadcast = next2Broadcast - ob.ts.SetNextNonce(ob.nextTxNonce2Broadcast) - found = true - } - } - if !found { - ob.logger.ChainLogger.Error().Msgf("initial nonce for Chain ID: %d not found", ob.chain.ChainId) - } - - return nil -} - func (ob *BitcoinChainClient) LoadLastBlock() error { bn, err := ob.rpcClient.GetBlockCount() if err != nil { @@ -902,12 +830,6 @@ func (ob *BitcoinChainClient) loadDB(dbpath string) error { return err } - //Load included transactions - err = ob.BuildIncludedTxMap() - if err != nil { - return err - } - //Load last block err = ob.LoadLastBlock() if err != nil { diff --git a/zetaclient/telemetry.go b/zetaclient/telemetry.go index 13de1ebf32..867c943a8b 100644 --- a/zetaclient/telemetry.go +++ b/zetaclient/telemetry.go @@ -90,18 +90,6 @@ func (t *TelemetryServer) GetCoreBlockNumber() int64 { return t.lastCoreBlockNumber } -func (t *TelemetryServer) SetNextNonce(nextNonce int) { - t.mu.Lock() - t.status.BTCNextNonce = nextNonce - t.mu.Unlock() -} - -func (t *TelemetryServer) GetNextNonce() int { - t.mu.Lock() - defer t.mu.Unlock() - return t.status.BTCNextNonce -} - func (t *TelemetryServer) SetNumberOfUTXOs(numberOfUTXOs int) { t.mu.Lock() t.status.BTCNumberOfUTXOs = numberOfUTXOs diff --git a/zetaclient/types/telemetry_types.go b/zetaclient/types/telemetry_types.go index e675516dc6..a63265a914 100644 --- a/zetaclient/types/telemetry_types.go +++ b/zetaclient/types/telemetry_types.go @@ -2,6 +2,5 @@ package types // Status type for telemetry. More fields can be added as needed type Status struct { - BTCNextNonce int `json:"btc_next_nonce"` BTCNumberOfUTXOs int `json:"btc_number_of_utxos"` }