Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add Solana RPC status check and some refactor around RPC status check #2751

Merged
merged 15 commits into from
Sep 13, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
* [2681](https://github.com/zeta-chain/node/pull/2681) - implement `MsgUpdateERC20CustodyPauseStatus` to pause or unpause ERC20 Custody contract (to be used for the migration process for smart contract V2)
* [2644](https://github.com/zeta-chain/node/pull/2644) - add created_timestamp to cctx status
* [2673](https://github.com/zeta-chain/node/pull/2673) - add relayer key importer, encryption and decryption
* [2751](https://github.com/zeta-chain/node/pull/2751) - add RPC status check for Solana chain

### Refactor

Expand Down
67 changes: 1 addition & 66 deletions zetaclient/chains/bitcoin/observer/observer.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"math"
"math/big"
"sort"
"time"

"github.com/btcsuite/btcd/btcjson"
"github.com/btcsuite/btcd/chaincfg"
Expand Down Expand Up @@ -224,70 +223,6 @@ func (ob *Observer) Start(ctx context.Context) {
bg.Work(ctx, ob.WatchRPCStatus, bg.WithName("WatchRPCStatus"), bg.WithLogger(ob.Logger().Chain))
}

// WatchRPCStatus watches the RPC status of the Bitcoin chain
// TODO(revamp): move ticker related functions to a specific file
// TODO(revamp): move inner logic in a separate function
func (ob *Observer) WatchRPCStatus(_ context.Context) error {
ob.logger.Chain.Info().Msgf("RPCStatus is starting")
ticker := time.NewTicker(60 * time.Second)

for {
select {
case <-ticker.C:
if !ob.GetChainParams().IsSupported {
continue
}

bn, err := ob.btcClient.GetBlockCount()
if err != nil {
ob.logger.Chain.Error().Err(err).Msg("RPC status check: RPC down? ")
continue
}

hash, err := ob.btcClient.GetBlockHash(bn)
if err != nil {
ob.logger.Chain.Error().Err(err).Msg("RPC status check: RPC down? ")
continue
}

header, err := ob.btcClient.GetBlockHeader(hash)
if err != nil {
ob.logger.Chain.Error().Err(err).Msg("RPC status check: RPC down? ")
continue
}

blockTime := header.Timestamp
elapsedSeconds := time.Since(blockTime).Seconds()
if elapsedSeconds > 1200 {
ob.logger.Chain.Error().Err(err).Msg("RPC status check: RPC down? ")
continue
}

tssAddr := ob.TSS().BTCAddressWitnessPubkeyHash()
res, err := ob.btcClient.ListUnspentMinMaxAddresses(0, 1000000, []btcutil.Address{tssAddr})
if err != nil {
ob.logger.Chain.Error().
Err(err).
Msg("RPC status check: can't list utxos of TSS address; wallet or loaded? TSS address is not imported? ")
continue
}

if len(res) == 0 {
ob.logger.Chain.Error().
Err(err).
Msg("RPC status check: TSS address has no utxos; TSS address is not imported? ")
continue
}

ob.logger.Chain.Info().
Msgf("[OK] RPC status check: latest block number %d, timestamp %s (%.fs ago), tss addr %s, #utxos: %d", bn, blockTime, elapsedSeconds, tssAddr, len(res))

case <-ob.StopChannel():
return nil
}
}
}

// GetPendingNonce returns the artificial pending nonce
// Note: pending nonce is accessed concurrently
func (ob *Observer) GetPendingNonce() uint64 {
Expand Down Expand Up @@ -399,12 +334,12 @@ func (ob *Observer) PostGasPrice(ctx context.Context) error {
// TODO(revamp): move in upper package to separate file (e.g., rpc.go)
func GetSenderAddressByVin(rpcClient interfaces.BTCRPCClient, vin btcjson.Vin, net *chaincfg.Params) (string, error) {
// query previous raw transaction by txid
// GetTransaction requires reconfiguring the bitcoin node (txindex=1), so we use GetRawTransaction instead
hash, err := chainhash.NewHashFromStr(vin.Txid)
if err != nil {
return "", err
}

// this requires running bitcoin node with 'txindex=1'
tx, err := rpcClient.GetRawTransaction(hash)
if err != nil {
return "", errors.Wrapf(err, "error getting raw transaction %s", vin.Txid)
Expand Down
33 changes: 33 additions & 0 deletions zetaclient/chains/bitcoin/observer/rpc_status.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package observer

import (
"context"
"time"

"github.com/zeta-chain/zetacore/zetaclient/chains/bitcoin/rpc"
"github.com/zeta-chain/zetacore/zetaclient/common"
)

// WatchRPCStatus watches the RPC status of the Bitcoin chain
func (ob *Observer) WatchRPCStatus(_ context.Context) error {
ob.Logger().Chain.Info().Msgf("WatchRPCStatus started for chain %d", ob.Chain().ChainId)

Check warning on line 13 in zetaclient/chains/bitcoin/observer/rpc_status.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/observer/rpc_status.go#L12-L13

Added lines #L12 - L13 were not covered by tests
ws4charlie marked this conversation as resolved.
Show resolved Hide resolved

ticker := time.NewTicker(common.RPCStatusCheckInterval)
swift1337 marked this conversation as resolved.
Show resolved Hide resolved
for {
select {
case <-ticker.C:
if !ob.GetChainParams().IsSupported {
continue

Check warning on line 20 in zetaclient/chains/bitcoin/observer/rpc_status.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/observer/rpc_status.go#L15-L20

Added lines #L15 - L20 were not covered by tests
}

tssAddress := ob.TSS().BTCAddressWitnessPubkeyHash()
err := rpc.CheckRPCStatus(ob.btcClient, tssAddress, ob.Logger().Chain)
if err != nil {
ob.Logger().Chain.Error().Err(err).Msg("RPC Status error")

Check warning on line 26 in zetaclient/chains/bitcoin/observer/rpc_status.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/observer/rpc_status.go#L23-L26

Added lines #L23 - L26 were not covered by tests
}

case <-ob.StopChannel():
return nil

Check warning on line 30 in zetaclient/chains/bitcoin/observer/rpc_status.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/observer/rpc_status.go#L29-L30

Added lines #L29 - L30 were not covered by tests
}
}
ws4charlie marked this conversation as resolved.
Show resolved Hide resolved
}
54 changes: 54 additions & 0 deletions zetaclient/chains/bitcoin/rpc/rpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@

import (
"fmt"
"time"

"github.com/btcsuite/btcd/btcjson"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/rpcclient"
"github.com/btcsuite/btcutil"
"github.com/pkg/errors"
"github.com/rs/zerolog"

"github.com/zeta-chain/zetacore/zetaclient/chains/bitcoin"
"github.com/zeta-chain/zetacore/zetaclient/chains/interfaces"
Expand All @@ -20,6 +23,10 @@

// defaultTestnetFeeRate is the default fee rate for testnet, 10 sat/byte
defaultTestnetFeeRate = 10

// rpcLatencyThreshold is the threshold for RPC latency to be considered unhealthy
// Bitcoin block time is 10 minutes, 1200s (20 minutes) is a reasonable threshold for Bitcoin
rpcLatencyThreshold = 1200
ws4charlie marked this conversation as resolved.
Show resolved Hide resolved
)

// NewRPCClient creates a new RPC client by the given config.
Expand Down Expand Up @@ -157,3 +164,50 @@
// #nosec G115 always in range
return uint64(highestRate), nil
}

// CheckRPCStatus checks the RPC status of the evm chain
func CheckRPCStatus(client interfaces.BTCRPCClient, tssAddress btcutil.Address, logger zerolog.Logger) error {

Check warning on line 169 in zetaclient/chains/bitcoin/rpc/rpc.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/rpc/rpc.go#L169

Added line #L169 was not covered by tests
// query latest block number
bn, err := client.GetBlockCount()
if err != nil {
return errors.Wrap(err, "GetBlockCount error: RPC down?")

Check warning on line 173 in zetaclient/chains/bitcoin/rpc/rpc.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/rpc/rpc.go#L171-L173

Added lines #L171 - L173 were not covered by tests
}

// query latest block header
hash, err := client.GetBlockHash(bn)
if err != nil {
return errors.Wrap(err, "GetBlockHash error: RPC down?")

Check warning on line 179 in zetaclient/chains/bitcoin/rpc/rpc.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/rpc/rpc.go#L177-L179

Added lines #L177 - L179 were not covered by tests
}

// query latest block header thru hash
header, err := client.GetBlockHeader(hash)
if err != nil {
return errors.Wrap(err, "GetBlockHeader error: RPC down?")

Check warning on line 185 in zetaclient/chains/bitcoin/rpc/rpc.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/rpc/rpc.go#L183-L185

Added lines #L183 - L185 were not covered by tests
}

// latest block should not be too old
blockTime := header.Timestamp
elapsedSeconds := time.Since(blockTime).Seconds()
if elapsedSeconds > rpcLatencyThreshold {
return errors.Errorf(
"Latest block %d is %.0fs old, RPC stale or chain stuck (check explorer)?",
bn,
elapsedSeconds,
)

Check warning on line 196 in zetaclient/chains/bitcoin/rpc/rpc.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/rpc/rpc.go#L189-L196

Added lines #L189 - L196 were not covered by tests
}

// should be able to list utxos owned by TSS address
res, err := client.ListUnspentMinMaxAddresses(0, 1000000, []btcutil.Address{tssAddress})
if err != nil {
return errors.Wrap(err, "can't list utxos of TSS address; TSS address is not imported?")

Check warning on line 202 in zetaclient/chains/bitcoin/rpc/rpc.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/rpc/rpc.go#L200-L202

Added lines #L200 - L202 were not covered by tests
}

// TSS address should have utxos
if len(res) == 0 {
return errors.New("TSS address has no utxos; TSS address is not imported?")

Check warning on line 207 in zetaclient/chains/bitcoin/rpc/rpc.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/rpc/rpc.go#L206-L207

Added lines #L206 - L207 were not covered by tests
}

logger.Info().
Msgf("RPC Status [OK]: latest block %d, timestamp %s (%.fs ago), tss addr %s, #utxos: %d", bn, blockTime, elapsedSeconds, tssAddress, len(res))
return nil

Check warning on line 212 in zetaclient/chains/bitcoin/rpc/rpc.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/rpc/rpc.go#L210-L212

Added lines #L210 - L212 were not covered by tests
}
ws4charlie marked this conversation as resolved.
Show resolved Hide resolved
19 changes: 18 additions & 1 deletion zetaclient/chains/bitcoin/rpc/rpc_live_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@ func TestBitcoinObserverLive(t *testing.T) {
// suite.Run(t, new(BitcoinClientTestSuite))

// LiveTestNewRPCClient(t)
// LiveTestCheckRPCStatus(t)
// LiveTestGetBlockHeightByHash(t)
// LiveTestBitcoinFeeRate(t)
// LiveTestAvgFeeRateMainnetMempoolSpace(t)
Expand All @@ -232,7 +233,7 @@ func LiveTestNewRPCClient(t *testing.T) {
btcConfig := config.BTCConfig{
RPCUsername: "user",
RPCPassword: "pass",
RPCHost: "bitcoin.rpc.zetachain.com/6315704c-49bc-4649-8b9d-e9278a1dfeb3",
RPCHost: os.Getenv("BTC_RPC_TESTNET"),
RPCParams: "mainnet",
}

Expand All @@ -246,6 +247,22 @@ func LiveTestNewRPCClient(t *testing.T) {
require.Greater(t, bn, int64(0))
}

// LiveTestCheckRPCStatus checks the RPC status of the Bitcoin chain
func LiveTestCheckRPCStatus(t *testing.T) {
// setup Bitcoin client
chainID := chains.BitcoinMainnet.ChainId
client, err := createRPCClient(chainID)
require.NoError(t, err)

// decode tss address
tssAddress, err := chains.DecodeBtcAddress(testutils.TSSAddressBTCMainnet, chainID)
require.NoError(t, err)

// check RPC status
err = rpc.CheckRPCStatus(client, tssAddress, log.Logger)
require.NoError(t, err)
}

// LiveTestGetBlockHeightByHash queries Bitcoin block height by hash
func LiveTestGetBlockHeightByHash(t *testing.T) {
// setup Bitcoin client
Expand Down
44 changes: 0 additions & 44 deletions zetaclient/chains/evm/observer/observer.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"math"
"math/big"
"strings"
"time"

ethcommon "github.com/ethereum/go-ethereum/common"
ethtypes "github.com/ethereum/go-ethereum/core/types"
Expand Down Expand Up @@ -202,49 +201,6 @@ func (ob *Observer) Start(ctx context.Context) {
bg.Work(ctx, ob.WatchRPCStatus, bg.WithName("WatchRPCStatus"), bg.WithLogger(ob.Logger().Chain))
}

// WatchRPCStatus watches the RPC status of the evm chain
// TODO(revamp): move ticker to ticker file
// TODO(revamp): move inner logic to a separate function
func (ob *Observer) WatchRPCStatus(ctx context.Context) error {
ob.Logger().Chain.Info().Msgf("Starting RPC status check for chain %d", ob.Chain().ChainId)
ticker := time.NewTicker(60 * time.Second)
for {
select {
case <-ticker.C:
if !ob.GetChainParams().IsSupported {
continue
}
bn, err := ob.evmClient.BlockNumber(ctx)
if err != nil {
ob.Logger().Chain.Error().Err(err).Msg("RPC Status Check error: RPC down?")
continue
}
gasPrice, err := ob.evmClient.SuggestGasPrice(ctx)
if err != nil {
ob.Logger().Chain.Error().Err(err).Msg("RPC Status Check error: RPC down?")
continue
}
header, err := ob.evmClient.HeaderByNumber(ctx, new(big.Int).SetUint64(bn))
if err != nil {
ob.Logger().Chain.Error().Err(err).Msg("RPC Status Check error: RPC down?")
continue
}
// #nosec G115 always in range
blockTime := time.Unix(int64(header.Time), 0).UTC()
elapsedSeconds := time.Since(blockTime).Seconds()
if elapsedSeconds > 100 {
ob.Logger().Chain.Warn().
Msgf("RPC Status Check warning: RPC stale or chain stuck (check explorer)? Latest block %d timestamp is %.0fs ago", bn, elapsedSeconds)
continue
}
ob.Logger().Chain.Info().
Msgf("[OK] RPC status: latest block num %d, timestamp %s ( %.0fs ago), suggested gas price %d", header.Number, blockTime.String(), elapsedSeconds, gasPrice.Uint64())
case <-ob.StopChannel():
return nil
}
}
}

// SetTxNReceipt sets the receipt and transaction in memory
func (ob *Observer) SetTxNReceipt(nonce uint64, receipt *ethtypes.Receipt, transaction *ethtypes.Transaction) {
ob.Mu().Lock()
Expand Down
32 changes: 32 additions & 0 deletions zetaclient/chains/evm/observer/rpc_status.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Package observer implements the EVM chain observer
package observer

import (
"context"
"time"

"github.com/zeta-chain/zetacore/zetaclient/chains/evm/rpc"
"github.com/zeta-chain/zetacore/zetaclient/common"
)

// WatchRPCStatus watches the RPC status of the evm chain
func (ob *Observer) WatchRPCStatus(ctx context.Context) error {
ob.Logger().Chain.Info().Msgf("WatchRPCStatus started for chain %d", ob.Chain().ChainId)

Check warning on line 14 in zetaclient/chains/evm/observer/rpc_status.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/evm/observer/rpc_status.go#L13-L14

Added lines #L13 - L14 were not covered by tests
ws4charlie marked this conversation as resolved.
Show resolved Hide resolved

ticker := time.NewTicker(common.RPCStatusCheckInterval)
ws4charlie marked this conversation as resolved.
Show resolved Hide resolved
for {
select {
case <-ticker.C:
if !ob.GetChainParams().IsSupported {
continue

Check warning on line 21 in zetaclient/chains/evm/observer/rpc_status.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/evm/observer/rpc_status.go#L16-L21

Added lines #L16 - L21 were not covered by tests
}

err := rpc.CheckRPCStatus(ctx, ob.evmClient, ob.Logger().Chain)
if err != nil {
ob.Logger().Chain.Error().Err(err).Msg("RPC Status error")

Check warning on line 26 in zetaclient/chains/evm/observer/rpc_status.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/evm/observer/rpc_status.go#L24-L26

Added lines #L24 - L26 were not covered by tests
}
case <-ob.StopChannel():
return nil

Check warning on line 29 in zetaclient/chains/evm/observer/rpc_status.go

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/evm/observer/rpc_status.go#L28-L29

Added lines #L28 - L29 were not covered by tests
}
}
ws4charlie marked this conversation as resolved.
Show resolved Hide resolved
}
Loading
Loading