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(adr-032): Add ResumeFinalityProposal and handler #242

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)

## Unreleased

### Improvements

* [#242](https://github.com/babylonlabs-io/babylon/pull/242) Add ResumeFinalityProposal and handler

## v0.15.0

### State Machine Breaking
Expand Down
2 changes: 2 additions & 0 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ import (
"github.com/babylonlabs-io/babylon/app/ante"
"github.com/babylonlabs-io/babylon/app/upgrades"
bbn "github.com/babylonlabs-io/babylon/types"
finalityclient "github.com/babylonlabs-io/babylon/x/finality/client"

appkeepers "github.com/babylonlabs-io/babylon/app/keepers"
appparams "github.com/babylonlabs-io/babylon/app/params"
Expand Down Expand Up @@ -327,6 +328,7 @@ func NewBabylonApp(
govtypes.ModuleName: gov.NewAppModuleBasic(
[]govclient.ProposalHandler{
paramsclient.ProposalHandler,
finalityclient.ResumeFinalityHandler,
},
),
})
Expand Down
70 changes: 70 additions & 0 deletions client/parsers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package client

import (
"github.com/cosmos/cosmos-sdk/client"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/address"
"github.com/cosmos/cosmos-sdk/x/gov/client/cli"
"github.com/spf13/cobra"
)

// adapted from
// https://github.com/osmosis-labs/osmosis/blob/2e85d1ee3e15e3f74898395d37b455af48649268/osmoutils/osmocli/parsers.go

var DefaultGovAuthority = sdk.AccAddress(address.Module("gov"))

const (
FlagIsExpedited = "is-expedited"
FlagAuthority = "authority"
)

func GetProposalInfo(cmd *cobra.Command) (client.Context, string, string, sdk.Coins, bool, sdk.AccAddress, error) {
clientCtx, err := client.GetClientTxContext(cmd)
if err != nil {
return client.Context{}, "", "", nil, false, nil, err
}

proposalTitle, err := cmd.Flags().GetString(cli.FlagTitle)
if err != nil {
return clientCtx, proposalTitle, "", nil, false, nil, err
}

summary, err := cmd.Flags().GetString(cli.FlagSummary)
if err != nil {
return client.Context{}, proposalTitle, summary, nil, false, nil, err
}

depositArg, err := cmd.Flags().GetString(cli.FlagDeposit)
if err != nil {
return client.Context{}, proposalTitle, summary, nil, false, nil, err
}

deposit, err := sdk.ParseCoinsNormalized(depositArg)
if err != nil {
return client.Context{}, proposalTitle, summary, deposit, false, nil, err
}

isExpedited, err := cmd.Flags().GetBool(FlagIsExpedited)
if err != nil {
return client.Context{}, proposalTitle, summary, deposit, false, nil, err
}

authorityString, err := cmd.Flags().GetString(FlagAuthority)
if err != nil {
return client.Context{}, proposalTitle, summary, deposit, false, nil, err
}
authority, err := sdk.AccAddressFromBech32(authorityString)
if err != nil {
return client.Context{}, proposalTitle, summary, deposit, false, nil, err
}

return clientCtx, proposalTitle, summary, deposit, isExpedited, authority, nil
}

func AddCommonProposalFlags(cmd *cobra.Command) {
cmd.Flags().String(cli.FlagTitle, "", "Title of proposal")
cmd.Flags().String(cli.FlagSummary, "", "Summary of proposal")
cmd.Flags().String(cli.FlagDeposit, "", "Deposit of proposal")
cmd.Flags().Bool(FlagIsExpedited, false, "Whether the proposal is expedited")
cmd.Flags().String(FlagAuthority, DefaultGovAuthority.String(), "The address of the governance account. Default is the sdk gov module account")
}
25 changes: 25 additions & 0 deletions proto/babylon/finality/v1/gov.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
syntax = "proto3";
package babylon.finality.v1;

import "cosmos_proto/cosmos.proto";
import "amino/amino.proto";
import "gogoproto/gogo.proto";

option go_package = "github.com/babylonlabs-io/babylon/x/finality/types";

// ResumeFinalityProposal is a gov Content type for resuming finality
// in case of finality is halting by jailing a list of sluggish finality
// providers from the halting height
message ResumeFinalityProposal {
option (gogoproto.goproto_getters) = false;
option (gogoproto.goproto_stringer) = false;
option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content";

string title = 1;
string description = 2;
// fp_pks is a list of finality provider public keys to jail
// the public key follows encoding in BIP-340 spec
repeated bytes fp_pks = 3 [ (gogoproto.customtype) = "github.com/babylonlabs-io/babylon/types.BIP340PubKey" ];
// halting_height is the height where the finality halting begins
uint32 halting_height = 4;
}
3 changes: 2 additions & 1 deletion x/btcstaking/keeper/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ import (
"fmt"
"math"

sdk "github.com/cosmos/cosmos-sdk/types"

bbn "github.com/babylonlabs-io/babylon/types"
"github.com/babylonlabs-io/babylon/x/btcstaking/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)

// InitGenesis initializes the module's state from a provided genesis state.
Expand Down
93 changes: 93 additions & 0 deletions x/finality/client/cli/gov.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package cli

import (
"fmt"
"os"
"path/filepath"
"strconv"

tmjson "github.com/cometbft/cometbft/libs/json"
"github.com/cosmos/cosmos-sdk/client/tx"
sdk "github.com/cosmos/cosmos-sdk/types"
v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1"
"github.com/spf13/cobra"

bbncli "github.com/babylonlabs-io/babylon/client"
bbntypes "github.com/babylonlabs-io/babylon/types"
"github.com/babylonlabs-io/babylon/x/finality/types"
)

type FinalityProviderPks struct {
FinalityProviders []string `json:"finality-providers"`
}

func NewCmdSubmitResumeFinalityProposal() *cobra.Command {
cmd := &cobra.Command{
Use: "resume-finality [fps-to-jail.json] [halting-height]",
Args: cobra.ExactArgs(2),
Short: "Submit a resume finality proposal",
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx, proposalTitle, summary, deposit, isExpedited, authority, err := bbncli.GetProposalInfo(cmd)
if err != nil {
return err
}

fps, err := loadFpsFromFile(args[0])
if err != nil {
return fmt.Errorf("cannot load finality providers from %s: %w", args[0], err)
}

haltingHeight, err := strconv.ParseUint(args[1], 10, 64)
if err != nil {
return fmt.Errorf("invalid halting-height %s: %w", args[1], err)
}

content := types.NewResumeFinalityProposal(proposalTitle, summary, fps, uint32(haltingHeight))

contentMsg, err := v1.NewLegacyContent(content, authority.String())
if err != nil {
return err
}

msg := v1.NewMsgExecLegacyContent(contentMsg.Content, authority.String())

proposalMsg, err := v1.NewMsgSubmitProposal([]sdk.Msg{msg}, deposit, clientCtx.GetFromAddress().String(), "", proposalTitle, summary, isExpedited)
if err != nil {
return err
}

return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), proposalMsg)
},
}

