Skip to content

Commit

Permalink
chore: Bitcoin heights and depths made uint32 (#181)
Browse files Browse the repository at this point in the history
Resolves #179 

This is an impactful change that brings the BTC height types that we use
more in sync with the expected types for BTC block heights, similar to
those that are used by other libraries. It is part of the code
improvement efforts that we are doing in preparation of the next
testnet.

Given that it touches many files, I believe that this change should
happen sooner than later so that it can be appropriately tested.
  • Loading branch information
vitsalis authored Oct 11, 2024
1 parent e66765c commit d0eca74
Show file tree
Hide file tree
Showing 76 changed files with 776 additions and 756 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)

## Unreleased

### State Machine Breaking

* [#181](https://github.com/babylonlabs-io/babylon/pull/181) Modify BTC heights
and depths to be of uint32 type instead of uint64.

### Bug fixes

* [#180](https://github.com/babylonlabs-io/babylon/pull/180) Non-determinism in
Expand Down
2 changes: 2 additions & 0 deletions btcstaking/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,8 @@ func BuildRelativeTimelockTaprootScript(

// ParseBlkHeightAndPubKeyFromStoreKey expects to receive a key with
// BigEndianUint64(blkHeight) || BIP340PubKey(fpBTCPK)
// TODO: this function should not be in the btcstaking library
// it is related to our internal cosmos sdk storage
func ParseBlkHeightAndPubKeyFromStoreKey(key []byte) (blkHeight uint64, fpBTCPK *bbn.BIP340PubKey, err error) {
sizeBigEndian := 8
if len(key) < sizeBigEndian+1 {
Expand Down
18 changes: 9 additions & 9 deletions cmd/babylond/cmd/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,12 @@ const (
type GenesisCLIArgs struct {
ChainID string
MaxActiveValidators uint32
BtcConfirmationDepth uint64
BtcFinalizationTimeout uint64
BtcConfirmationDepth uint32
BtcFinalizationTimeout uint32
CheckpointTag string
EpochInterval uint64
BaseBtcHeaderHex string
BaseBtcHeaderHeight uint64
BaseBtcHeaderHeight uint32
AllowedReporterAddresses []string
InflationRateChange float64
InflationMax float64
Expand Down Expand Up @@ -87,16 +87,16 @@ func addGenesisFlags(cmd *cobra.Command) {
// staking flags
cmd.Flags().Uint32(flagMaxActiveValidators, 10, "Maximum number of validators.")
// btccheckpoint flags
cmd.Flags().Uint64(flagBtcConfirmationDepth, 6, "Confirmation depth for Bitcoin headers.")
cmd.Flags().Uint64(flagBtcFinalizationTimeout, 20, "Finalization timeout for Bitcoin headers.")
cmd.Flags().Uint32(flagBtcConfirmationDepth, 6, "Confirmation depth for Bitcoin headers.")
cmd.Flags().Uint32(flagBtcFinalizationTimeout, 20, "Finalization timeout for Bitcoin headers.")
cmd.Flags().String(flagCheckpointTag, btcctypes.DefaultCheckpointTag, "Hex encoded tag for babylon checkpoint on btc")
// epoch args
cmd.Flags().Uint64(flagEpochInterval, 400, "Number of blocks between epochs. Must be more than 0.")
// btclightclient args
// Genesis header for the simnet
cmd.Flags().String(flagBaseBtcHeaderHex, "0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a45068653ffff7f2002000000", "Hex of the base Bitcoin header.")
cmd.Flags().String(flagAllowedReporterAddresses, strings.Join(btcltypes.DefaultParams().InsertHeadersAllowList, ","), "addresses of reporters allowed to submit Bitcoin headers to babylon")
cmd.Flags().Uint64(flagBaseBtcHeaderHeight, 0, "Height of the base Bitcoin header.")
cmd.Flags().Uint32(flagBaseBtcHeaderHeight, 0, "Height of the base Bitcoin header.")
// btcstaking args
cmd.Flags().String(flagCovenantPks, strings.Join(btcstypes.DefaultParams().CovenantPksHex(), ","), "Bitcoin staking covenant public keys, comma separated")
cmd.Flags().Uint32(flagCovenantQuorum, btcstypes.DefaultParams().CovenantQuorum, "Bitcoin staking covenant quorum")
Expand Down Expand Up @@ -127,12 +127,12 @@ func addGenesisFlags(cmd *cobra.Command) {
func parseGenesisFlags(cmd *cobra.Command) *GenesisCLIArgs {
chainID, _ := cmd.Flags().GetString(flags.FlagChainID)
maxActiveValidators, _ := cmd.Flags().GetUint32(flagMaxActiveValidators)
btcConfirmationDepth, _ := cmd.Flags().GetUint64(flagBtcConfirmationDepth)
btcFinalizationTimeout, _ := cmd.Flags().GetUint64(flagBtcFinalizationTimeout)
btcConfirmationDepth, _ := cmd.Flags().GetUint32(flagBtcConfirmationDepth)
btcFinalizationTimeout, _ := cmd.Flags().GetUint32(flagBtcFinalizationTimeout)
checkpointTag, _ := cmd.Flags().GetString(flagCheckpointTag)
epochInterval, _ := cmd.Flags().GetUint64(flagEpochInterval)
baseBtcHeaderHex, _ := cmd.Flags().GetString(flagBaseBtcHeaderHex)
baseBtcHeaderHeight, _ := cmd.Flags().GetUint64(flagBaseBtcHeaderHeight)
baseBtcHeaderHeight, _ := cmd.Flags().GetUint32(flagBaseBtcHeaderHeight)
reporterAddresses, _ := cmd.Flags().GetString(flagAllowedReporterAddresses)
covenantPks, _ := cmd.Flags().GetString(flagCovenantPks)
covenantQuorum, _ := cmd.Flags().GetUint32(flagCovenantQuorum)
Expand Down
6 changes: 3 additions & 3 deletions cmd/babylond/cmd/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,12 +265,12 @@ type GenesisParams struct {

func TestnetGenesisParams(
maxActiveValidators uint32,
btcConfirmationDepth uint64,
btcFinalizationTimeout uint64,
btcConfirmationDepth uint32,
btcFinalizationTimeout uint32,
checkpointTag string,
epochInterval uint64,
baseBtcHeaderHex string,
baseBtcHeaderHeight uint64,
baseBtcHeaderHeight uint32,
allowedReporters []string,
covenantPKs []string,
covenantQuorum uint32,
Expand Down
4 changes: 2 additions & 2 deletions cmd/babylond/cmd/genhelpers/set_btc_delegations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ func FuzzCmdSetBtcDels(f *testing.F) {
slashingPkScript, err := txscript.PayToAddrScript(slashingAddress)
require.NoError(t, err)

startHeight := datagen.RandomInt(r, 100) + 1
endHeight := datagen.RandomInt(r, 1000) + startHeight + btcctypes.DefaultParams().CheckpointFinalizationTimeout + 1
startHeight := uint32(datagen.RandomInt(r, 100)) + 1
endHeight := uint32(datagen.RandomInt(r, 1000)) + startHeight + btcctypes.DefaultParams().CheckpointFinalizationTimeout + 1
slashingRate := sdkmath.LegacyNewDecWithPrec(int64(datagen.RandomInt(r, 41)+10), 2)
slashingChangeLockTime := uint16(101)

Expand Down
4 changes: 0 additions & 4 deletions cmd/babylond/cmd/testnet.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package cmd
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"net"
"os"
Expand Down Expand Up @@ -88,9 +87,6 @@ Example:
btcNetwork, _ := cmd.Flags().GetString(flagBtcNetwork)
additionalAccount, _ := cmd.Flags().GetBool(flagAdditionalSenderAccount)
timeBetweenBlocks, _ := cmd.Flags().GetUint64(flagTimeBetweenBlocks)
if err != nil {
return errors.New("base Bitcoin header height should be a uint64")
}

genesisParams := TestnetGenesisParams(
genesisCliArgs.MaxActiveValidators,
Expand Down
2 changes: 1 addition & 1 deletion proto/babylon/btccheckpoint/v1/btccheckpoint.proto
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ message BTCCheckpointInfo {
// epoch number of this checkpoint
uint64 epoch_number = 1;
// btc height of the best submission of the epoch
uint64 best_submission_btc_block_height = 2;
uint32 best_submission_btc_block_height = 2;
// hash of the btc block which determines checkpoint btc block height i.e.
// youngest block of best submission
bytes best_submission_btc_block_hash = 3
Expand Down
4 changes: 2 additions & 2 deletions proto/babylon/btccheckpoint/v1/params.proto
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ message Params {
// btc_confirmation_depth is the confirmation depth in BTC.
// A block is considered irreversible only when it is at least k-deep in BTC
// (k in research paper)
uint64 btc_confirmation_depth = 1
uint32 btc_confirmation_depth = 1
[ (gogoproto.moretags) = "yaml:\"btc_confirmation_depth\"" ];

// checkpoint_finalization_timeout is the maximum time window (measured in BTC
Expand All @@ -21,7 +21,7 @@ message Params {
// - being reported back to BBN
// If a checkpoint has not been reported back within w BTC blocks, then BBN
// has dishonest majority and is stalling checkpoints (w in research paper)
uint64 checkpoint_finalization_timeout = 2
uint32 checkpoint_finalization_timeout = 2
[ (gogoproto.moretags) = "yaml:\"checkpoint_finalization_timeout\"" ];

// 4byte tag in hex format, required to be present in the OP_RETURN transaction
Expand Down
2 changes: 1 addition & 1 deletion proto/babylon/btccheckpoint/v1/query.proto
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ message BTCCheckpointInfoResponse {
// EpochNumber of this checkpoint.
uint64 epoch_number = 1;
// btc height of the best submission of the epoch
uint64 best_submission_btc_block_height = 2;
uint32 best_submission_btc_block_height = 2;
// hash of the btc block which determines checkpoint btc block height i.e.
// youngest block of best submission Hexadecimal
string best_submission_btc_block_hash = 3;
Expand Down
2 changes: 1 addition & 1 deletion proto/babylon/btclightclient/v1/btclightclient.proto
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ message BTCHeaderInfo {
bytes hash = 2
[ (gogoproto.customtype) =
"github.com/babylonlabs-io/babylon/types.BTCHeaderHashBytes" ];
uint64 height = 3;
uint32 height = 3;
bytes work = 4
[ (gogoproto.customtype) = "cosmossdk.io/math.Uint" ];
}
4 changes: 2 additions & 2 deletions proto/babylon/btclightclient/v1/query.proto
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ message QueryHeaderDepthRequest { string hash = 1; }

// QueryMainChainDepthResponse is the response type for the Query/MainChainDepth RPC
// it contains depth of the block in main chain
message QueryHeaderDepthResponse { uint64 depth = 1; }
message QueryHeaderDepthResponse { uint32 depth = 1; }

// BTCHeaderInfoResponse is a structure that contains all relevant information about a
// BTC header response
Expand All @@ -146,7 +146,7 @@ message QueryHeaderDepthResponse { uint64 depth = 1; }
message BTCHeaderInfoResponse {
string header_hex = 1;
string hash_hex = 2;
uint64 height = 3;
uint32 height = 3;
// Work is the sdkmath.Uint as string.
string work = 4 [
(cosmos_proto.scalar) = "cosmos.Uint",
Expand Down
8 changes: 4 additions & 4 deletions proto/babylon/btcstaking/v1/btcstaking.proto
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ message FinalityProvider {
// slashed_btc_height indicates the BTC height when
// the finality provider is slashed.
// if it's 0 then the finality provider is not slashed
uint64 slashed_btc_height = 7;
uint32 slashed_btc_height = 7;
// jailed defines whether the finality provider is jailed
bool jailed = 8;
}
Expand All @@ -54,7 +54,7 @@ message FinalityProviderWithMeta {
// slashed_btc_height indicates the BTC height when
// the finality provider is slashed.
// if it's 0 then the finality provider is not slashed
uint64 slashed_btc_height = 5;
uint32 slashed_btc_height = 5;
// jailed defines whether the finality provider is detected jailed
bool jailed = 6;
}
Expand All @@ -77,10 +77,10 @@ message BTCDelegation {
uint32 staking_time = 5;
// start_height is the start BTC height of the BTC delegation
// it is the start BTC height of the timelock
uint64 start_height = 6;
uint32 start_height = 6;
// end_height is the end height of the BTC delegation
// it is calculated by end_height = start_height + staking_time
uint64 end_height = 7;
uint32 end_height = 7;
// total_sat is the total amount of BTC stakes in this delegation
// quantified in satoshi
uint64 total_sat = 8;
Expand Down
4 changes: 2 additions & 2 deletions proto/babylon/btcstaking/v1/genesis.proto
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ message BlockHeightBbnToBtc {
// block_height_bbn is the height of the block in the babylon chain.
uint64 block_height_bbn = 1;
// block_height_btc is the height of the block in the BTC.
uint64 block_height_btc = 2;
uint32 block_height_btc = 2;
}

// BTCDelegator BTC delegator information with the associated finality provider.
Expand All @@ -72,7 +72,7 @@ message EventIndex {
// idx is the index the event was stored.
uint64 idx = 1;
// block_height_btc is the height of the block in the BTC chain.
uint64 block_height_btc = 2;
uint32 block_height_btc = 2;
// event the event stored.
EventPowerDistUpdate event = 3;
}
6 changes: 3 additions & 3 deletions proto/babylon/btcstaking/v1/query.proto
Original file line number Diff line number Diff line change
Expand Up @@ -253,10 +253,10 @@ message BTCDelegationResponse {
repeated bytes fp_btc_pk_list = 3 [ (gogoproto.customtype) = "github.com/babylonlabs-io/babylon/types.BIP340PubKey" ];
// start_height is the start BTC height of the BTC delegation
// it is the start BTC height of the timelock
uint64 start_height = 4;
uint32 start_height = 4;
// end_height is the end height of the BTC delegation
// it is the end BTC height of the timelock - w
uint64 end_height = 5;
uint32 end_height = 5;
// total_sat is the total amount of BTC stakes in this delegation
// quantified in satoshi
uint64 total_sat = 6;
Expand Down Expand Up @@ -344,7 +344,7 @@ message FinalityProviderResponse {
// slashed_btc_height indicates the BTC height when
// the finality provider is slashed.
// if it's 0 then the finality provider is not slashed
uint64 slashed_btc_height = 7;
uint32 slashed_btc_height = 7;
// height is the queried Babylon height
uint64 height = 8;
// voting_power is the voting power of this finality provider at the given height
Expand Down
4 changes: 2 additions & 2 deletions proto/babylon/monitor/v1/query.proto
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ message QueryEndedEpochBtcHeightRequest { uint64 epoch_num = 1; }
// EndedEpochBtcHeight RPC method
message QueryEndedEpochBtcHeightResponse {
// height of btc light client when epoch ended
uint64 btc_light_client_height = 1;
uint32 btc_light_client_height = 1;
}

// QueryReportedCheckpointBtcHeightRequest defines a query type for
Expand All @@ -44,5 +44,5 @@ message QueryReportedCheckpointBtcHeightRequest {
// ReportedCheckpointBtcHeight RPC method
message QueryReportedCheckpointBtcHeightResponse {
// height of btc light client when checkpoint is reported
uint64 btc_light_client_height = 1;
uint32 btc_light_client_height = 1;
}
6 changes: 3 additions & 3 deletions test/e2e/btc_timestamping_e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func (s *BTCTimestampingTestSuite) Test1ConnectIbc() {

func (s *BTCTimestampingTestSuite) Test2BTCBaseHeader() {
hardcodedHeader, _ := bbn.NewBTCHeaderBytesFromHex("0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a45068653ffff7f2002000000")
hardcodedHeaderHeight := uint64(0)
hardcodedHeaderHeight := uint32(0)

chainA := s.configurer.GetChainConfig(0)
nonValidatorNode, err := chainA.GetNodeAtIndex(2)
Expand Down Expand Up @@ -97,12 +97,12 @@ func (s *BTCTimestampingTestSuite) Test3SendTx() {
// check that light client properly updates its state
tip1Depth, err := nonValidatorNode.QueryHeaderDepth(tip1.HashHex)
s.NoError(err)
s.Equal(tip1Depth, uint64(1))
s.Equal(tip1Depth, uint32(1))

tip2Depth, err := nonValidatorNode.QueryHeaderDepth(tip2.HashHex)
s.NoError(err)
// tip should have 0 depth
s.Equal(tip2Depth, uint64(0))
s.Equal(tip2Depth, uint32(0))
}

func (s *BTCTimestampingTestSuite) Test4GenerateAndWithdrawReward() {
Expand Down
4 changes: 2 additions & 2 deletions test/e2e/configurer/chain/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,8 @@ func (n *NodeConfig) WaitForCondition(doneCondition func() bool, errorMsg string
n.t.Errorf("node %s timed out waiting for condition. Msg: %s", n.Name, errorMsg)
}

func (n *NodeConfig) WaitUntilBtcHeight(height uint64) {
var latestBlockHeight uint64
func (n *NodeConfig) WaitUntilBtcHeight(height uint32) {
var latestBlockHeight uint32
n.WaitForCondition(func() bool {
btcTip, err := n.QueryTip()
require.NoError(n.t, err)
Expand Down
6 changes: 3 additions & 3 deletions test/e2e/configurer/chain/queries.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ func (n *NodeConfig) QueryTip() (*blc.BTCHeaderInfoResponse, error) {
return blcResponse.Header, nil
}

func (n *NodeConfig) QueryHeaderDepth(hash string) (uint64, error) {
func (n *NodeConfig) QueryHeaderDepth(hash string) (uint32, error) {
path := fmt.Sprintf("babylon/btclightclient/v1/depth/%s", hash)
bz, err := n.QueryGRPCGateway(path, url.Values{})
require.NoError(n.t, err)
Expand All @@ -271,7 +271,7 @@ func (n *NodeConfig) QueryCurrentEpoch() (uint64, error) {
return epochResponse.CurrentEpoch, nil
}

func (n *NodeConfig) QueryLightClientHeightEpochEnd(epoch uint64) (uint64, error) {
func (n *NodeConfig) QueryLightClientHeightEpochEnd(epoch uint64) (uint32, error) {
monitorPath := fmt.Sprintf("/babylon/monitor/v1/epochs/%d", epoch)
bz, err := n.QueryGRPCGateway(monitorPath, url.Values{})
require.NoError(n.t, err)
Expand All @@ -282,7 +282,7 @@ func (n *NodeConfig) QueryLightClientHeightEpochEnd(epoch uint64) (uint64, error
return mResponse.BtcLightClientHeight, nil
}

func (n *NodeConfig) QueryLightClientHeightCheckpointReported(ckptHash []byte) (uint64, error) {
func (n *NodeConfig) QueryLightClientHeightCheckpointReported(ckptHash []byte) (uint32, error) {
monitorPath := fmt.Sprintf("/babylon/monitor/v1/checkpoints/%x", ckptHash)
bz, err := n.QueryGRPCGateway(monitorPath, url.Values{})
require.NoError(n.t, err)
Expand Down
11 changes: 5 additions & 6 deletions testutil/datagen/btc_header_chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,19 @@ var initHeader = chaincfg.SimNetParams.GenesisBlock.Header
type BTCHeaderPartialChain struct {
// slice of Headers forming valid chain
Headers []*wire.BlockHeader
initialHeaderHeight uint64
initialHeaderHeight uint32
inititialHeaderTotalWork sdkmath.Uint
}

func NewBTCHeaderChainWithLength(
r *rand.Rand,
initialHeaderHeight uint64,
initialHeaderTotalWork uint64,
initialHeaderHeight uint32,
initialHeaderTotalWork uint32,
length uint32) *BTCHeaderPartialChain {
return NewBTCHeaderChainFromParent(
r,
initialHeaderHeight,
sdkmath.NewUint(initialHeaderTotalWork),
sdkmath.NewUint(uint64(initialHeaderTotalWork)),
&initHeader,
length,
)
Expand All @@ -50,14 +50,13 @@ func NewBTCHeaderChainFromParentInfo(

func NewBTCHeaderChainFromParent(
r *rand.Rand,
initialHeaderHeight uint64,
initialHeaderHeight uint32,
initialHeaderTotalWork sdkmath.Uint,
parent *wire.BlockHeader,
length uint32,
) *BTCHeaderPartialChain {
headers := GenRandomValidChainStartingFrom(
r,
initialHeaderHeight,
parent,
nil,
length,
Expand Down
Loading

0 comments on commit d0eca74

Please sign in to comment.