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

fix: special handle Bitcoin Testnet gas price estimator #2452

Merged
merged 4 commits into from
Jul 11, 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 @@ -89,6 +89,7 @@
* [2327](https://github.com/zeta-chain/node/pull/2327) - partially cherry picked the fix to Bitcoin outbound dust amount
* [2362](https://github.com/zeta-chain/node/pull/2362) - set 1000 satoshis as minimum BTC amount that can be withdrawn from zEVM
* [2382](https://github.com/zeta-chain/node/pull/2382) - add tx input and gas in rpc methods for synthetic eth txs
* [2396](https://github.com/zeta-chain/node/issues/2386) - special handle bitcoin testnet gas price estimator

### CI
* [2388](https://github.com/zeta-chain/node/pull/2388) - added GitHub attestations of binaries produced in the release workflow.
Expand Down
62 changes: 39 additions & 23 deletions zetaclient/chains/bitcoin/observer/observer.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
observertypes "github.com/zeta-chain/zetacore/x/observer/types"
"github.com/zeta-chain/zetacore/zetaclient/chains/base"
"github.com/zeta-chain/zetacore/zetaclient/chains/bitcoin"
"github.com/zeta-chain/zetacore/zetaclient/chains/bitcoin/rpc"
"github.com/zeta-chain/zetacore/zetaclient/chains/interfaces"
"github.com/zeta-chain/zetacore/zetaclient/context"
"github.com/zeta-chain/zetacore/zetaclient/metrics"
Expand Down Expand Up @@ -341,44 +342,42 @@
// PostGasPrice posts gas price to zetacore
// TODO(revamp): move to gas price file
func (ob *Observer) PostGasPrice() error {
// hardcode gas price here since this RPC is not available on regtest
if chains.IsBitcoinRegnet(ob.Chain().ChainId) {
blockNumber, err := ob.btcClient.GetBlockCount()
var err error
feeRateEstimated := uint64(0)

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/observer/observer.go#L345-L346

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

// special handle regnet and testnet gas rate
ws4charlie marked this conversation as resolved.
Show resolved Hide resolved
if ob.Chain().NetworkType != chains.NetworkType_mainnet {
feeRateEstimated, err = ob.specialHandleFeeRate()

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/observer/observer.go#L349-L350

Added lines #L349 - L350 were not covered by tests
if err != nil {
ob.logger.GasPrice.Err(err).Msg("error specialHandleFeeRate")

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/observer/observer.go#L352

Added line #L352 was not covered by tests
return err
}

// #nosec G701 always in range
_, err = ob.ZetacoreClient().PostGasPrice(ob.Chain(), 1, "100", uint64(blockNumber))
} else {

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/observer/observer.go#L355

Added line #L355 was not covered by tests
// EstimateSmartFee returns the fees per kilobyte (BTC/kb) targeting given block confirmation
feeResult, err := ob.btcClient.EstimateSmartFee(1, &btcjson.EstimateModeEconomical)

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/observer/observer.go#L357

Added line #L357 was not covered by tests
if err != nil {
ob.logger.GasPrice.Err(err).Msg("PostGasPrice:")
ob.logger.GasPrice.Err(err).Msg("error EstimateSmartFee")

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/observer/observer.go#L359

Added line #L359 was not covered by tests
return err
}
return nil
}

// EstimateSmartFee returns the fees per kilobyte (BTC/kb) targeting given block confirmation
feeResult, err := ob.btcClient.EstimateSmartFee(1, &btcjson.EstimateModeEconomical)
if err != nil {
return err
}
if feeResult.Errors != nil || feeResult.FeeRate == nil {
return fmt.Errorf("error getting gas price: %s", feeResult.Errors)
}
if *feeResult.FeeRate > math.MaxInt64 {
return fmt.Errorf("gas price is too large: %f", *feeResult.FeeRate)
if feeResult.Errors != nil || feeResult.FeeRate == nil {
return fmt.Errorf("error getting gas price: %s", feeResult.Errors)

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/observer/observer.go#L362-L363

Added lines #L362 - L363 were not covered by tests
}
if *feeResult.FeeRate > math.MaxInt64 {
return fmt.Errorf("gas price is too large: %f", *feeResult.FeeRate)

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/observer/observer.go#L365-L366

Added lines #L365 - L366 were not covered by tests
}
feeRateEstimated = bitcoin.FeeRateToSatPerByte(*feeResult.FeeRate).Uint64()

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/observer/observer.go#L368

Added line #L368 was not covered by tests
}
feeRatePerByte := bitcoin.FeeRateToSatPerByte(*feeResult.FeeRate)

// query the current block number
blockNumber, err := ob.btcClient.GetBlockCount()
if err != nil {
return err
}

// #nosec G701 always positive
_, err = ob.ZetacoreClient().PostGasPrice(ob.Chain(), feeRatePerByte.Uint64(), "100", uint64(blockNumber))
_, err = ob.ZetacoreClient().PostGasPrice(ob.Chain(), feeRateEstimated, "100", uint64(blockNumber))

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/observer/observer.go#L378

Added line #L378 was not covered by tests
if err != nil {
ob.logger.GasPrice.Err(err).Msg("PostGasPrice:")
ob.logger.GasPrice.Err(err).Msg("err PostGasPrice")

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/observer/observer.go#L380

Added line #L380 was not covered by tests
return err
}

Expand Down Expand Up @@ -644,6 +643,23 @@
return nil
}

// specialHandleFeeRate handles the fee rate for regnet and testnet
func (ob *Observer) specialHandleFeeRate() (uint64, error) {
switch ob.Chain().NetworkType {
case chains.NetworkType_privnet:

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/observer/observer.go#L647-L649

Added lines #L647 - L649 were not covered by tests
ws4charlie marked this conversation as resolved.
Show resolved Hide resolved
// hardcode gas price here since RPC 'EstimateSmartFee' is not available on regtest (privnet)
return 1, nil
case chains.NetworkType_testnet:
feeRateEstimated, err := rpc.GetRecentFeeRate(ob.btcClient, ob.netParams)
if err != nil {
return 0, errors.Wrapf(err, "error GetRecentFeeRate")

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/observer/observer.go#L651-L655

Added lines #L651 - L655 were not covered by tests
}
return feeRateEstimated, nil
default:
return 0, fmt.Errorf(" unsupported bitcoin network type %d", ob.Chain().NetworkType)

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/observer/observer.go#L657-L659

Added lines #L657 - L659 were not covered by tests
}
}

// isTssTransaction checks if a given transaction was sent by TSS itself.
// An unconfirmed transaction is safe to spend only if it was sent by TSS and verified by ourselves.
func (ob *Observer) isTssTransaction(txid string) bool {
Expand Down
50 changes: 50 additions & 0 deletions zetaclient/chains/bitcoin/rpc/rpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,24 @@
"fmt"

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

"github.com/zeta-chain/zetacore/zetaclient/chains/bitcoin"
"github.com/zeta-chain/zetacore/zetaclient/chains/interfaces"
"github.com/zeta-chain/zetacore/zetaclient/config"
)

const (
// feeRateCountBackBlocks is the default number of blocks to look back for fee rate estimation
feeRateCountBackBlocks = 2

// defaultTestnetFeeRate is the default fee rate for testnet, 10 sat/byte
defaultTestnetFeeRate = 10
kingpinXD marked this conversation as resolved.
Show resolved Hide resolved
)

// NewRPCClient creates a new RPC client by the given config.
func NewRPCClient(btcConfig config.BTCConfig) (*rpcclient.Client, error) {
connCfg := &rpcclient.ConnConfig{
Expand Down Expand Up @@ -107,3 +117,43 @@
// res.Confirmations < 0 (meaning not included)
return btcjson.TxRawResult{}, fmt.Errorf("GetRawTxResult: tx %s not included yet", hash)
}

// GetRecentFeeRate gets the highest fee rate from recent blocks
// Note: this method is only used for testnet
func GetRecentFeeRate(rpcClient interfaces.BTCRPCClient, netParams *chaincfg.Params) (uint64, error) {
blockNumber, err := rpcClient.GetBlockCount()
if err != nil {
return 0, err

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/rpc/rpc.go#L123-L126

Added lines #L123 - L126 were not covered by tests
ws4charlie marked this conversation as resolved.
Show resolved Hide resolved
}

// get the highest fee rate among recent 'countBack' blocks to avoid underestimation
highestRate := int64(0)
for i := int64(0); i < feeRateCountBackBlocks; i++ {

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/rpc/rpc.go#L130-L131

Added lines #L130 - L131 were not covered by tests
// get the block
hash, err := rpcClient.GetBlockHash(blockNumber - i)
if err != nil {
return 0, err

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/rpc/rpc.go#L133-L135

Added lines #L133 - L135 were not covered by tests
}
block, err := rpcClient.GetBlockVerboseTx(hash)
if err != nil {
return 0, err

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/rpc/rpc.go#L137-L139

Added lines #L137 - L139 were not covered by tests
}

// computes the average fee rate of the block and take the higher rate
avgFeeRate, err := bitcoin.CalcBlockAvgFeeRate(block, netParams)
if err != nil {
return 0, err

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/rpc/rpc.go#L143-L145

Added lines #L143 - L145 were not covered by tests
}
if avgFeeRate > highestRate {
highestRate = avgFeeRate

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/rpc/rpc.go#L147-L148

Added lines #L147 - L148 were not covered by tests
}
}

// use 10 sat/byte as default estimation if recent fee rate drops to 0
if highestRate == 0 {
highestRate = defaultTestnetFeeRate

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

View check run for this annotation

Codecov / codecov/patch

zetaclient/chains/bitcoin/rpc/rpc.go#L153-L154

Added lines #L153 - L154 were not covered by tests
}

// #nosec G701 always in range
return uint64(highestRate), nil

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

View check run for this annotation

Codecov / codecov/patch

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

Added line #L158 was not covered by tests
}
34 changes: 24 additions & 10 deletions zetaclient/chains/bitcoin/rpc/rpc_live_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func (suite *BitcoinObserverTestSuite) SetupTest() {
base.DefaultLogger(), nil)
suite.Require().NoError(err)
suite.Require().NotNil(ob)
suite.rpcClient, err = getRPCClient(18332)
suite.rpcClient, err = createRPCClient(18332)
suite.Require().NoError(err)
skBytes, err := hex.DecodeString(skHex)
suite.Require().NoError(err)
Expand Down Expand Up @@ -91,13 +91,14 @@ func (suite *BitcoinObserverTestSuite) SetupTest() {
func (suite *BitcoinObserverTestSuite) TearDownSuite() {
}

func getRPCClient(chainID int64) (*rpcclient.Client, error) {
// createRPCClient creates a new Bitcoin RPC client for given chainID
func createRPCClient(chainID int64) (*rpcclient.Client, error) {
var connCfg *rpcclient.ConnConfig
rpcMainnet := os.Getenv("BTC_RPC_MAINNET")
rpcTestnet := os.Getenv("BTC_RPC_TESTNET")

// mainnet
if chainID == 8332 {
if chainID == chains.BitcoinMainnet.ChainId {
connCfg = &rpcclient.ConnConfig{
Host: rpcMainnet, // mainnet endpoint goes here
User: "user",
Expand All @@ -108,7 +109,7 @@ func getRPCClient(chainID int64) (*rpcclient.Client, error) {
}
}
// testnet3
if chainID == 18332 {
if chainID == chains.BitcoinTestnet.ChainId {
connCfg = &rpcclient.ConnConfig{
Host: rpcTestnet, // testnet endpoint goes here
User: "user",
Expand Down Expand Up @@ -218,6 +219,7 @@ func TestBitcoinObserverLive(t *testing.T) {
// LiveTestBitcoinFeeRate(t)
// LiveTestAvgFeeRateMainnetMempoolSpace(t)
// LiveTestAvgFeeRateTestnetMempoolSpace(t)
// LiveTestGetRecentFeeRate(t)
// LiveTestGetSenderByVin(t)
}

Expand All @@ -243,7 +245,7 @@ func LiveTestNewRPCClient(t *testing.T) {
// LiveTestGetBlockHeightByHash queries Bitcoin block height by hash
func LiveTestGetBlockHeightByHash(t *testing.T) {
// setup Bitcoin client
client, err := getRPCClient(8332)
client, err := createRPCClient(chains.BitcoinMainnet.ChainId)
require.NoError(t, err)

// the block hashes to test
Expand All @@ -265,7 +267,7 @@ func LiveTestGetBlockHeightByHash(t *testing.T) {
// and compares Conservative and Economical fee rates for different block targets (1 and 2)
func LiveTestBitcoinFeeRate(t *testing.T) {
// setup Bitcoin client
client, err := getRPCClient(8332)
client, err := createRPCClient(chains.BitcoinMainnet.ChainId)
require.NoError(t, err)
bn, err := client.GetBlockCount()
if err != nil {
Expand Down Expand Up @@ -390,7 +392,7 @@ func compareAvgFeeRate(t *testing.T, client *rpcclient.Client, startBlock int, e
// LiveTestAvgFeeRateMainnetMempoolSpace compares calculated fee rate with mempool.space fee rate for mainnet
func LiveTestAvgFeeRateMainnetMempoolSpace(t *testing.T) {
// setup Bitcoin client
client, err := getRPCClient(8332)
client, err := createRPCClient(chains.BitcoinMainnet.ChainId)
require.NoError(t, err)

// test against mempool.space API for 10000 blocks
Expand All @@ -404,7 +406,7 @@ func LiveTestAvgFeeRateMainnetMempoolSpace(t *testing.T) {
// LiveTestAvgFeeRateTestnetMempoolSpace compares calculated fee rate with mempool.space fee rate for testnet
func LiveTestAvgFeeRateTestnetMempoolSpace(t *testing.T) {
// setup Bitcoin client
client, err := getRPCClient(18332)
client, err := createRPCClient(chains.BitcoinTestnet.ChainId)
require.NoError(t, err)

// test against mempool.space API for 10000 blocks
Expand All @@ -415,11 +417,23 @@ func LiveTestAvgFeeRateTestnetMempoolSpace(t *testing.T) {
compareAvgFeeRate(t, client, startBlock, endBlock, true)
}

// LiveTestGetRecentFeeRate gets the highest fee rate from recent blocks
func LiveTestGetRecentFeeRate(t *testing.T) {
// setup Bitcoin testnet client
client, err := createRPCClient(chains.BitcoinTestnet.ChainId)
require.NoError(t, err)

// get fee rate from recent blocks
feeRate, err := rpc.GetRecentFeeRate(client, &chaincfg.TestNet3Params)
require.NoError(t, err)
require.Greater(t, feeRate, uint64(0))
}

// LiveTestGetSenderByVin gets sender address for each vin and compares with mempool.space sender address
func LiveTestGetSenderByVin(t *testing.T) {
// setup Bitcoin client
chainID := int64(8332)
client, err := getRPCClient(chainID)
chainID := chains.BitcoinMainnet.ChainId
client, err := createRPCClient(chainID)
require.NoError(t, err)

// net params
Expand Down
Loading