bbncli.AddCommonProposalFlags(cmd)

return cmd
}

func loadFpsFromFile(filePath string) ([]bbntypes.BIP340PubKey, error) {
bz, err := os.ReadFile(filepath.Clean(filePath))
if err != nil {
return nil, err
}
fps := new(FinalityProviderPks)
err = tmjson.Unmarshal(bz, fps)
if err != nil {
return nil, err
}

if len(fps.FinalityProviders) == 0 {
return nil, fmt.Errorf("empty finality providers")
}

fpPks := make([]bbntypes.BIP340PubKey, len(fps.FinalityProviders))
for i, pkStr := range fps.FinalityProviders {
pk, err := bbntypes.NewBIP340PubKeyFromHex(pkStr)
if err != nil {
return nil, fmt.Errorf("invalid finality provider public key %s: %w", pkStr, err)
}
fpPks[i] = *pk
}
Comment on lines +83 to +90
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
fpPks := make([]bbntypes.BIP340PubKey, len(fps.FinalityProviders))
for i, pkStr := range fps.FinalityProviders {
pk, err := bbntypes.NewBIP340PubKeyFromHex(pkStr)
if err != nil {
return nil, fmt.Errorf("invalid finality provider public key %s: %w", pkStr, err)
}
fpPks[i] = *pk
}
fpPks := make([]bbntypes.BIP340PubKey, 0, len(fps.FinalityProviders)) // avoid wrangling indexes
for i, pkStr := range fps.FinalityProviders {
pk, err := bbntypes.NewBIP340PubKeyFromHex(pkStr)
if err != nil {
return nil, fmt.Errorf("invalid finality provider public key %s: %w", pkStr, err)
}
fpPks = append(fpPks, *pk)
}


return fpPks, nil
}
11 changes: 11 additions & 0 deletions x/finality/client/proposal_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package client

import (
govclient "github.com/cosmos/cosmos-sdk/x/gov/client"

"github.com/babylonlabs-io/babylon/x/finality/client/cli"
)

var (
ResumeFinalityHandler = govclient.NewProposalHandler(cli.NewCmdSubmitResumeFinalityProposal)
)
29 changes: 29 additions & 0 deletions x/finality/gov.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package finality

