diff --git a/changelog.md b/changelog.md index 0538e8d193..7a86d4b43f 100644 --- a/changelog.md +++ b/changelog.md @@ -9,12 +9,17 @@ ### Refactor * [1783](https://github.com/zeta-chain/node/pull/1783) - refactor zetaclient metrics naming and structure +* [1774](https://github.com/zeta-chain/node/pull/1774) - split params and config in zetaclient ### Tests * [1767](https://github.com/zeta-chain/node/pull/1767) - add unit tests for emissions module begin blocker * [1791](https://github.com/zeta-chain/node/pull/1791) - add e2e tests for feature of restricted address +### Chores + +* [1814](https://github.com/zeta-chain/node/pull/1814) - fix code coverage ignore for protobuf generated files + ## Version: v13.0.0 * `zetaclientd start` : 2 inputs required from stdin diff --git a/cmd/zetaclientd/debug.go b/cmd/zetaclientd/debug.go index 4bc251d54a..8dcb6e666a 100644 --- a/cmd/zetaclientd/debug.go +++ b/cmd/zetaclientd/debug.go @@ -9,6 +9,7 @@ import ( "sync" "github.com/zeta-chain/zetacore/zetaclient/bitcoin" + corecontext "github.com/zeta-chain/zetacore/zetaclient/core_context" "github.com/zeta-chain/zetacore/zetaclient/evm" "github.com/zeta-chain/zetacore/zetaclient/keys" "github.com/zeta-chain/zetacore/zetaclient/metrics" @@ -51,6 +52,7 @@ func DebugCmd() *cobra.Command { if err != nil { return err } + coreContext := corecontext.NewZetaCoreContext(cfg) chainID, err := strconv.ParseInt(args[1], 10, 64) if err != nil { return err @@ -122,14 +124,17 @@ func DebugCmd() *cobra.Command { for _, chainParams := range chainParams { if chainParams.ChainId == chainID { - ob.WithParams(observertypes.ChainParams{ + ob.SetChainParams(observertypes.ChainParams{ ChainId: chainID, ConnectorContractAddress: chainParams.ConnectorContractAddress, ZetaTokenContractAddress: chainParams.ZetaTokenContractAddress, Erc20CustodyContractAddress: chainParams.Erc20CustodyContractAddress, }) - cfg.EVMChainConfigs[chainID].ZetaTokenContractAddress = chainParams.ZetaTokenContractAddress - ob.SetConfig(cfg) + evmChainParams, found := coreContext.GetEVMChainParams(chainID) + if !found { + return fmt.Errorf("missing chain params for chain %d", chainID) + } + evmChainParams.ZetaTokenContractAddress = chainParams.ZetaTokenContractAddress if strings.EqualFold(tx.To().Hex(), chainParams.ConnectorContractAddress) { coinType = common.CoinType_Zeta } else if strings.EqualFold(tx.To().Hex(), chainParams.Erc20CustodyContractAddress) { diff --git a/cmd/zetaclientd/keygen_tss.go b/cmd/zetaclientd/keygen_tss.go index 119a547a3a..16f79581b5 100644 --- a/cmd/zetaclientd/keygen_tss.go +++ b/cmd/zetaclientd/keygen_tss.go @@ -7,6 +7,7 @@ import ( "fmt" "time" + appcontext "github.com/zeta-chain/zetacore/zetaclient/app_context" mc "github.com/zeta-chain/zetacore/zetaclient/tss" "github.com/zeta-chain/zetacore/zetaclient/zetabridge" @@ -18,12 +19,12 @@ import ( "github.com/zeta-chain/go-tss/p2p" "github.com/zeta-chain/zetacore/common" observertypes "github.com/zeta-chain/zetacore/x/observer/types" - "github.com/zeta-chain/zetacore/zetaclient/config" "github.com/zeta-chain/zetacore/zetaclient/metrics" ) -func GenerateTss(logger zerolog.Logger, - cfg *config.Config, +func GenerateTss( + appContext *appcontext.AppContext, + logger zerolog.Logger, zetaBridge *zetabridge.ZetaCoreBridge, peers p2p.AddrList, priKey secp256k1.PrivKey, @@ -37,15 +38,16 @@ func GenerateTss(logger zerolog.Logger, // TODO: remove this once we have a better way to determine the signature format // https://github.com/zeta-chain/node/issues/1397 bitcoinChainID := common.BtcRegtestChain().ChainId - if cfg.BitcoinConfig != nil { - bitcoinChainID = cfg.BitcoinConfig.ChainId + btcChain, _, btcEnabled := appContext.GetBTCChainAndConfig() + if btcEnabled { + bitcoinChainID = btcChain.ChainId } tss, err := mc.NewTSS( + appContext, peers, priKey, preParams, - cfg, zetaBridge, tssHistoricalList, bitcoinChainID, @@ -72,7 +74,7 @@ func GenerateTss(logger zerolog.Logger, // This loop will try keygen at the keygen block and then wait for keygen to be successfully reported by all nodes before breaking out of the loop. // If keygen is unsuccessful, it will reset the triedKeygenAtBlock flag and try again at a new keygen block. - keyGen := cfg.GetKeygen() + keyGen := appContext.ZetaCoreContext().GetKeygen() if keyGen.Status == observertypes.KeygenStatus_KeyGenSuccess { return tss, nil } @@ -98,13 +100,13 @@ func GenerateTss(logger zerolog.Logger, if currentBlock != keyGen.BlockNumber { if currentBlock > lastBlock { lastBlock = currentBlock - keygenLogger.Info().Msgf("Waiting For Keygen Block to arrive or new keygen block to be set. Keygen Block : %d Current Block : %d ChainID %s ", keyGen.BlockNumber, currentBlock, cfg.ChainID) + keygenLogger.Info().Msgf("Waiting For Keygen Block to arrive or new keygen block to be set. Keygen Block : %d Current Block : %d ChainID %s ", keyGen.BlockNumber, currentBlock, appContext.Config().ChainID) } continue } // Try keygen only once at a particular block, irrespective of whether it is successful or failure triedKeygenAtBlock = true - err = keygenTss(cfg, tss, keygenLogger) + err = keygenTss(keyGen, tss, keygenLogger) if err != nil { keygenLogger.Error().Err(err).Msg("keygenTss error") tssFailedVoteHash, err := zetaBridge.SetTSS("", keyGen.BlockNumber, common.ReceiveStatus_Failed) @@ -147,9 +149,7 @@ func GenerateTss(logger zerolog.Logger, return nil, errors.New("unexpected state for TSS generation") } -func keygenTss(cfg *config.Config, tss *mc.TSS, keygenLogger zerolog.Logger) error { - - keyGen := cfg.GetKeygen() +func keygenTss(keyGen observertypes.Keygen, tss *mc.TSS, keygenLogger zerolog.Logger) error { keygenLogger.Info().Msgf("Keygen at blocknum %d , TSS signers %s ", keyGen.BlockNumber, keyGen.GranteePubkeys) var req keygen.Request req = keygen.NewRequest(keyGen.GranteePubkeys, keyGen.BlockNumber, "0.14.0") diff --git a/cmd/zetaclientd/start.go b/cmd/zetaclientd/start.go index e6046586cc..8458acb802 100644 --- a/cmd/zetaclientd/start.go +++ b/cmd/zetaclientd/start.go @@ -22,7 +22,9 @@ import ( "github.com/zeta-chain/zetacore/common" observerTypes "github.com/zeta-chain/zetacore/x/observer/types" mc "github.com/zeta-chain/zetacore/zetaclient" + appcontext "github.com/zeta-chain/zetacore/zetaclient/app_context" "github.com/zeta-chain/zetacore/zetaclient/config" + corecontext "github.com/zeta-chain/zetacore/zetaclient/core_context" "github.com/zeta-chain/zetacore/zetaclient/metrics" ) @@ -119,15 +121,15 @@ func start(_ *cobra.Command, _ []string) error { startLogger.Debug().Msgf("CreateAuthzSigner is ready") // Initialize core parameters from zetacore - err = zetaBridge.UpdateConfigFromCore(cfg, true) + appContext := appcontext.NewAppContext(corecontext.NewZetaCoreContext(cfg), cfg) + err = zetaBridge.UpdateZetaCoreContext(appContext.ZetaCoreContext(), true) if err != nil { startLogger.Error().Err(err).Msg("Error getting core parameters") return err } startLogger.Info().Msgf("Config is updated from ZetaCore %s", maskCfg(cfg)) - // ConfigUpdater: A polling goroutine checks and updates core parameters at every height. Zetacore stores core parameters for all clients - go zetaBridge.ConfigUpdater(cfg) + go zetaBridge.CoreContextUpdater(appContext) // Generate TSS address . The Tss address is generated through Keygen ceremony. The TSS key is used to sign all outbound transactions . // The bridgePk is private key for the Hotkey. The Hotkey is used to sign all inbound transactions @@ -173,7 +175,7 @@ func start(_ *cobra.Command, _ []string) error { } telemetryServer.SetIPAddress(cfg.PublicIP) - tss, err := GenerateTss(masterLogger, cfg, zetaBridge, peers, priKey, telemetryServer, tssHistoricalList, tssKeyPass, hotkeyPass) + tss, err := GenerateTss(appContext, masterLogger, zetaBridge, peers, priKey, telemetryServer, tssHistoricalList, tssKeyPass, hotkeyPass) if err != nil { return err } @@ -188,8 +190,8 @@ func start(_ *cobra.Command, _ []string) error { // For existing keygen, this should directly proceed to the next step ticker := time.NewTicker(time.Second * 1) for range ticker.C { - if cfg.Keygen.Status != observerTypes.KeygenStatus_KeyGenSuccess { - startLogger.Info().Msgf("Waiting for TSS Keygen to be a success, current status %s", cfg.Keygen.Status) + if appContext.ZetaCoreContext().GetKeygen().Status != observerTypes.KeygenStatus_KeyGenSuccess { + startLogger.Info().Msgf("Waiting for TSS Keygen to be a success, current status %s", appContext.ZetaCoreContext().GetKeygen().Status) continue } break @@ -207,7 +209,7 @@ func start(_ *cobra.Command, _ []string) error { // Defensive check: Make sure the tss address is set to the current TSS address and not the newly generated one tss.CurrentPubkey = currentTss.TssPubkey startLogger.Info().Msgf("Current TSS address \n ETH : %s \n BTC : %s \n PubKey : %s ", tss.EVMAddress(), tss.BTCAddress(), tss.CurrentPubkey) - if len(cfg.ChainsEnabled) == 0 { + if len(appContext.ZetaCoreContext().GetEnabledChains()) == 0 { startLogger.Error().Msgf("No chains enabled in updated config %s ", cfg.String()) } @@ -224,8 +226,8 @@ func start(_ *cobra.Command, _ []string) error { } } - // CreateSignerMap: This creates a map of all signers for each chain. Each signer is responsible for signing transactions for a particular chain - signerMap, err := CreateSignerMap(tss, loggers, cfg, telemetryServer) + // CreateSignerMap: This creates a map of all signers for each chain . Each signer is responsible for signing transactions for a particular chain + signerMap, err := CreateSignerMap(appContext, tss, loggers, telemetryServer) if err != nil { log.Error().Err(err).Msg("CreateSignerMap") return err @@ -238,10 +240,10 @@ func start(_ *cobra.Command, _ []string) error { } dbpath := filepath.Join(userDir, ".zetaclient/chainobserver") - // CreateChainClientMap : This creates a map of all chain clients. Each chain client is responsible for listening to events on the chain and processing them - chainClientMap, err := CreateChainClientMap(zetaBridge, tss, dbpath, loggers, cfg, telemetryServer) + // CreateChainClientMap : This creates a map of all chain clients . Each chain client is responsible for listening to events on the chain and processing them + chainClientMap, err := CreateChainClientMap(appContext, zetaBridge, tss, dbpath, loggers, telemetryServer) if err != nil { - startLogger.Err(err).Msg("CreateSignerMap") + startLogger.Err(err).Msg("CreateChainClientMap") return err } @@ -255,8 +257,8 @@ func start(_ *cobra.Command, _ []string) error { } // CreateCoreObserver : Core observer wraps the zetacore bridge and adds the client and signer maps to it . This is the high level object used for CCTX interactions - mo1 := mc.NewCoreObserver(zetaBridge, signerMap, chainClientMap, masterLogger, cfg, telemetryServer) - mo1.MonitorCore() + mo1 := mc.NewCoreObserver(zetaBridge, signerMap, chainClientMap, masterLogger, telemetryServer) + mo1.MonitorCore(appContext) // start zeta supply checker // TODO: enable diff --git a/cmd/zetaclientd/start_utils.go b/cmd/zetaclientd/start_utils.go index 47ed135442..042f2fb20d 100644 --- a/cmd/zetaclientd/start_utils.go +++ b/cmd/zetaclientd/start_utils.go @@ -68,9 +68,8 @@ func maskCfg(cfg *config.Config) string { maskedCfg.EVMChainConfigs = map[int64]*config.EVMConfig{} for key, val := range cfg.EVMChainConfigs { maskedCfg.EVMChainConfigs[key] = &config.EVMConfig{ - ChainParams: val.ChainParams, - Chain: val.Chain, - Endpoint: val.Endpoint, + Chain: val.Chain, + Endpoint: val.Endpoint, } } diff --git a/cmd/zetaclientd/utils.go b/cmd/zetaclientd/utils.go index e04f62bfc2..82a16dcb7f 100644 --- a/cmd/zetaclientd/utils.go +++ b/cmd/zetaclientd/utils.go @@ -5,6 +5,7 @@ import ( ethcommon "github.com/ethereum/go-ethereum/common" "github.com/zeta-chain/zetacore/common" "github.com/zeta-chain/zetacore/common/cosmos" + appcontext "github.com/zeta-chain/zetacore/zetaclient/app_context" "github.com/zeta-chain/zetacore/zetaclient/authz" "github.com/zeta-chain/zetacore/zetaclient/bitcoin" clientcommon "github.com/zeta-chain/zetacore/zetaclient/common" @@ -50,19 +51,24 @@ func CreateZetaBridge(cfg *config.Config, telemetry *metrics.TelemetryServer, ho } func CreateSignerMap( + appContext *appcontext.AppContext, tss interfaces.TSSSigner, loggers clientcommon.ClientLogger, - cfg *config.Config, ts *metrics.TelemetryServer, ) (map[common.Chain]interfaces.ChainSigner, error) { signerMap := make(map[common.Chain]interfaces.ChainSigner) // EVM signers - for _, evmConfig := range cfg.GetAllEVMConfigs() { + for _, evmConfig := range appContext.Config().GetAllEVMConfigs() { if evmConfig.Chain.IsZetaChain() { continue } - mpiAddress := ethcommon.HexToAddress(evmConfig.ChainParams.ConnectorContractAddress) - erc20CustodyAddress := ethcommon.HexToAddress(evmConfig.ChainParams.Erc20CustodyContractAddress) + evmChainParams, found := appContext.ZetaCoreContext().GetEVMChainParams(evmConfig.Chain.ChainId) + if !found { + loggers.Std.Error().Msgf("ChainParam not found for chain %s", evmConfig.Chain.String()) + continue + } + mpiAddress := ethcommon.HexToAddress(evmChainParams.ConnectorContractAddress) + erc20CustodyAddress := ethcommon.HexToAddress(evmChainParams.Erc20CustodyContractAddress) signer, err := evm.NewEVMSigner(evmConfig.Chain, evmConfig.Endpoint, tss, config.GetConnectorABI(), config.GetERC20CustodyABI(), mpiAddress, erc20CustodyAddress, loggers, ts) if err != nil { loggers.Std.Error().Err(err).Msgf("NewEVMSigner error for chain %s", evmConfig.Chain.String()) @@ -71,7 +77,7 @@ func CreateSignerMap( signerMap[evmConfig.Chain] = signer } // BTC signer - btcChain, btcConfig, enabled := cfg.GetBTCConfig() + btcChain, btcConfig, enabled := appContext.GetBTCChainAndConfig() if enabled { signer, err := bitcoin.NewBTCSigner(btcConfig, tss, loggers, ts) if err != nil { @@ -85,20 +91,20 @@ func CreateSignerMap( } func CreateChainClientMap( + appContext *appcontext.AppContext, bridge *zetabridge.ZetaCoreBridge, tss interfaces.TSSSigner, dbpath string, loggers clientcommon.ClientLogger, - cfg *config.Config, ts *metrics.TelemetryServer, ) (map[common.Chain]interfaces.ChainClient, error) { clientMap := make(map[common.Chain]interfaces.ChainClient) // EVM clients - for _, evmConfig := range cfg.GetAllEVMConfigs() { + for _, evmConfig := range appContext.Config().GetAllEVMConfigs() { if evmConfig.Chain.IsZetaChain() { continue } - co, err := evm.NewEVMChainClient(bridge, tss, dbpath, loggers, cfg, *evmConfig, ts) + co, err := evm.NewEVMChainClient(appContext, bridge, tss, dbpath, loggers, *evmConfig, ts) if err != nil { loggers.Std.Error().Err(err).Msgf("NewEVMChainClient error for chain %s", evmConfig.Chain.String()) continue @@ -106,9 +112,9 @@ func CreateChainClientMap( clientMap[evmConfig.Chain] = co } // BTC client - btcChain, btcConfig, enabled := cfg.GetBTCConfig() + btcChain, _, enabled := appContext.GetBTCChainAndConfig() if enabled { - co, err := bitcoin.NewBitcoinClient(btcChain, bridge, tss, dbpath, loggers, btcConfig, ts) + co, err := bitcoin.NewBitcoinClient(appContext, btcChain, bridge, tss, dbpath, loggers, ts) if err != nil { loggers.Std.Error().Err(err).Msgf("NewBitcoinClient error for chain %s", btcChain.String()) diff --git a/codecov.yml b/codecov.yml index 647094cf84..48d3aed9a9 100644 --- a/codecov.yml +++ b/codecov.yml @@ -54,13 +54,13 @@ ignore: - "x/**/module.go" - "x/**/module_simulation.go" - "x/**/simulation/" - - "*.proto" - - "*.md" - - "*.yml" - - "*.yaml" - - "*.pb.go" - - "*.pb.gw.go" - - "*.json" + - "**/*.proto" + - "**/*.md" + - "**/*.yml" + - "**/*.yaml" + - "**/*.pb.go" + - "**/*.pb.gw.go" + - "**/*.json" - ".github/" - "app/" - "cmd/" diff --git a/zetaclient/app_context/app_context.go b/zetaclient/app_context/app_context.go new file mode 100644 index 0000000000..deab613618 --- /dev/null +++ b/zetaclient/app_context/app_context.go @@ -0,0 +1,44 @@ +package appcontext + +import ( + "github.com/zeta-chain/zetacore/common" + "github.com/zeta-chain/zetacore/zetaclient/config" + corecontext "github.com/zeta-chain/zetacore/zetaclient/core_context" +) + +// AppContext contains global app structs like config, core context and logger +type AppContext struct { + coreContext *corecontext.ZetaCoreContext + config *config.Config +} + +// NewAppContext creates and returns new AppContext +func NewAppContext( + coreContext *corecontext.ZetaCoreContext, + config *config.Config, +) *AppContext { + return &AppContext{ + coreContext: coreContext, + config: config, + } +} + +func (a *AppContext) Config() *config.Config { + return a.config +} + +func (a *AppContext) ZetaCoreContext() *corecontext.ZetaCoreContext { + return a.coreContext +} + +// GetBTCChainAndConfig returns btc chain and config if enabled +func (a *AppContext) GetBTCChainAndConfig() (common.Chain, config.BTCConfig, bool) { + btcConfig, configEnabled := a.Config().GetBTCConfig() + btcChain, _, paramsEnabled := a.ZetaCoreContext().GetBTCChainParams() + + if !configEnabled || !paramsEnabled { + return common.Chain{}, config.BTCConfig{}, false + } + + return btcChain, btcConfig, true +} diff --git a/zetaclient/bitcoin/bitcoin_client.go b/zetaclient/bitcoin/bitcoin_client.go index 6a5e3b336a..f4b0cc4d42 100644 --- a/zetaclient/bitcoin/bitcoin_client.go +++ b/zetaclient/bitcoin/bitcoin_client.go @@ -13,7 +13,11 @@ import ( "sync/atomic" "time" + appcontext "github.com/zeta-chain/zetacore/zetaclient/app_context" + clientcommon "github.com/zeta-chain/zetacore/zetaclient/common" + "github.com/zeta-chain/zetacore/zetaclient/config" "github.com/zeta-chain/zetacore/zetaclient/interfaces" + "github.com/zeta-chain/zetacore/zetaclient/metrics" "github.com/zeta-chain/zetacore/zetaclient/zetabridge" cosmosmath "cosmossdk.io/math" @@ -30,9 +34,6 @@ import ( "github.com/zeta-chain/zetacore/common" "github.com/zeta-chain/zetacore/x/crosschain/types" observertypes "github.com/zeta-chain/zetacore/x/observer/types" - clientcommon "github.com/zeta-chain/zetacore/zetaclient/common" - "github.com/zeta-chain/zetacore/zetaclient/config" - "github.com/zeta-chain/zetacore/zetaclient/metrics" clienttypes "github.com/zeta-chain/zetacore/zetaclient/types" "gorm.io/driver/sqlite" "gorm.io/gorm" @@ -133,12 +134,12 @@ func (ob *BTCChainClient) GetChainParams() observertypes.ChainParams { // NewBitcoinClient returns a new configuration based on supplied target chain func NewBitcoinClient( + appcontext *appcontext.AppContext, chain common.Chain, bridge interfaces.ZetaCoreBridger, tss interfaces.TSSSigner, dbpath string, loggers clientcommon.ClientLogger, - btcCfg config.BTCConfig, ts *metrics.TelemetryServer, ) (*BTCChainClient, error) { ob := BTCChainClient{ @@ -167,9 +168,13 @@ func NewBitcoinClient( ob.includedTxHashes = make(map[string]bool) ob.includedTxResults = make(map[string]*btcjson.GetTransactionResult) ob.broadcastedTx = make(map[string]string) - ob.params = btcCfg.ChainParams - + _, chainParams, found := appcontext.ZetaCoreContext().GetBTCChainParams() + if !found { + return nil, fmt.Errorf("btc chains params not initialized") + } + ob.params = *chainParams // initialize the Client + btcCfg := appcontext.Config().BitcoinConfig ob.logger.ChainLogger.Info().Msgf("Chain %s endpoint %s", ob.chain.String(), btcCfg.RPCHost) connCfg := &rpcclient.ConnConfig{ Host: btcCfg.RPCHost, diff --git a/zetaclient/bitcoin/bitcoin_client_rpc_test.go b/zetaclient/bitcoin/bitcoin_client_rpc_test.go index d1a00b907f..d40a08152c 100644 --- a/zetaclient/bitcoin/bitcoin_client_rpc_test.go +++ b/zetaclient/bitcoin/bitcoin_client_rpc_test.go @@ -9,6 +9,11 @@ import ( "testing" "time" + "github.com/zeta-chain/zetacore/common" + appcontext "github.com/zeta-chain/zetacore/zetaclient/app_context" + clientcommon "github.com/zeta-chain/zetacore/zetaclient/common" + "github.com/zeta-chain/zetacore/zetaclient/config" + corecontext "github.com/zeta-chain/zetacore/zetaclient/core_context" "github.com/zeta-chain/zetacore/zetaclient/interfaces" "github.com/btcsuite/btcd/btcjson" @@ -20,9 +25,6 @@ import ( "github.com/rs/zerolog/log" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - "github.com/zeta-chain/zetacore/common" - clientcommon "github.com/zeta-chain/zetacore/zetaclient/common" - "github.com/zeta-chain/zetacore/zetaclient/config" "github.com/zeta-chain/zetacore/zetaclient/testutils" ) @@ -44,8 +46,8 @@ func (suite *BitcoinClientTestSuite) SetupTest() { tss := interfaces.TestSigner{ PrivKey: privateKey, } - //client, err := NewBitcoinClient(common.BtcTestNetChain(), nil, tss, "", nil) - client, err := NewBitcoinClient(common.BtcRegtestChain(), nil, tss, "/tmp", clientcommon.DefaultLoggers(), config.BTCConfig{}, nil) + appContext := appcontext.NewAppContext(&corecontext.ZetaCoreContext{}, &config.Config{}) + client, err := NewBitcoinClient(appContext, common.BtcRegtestChain(), nil, tss, "/tmp", clientcommon.DefaultLoggers(), nil) suite.Require().NoError(err) suite.BitcoinChainClient = client skBytes, err := hex.DecodeString(skHex) diff --git a/zetaclient/config/config.go b/zetaclient/config/config.go index 78c2d6ae9a..08a9d4c002 100644 --- a/zetaclient/config/config.go +++ b/zetaclient/config/config.go @@ -67,7 +67,6 @@ func Load(path string) (*Config, error) { // fields sanitization cfg.TssPath = GetPath(cfg.TssPath) cfg.PreParamsPath = GetPath(cfg.PreParamsPath) - cfg.CurrentTssPubkey = "" cfg.ZetaCoreHome = path // load compliance config diff --git a/zetaclient/config/config_chain.go b/zetaclient/config/config_chain.go index 369ebb994b..2596c554a5 100644 --- a/zetaclient/config/config_chain.go +++ b/zetaclient/config/config_chain.go @@ -35,7 +35,6 @@ func New() Config { return Config{ EVMChainConfigs: evmChainsConfigs, BitcoinConfig: bitcoinConfigRegnet, - ChainsEnabled: []common.Chain{}, } } diff --git a/zetaclient/config/types.go b/zetaclient/config/types.go index e2a9ccc1c2..a85f9f269e 100644 --- a/zetaclient/config/types.go +++ b/zetaclient/config/types.go @@ -3,12 +3,10 @@ package config import ( "encoding/json" "fmt" - "sort" "strings" "sync" ethcommon "github.com/ethereum/go-ethereum/common" - "github.com/rs/zerolog" "github.com/zeta-chain/zetacore/common" observertypes "github.com/zeta-chain/zetacore/x/observer/types" ) @@ -32,14 +30,11 @@ type ClientConfiguration struct { } type EVMConfig struct { - observertypes.ChainParams Chain common.Chain Endpoint string } type BTCConfig struct { - observertypes.ChainParams - // the following are rpcclient ConnConfig fields RPCUsername string RPCPassword string @@ -56,6 +51,8 @@ type ComplianceConfig struct { // TODO: use snake case for json fields // https://github.com/zeta-chain/node/issues/1020 type Config struct { + cfgLock *sync.RWMutex `json:"-"` + Peer string `json:"Peer"` PublicIP string `json:"PublicIP"` LogFormat string `json:"LogFormat"` @@ -72,15 +69,10 @@ type Config struct { P2PDiagnosticTicker uint64 `json:"P2PDiagnosticTicker"` TssPath string `json:"TssPath"` TestTssKeysign bool `json:"TestTssKeysign"` - CurrentTssPubkey string `json:"CurrentTssPubkey"` KeyringBackend KeyringBackend `json:"KeyringBackend"` HsmMode bool `json:"HsmMode"` HsmHotKey string `json:"HsmHotKey"` - // chain specific fields are updatable at runtime and shared across threads - cfgLock *sync.RWMutex `json:"-"` - Keygen observertypes.Keygen `json:"Keygen"` - ChainsEnabled []common.Chain `json:"ChainsEnabled"` EVMChainConfigs map[int64]*EVMConfig `json:"EVMChainConfigs"` BitcoinConfig *BTCConfig `json:"BitcoinConfig"` @@ -104,27 +96,6 @@ func (c *Config) String() string { return string(s) } -func (c *Config) GetKeygen() observertypes.Keygen { - c.cfgLock.RLock() - defer c.cfgLock.RUnlock() - copiedPubkeys := make([]string, len(c.Keygen.GranteePubkeys)) - copy(copiedPubkeys, c.Keygen.GranteePubkeys) - - return observertypes.Keygen{ - Status: c.Keygen.Status, - GranteePubkeys: copiedPubkeys, - BlockNumber: c.Keygen.BlockNumber, - } -} - -func (c *Config) GetEnabledChains() []common.Chain { - c.cfgLock.RLock() - defer c.cfgLock.RUnlock() - copiedChains := make([]common.Chain, len(c.ChainsEnabled)) - copy(copiedChains, c.ChainsEnabled) - return copiedChains -} - func (c *Config) GetEVMConfig(chainID int64) (EVMConfig, bool) { c.cfgLock.RLock() defer c.cfgLock.RUnlock() @@ -145,18 +116,14 @@ func (c *Config) GetAllEVMConfigs() map[int64]*EVMConfig { return copied } -func (c *Config) GetBTCConfig() (common.Chain, BTCConfig, bool) { +func (c *Config) GetBTCConfig() (BTCConfig, bool) { c.cfgLock.RLock() defer c.cfgLock.RUnlock() if c.BitcoinConfig == nil { // bitcoin is not enabled - return common.Chain{}, BTCConfig{}, false - } - chain := common.GetChainFromChainID(c.BitcoinConfig.ChainId) - if chain == nil { - panic(fmt.Sprintf("BTCChain is missing for chainID %d", c.BitcoinConfig.ChainId)) + return BTCConfig{}, false } - return *chain, *c.BitcoinConfig, true + return *c.BitcoinConfig, true } // GetRestrictedAddressBook returns a map of restricted addresses @@ -179,103 +146,6 @@ func (c *Config) GetKeyringBackend() KeyringBackend { return c.KeyringBackend } -// UpdateChainParams updates core params for all chains -// this must be the ONLY function that writes to core params -func (c *Config) UpdateChainParams( - keygen *observertypes.Keygen, - newChains []common.Chain, - evmChainParams map[int64]*observertypes.ChainParams, - btcChainParams *observertypes.ChainParams, - init bool, - logger zerolog.Logger, -) { - c.cfgLock.Lock() - defer c.cfgLock.Unlock() - - // Ignore whatever order zetabridge organizes chain list in state - sort.SliceStable(newChains, func(i, j int) bool { - return newChains[i].ChainId < newChains[j].ChainId - }) - if len(newChains) == 0 { - logger.Warn().Msg("UpdateChainParams: No chains enabled in ZeroCore") - } - - // Add some warnings if chain list changes at runtime - if !init { - if len(c.ChainsEnabled) != len(newChains) { - logger.Warn().Msgf( - "UpdateChainParams: ChainsEnabled changed at runtime!! current: %v, new: %v", - c.ChainsEnabled, - newChains, - ) - } else { - for i, chain := range newChains { - if chain != c.ChainsEnabled[i] { - logger.Warn().Msgf( - "UpdateChainParams: ChainsEnabled changed at runtime!! current: %v, new: %v", - c.ChainsEnabled, - newChains, - ) - } - } - } - } - c.Keygen = *keygen - c.ChainsEnabled = newChains - // update chain params for bitcoin if it has config in file - if c.BitcoinConfig != nil && btcChainParams != nil { - c.BitcoinConfig.ChainParams = *btcChainParams - } - // update core params for evm chains we have configs in file - for _, params := range evmChainParams { - curCfg, found := c.EVMChainConfigs[params.ChainId] - if found { - curCfg.ChainParams = *params - } - } -} - -// Clone makes a separate (deep) copy of the config -func (c *Config) Clone() *Config { - c.cfgLock.RLock() - defer c.cfgLock.RUnlock() - copied := &Config{ - Peer: c.Peer, - PublicIP: c.PublicIP, - LogFormat: c.LogFormat, - LogLevel: c.LogLevel, - LogSampler: c.LogSampler, - PreParamsPath: c.PreParamsPath, - ChainID: c.ChainID, - ZetaCoreURL: c.ZetaCoreURL, - AuthzGranter: c.AuthzGranter, - AuthzHotkey: c.AuthzHotkey, - P2PDiagnostic: c.P2PDiagnostic, - ConfigUpdateTicker: c.ConfigUpdateTicker, - P2PDiagnosticTicker: c.P2PDiagnosticTicker, - TssPath: c.TssPath, - TestTssKeysign: c.TestTssKeysign, - KeyringBackend: c.KeyringBackend, - - cfgLock: &sync.RWMutex{}, - Keygen: c.GetKeygen(), - ChainsEnabled: c.GetEnabledChains(), - EVMChainConfigs: make(map[int64]*EVMConfig, len(c.EVMChainConfigs)), - BitcoinConfig: nil, - } - // deep copy evm & btc configs - for chainID, evmConfig := range c.EVMChainConfigs { - copied.EVMChainConfigs[chainID] = &EVMConfig{} - *copied.EVMChainConfigs[chainID] = *evmConfig - } - if c.BitcoinConfig != nil { - copied.BitcoinConfig = &BTCConfig{} - *copied.BitcoinConfig = *c.BitcoinConfig - } - - return copied -} - // ValidateChainParams performs some basic checks on core params func ValidateChainParams(chainParams *observertypes.ChainParams) error { if chainParams == nil { diff --git a/zetaclient/core_context/zeta_core_context.go b/zetaclient/core_context/zeta_core_context.go new file mode 100644 index 0000000000..27a88b8951 --- /dev/null +++ b/zetaclient/core_context/zeta_core_context.go @@ -0,0 +1,166 @@ +package corecontext + +import ( + "fmt" + "sort" + "sync" + + "github.com/rs/zerolog" + "github.com/zeta-chain/zetacore/common" + observertypes "github.com/zeta-chain/zetacore/x/observer/types" + "github.com/zeta-chain/zetacore/zetaclient/config" +) + +// ZetaCoreContext contains core context params +// these are initialized and updated at runtime at every height +type ZetaCoreContext struct { + coreContextLock *sync.RWMutex + keygen *observertypes.Keygen + chainsEnabled []common.Chain + evmChainParams map[int64]*observertypes.ChainParams + bitcoinChainParams *observertypes.ChainParams + currentTssPubkey string +} + +// NewZetaCoreContext creates and returns new ZetaCoreContext +// it is initializing chain params from provided config +func NewZetaCoreContext(cfg *config.Config) *ZetaCoreContext { + evmChainParams := make(map[int64]*observertypes.ChainParams) + for _, e := range cfg.EVMChainConfigs { + evmChainParams[e.Chain.ChainId] = &observertypes.ChainParams{} + } + var bitcoinChainParams *observertypes.ChainParams + _, found := cfg.GetBTCConfig() + if found { + bitcoinChainParams = &observertypes.ChainParams{} + } + return &ZetaCoreContext{ + coreContextLock: new(sync.RWMutex), + chainsEnabled: []common.Chain{}, + evmChainParams: evmChainParams, + bitcoinChainParams: bitcoinChainParams, + } +} + +func (c *ZetaCoreContext) GetKeygen() observertypes.Keygen { + c.coreContextLock.RLock() + defer c.coreContextLock.RUnlock() + copiedPubkeys := make([]string, len(c.keygen.GranteePubkeys)) + copy(copiedPubkeys, c.keygen.GranteePubkeys) + + return observertypes.Keygen{ + Status: c.keygen.Status, + GranteePubkeys: copiedPubkeys, + BlockNumber: c.keygen.BlockNumber, + } +} + +func (c *ZetaCoreContext) GetCurrentTssPubkey() string { + c.coreContextLock.RLock() + defer c.coreContextLock.RUnlock() + return c.currentTssPubkey +} + +func (c *ZetaCoreContext) GetEnabledChains() []common.Chain { + c.coreContextLock.RLock() + defer c.coreContextLock.RUnlock() + copiedChains := make([]common.Chain, len(c.chainsEnabled)) + copy(copiedChains, c.chainsEnabled) + return copiedChains +} + +func (c *ZetaCoreContext) GetEVMChainParams(chainID int64) (*observertypes.ChainParams, bool) { + c.coreContextLock.RLock() + defer c.coreContextLock.RUnlock() + evmChainParams, found := c.evmChainParams[chainID] + return evmChainParams, found +} + +func (c *ZetaCoreContext) GetAllEVMChainParams() map[int64]*observertypes.ChainParams { + c.coreContextLock.RLock() + defer c.coreContextLock.RUnlock() + + // deep copy evm chain params + copied := make(map[int64]*observertypes.ChainParams, len(c.evmChainParams)) + for chainID, evmConfig := range c.evmChainParams { + copied[chainID] = &observertypes.ChainParams{} + *copied[chainID] = *evmConfig + } + return copied +} + +func (c *ZetaCoreContext) GetBTCChainParams() (common.Chain, *observertypes.ChainParams, bool) { + c.coreContextLock.RLock() + defer c.coreContextLock.RUnlock() + + if c.bitcoinChainParams == nil { // bitcoin is not enabled + return common.Chain{}, &observertypes.ChainParams{}, false + } + chain := common.GetChainFromChainID(c.bitcoinChainParams.ChainId) + if chain == nil { + panic(fmt.Sprintf("BTCChain is missing for chainID %d", c.bitcoinChainParams.ChainId)) + } + return *chain, c.bitcoinChainParams, true +} + +// Update updates core context and params for all chains +// this must be the ONLY function that writes to core context +func (c *ZetaCoreContext) Update( + keygen *observertypes.Keygen, + newChains []common.Chain, + evmChainParams map[int64]*observertypes.ChainParams, + btcChainParams *observertypes.ChainParams, + tssPubKey string, + init bool, + logger zerolog.Logger, +) { + c.coreContextLock.Lock() + defer c.coreContextLock.Unlock() + + // Ignore whatever order zetabridge organizes chain list in state + sort.SliceStable(newChains, func(i, j int) bool { + return newChains[i].ChainId < newChains[j].ChainId + }) + if len(newChains) == 0 { + logger.Warn().Msg("UpdateChainParams: No chains enabled in ZeroCore") + } + + // Add some warnings if chain list changes at runtime + if !init { + if len(c.chainsEnabled) != len(newChains) { + logger.Warn().Msgf( + "UpdateChainParams: ChainsEnabled changed at runtime!! current: %v, new: %v", + c.chainsEnabled, + newChains, + ) + } else { + for i, chain := range newChains { + if chain != c.chainsEnabled[i] { + logger.Warn().Msgf( + "UpdateChainParams: ChainsEnabled changed at runtime!! current: %v, new: %v", + c.chainsEnabled, + newChains, + ) + } + } + } + } + c.keygen = keygen + c.chainsEnabled = newChains + // update chain params for bitcoin if it has config in file + if c.bitcoinChainParams != nil && btcChainParams != nil { + c.bitcoinChainParams = btcChainParams + } + // update core params for evm chains we have configs in file + for _, params := range evmChainParams { + _, found := c.evmChainParams[params.ChainId] + if !found { + continue + } + c.evmChainParams[params.ChainId] = params + } + + if tssPubKey != "" { + c.currentTssPubkey = tssPubKey + } +} diff --git a/zetaclient/evm/evm_client.go b/zetaclient/evm/evm_client.go index 88cee1784d..b0d85631ca 100644 --- a/zetaclient/evm/evm_client.go +++ b/zetaclient/evm/evm_client.go @@ -14,6 +14,9 @@ import ( "sync/atomic" "time" + appcontext "github.com/zeta-chain/zetacore/zetaclient/app_context" + corecontext "github.com/zeta-chain/zetacore/zetaclient/core_context" + "github.com/zeta-chain/zetacore/zetaclient/interfaces" "github.com/zeta-chain/zetacore/zetaclient/metrics" "github.com/zeta-chain/zetacore/zetaclient/zetabridge" @@ -93,21 +96,22 @@ type ChainClient struct { OutTxChan chan OutTx // send to this channel if you want something back! stop chan struct{} logger Log - cfg *config.Config - params observertypes.ChainParams + coreContext *corecontext.ZetaCoreContext + chainParams observertypes.ChainParams ts *metrics.TelemetryServer - blockCache *lru.Cache - blockCacheV3 *lru.Cache // blockCacheV3 caches blocks containing type-3 (BlobTxType) transactions - headerCache *lru.Cache + + blockCache *lru.Cache + blockCacheV3 *lru.Cache // blockCacheV3 caches blocks containing type-3 (BlobTxType) transactions + headerCache *lru.Cache } // NewEVMChainClient returns a new configuration based on supplied target chain func NewEVMChainClient( + appContext *appcontext.AppContext, bridge interfaces.ZetaCoreBridger, tss interfaces.TSSSigner, dbpath string, loggers clientcommon.ClientLogger, - cfg *config.Config, evmCfg config.EVMConfig, ts *metrics.TelemetryServer, ) (*ChainClient, error) { @@ -122,8 +126,12 @@ func NewEVMChainClient( ObserveOutTx: chainLogger.With().Str("module", "ObserveOutTx").Logger(), Compliance: loggers.Compliance, } - ob.cfg = cfg - ob.params = evmCfg.ChainParams + ob.coreContext = appContext.ZetaCoreContext() + chainParams, found := ob.coreContext.GetEVMChainParams(evmCfg.Chain.ChainId) + if !found { + return nil, fmt.Errorf("evm chains params not initialized for chain %d", evmCfg.Chain.ChainId) + } + ob.chainParams = *chainParams ob.stop = make(chan struct{}) ob.chain = evmCfg.Chain ob.Mu = &sync.Mutex{} @@ -198,28 +206,16 @@ func (ob *ChainClient) WithZetaClient(bridge *zetabridge.ZetaCoreBridge) { ob.zetaClient = bridge } -func (ob *ChainClient) WithParams(params observertypes.ChainParams) { - ob.Mu.Lock() - defer ob.Mu.Unlock() - ob.params = params -} - -func (ob *ChainClient) SetConfig(cfg *config.Config) { - ob.Mu.Lock() - defer ob.Mu.Unlock() - ob.cfg = cfg -} - func (ob *ChainClient) SetChainParams(params observertypes.ChainParams) { ob.Mu.Lock() defer ob.Mu.Unlock() - ob.params = params + ob.chainParams = params } func (ob *ChainClient) GetChainParams() observertypes.ChainParams { ob.Mu.Lock() defer ob.Mu.Unlock() - return ob.params + return ob.chainParams } func (ob *ChainClient) GetConnectorContract() (ethcommon.Address, *zetaconnector.ZetaConnectorNonEth, error) { diff --git a/zetaclient/evm/inbounds.go b/zetaclient/evm/inbounds.go index 9eca478955..ffb65fd5f4 100644 --- a/zetaclient/evm/inbounds.go +++ b/zetaclient/evm/inbounds.go @@ -354,12 +354,13 @@ func (ob *ChainClient) GetInboundVoteMsgForZetaSentEvent(event *zetaconnector.Ze } if !destChain.IsZetaChain() { - cfgDest, found := ob.cfg.GetEVMConfig(destChain.ChainId) + paramsDest, found := ob.coreContext.GetEVMChainParams(destChain.ChainId) if !found { - ob.logger.ExternalChainWatcher.Warn().Msgf("chain id not present in EVMChainConfigs %d", event.DestinationChainId.Int64()) + ob.logger.ExternalChainWatcher.Warn().Msgf("chain id not present in EVMChainParams %d", event.DestinationChainId.Int64()) return nil } - if strings.EqualFold(destAddr, cfgDest.ZetaTokenContractAddress) { + + if strings.EqualFold(destAddr, paramsDest.ZetaTokenContractAddress) { ob.logger.ExternalChainWatcher.Warn().Msgf("potential attack attempt: %s destination address is ZETA token contract address %s", destChain, destAddr) return nil } diff --git a/zetaclient/supplychecker/zeta_supply_checker.go b/zetaclient/supplychecker/zeta_supply_checker.go index 1d560794e5..2a2e112c4a 100644 --- a/zetaclient/supplychecker/zeta_supply_checker.go +++ b/zetaclient/supplychecker/zeta_supply_checker.go @@ -3,6 +3,7 @@ package supplychecker import ( "fmt" + appcontext "github.com/zeta-chain/zetacore/zetaclient/app_context" "github.com/zeta-chain/zetacore/zetaclient/bitcoin" "github.com/zeta-chain/zetacore/zetaclient/interfaces" "github.com/zeta-chain/zetacore/zetaclient/zetabridge" @@ -16,12 +17,12 @@ import ( "github.com/rs/zerolog" "github.com/zeta-chain/zetacore/common" "github.com/zeta-chain/zetacore/x/crosschain/types" - "github.com/zeta-chain/zetacore/zetaclient/config" + corecontext "github.com/zeta-chain/zetacore/zetaclient/core_context" clienttypes "github.com/zeta-chain/zetacore/zetaclient/types" ) type ZetaSupplyChecker struct { - cfg *config.Config + coreContext *corecontext.ZetaCoreContext evmClient map[int64]*ethclient.Client zetaClient *zetabridge.ZetaCoreBridge ticker *clienttypes.DynamicTicker @@ -32,7 +33,7 @@ type ZetaSupplyChecker struct { genesisSupply sdkmath.Int } -func NewZetaSupplyChecker(cfg *config.Config, zetaClient *zetabridge.ZetaCoreBridge, logger zerolog.Logger) (ZetaSupplyChecker, error) { +func NewZetaSupplyChecker(appContext *appcontext.AppContext, zetaClient *zetabridge.ZetaCoreBridge, logger zerolog.Logger) (ZetaSupplyChecker, error) { dynamicTicker, err := clienttypes.NewDynamicTicker("ZETASupplyTicker", 15) if err != nil { return ZetaSupplyChecker{}, err @@ -45,10 +46,10 @@ func NewZetaSupplyChecker(cfg *config.Config, zetaClient *zetabridge.ZetaCoreBri logger: logger.With(). Str("module", "ZetaSupplyChecker"). Logger(), - cfg: cfg, - zetaClient: zetaClient, + coreContext: appContext.ZetaCoreContext(), + zetaClient: zetaClient, } - for _, evmConfig := range cfg.GetAllEVMConfigs() { + for _, evmConfig := range appContext.Config().GetAllEVMConfigs() { if evmConfig.Chain.IsZetaChain() { continue } @@ -106,11 +107,12 @@ func (zs *ZetaSupplyChecker) CheckZetaTokenSupply() error { externalChainTotalSupply := sdkmath.ZeroInt() for _, chain := range zs.externalEvmChain { - externalEvmChainConfig, ok := zs.cfg.GetEVMConfig(chain.ChainId) + externalEvmChainParams, ok := zs.coreContext.GetEVMChainParams(chain.ChainId) if !ok { - return fmt.Errorf("externalEvmChainConfig not found for chain id %d", chain.ChainId) + return fmt.Errorf("externalEvmChainParams not found for chain id %d", chain.ChainId) } - zetaTokenAddressString := externalEvmChainConfig.ZetaTokenContractAddress + + zetaTokenAddressString := externalEvmChainParams.ZetaTokenContractAddress zetaTokenAddress := ethcommon.HexToAddress(zetaTokenAddressString) zetatokenNonEth, err := evm.FetchZetaZetaNonEthTokenContract(zetaTokenAddress, zs.evmClient[chain.ChainId]) if err != nil { @@ -128,11 +130,11 @@ func (zs *ZetaSupplyChecker) CheckZetaTokenSupply() error { externalChainTotalSupply = externalChainTotalSupply.Add(totalSupplyInt) } - ethConfig, ok := zs.cfg.GetEVMConfig(zs.ethereumChain.ChainId) + evmChainParams, ok := zs.coreContext.GetEVMChainParams(zs.ethereumChain.ChainId) if !ok { return fmt.Errorf("eth config not found for chain id %d", zs.ethereumChain.ChainId) } - ethConnectorAddressString := ethConfig.ConnectorContractAddress + ethConnectorAddressString := evmChainParams.ConnectorContractAddress ethConnectorAddress := ethcommon.HexToAddress(ethConnectorAddressString) ethConnectorContract, err := evm.FetchConnectorContractEth(ethConnectorAddress, zs.evmClient[zs.ethereumChain.ChainId]) if err != nil { diff --git a/zetaclient/tss/tss_signer.go b/zetaclient/tss/tss_signer.go index 00bdd43d6c..f9abdb78ee 100644 --- a/zetaclient/tss/tss_signer.go +++ b/zetaclient/tss/tss_signer.go @@ -12,6 +12,7 @@ import ( "strings" "time" + appcontext "github.com/zeta-chain/zetacore/zetaclient/app_context" "github.com/zeta-chain/zetacore/zetaclient/interfaces" "github.com/zeta-chain/zetacore/zetaclient/keys" @@ -81,34 +82,34 @@ type TSS struct { // NewTSS creates a new TSS instance func NewTSS( + appContext *appcontext.AppContext, peer p2p.AddrList, privkey tmcrypto.PrivKey, preParams *keygen.LocalPreParams, - cfg *config.Config, bridge interfaces.ZetaCoreBridger, tssHistoricalList []observertypes.TSS, bitcoinChainID int64, tssPassword string, hotkeyPassword string, ) (*TSS, error) { - server, err := SetupTSSServer(peer, privkey, preParams, cfg, tssPassword) + server, err := SetupTSSServer(peer, privkey, preParams, appContext.Config(), tssPassword) if err != nil { return nil, fmt.Errorf("SetupTSSServer error: %w", err) } newTss := TSS{ Server: server, Keys: make(map[string]*Key), - CurrentPubkey: cfg.CurrentTssPubkey, + CurrentPubkey: appContext.ZetaCoreContext().GetCurrentTssPubkey(), logger: log.With().Str("module", "tss_signer").Logger(), CoreBridge: bridge, BitcoinChainID: bitcoinChainID, } - err = newTss.LoadTssFilesFromDirectory(cfg.TssPath) + err = newTss.LoadTssFilesFromDirectory(appContext.Config().TssPath) if err != nil { return nil, err } - _, pubkeyInBech32, err := keys.GetKeyringKeybase(cfg, hotkeyPassword) + _, pubkeyInBech32, err := keys.GetKeyringKeybase(appContext.Config(), hotkeyPassword) if err != nil { return nil, err } diff --git a/zetaclient/zetabridge/tx.go b/zetaclient/zetabridge/tx.go index 863f7a3254..a142ad44f0 100644 --- a/zetaclient/zetabridge/tx.go +++ b/zetaclient/zetabridge/tx.go @@ -7,6 +7,7 @@ import ( "time" "cosmossdk.io/math" + appcontext "github.com/zeta-chain/zetacore/zetaclient/app_context" authz2 "github.com/zeta-chain/zetacore/zetaclient/authz" sdk "github.com/cosmos/cosmos-sdk/types" @@ -16,7 +17,6 @@ import ( "github.com/zeta-chain/zetacore/common" "github.com/zeta-chain/zetacore/x/crosschain/types" observerTypes "github.com/zeta-chain/zetacore/x/observer/types" - "github.com/zeta-chain/zetacore/zetaclient/config" ) const ( @@ -151,19 +151,20 @@ func (b *ZetaCoreBridge) SetTSS(tssPubkey string, keyGenZetaHeight int64, status return "", fmt.Errorf("set tss failed | err %s", err.Error()) } -func (b *ZetaCoreBridge) ConfigUpdater(cfg *config.Config) { - b.logger.Info().Msg("ConfigUpdater started") - ticker := time.NewTicker(time.Duration(cfg.ConfigUpdateTicker) * time.Second) +// CoreContextUpdater is a polling goroutine that checks and updates core context at every height +func (b *ZetaCoreBridge) CoreContextUpdater(appContext *appcontext.AppContext) { + b.logger.Info().Msg("CoreContextUpdater started") + ticker := time.NewTicker(time.Duration(appContext.Config().ConfigUpdateTicker) * time.Second) for { select { case <-ticker.C: b.logger.Debug().Msg("Running Updater") - err := b.UpdateConfigFromCore(cfg, false) + err := b.UpdateZetaCoreContext(appContext.ZetaCoreContext(), false) if err != nil { - b.logger.Err(err).Msg("ConfigUpdater failed to update config") + b.logger.Err(err).Msg("CoreContextUpdater failed to update config") } case <-b.stop: - b.logger.Info().Msg("ConfigUpdater stopped") + b.logger.Info().Msg("CoreContextUpdater stopped") return } } @@ -301,7 +302,6 @@ func (b *ZetaCoreBridge) MonitorVoteInboundTxResult(zetaTxHash string, retryGasL b.logger.Error().Err(lastErr).Msgf( "MonitorInboundTxResult: unable to query tx result for txHash %s, err %s", zetaTxHash, lastErr.Error(), ) - return } // PostVoteOutbound posts a vote on an observed outbound tx @@ -427,5 +427,4 @@ func (b *ZetaCoreBridge) MonitorVoteOutboundTxResult(zetaTxHash string, retryGas b.logger.Error().Err(lastErr).Msgf( "MonitorVoteOutboundTxResult: unable to query tx result for txHash %s, err %s", zetaTxHash, lastErr.Error(), ) - return } diff --git a/zetaclient/zetabridge/zetacore_bridge.go b/zetaclient/zetabridge/zetacore_bridge.go index 15a462f818..9e5a38ca11 100644 --- a/zetaclient/zetabridge/zetacore_bridge.go +++ b/zetaclient/zetabridge/zetacore_bridge.go @@ -22,6 +22,7 @@ import ( crosschaintypes "github.com/zeta-chain/zetacore/x/crosschain/types" observertypes "github.com/zeta-chain/zetacore/x/observer/types" "github.com/zeta-chain/zetacore/zetaclient/config" + corecontext "github.com/zeta-chain/zetacore/zetaclient/core_context" "google.golang.org/grpc" ) @@ -189,7 +190,9 @@ func (b *ZetaCoreBridge) GetKeys() *keys.Keys { return b.keys } -func (b *ZetaCoreBridge) UpdateConfigFromCore(cfg *config.Config, init bool) error { +// UpdateZetaCoreContext updates core context +// zetacore stores core context for all clients +func (b *ZetaCoreBridge) UpdateZetaCoreContext(coreContext *corecontext.ZetaCoreContext, init bool) error { bn, err := b.GetZetaBlockHeight() if err != nil { return err @@ -243,14 +246,16 @@ func (b *ZetaCoreBridge) UpdateConfigFromCore(cfg *config.Config, init bool) err if err != nil { b.logger.Info().Msg("Unable to fetch keygen from zetabridge") } - cfg.UpdateChainParams(keyGen, newChains, newEVMParams, newBTCParams, init, b.logger) + tssPubKey := "" tss, err := b.GetCurrentTss() if err != nil { b.logger.Debug().Err(err).Msg("Unable to fetch TSS from zetabridge") } else { - cfg.CurrentTssPubkey = tss.GetTssPubkey() + tssPubKey = tss.GetTssPubkey() } + + coreContext.Update(keyGen, newChains, newEVMParams, newBTCParams, tssPubKey, init, b.logger) return nil } diff --git a/zetaclient/zetacore_observer.go b/zetaclient/zetacore_observer.go index c3b94c8c54..6d3320c746 100644 --- a/zetaclient/zetacore_observer.go +++ b/zetaclient/zetacore_observer.go @@ -5,9 +5,9 @@ import ( "math" "time" + appcontext "github.com/zeta-chain/zetacore/zetaclient/app_context" "github.com/zeta-chain/zetacore/zetaclient/bitcoin" "github.com/zeta-chain/zetacore/zetaclient/interfaces" - "github.com/zeta-chain/zetacore/zetaclient/metrics" "github.com/zeta-chain/zetacore/zetaclient/outtxprocessor" observertypes "github.com/zeta-chain/zetacore/x/observer/types" @@ -17,7 +17,7 @@ import ( "github.com/rs/zerolog" "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" ) const ( @@ -35,7 +35,6 @@ type CoreObserver struct { signerMap map[common.Chain]interfaces.ChainSigner clientMap map[common.Chain]interfaces.ChainClient logger ZetaCoreLog - cfg *config.Config ts *metrics.TelemetryServer stop chan struct{} lastOperatorBalance sdkmath.Int @@ -47,14 +46,12 @@ func NewCoreObserver( signerMap map[common.Chain]interfaces.ChainSigner, clientMap map[common.Chain]interfaces.ChainClient, logger zerolog.Logger, - cfg *config.Config, ts *metrics.TelemetryServer, ) *CoreObserver { co := CoreObserver{ ts: ts, stop: make(chan struct{}), } - co.cfg = cfg chainLogger := logger.With(). Str("chain", "ZetaChain"). Logger() @@ -77,14 +74,10 @@ func NewCoreObserver( return &co } -func (co *CoreObserver) Config() *config.Config { - return co.cfg -} - -func (co *CoreObserver) MonitorCore() { +func (co *CoreObserver) MonitorCore(appContext *appcontext.AppContext) { myid := co.bridge.GetKeys().GetAddress() co.logger.ZetaChainWatcher.Info().Msgf("Starting Send Scheduler for %s", myid) - go co.startCctxScheduler() + go co.startCctxScheduler(appContext) go func() { // bridge queries UpgradePlan from zetabridge and send to its pause channel if upgrade height is reached @@ -98,7 +91,7 @@ func (co *CoreObserver) MonitorCore() { } // startCctxScheduler schedules keysigns for cctxs on each ZetaChain block (the ticker) -func (co *CoreObserver) startCctxScheduler() { +func (co *CoreObserver) startCctxScheduler(appContext *appcontext.AppContext) { outTxMan := outtxprocessor.NewOutTxProcessorManager(co.logger.ChainLogger) observeTicker := time.NewTicker(3 * time.Second) var lastBlockNum int64 @@ -142,7 +135,7 @@ func (co *CoreObserver) startCctxScheduler() { metrics.HotKeyBurnRate.Set(float64(co.ts.HotKeyBurnRate.GetBurnRate().Int64())) // schedule keysign for pending cctxs on each chain - supportedChains := co.Config().GetEnabledChains() + supportedChains := appContext.ZetaCoreContext().GetEnabledChains() for _, c := range supportedChains { if c.ChainId == co.bridge.ZetaChain().ChainId { continue @@ -154,7 +147,7 @@ func (co *CoreObserver) startCctxScheduler() { co.logger.ZetaChainWatcher.Error().Err(err).Msgf("startCctxScheduler: ListPendingCctx failed for chain %d", c.ChainId) continue } - ob, err := co.getUpdatedChainOb(c.ChainId) + ob, err := co.getUpdatedChainOb(appContext, c.ChainId) if err != nil { co.logger.ZetaChainWatcher.Error().Err(err).Msgf("startCctxScheduler: getTargetChainOb failed for chain %d", c.ChainId) continue @@ -324,7 +317,7 @@ func (co *CoreObserver) scheduleCctxBTC( } } -func (co *CoreObserver) getUpdatedChainOb(chainID int64) (interfaces.ChainClient, error) { +func (co *CoreObserver) getUpdatedChainOb(appContext *appcontext.AppContext, chainID int64) (interfaces.ChainClient, error) { chainOb, err := co.getTargetChainOb(chainID) if err != nil { return nil, err @@ -332,22 +325,23 @@ func (co *CoreObserver) getUpdatedChainOb(chainID int64) (interfaces.ChainClient // update chain client core parameters curParams := chainOb.GetChainParams() if common.IsEVMChain(chainID) { - evmCfg, found := co.cfg.GetEVMConfig(chainID) - if found && !observertypes.ChainParamsEqual(curParams, evmCfg.ChainParams) { - chainOb.SetChainParams(evmCfg.ChainParams) + evmParams, found := appContext.ZetaCoreContext().GetEVMChainParams(chainID) + if found && !observertypes.ChainParamsEqual(curParams, *evmParams) { + chainOb.SetChainParams(*evmParams) co.logger.ZetaChainWatcher.Info().Msgf( "updated chain params for chainID %d, new params: %v", chainID, - evmCfg.ChainParams, + *evmParams, ) } } else if common.IsBitcoinChain(chainID) { - _, btcCfg, found := co.cfg.GetBTCConfig() - if found && !observertypes.ChainParamsEqual(curParams, btcCfg.ChainParams) { - chainOb.SetChainParams(btcCfg.ChainParams) + _, btcParams, found := appContext.ZetaCoreContext().GetBTCChainParams() + + if found && !observertypes.ChainParamsEqual(curParams, *btcParams) { + chainOb.SetChainParams(*btcParams) co.logger.ZetaChainWatcher.Info().Msgf( "updated chain params for Bitcoin, new params: %v", - btcCfg.ChainParams, + *btcParams, ) } }