import (
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
govtypesv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1"

"github.com/babylonlabs-io/babylon/x/finality/keeper"
"github.com/babylonlabs-io/babylon/x/finality/types"
)

// NewResumeFinalityProposalHandler is a handler for governance proposal on resume finality.
func NewResumeFinalityProposalHandler(k keeper.Keeper) govtypesv1.Handler {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm why usage of the old way of handling proposals ? (which I think is discouraged)

Wouldn't it be better to have separate message on finality provider message server which can be only executed by governance module ? (similar to parameters updates)

return func(ctx sdk.Context, content govtypesv1.Content) error {
switch c := content.(type) {
case *types.ResumeFinalityProposal:
return handleResumeFinalityProposal(ctx, k, c)

default:
return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized resume finality proposal content type: %T", c)
}
}
}

// handleResumeFinalityProposal is a handler for jail finality provider proposals
func handleResumeFinalityProposal(ctx sdk.Context, k keeper.Keeper, p *types.ResumeFinalityProposal) error {
return k.HandleResumeFinalityProposal(ctx, p)
}
85 changes: 85 additions & 0 deletions x/finality/keeper/gov.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package keeper

import (
"errors"
"fmt"

sdk "github.com/cosmos/cosmos-sdk/types"

bstypes "github.com/babylonlabs-io/babylon/x/btcstaking/types"
"github.com/babylonlabs-io/babylon/x/finality/types"
)

// HandleResumeFinalityProposal handles the resume finality proposal in the following steps:
// 1. check the validity of the proposal
// 2. jail the finality providers from the list and adjust the voting power cache from the
// halting height to the current height
// 3. tally blocks to ensure finality is resumed
func (k Keeper) HandleResumeFinalityProposal(ctx sdk.Context, p *types.ResumeFinalityProposal) error {
// a valid proposal should be
// 1. the halting height along with some parameterized future heights should be indeed non-finalized
// 2. all the fps from the proposal should have missed the vote for the halting height
// TODO introduce a parameter to define the finality has been halting for at least some heights

params := k.GetParams(ctx)
currentHeight := ctx.HeaderInfo().Height
currentTime := ctx.HeaderInfo().Time

// jail the given finality providers
for _, fpPk := range p.FpPks {
fpHex := fpPk.MarshalHex()
voters := k.GetVoters(ctx, uint64(p.HaltingHeight))
_, voted := voters[fpPk.MarshalHex()]
if voted {
// all the given finality providers should not have voted for the halting height
return fmt.Errorf("the finality provider %s has voted for height %d", fpHex, p.HaltingHeight)
}

err := k.jailSluggishFinalityProvider(ctx, &fpPk)
if err != nil && !errors.Is(err, bstypes.ErrFpAlreadyJailed) {
return fmt.Errorf("failed to jail the finality provider %s: %w", fpHex, err)
}

// update signing info
signInfo, err := k.FinalityProviderSigningTracker.Get(ctx, fpPk.MustMarshal())
if err != nil {
return fmt.Errorf("the signing info of finality provider %s is not created: %w", fpHex, err)
}
signInfo.JailedUntil = currentTime.Add(params.JailDuration)
signInfo.MissedBlocksCounter = 0
if err := k.DeleteMissedBlockBitmap(ctx, &fpPk); err != nil {
return fmt.Errorf("failed to remove the missed block bit map for finality provider %s: %w", fpHex, err)
}
err = k.FinalityProviderSigningTracker.Set(ctx, fpPk.MustMarshal(), signInfo)
if err != nil {
return fmt.Errorf("failed to set the signing info for finality provider %s: %w", fpHex, err)
}

k.Logger(ctx).Info(
"finality provider is jailed in the proposal",
"height", p.HaltingHeight,
"public_key", fpHex,
)
}

// set the all the given finality providers voting power to 0
for h := uint64(p.HaltingHeight); h <= uint64(currentHeight); h++ {
distCache := k.GetVotingPowerDistCache(ctx, h)
activeFps := distCache.GetActiveFinalityProviderSet()
for _, fpToJail := range p.FpPks {
if fp, exists := activeFps[fpToJail.MarshalHex()]; exists {
fp.IsJailed = true
k.SetVotingPower(ctx, fpToJail, h, 0)
}
}

distCache.ApplyActiveFinalityProviders(params.MaxActiveFinalityProviders)

// set the voting power distribution cache of the current height
k.SetVotingPowerDistCache(ctx, h, distCache)
}

k.TallyBlocks(ctx)

return nil
}
Loading
Loading