diff --git a/.circleci/config.yml b/.circleci/config.yml index 870bb6f8..f3bb04ab 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -58,11 +58,11 @@ jobs: - run: name: Save Docker image to export it to workspace command: | - docker save $(docker image ls --format '{{.Repository}}:{{.Tag}}') > /tmp/btcvalidator.tar + docker save $(docker image ls --format '{{.Repository}}:{{.Tag}}') > /tmp/finality-provider.tar - persist_to_workspace: root: /tmp paths: - - btcvalidator.tar + - finality-provider.tar push_docker: machine: @@ -74,7 +74,7 @@ jobs: - run: name: Load Docker image from workspace command: | - docker load -i /tmp/btcvalidator.tar + docker load -i /tmp/finality-provider.tar - aws-ecr/ecr-login: aws-access-key-id: AWS_ACCESS_KEY_ID aws-secret-access-key: AWS_SECRET_ACCESS_KEY diff --git a/Dockerfile b/Dockerfile index 5d527bc5..6e0efcde 100644 --- a/Dockerfile +++ b/Dockerfile @@ -17,12 +17,12 @@ RUN git config --global url."git@github.com:".insteadOf "https://github.com/" ENV GOPRIVATE=github.com/babylonchain/* # Build -WORKDIR /go/src/github.com/babylonchain/btc-validator +WORKDIR /go/src/github.com/babylonchain/finality-provider # Cache dependencies -COPY go.mod go.sum /go/src/github.com/babylonchain/btc-validator/ +COPY go.mod go.sum /go/src/github.com/babylonchain/finality-provider/ RUN --mount=type=secret,id=sshKey,target=/root/.ssh/id_rsa go mod download # Copy the rest of the files -COPY ./ /go/src/github.com/babylonchain/btc-validator/ +COPY ./ /go/src/github.com/babylonchain/finality-provider/ # Cosmwasm - Download correct libwasmvm version RUN WASMVM_VERSION=$(go list -m github.com/CosmWasm/wasmvm | cut -d ' ' -f 2) && \ @@ -41,15 +41,15 @@ RUN CGO_LDFLAGS="$CGO_LDFLAGS -lstdc++ -lm -lsodium" \ # FINAL IMAGE FROM alpine:3.16 AS run -RUN addgroup --gid 1138 -S btcvalidator && adduser --uid 1138 -S btcvalidator -G btcvalidator +RUN addgroup --gid 1138 -S finality-provider && adduser --uid 1138 -S finality-provider -G finality-provider RUN apk add bash curl jq -COPY --from=builder /go/src/github.com/babylonchain/btc-validator/build/vald /bin/vald -COPY --from=builder /go/src/github.com/babylonchain/btc-validator/build/valcli /bin/valcli -COPY --from=builder /go/src/github.com/babylonchain/btc-validator/build/covd /bin/covd -COPY --from=builder /go/src/github.com/babylonchain/btc-validator/build/eotsd /bin/eotsd +COPY --from=builder /go/src/github.com/babylonchain/finality-provider/build/fpd /bin/fpd +COPY --from=builder /go/src/github.com/babylonchain/finality-provider/build/fpcli /bin/fpcli +COPY --from=builder /go/src/github.com/babylonchain/finality-provider/build/covd /bin/covd +COPY --from=builder /go/src/github.com/babylonchain/finality-provider/build/eotsd /bin/eotsd -WORKDIR /home/btcvalidator -RUN chown -R btcvalidator /home/btcvalidator -USER btcvalidator +WORKDIR /home/finality-provider +RUN chown -R finality-provider /home/finality-provider +USER finality-provider diff --git a/Makefile b/Makefile index 5db0f649..23d9690a 100644 --- a/Makefile +++ b/Makefile @@ -41,7 +41,7 @@ $(BUILDDIR)/: mkdir -p $(BUILDDIR)/ build-docker: - $(DOCKER) build --secret id=sshKey,src=${BBN_PRIV_DEPLOY_KEY} --tag babylonchain/btc-validator -f Dockerfile \ + $(DOCKER) build --secret id=sshKey,src=${BBN_PRIV_DEPLOY_KEY} --tag babylonchain/finality-provider -f Dockerfile \ $(shell git rev-parse --show-toplevel) .PHONY: build build-docker @@ -61,7 +61,7 @@ proto-all: proto-gen proto-gen: make -C eotsmanager proto-gen - make -C validator proto-gen + make -C finality-provider proto-gen .PHONY: proto-gen diff --git a/clientcontroller/babylon.go b/clientcontroller/babylon.go index 2708acd5..86c5996f 100644 --- a/clientcontroller/babylon.go +++ b/clientcontroller/babylon.go @@ -4,6 +4,7 @@ import ( "context" "encoding/hex" "fmt" + "github.com/btcsuite/btcd/btcec/v2" "time" "cosmossdk.io/math" @@ -13,7 +14,6 @@ import ( btcstakingtypes "github.com/babylonchain/babylon/x/btcstaking/types" finalitytypes "github.com/babylonchain/babylon/x/finality/types" bbnclient "github.com/babylonchain/rpc-client/client" - "github.com/btcsuite/btcd/btcec/v2" "github.com/btcsuite/btcd/btcec/v2/schnorr" "github.com/btcsuite/btcd/btcutil" "github.com/btcsuite/btcd/chaincfg" @@ -25,8 +25,8 @@ import ( "github.com/cosmos/relayer/v2/relayer/provider" "go.uber.org/zap" - "github.com/babylonchain/btc-validator/config" - "github.com/babylonchain/btc-validator/types" + "github.com/babylonchain/finality-provider/config" + "github.com/babylonchain/finality-provider/types" ) var _ ClientController = &BabylonController{} @@ -110,7 +110,7 @@ func (bc *BabylonController) QueryStakingParams() (*types.StakingParams, error) for _, pk := range stakingParamRes.Params.CovenantPks { covPk, err := pk.ToBTCPK() if err != nil { - return nil, fmt.Errorf("invalida covenant public key") + return nil, fmt.Errorf("invalid covenant public key") } covenantPks = append(covenantPks, covPk) } @@ -143,11 +143,11 @@ func (bc *BabylonController) reliablySendMsgs(msgs []sdk.Msg) (*provider.Relayer ) } -// RegisterValidator registers a BTC validator via a MsgCreateBTCValidator to Babylon +// RegisterFinalityProvider registers a finality provider via a MsgCreateFinalityProvider to Babylon // it returns tx hash and error -func (bc *BabylonController) RegisterValidator( +func (bc *BabylonController) RegisterFinalityProvider( chainPk []byte, - valPk *btcec.PublicKey, + fpPk *btcec.PublicKey, pop []byte, commission *math.LegacyDec, description []byte, @@ -162,10 +162,10 @@ func (bc *BabylonController) RegisterValidator( return nil, fmt.Errorf("invalid description: %w", err) } - msg := &btcstakingtypes.MsgCreateBTCValidator{ + msg := &btcstakingtypes.MsgCreateFinalityProvider{ Signer: bc.mustGetTxSigner(), BabylonPk: &secp256k1.PubKey{Key: chainPk}, - BtcPk: bbntypes.NewBIP340PubKeyFromBTCPK(valPk), + BtcPk: bbntypes.NewBIP340PubKeyFromBTCPK(fpPk), Pop: &bbnPop, Commission: commission, Description: &sdkDescription, @@ -182,7 +182,7 @@ func (bc *BabylonController) RegisterValidator( // CommitPubRandList commits a list of Schnorr public randomness via a MsgCommitPubRand to Babylon // it returns tx hash and error func (bc *BabylonController) CommitPubRandList( - valPk *btcec.PublicKey, + fpPk *btcec.PublicKey, startHeight uint64, pubRandList []*btcec.FieldVal, sig *schnorr.Signature, @@ -197,7 +197,7 @@ func (bc *BabylonController) CommitPubRandList( msg := &finalitytypes.MsgCommitPubRandList{ Signer: bc.mustGetTxSigner(), - ValBtcPk: bbntypes.NewBIP340PubKeyFromBTCPK(valPk), + FpBtcPk: bbntypes.NewBIP340PubKeyFromBTCPK(fpPk), StartHeight: startHeight, PubRandList: schnorrPubRandList, Sig: bip340Sig, @@ -240,10 +240,10 @@ func (bc *BabylonController) SubmitCovenantSigs( } // SubmitFinalitySig submits the finality signature via a MsgAddVote to Babylon -func (bc *BabylonController) SubmitFinalitySig(valPk *btcec.PublicKey, blockHeight uint64, blockHash []byte, sig *btcec.ModNScalar) (*types.TxResponse, error) { +func (bc *BabylonController) SubmitFinalitySig(fpPk *btcec.PublicKey, blockHeight uint64, blockHash []byte, sig *btcec.ModNScalar) (*types.TxResponse, error) { msg := &finalitytypes.MsgAddFinalitySig{ Signer: bc.mustGetTxSigner(), - ValBtcPk: bbntypes.NewBIP340PubKeyFromBTCPK(valPk), + FpBtcPk: bbntypes.NewBIP340PubKeyFromBTCPK(fpPk), BlockHeight: blockHeight, BlockAppHash: blockHash, FinalitySig: bbntypes.NewSchnorrEOTSSigFromModNScalar(sig), @@ -258,7 +258,7 @@ func (bc *BabylonController) SubmitFinalitySig(valPk *btcec.PublicKey, blockHeig } // SubmitBatchFinalitySigs submits a batch of finality signatures to Babylon -func (bc *BabylonController) SubmitBatchFinalitySigs(valPk *btcec.PublicKey, blocks []*types.BlockInfo, sigs []*btcec.ModNScalar) (*types.TxResponse, error) { +func (bc *BabylonController) SubmitBatchFinalitySigs(fpPk *btcec.PublicKey, blocks []*types.BlockInfo, sigs []*btcec.ModNScalar) (*types.TxResponse, error) { if len(blocks) != len(sigs) { return nil, fmt.Errorf("the number of blocks %v should match the number of finality signatures %v", len(blocks), len(sigs)) } @@ -267,7 +267,7 @@ func (bc *BabylonController) SubmitBatchFinalitySigs(valPk *btcec.PublicKey, blo for i, b := range blocks { msg := &finalitytypes.MsgAddFinalitySig{ Signer: bc.mustGetTxSigner(), - ValBtcPk: bbntypes.NewBIP340PubKeyFromBTCPK(valPk), + FpBtcPk: bbntypes.NewBIP340PubKeyFromBTCPK(fpPk), BlockHeight: b.Height, BlockAppHash: b.Hash, FinalitySig: bbntypes.NewSchnorrEOTSSigFromModNScalar(sigs[i]), @@ -308,28 +308,28 @@ func (bc *BabylonController) queryDelegationsWithStatus(status btcstakingtypes.B return dels, nil } -func (bc *BabylonController) QueryValidatorSlashed(valPk *btcec.PublicKey) (bool, error) { +func (bc *BabylonController) QueryFinalityProviderSlashed(fpPk *btcec.PublicKey) (bool, error) { ctx, cancel := getContextWithCancel(bc.cfg.Timeout) defer cancel() clientCtx := sdkclient.Context{Client: bc.bbnClient.RPCClient} - valPubKey := bbntypes.NewBIP340PubKeyFromBTCPK(valPk) + fpPubKey := bbntypes.NewBIP340PubKeyFromBTCPK(fpPk) - queryRequest := &btcstakingtypes.QueryBTCValidatorRequest{ValBtcPkHex: valPubKey.MarshalHex()} + queryRequest := &btcstakingtypes.QueryFinalityProviderRequest{FpBtcPkHex: fpPubKey.MarshalHex()} queryClient := btcstakingtypes.NewQueryClient(clientCtx) - res, err := queryClient.BTCValidator(ctx, queryRequest) + res, err := queryClient.FinalityProvider(ctx, queryRequest) if err != nil { - return false, fmt.Errorf("failed to query the validator %s: %v", valPubKey.MarshalHex(), err) + return false, fmt.Errorf("failed to query the finality provider %s: %v", fpPubKey.MarshalHex(), err) } - slashed := res.BtcValidator.SlashedBtcHeight > 0 + slashed := res.FinalityProvider.SlashedBtcHeight > 0 return slashed, nil } func (bc *BabylonController) getNDelegations( - valBtcPk *bbntypes.BIP340PubKey, + fpBtcPk *bbntypes.BIP340PubKey, startKey []byte, n uint64, ) ([]*types.Delegation, []byte, error) { @@ -338,7 +338,7 @@ func (bc *BabylonController) getNDelegations( Limit: n, } - res, err := bc.bbnClient.QueryClient.BTCValidatorDelegations(valBtcPk.MarshalHex(), pagination) + res, err := bc.bbnClient.QueryClient.FinalityProviderDelegations(fpBtcPk.MarshalHex(), pagination) if err != nil { return nil, nil, fmt.Errorf("failed to query BTC delegations: %v", err) @@ -361,8 +361,8 @@ func (bc *BabylonController) getNDelegations( return delegations, nextKey, nil } -func (bc *BabylonController) getNValidatorDelegationsMatchingCriteria( - valBtcPk *bbntypes.BIP340PubKey, +func (bc *BabylonController) getNFinalityProviderDelegationsMatchingCriteria( + fpBtcPk *bbntypes.BIP340PubKey, n uint64, match func(*types.Delegation) bool, ) ([]*types.Delegation, error) { @@ -371,7 +371,7 @@ func (bc *BabylonController) getNValidatorDelegationsMatchingCriteria( var startKey []byte for { - dels, nextKey, err := bc.getNDelegations(valBtcPk, startKey, uint64(batchSize)) + dels, nextKey, err := bc.getNDelegations(fpBtcPk, startKey, uint64(batchSize)) if err != nil { return nil, err } @@ -397,10 +397,10 @@ func (bc *BabylonController) getNValidatorDelegationsMatchingCriteria( } } -// QueryValidatorVotingPower queries the voting power of the validator at a given height -func (bc *BabylonController) QueryValidatorVotingPower(valPk *btcec.PublicKey, blockHeight uint64) (uint64, error) { - res, err := bc.bbnClient.QueryClient.BTCValidatorPowerAtHeight( - bbntypes.NewBIP340PubKeyFromBTCPK(valPk).MarshalHex(), +// QueryFinalityProviderVotingPower queries the voting power of the finality provider at a given height +func (bc *BabylonController) QueryFinalityProviderVotingPower(fpPk *btcec.PublicKey, blockHeight uint64) (uint64, error) { + res, err := bc.bbnClient.QueryClient.FinalityProviderPowerAtHeight( + bbntypes.NewBIP340PubKeyFromBTCPK(fpPk).MarshalHex(), blockHeight, ) if err != nil { @@ -554,14 +554,14 @@ func ConvertDelegationType(del *btcstakingtypes.BTCDelegation) *types.Delegation undelegation = ConvertUndelegationType(del.BtcUndelegation) } - valBtcPks := make([]*btcec.PublicKey, 0, len(del.ValBtcPkList)) - for _, val := range del.ValBtcPkList { - valBtcPks = append(valBtcPks, val.MustToBTCPK()) + fpBtcPks := make([]*btcec.PublicKey, 0, len(del.FpBtcPkList)) + for _, fp := range del.FpBtcPkList { + fpBtcPks = append(fpBtcPks, fp.MustToBTCPK()) } return &types.Delegation{ BtcPk: del.BtcPk.MustToBTCPK(), - ValBtcPks: valBtcPks, + FpBtcPks: fpBtcPks, TotalSat: del.TotalSat, StartHeight: del.StartHeight, EndHeight: del.EndHeight, @@ -626,7 +626,7 @@ func ConvertUndelegationType(undel *btcstakingtypes.BTCUndelegation) *types.Unde func (bc *BabylonController) CreateBTCDelegation( delBabylonPk *secp256k1.PubKey, delBtcPk *bbntypes.BIP340PubKey, - valPks []*btcec.PublicKey, + fpPks []*btcec.PublicKey, pop *btcstakingtypes.ProofOfPossession, stakingTime uint32, stakingValue int64, @@ -639,16 +639,16 @@ func (bc *BabylonController) CreateBTCDelegation( unbondingSlashingTx *btcstakingtypes.BTCSlashingTx, delUnbondingSlashingSig *bbntypes.BIP340Signature, ) (*types.TxResponse, error) { - valBtcPks := make([]bbntypes.BIP340PubKey, 0, len(valPks)) - for _, v := range valPks { - valBtcPks = append(valBtcPks, *bbntypes.NewBIP340PubKeyFromBTCPK(v)) + fpBtcPks := make([]bbntypes.BIP340PubKey, 0, len(fpPks)) + for _, v := range fpPks { + fpBtcPks = append(fpBtcPks, *bbntypes.NewBIP340PubKeyFromBTCPK(v)) } msg := &btcstakingtypes.MsgCreateBTCDelegation{ Signer: bc.mustGetTxSigner(), BabylonPk: delBabylonPk, Pop: pop, BtcPk: delBtcPk, - ValBtcPkList: valBtcPks, + FpBtcPkList: fpBtcPks, StakingTime: stakingTime, StakingValue: stakingValue, StakingTx: stakingTxInfo, @@ -685,10 +685,10 @@ func (bc *BabylonController) InsertBtcBlockHeaders(headers []bbntypes.BTCHeaderB return res, nil } -// QueryValidators queries BTC validators +// QueryFinalityProvider queries finality providers // Currently this is only used for e2e tests, probably does not need to add this into the interface -func (bc *BabylonController) QueryValidators() ([]*btcstakingtypes.BTCValidator, error) { - var validators []*btcstakingtypes.BTCValidator +func (bc *BabylonController) QueryFinalityProviders() ([]*btcstakingtypes.FinalityProvider, error) { + var fps []*btcstakingtypes.FinalityProvider pagination := &sdkquery.PageRequest{ Limit: 100, } @@ -701,14 +701,14 @@ func (bc *BabylonController) QueryValidators() ([]*btcstakingtypes.BTCValidator, queryClient := btcstakingtypes.NewQueryClient(clientCtx) for { - queryRequest := &btcstakingtypes.QueryBTCValidatorsRequest{ + queryRequest := &btcstakingtypes.QueryFinalityProvidersRequest{ Pagination: pagination, } - res, err := queryClient.BTCValidators(ctx, queryRequest) + res, err := queryClient.FinalityProviders(ctx, queryRequest) if err != nil { - return nil, fmt.Errorf("failed to query BTC validators: %v", err) + return nil, fmt.Errorf("failed to query finality providers: %v", err) } - validators = append(validators, res.BtcValidators...) + fps = append(fps, res.FinalityProviders...) if res.Pagination == nil || res.Pagination.NextKey == nil { break } @@ -716,7 +716,7 @@ func (bc *BabylonController) QueryValidators() ([]*btcstakingtypes.BTCValidator, pagination.Key = res.Pagination.NextKey } - return validators, nil + return fps, nil } // Currently this is only used for e2e tests, probably does not need to add this into the interface @@ -738,9 +738,9 @@ func (bc *BabylonController) QueryBtcLightClientTip() (*btclctypes.BTCHeaderInfo } // Currently this is only used for e2e tests, probably does not need to add this into the interface -func (bc *BabylonController) QueryBTCValidatorDelegations(valBtcPk *bbntypes.BIP340PubKey, max uint64) ([]*types.Delegation, error) { - return bc.getNValidatorDelegationsMatchingCriteria( - valBtcPk, +func (bc *BabylonController) QueryFinalityProviderDelegations(fpBtcPk *bbntypes.BIP340PubKey, max uint64) ([]*types.Delegation, error) { + return bc.getNFinalityProviderDelegationsMatchingCriteria( + fpBtcPk, max, // fitlering function which always returns true as we want all delegations func(*types.Delegation) bool { return true }, diff --git a/clientcontroller/interface.go b/clientcontroller/interface.go index a9e3d2b7..a51c7d53 100644 --- a/clientcontroller/interface.go +++ b/clientcontroller/interface.go @@ -9,8 +9,8 @@ import ( "github.com/btcsuite/btcd/btcec/v2" "github.com/btcsuite/btcd/btcec/v2/schnorr" - "github.com/babylonchain/btc-validator/config" - "github.com/babylonchain/btc-validator/types" + "github.com/babylonchain/finality-provider/config" + "github.com/babylonchain/finality-provider/types" ) const ( @@ -18,7 +18,7 @@ const ( ) type ClientController interface { - ValidatorAPIs + FinalityProviderAPIs CovenantAPIs @@ -27,13 +27,13 @@ type ClientController interface { Close() error } -// ValidatorAPIs contains interfaces needed when the program is running in the validator mode -type ValidatorAPIs interface { - // RegisterValidator registers a BTC validator to the consumer chain +// FinalityProviderAPIs contains interfaces needed when the program is running in the finality provider mode +type FinalityProviderAPIs interface { + // RegisterFinalityProvider registers a finality provider to the consumer chain // it returns tx hash and error - RegisterValidator( + RegisterFinalityProvider( chainPk []byte, - valPk *btcec.PublicKey, + fpPk *btcec.PublicKey, pop []byte, commission *math.LegacyDec, description []byte, @@ -41,21 +41,21 @@ type ValidatorAPIs interface { // CommitPubRandList commits a list of EOTS public randomness the consumer chain // it returns tx hash and error - CommitPubRandList(valPk *btcec.PublicKey, startHeight uint64, pubRandList []*btcec.FieldVal, sig *schnorr.Signature) (*types.TxResponse, error) + CommitPubRandList(fpPk *btcec.PublicKey, startHeight uint64, pubRandList []*btcec.FieldVal, sig *schnorr.Signature) (*types.TxResponse, error) // SubmitFinalitySig submits the finality signature to the consumer chain - SubmitFinalitySig(valPk *btcec.PublicKey, blockHeight uint64, blockHash []byte, sig *btcec.ModNScalar) (*types.TxResponse, error) + SubmitFinalitySig(fpPk *btcec.PublicKey, blockHeight uint64, blockHash []byte, sig *btcec.ModNScalar) (*types.TxResponse, error) // SubmitBatchFinalitySigs submits a batch of finality signatures to the consumer chain - SubmitBatchFinalitySigs(valPk *btcec.PublicKey, blocks []*types.BlockInfo, sigs []*btcec.ModNScalar) (*types.TxResponse, error) + SubmitBatchFinalitySigs(fpPk *btcec.PublicKey, blocks []*types.BlockInfo, sigs []*btcec.ModNScalar) (*types.TxResponse, error) // Note: the following queries are only for PoC - // QueryValidatorVotingPower queries the voting power of the validator at a given height - QueryValidatorVotingPower(valPk *btcec.PublicKey, blockHeight uint64) (uint64, error) + // QueryFinalityProviderVotingPower queries the voting power of the finality provider at a given height + QueryFinalityProviderVotingPower(fpPk *btcec.PublicKey, blockHeight uint64) (uint64, error) - // QueryValidatorSlashed queries if the validator is slashed - QueryValidatorSlashed(valPk *btcec.PublicKey) (bool, error) + // QueryFinalityProviderSlashed queries if the finality provider is slashed + QueryFinalityProviderSlashed(fpPk *btcec.PublicKey) (bool, error) // QueryLatestFinalizedBlocks returns the latest finalized blocks QueryLatestFinalizedBlocks(count uint64) ([]*types.BlockInfo, error) @@ -77,7 +77,7 @@ type ValidatorAPIs interface { // CovenantAPIs contains interfaces needed when the program is running in the covenant mode type CovenantAPIs interface { // SubmitCovenantSigs submits Covenant signatures to the consumer chain, each corresponding to - // a validator that the delegation is (re-)staked to + // a finality provider that the delegation is (re-)staked to // it returns tx hash and error SubmitCovenantSigs(covPk *btcec.PublicKey, stakingTxHash string, sigs [][]byte, unbondingSig *schnorr.Signature, unbondingSlashingSigs [][]byte) (*types.TxResponse, error) diff --git a/clientcontroller/retry_utils.go b/clientcontroller/retry_utils.go index d84721b8..486bf5e6 100644 --- a/clientcontroller/retry_utils.go +++ b/clientcontroller/retry_utils.go @@ -9,7 +9,7 @@ import ( ) // these errors are considered unrecoverable because these indicate -// something critical in the validator program or the consumer chain +// something critical in the finality provider program or the consumer chain var unrecoverableErrors = []*sdkErr.Error{ finalitytypes.ErrBlockNotFound, finalitytypes.ErrInvalidFinalitySig, @@ -18,7 +18,7 @@ var unrecoverableErrors = []*sdkErr.Error{ finalitytypes.ErrNoPubRandYet, finalitytypes.ErrPubRandNotFound, finalitytypes.ErrTooFewPubRand, - btcstakingtypes.ErrBTCValAlreadySlashed, + btcstakingtypes.ErrFpAlreadySlashed, } // IsUnrecoverable returns true when the error is in the unrecoverableErrors list diff --git a/covenant/cmd/covd/init.go b/covenant/cmd/covd/init.go index b28dfebb..830a95b0 100644 --- a/covenant/cmd/covd/init.go +++ b/covenant/cmd/covd/init.go @@ -2,8 +2,8 @@ package main import ( "fmt" - covcfg "github.com/babylonchain/btc-validator/covenant/config" - "github.com/babylonchain/btc-validator/util" + covcfg "github.com/babylonchain/finality-provider/covenant/config" + "github.com/babylonchain/finality-provider/util" "github.com/jessevdk/go-flags" "github.com/urfave/cli" "path/filepath" diff --git a/covenant/cmd/covd/key.go b/covenant/cmd/covd/key.go index 46573398..baefe391 100644 --- a/covenant/cmd/covd/key.go +++ b/covenant/cmd/covd/key.go @@ -4,8 +4,8 @@ import ( "encoding/json" "fmt" "github.com/babylonchain/babylon/types" - "github.com/babylonchain/btc-validator/covenant" - covcfg "github.com/babylonchain/btc-validator/covenant/config" + "github.com/babylonchain/finality-provider/covenant" + covcfg "github.com/babylonchain/finality-provider/covenant/config" "github.com/urfave/cli" ) diff --git a/covenant/cmd/covd/start.go b/covenant/cmd/covd/start.go index afe479bf..31e8e577 100644 --- a/covenant/cmd/covd/start.go +++ b/covenant/cmd/covd/start.go @@ -2,18 +2,18 @@ package main import ( "fmt" - "github.com/babylonchain/btc-validator/eotsmanager/config" - "github.com/babylonchain/btc-validator/log" - "github.com/babylonchain/btc-validator/util" + "github.com/babylonchain/finality-provider/eotsmanager/config" + "github.com/babylonchain/finality-provider/log" + "github.com/babylonchain/finality-provider/util" "path/filepath" "github.com/lightningnetwork/lnd/signal" "github.com/urfave/cli" - "github.com/babylonchain/btc-validator/clientcontroller" - "github.com/babylonchain/btc-validator/covenant" - covcfg "github.com/babylonchain/btc-validator/covenant/config" - covsrv "github.com/babylonchain/btc-validator/covenant/service" + "github.com/babylonchain/finality-provider/clientcontroller" + "github.com/babylonchain/finality-provider/covenant" + covcfg "github.com/babylonchain/finality-provider/covenant/config" + covsrv "github.com/babylonchain/finality-provider/covenant/service" ) var startCommand = cli.Command{ diff --git a/covenant/config/config.go b/covenant/config/config.go index 42e7dbe9..b918e158 100644 --- a/covenant/config/config.go +++ b/covenant/config/config.go @@ -2,7 +2,7 @@ package config import ( "fmt" - "github.com/babylonchain/btc-validator/util" + "github.com/babylonchain/finality-provider/util" "path/filepath" "time" @@ -10,7 +10,7 @@ import ( "github.com/btcsuite/btcd/chaincfg" "github.com/jessevdk/go-flags" - "github.com/babylonchain/btc-validator/config" + "github.com/babylonchain/finality-provider/config" ) const ( @@ -27,7 +27,7 @@ const ( var ( // DefaultCovenantDir specifies the default home directory for the covenant: // C:\Users\\AppData\Local\ on Windows - // ~/.vald on Linux + // ~/.covd on Linux // ~/Library/Application Support/Covd on MacOS DefaultCovenantDir = btcutil.AppDataDir("covd", false) diff --git a/covenant/covenant.go b/covenant/covenant.go index c842d589..cfee5f6c 100644 --- a/covenant/covenant.go +++ b/covenant/covenant.go @@ -2,25 +2,25 @@ package covenant import ( "fmt" + "github.com/avast/retry-go/v4" + "github.com/btcsuite/btcd/btcec/v2" "strings" "sync" "time" "go.uber.org/zap" - "github.com/babylonchain/btc-validator/keyring" + "github.com/babylonchain/finality-provider/keyring" - "github.com/avast/retry-go/v4" "github.com/babylonchain/babylon/btcstaking" asig "github.com/babylonchain/babylon/crypto/schnorr-adaptor-signature" bbntypes "github.com/babylonchain/babylon/types" bstypes "github.com/babylonchain/babylon/x/btcstaking/types" - "github.com/btcsuite/btcd/btcec/v2" "github.com/btcsuite/btcd/btcutil" - "github.com/babylonchain/btc-validator/clientcontroller" - covcfg "github.com/babylonchain/btc-validator/covenant/config" - "github.com/babylonchain/btc-validator/types" + "github.com/babylonchain/finality-provider/clientcontroller" + covcfg "github.com/babylonchain/finality-provider/covenant/config" + "github.com/babylonchain/finality-provider/types" ) var ( @@ -164,7 +164,7 @@ func (ce *CovenantEmulator) AddCovenantSignature(btcDel *types.Delegation) (*Add unbondingInfo, err := btcstaking.BuildUnbondingInfo( btcDel.BtcPk, - btcDel.ValBtcPks, + btcDel.FpBtcPks, ce.params.CovenantPks, ce.params.CovenantQuorum, uint16(btcDel.BtcUndelegation.UnbondingTime), @@ -196,7 +196,7 @@ func (ce *CovenantEmulator) AddCovenantSignature(btcDel *types.Delegation) (*Add stakingInfo, err := btcstaking.BuildStakingInfo( btcDel.BtcPk, - btcDel.ValBtcPks, + btcDel.FpBtcPks, ce.params.CovenantPks, ce.params.CovenantQuorum, btcDel.GetStakingTime(), @@ -212,8 +212,8 @@ func (ce *CovenantEmulator) AddCovenantSignature(btcDel *types.Delegation) (*Add return nil, err } - covSigs := make([][]byte, 0, len(btcDel.ValBtcPks)) - for _, valPk := range btcDel.ValBtcPks { + covSigs := make([][]byte, 0, len(btcDel.FpBtcPks)) + for _, valPk := range btcDel.FpBtcPks { encKey, err := asig.NewEncryptionKeyFromBTCPK(valPk) if err != nil { return nil, err @@ -258,9 +258,9 @@ func (ce *CovenantEmulator) AddCovenantSignature(btcDel *types.Delegation) (*Add return nil, err } - covSlashingSigs := make([][]byte, 0, len(btcDel.ValBtcPks)) - for _, valPk := range btcDel.ValBtcPks { - encKey, err := asig.NewEncryptionKeyFromBTCPK(valPk) + covSlashingSigs := make([][]byte, 0, len(btcDel.FpBtcPks)) + for _, fpPk := range btcDel.FpBtcPks { + encKey, err := asig.NewEncryptionKeyFromBTCPK(fpPk) if err != nil { return nil, err } diff --git a/covenant/covenant_test.go b/covenant/covenant_test.go index 88b78816..9a5f954a 100644 --- a/covenant/covenant_test.go +++ b/covenant/covenant_test.go @@ -14,10 +14,10 @@ import ( "github.com/stretchr/testify/require" "go.uber.org/zap" - "github.com/babylonchain/btc-validator/covenant" - covcfg "github.com/babylonchain/btc-validator/covenant/config" - "github.com/babylonchain/btc-validator/testutil" - "github.com/babylonchain/btc-validator/types" + "github.com/babylonchain/finality-provider/covenant" + covcfg "github.com/babylonchain/finality-provider/covenant/config" + "github.com/babylonchain/finality-provider/testutil" + "github.com/babylonchain/finality-provider/types" ) const ( @@ -64,14 +64,14 @@ func FuzzAddCovenantSig(f *testing.F) { require.NoError(t, err) stakingTimeBlocks := uint16(5) stakingValue := int64(2 * 10e8) - valNum := datagen.RandomInt(r, 5) + 1 - valPks := testutil.GenBtcPublicKeys(r, t, int(valNum)) + fpNum := datagen.RandomInt(r, 5) + 1 + fpPks := testutil.GenBtcPublicKeys(r, t, int(fpNum)) testInfo := datagen.GenBTCStakingSlashingInfo( r, t, net, delSK, - valPks, + fpPks, params.CovenantPks, params.CovenantQuorum, stakingTimeBlocks, @@ -85,7 +85,7 @@ func FuzzAddCovenantSig(f *testing.F) { startHeight := datagen.RandomInt(r, 1000) + 100 btcDel := &types.Delegation{ BtcPk: delPK, - ValBtcPks: valPks, + FpBtcPks: fpPks, StartHeight: startHeight, // not relevant here EndHeight: startHeight + uint64(stakingTimeBlocks), TotalSat: uint64(stakingValue), @@ -96,9 +96,9 @@ func FuzzAddCovenantSig(f *testing.F) { // generate covenant staking sigs slashingSpendInfo, err := testInfo.StakingInfo.SlashingPathSpendInfo() require.NoError(t, err) - covSigs := make([][]byte, 0, len(valPks)) - for _, valPk := range valPks { - encKey, err := asig.NewEncryptionKeyFromBTCPK(valPk) + covSigs := make([][]byte, 0, len(fpPks)) + for _, fpPk := range fpPks { + encKey, err := asig.NewEncryptionKeyFromBTCPK(fpPk) require.NoError(t, err) covenantSig, err := testInfo.SlashingTx.EncSign( testInfo.StakingTx, @@ -120,7 +120,7 @@ func FuzzAddCovenantSig(f *testing.F) { t, net, delSK, - btcDel.ValBtcPks, + btcDel.FpBtcPks, params.CovenantPks, params.CovenantQuorum, wire.NewOutPoint(&stakingTxHash, 0), @@ -156,9 +156,9 @@ func FuzzAddCovenantSig(f *testing.F) { ) require.NoError(t, err) // generate covenant unbonding slashing sigs - unbondingCovSlashingSigs := make([][]byte, 0, len(valPks)) - for _, valPk := range valPks { - encKey, err := asig.NewEncryptionKeyFromBTCPK(valPk) + unbondingCovSlashingSigs := make([][]byte, 0, len(fpPks)) + for _, fpPk := range fpPks { + encKey, err := asig.NewEncryptionKeyFromBTCPK(fpPk) require.NoError(t, err) covenantSig, err := testUnbondingInfo.SlashingTx.EncSign( testUnbondingInfo.UnbondingTx, diff --git a/covenant/service/server.go b/covenant/service/server.go index 36162a8b..a0d283c6 100644 --- a/covenant/service/server.go +++ b/covenant/service/server.go @@ -7,7 +7,7 @@ import ( "github.com/lightningnetwork/lnd/signal" "go.uber.org/zap" - "github.com/babylonchain/btc-validator/covenant" + "github.com/babylonchain/finality-provider/covenant" ) // CovenantServer is the main daemon construct for the covenant emulator. diff --git a/eotsmanager/client/rpcclient.go b/eotsmanager/client/rpcclient.go index b6caf494..47879a03 100644 --- a/eotsmanager/client/rpcclient.go +++ b/eotsmanager/client/rpcclient.go @@ -9,9 +9,9 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" - "github.com/babylonchain/btc-validator/eotsmanager" - "github.com/babylonchain/btc-validator/eotsmanager/proto" - "github.com/babylonchain/btc-validator/eotsmanager/types" + "github.com/babylonchain/finality-provider/eotsmanager" + "github.com/babylonchain/finality-provider/eotsmanager/proto" + "github.com/babylonchain/finality-provider/eotsmanager/types" ) var _ eotsmanager.EOTSManager = &EOTSManagerGRpcClient{} diff --git a/eotsmanager/cmd/eotsd/init.go b/eotsmanager/cmd/eotsd/init.go index 153397ef..757083c6 100644 --- a/eotsmanager/cmd/eotsd/init.go +++ b/eotsmanager/cmd/eotsd/init.go @@ -2,8 +2,8 @@ package main import ( "fmt" - eotscfg "github.com/babylonchain/btc-validator/eotsmanager/config" - "github.com/babylonchain/btc-validator/util" + eotscfg "github.com/babylonchain/finality-provider/eotsmanager/config" + "github.com/babylonchain/finality-provider/util" "github.com/jessevdk/go-flags" "github.com/urfave/cli" "path/filepath" diff --git a/eotsmanager/cmd/eotsd/start.go b/eotsmanager/cmd/eotsd/start.go index 055deab0..702f571f 100644 --- a/eotsmanager/cmd/eotsd/start.go +++ b/eotsmanager/cmd/eotsd/start.go @@ -2,11 +2,11 @@ package main import ( "fmt" - "github.com/babylonchain/btc-validator/eotsmanager" - "github.com/babylonchain/btc-validator/eotsmanager/config" - eotsservice "github.com/babylonchain/btc-validator/eotsmanager/service" - "github.com/babylonchain/btc-validator/log" - "github.com/babylonchain/btc-validator/util" + "github.com/babylonchain/finality-provider/eotsmanager" + "github.com/babylonchain/finality-provider/eotsmanager/config" + eotsservice "github.com/babylonchain/finality-provider/eotsmanager/service" + "github.com/babylonchain/finality-provider/log" + "github.com/babylonchain/finality-provider/util" "github.com/lightningnetwork/lnd/signal" "github.com/urfave/cli" "path/filepath" diff --git a/eotsmanager/config/config.go b/eotsmanager/config/config.go index 89a84ea8..f7ae10aa 100644 --- a/eotsmanager/config/config.go +++ b/eotsmanager/config/config.go @@ -2,8 +2,8 @@ package config import ( "fmt" - "github.com/babylonchain/btc-validator/config" - "github.com/babylonchain/btc-validator/util" + "github.com/babylonchain/finality-provider/config" + "github.com/babylonchain/finality-provider/util" "github.com/btcsuite/btcd/btcutil" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/jessevdk/go-flags" @@ -26,7 +26,7 @@ const ( var ( // DefaultEOTSDir the default EOTS home directory: // C:\Users\\AppData\Local\ on Windows - // ~/.vald on Linux + // ~/.eotsd on Linux // ~/Library/Application Support/Eotsd on MacOS DefaultEOTSDir = btcutil.AppDataDir("eotsd", false) diff --git a/eotsmanager/eotsmanager.go b/eotsmanager/eotsmanager.go index c24d4fb2..2e8e1619 100644 --- a/eotsmanager/eotsmanager.go +++ b/eotsmanager/eotsmanager.go @@ -4,7 +4,7 @@ import ( "github.com/btcsuite/btcd/btcec/v2" "github.com/btcsuite/btcd/btcec/v2/schnorr" - "github.com/babylonchain/btc-validator/eotsmanager/types" + "github.com/babylonchain/finality-provider/eotsmanager/types" ) type EOTSManager interface { @@ -15,24 +15,24 @@ type EOTSManager interface { // CreateRandomnessPairList generates a list of Schnorr randomness pairs from // startHeight to startHeight+(num-1) where num means the number of public randomness - // It fails if the validator does not exist or a randomness pair has been created before + // It fails if the finality provider does not exist or a randomness pair has been created before // or passPhrase is incorrect // NOTE: the randomness is deterministically generated based on the EOTS key, chainID and // block height CreateRandomnessPairList(uid []byte, chainID []byte, startHeight uint64, num uint32, passphrase string) ([]*btcec.FieldVal, error) - // KeyRecord returns the validator record - // It fails if the validator does not exist or passPhrase is incorrect + // KeyRecord returns the finality provider record + // It fails if the finality provider does not exist or passPhrase is incorrect KeyRecord(uid []byte, passphrase string) (*types.KeyRecord, error) - // SignEOTS signs an EOTS using the private key of the validator and the corresponding + // SignEOTS signs an EOTS using the private key of the finality provider and the corresponding // secret randomness of the give chain at the given height - // It fails if the validator does not exist or there's no randomness committed to the given height + // It fails if the finality provider does not exist or there's no randomness committed to the given height // or passPhrase is incorrect SignEOTS(uid []byte, chainID []byte, msg []byte, height uint64, passphrase string) (*btcec.ModNScalar, error) - // SignSchnorrSig signs a Schnorr signature using the private key of the validator - // It fails if the validator does not exist or the message size is not 32 bytes + // SignSchnorrSig signs a Schnorr signature using the private key of the finality provider + // It fails if the finality provider does not exist or the message size is not 32 bytes // or passPhrase is incorrect SignSchnorrSig(uid []byte, msg []byte, passphrase string) (*schnorr.Signature, error) diff --git a/eotsmanager/eotsstore.go b/eotsmanager/eotsstore.go index 39992aca..40cf8401 100644 --- a/eotsmanager/eotsstore.go +++ b/eotsmanager/eotsstore.go @@ -3,12 +3,12 @@ package eotsmanager import ( "fmt" - "github.com/babylonchain/btc-validator/eotsmanager/types" - "github.com/babylonchain/btc-validator/store" + "github.com/babylonchain/finality-provider/eotsmanager/types" + "github.com/babylonchain/finality-provider/store" ) const ( - validatorKeyNamePrefix = "val-key" + finalityProviderKeyNamePrefix = "fp-key" ) type EOTSStore struct { @@ -32,22 +32,22 @@ func (es *EOTSStore) Close() error { return nil } -func (es *EOTSStore) saveValidatorKey(pk []byte, keyName string) error { - k := getValidatorKeyNameKey(pk) +func (es *EOTSStore) saveFinalityProviderKey(pk []byte, keyName string) error { + k := getFinalityProviderKeyNameKey(pk) exists, err := es.s.Exists(k) if err != nil { return nil } if exists { - return types.ErrValidatorAlreadyExisted + return types.ErrFinalityProviderAlreadyExisted } return es.s.Put(k, []byte(keyName)) } -func (es *EOTSStore) getValidatorKeyName(pk []byte) (string, error) { - k := getValidatorKeyNameKey(pk) +func (es *EOTSStore) getFinalityProviderKeyName(pk []byte) (string, error) { + k := getFinalityProviderKeyNameKey(pk) v, err := es.s.Get(k) if err != nil { return "", err @@ -56,8 +56,8 @@ func (es *EOTSStore) getValidatorKeyName(pk []byte) (string, error) { return string(v), nil } -func getValidatorKeyNameKey(pk []byte) []byte { - return append([]byte(validatorKeyNamePrefix), pk...) +func getFinalityProviderKeyNameKey(pk []byte) []byte { + return append([]byte(finalityProviderKeyNamePrefix), pk...) } func openStore(dbPath string, dbName string, dbBackend string) (store.Store, error) { diff --git a/eotsmanager/localmanager.go b/eotsmanager/localmanager.go index dc9d55bb..4d07a980 100644 --- a/eotsmanager/localmanager.go +++ b/eotsmanager/localmanager.go @@ -2,7 +2,7 @@ package eotsmanager import ( "fmt" - "github.com/babylonchain/btc-validator/util" + "github.com/babylonchain/finality-provider/util" "strings" "github.com/babylonchain/babylon/crypto/eots" @@ -14,10 +14,10 @@ import ( "github.com/cosmos/go-bip39" "go.uber.org/zap" - "github.com/babylonchain/btc-validator/codec" - "github.com/babylonchain/btc-validator/eotsmanager/config" - "github.com/babylonchain/btc-validator/eotsmanager/randgenerator" - eotstypes "github.com/babylonchain/btc-validator/eotsmanager/types" + "github.com/babylonchain/finality-provider/codec" + "github.com/babylonchain/finality-provider/eotsmanager/config" + "github.com/babylonchain/finality-provider/eotsmanager/randgenerator" + eotstypes "github.com/babylonchain/finality-provider/eotsmanager/types" ) const ( @@ -77,7 +77,7 @@ func initKeyring(homeDir string, eotsCfg *config.Config, inputReader *strings.Re func (lm *LocalEOTSManager) CreateKey(name, passphrase, hdPath string) ([]byte, error) { if lm.keyExists(name) { - return nil, eotstypes.ErrValidatorAlreadyExisted + return nil, eotstypes.ErrFinalityProviderAlreadyExisted } keyringAlgos, _ := lm.kr.SupportedAlgorithms() @@ -123,7 +123,7 @@ func (lm *LocalEOTSManager) CreateKey(name, passphrase, hdPath string) ([]byte, return nil, fmt.Errorf("unsupported key type in keyring") } - if err := lm.es.saveValidatorKey(eotsPk.MustMarshal(), name); err != nil { + if err := lm.es.saveFinalityProviderKey(eotsPk.MustMarshal(), name); err != nil { return nil, err } @@ -138,14 +138,14 @@ func (lm *LocalEOTSManager) CreateKey(name, passphrase, hdPath string) ([]byte, // TODO the current implementation is a PoC, which does not contain any anti-slasher mechanism // -// a simple anti-slasher mechanism could be that the manager remembers the tuple (valPk, chainID, height) or +// a simple anti-slasher mechanism could be that the manager remembers the tuple (fpPk, chainID, height) or // the hash of each generated randomness and return error if the same randomness is requested tweice -func (lm *LocalEOTSManager) CreateRandomnessPairList(valPk []byte, chainID []byte, startHeight uint64, num uint32, passphrase string) ([]*btcec.FieldVal, error) { +func (lm *LocalEOTSManager) CreateRandomnessPairList(fpPk []byte, chainID []byte, startHeight uint64, num uint32, passphrase string) ([]*btcec.FieldVal, error) { prList := make([]*btcec.FieldVal, 0, num) for i := uint32(0); i < num; i++ { height := startHeight + uint64(i) - _, pubRand, err := lm.getRandomnessPair(valPk, chainID, height, passphrase) + _, pubRand, err := lm.getRandomnessPair(fpPk, chainID, height, passphrase) if err != nil { return nil, err } @@ -156,13 +156,13 @@ func (lm *LocalEOTSManager) CreateRandomnessPairList(valPk []byte, chainID []byt return prList, nil } -func (lm *LocalEOTSManager) SignEOTS(valPk []byte, chainID []byte, msg []byte, height uint64, passphrase string) (*btcec.ModNScalar, error) { - privRand, _, err := lm.getRandomnessPair(valPk, chainID, height, passphrase) +func (lm *LocalEOTSManager) SignEOTS(fpPk []byte, chainID []byte, msg []byte, height uint64, passphrase string) (*btcec.ModNScalar, error) { + privRand, _, err := lm.getRandomnessPair(fpPk, chainID, height, passphrase) if err != nil { return nil, fmt.Errorf("failed to get private randomness: %w", err) } - privKey, err := lm.getEOTSPrivKey(valPk, passphrase) + privKey, err := lm.getEOTSPrivKey(fpPk, passphrase) if err != nil { return nil, fmt.Errorf("failed to get EOTS private key: %w", err) } @@ -170,8 +170,8 @@ func (lm *LocalEOTSManager) SignEOTS(valPk []byte, chainID []byte, msg []byte, h return eots.Sign(privKey, privRand, msg) } -func (lm *LocalEOTSManager) SignSchnorrSig(valPk []byte, msg []byte, passphrase string) (*schnorr.Signature, error) { - privKey, err := lm.getEOTSPrivKey(valPk, passphrase) +func (lm *LocalEOTSManager) SignSchnorrSig(fpPk []byte, msg []byte, passphrase string) (*schnorr.Signature, error) { + privKey, err := lm.getEOTSPrivKey(fpPk, passphrase) if err != nil { return nil, fmt.Errorf("failed to get EOTS private key: %w", err) } @@ -183,9 +183,9 @@ func (lm *LocalEOTSManager) Close() error { return lm.es.Close() } -// getRandomnessPair returns a randomness pair generated based on the given validator key, chainID and height -func (lm *LocalEOTSManager) getRandomnessPair(valPk []byte, chainID []byte, height uint64, passphrase string) (*eots.PrivateRand, *eots.PublicRand, error) { - record, err := lm.KeyRecord(valPk, passphrase) +// getRandomnessPair returns a randomness pair generated based on the given finality provider key, chainID and height +func (lm *LocalEOTSManager) getRandomnessPair(fpPk []byte, chainID []byte, height uint64, passphrase string) (*eots.PrivateRand, *eots.PublicRand, error) { + record, err := lm.KeyRecord(fpPk, passphrase) if err != nil { return nil, nil, err } @@ -194,12 +194,12 @@ func (lm *LocalEOTSManager) getRandomnessPair(valPk []byte, chainID []byte, heig } // TODO: we ignore passPhrase in local implementation for now -func (lm *LocalEOTSManager) KeyRecord(valPk []byte, passphrase string) (*eotstypes.KeyRecord, error) { - name, err := lm.es.getValidatorKeyName(valPk) +func (lm *LocalEOTSManager) KeyRecord(fpPk []byte, passphrase string) (*eotstypes.KeyRecord, error) { + name, err := lm.es.getFinalityProviderKeyName(fpPk) if err != nil { return nil, err } - privKey, err := lm.getEOTSPrivKey(valPk, passphrase) + privKey, err := lm.getEOTSPrivKey(fpPk, passphrase) if err != nil { return nil, err } @@ -210,8 +210,8 @@ func (lm *LocalEOTSManager) KeyRecord(valPk []byte, passphrase string) (*eotstyp }, nil } -func (lm *LocalEOTSManager) getEOTSPrivKey(valPk []byte, passphrase string) (*btcec.PrivateKey, error) { - keyName, err := lm.es.getValidatorKeyName(valPk) +func (lm *LocalEOTSManager) getEOTSPrivKey(fpPk []byte, passphrase string) (*btcec.PrivateKey, error) { + keyName, err := lm.es.getFinalityProviderKeyName(fpPk) if err != nil { return nil, err } diff --git a/eotsmanager/localmanager_test.go b/eotsmanager/localmanager_test.go index 24a90fb6..29f5d43f 100644 --- a/eotsmanager/localmanager_test.go +++ b/eotsmanager/localmanager_test.go @@ -8,9 +8,9 @@ import ( "testing" "github.com/babylonchain/babylon/testutil/datagen" - "github.com/babylonchain/btc-validator/eotsmanager" - "github.com/babylonchain/btc-validator/eotsmanager/types" - "github.com/babylonchain/btc-validator/testutil" + "github.com/babylonchain/finality-provider/eotsmanager" + "github.com/babylonchain/finality-provider/eotsmanager/types" + "github.com/babylonchain/finality-provider/testutil" "github.com/stretchr/testify/require" ) @@ -25,7 +25,7 @@ func FuzzCreateKey(f *testing.F) { f.Fuzz(func(t *testing.T, seed int64) { r := rand.New(rand.NewSource(seed)) - valName := testutil.GenRandomHexStr(r, 4) + fpName := testutil.GenRandomHexStr(r, 4) homeDir := filepath.Join(t.TempDir(), "eots-home") eotsCfg := testutil.GenEOTSConfig(r, t) defer func() { @@ -36,19 +36,19 @@ func FuzzCreateKey(f *testing.F) { lm, err := eotsmanager.NewLocalEOTSManager(homeDir, eotsCfg, zap.NewNop()) require.NoError(t, err) - valPk, err := lm.CreateKey(valName, passphrase, hdPath) + fpPk, err := lm.CreateKey(fpName, passphrase, hdPath) require.NoError(t, err) - valRecord, err := lm.KeyRecord(valPk, passphrase) + fpRecord, err := lm.KeyRecord(fpPk, passphrase) require.NoError(t, err) - require.Equal(t, valName, valRecord.Name) + require.Equal(t, fpName, fpRecord.Name) - sig, err := lm.SignSchnorrSig(valPk, datagen.GenRandomByteArray(r, 32), passphrase) + sig, err := lm.SignSchnorrSig(fpPk, datagen.GenRandomByteArray(r, 32), passphrase) require.NoError(t, err) require.NotNil(t, sig) - _, err = lm.CreateKey(valName, passphrase, hdPath) - require.ErrorIs(t, err, types.ErrValidatorAlreadyExisted) + _, err = lm.CreateKey(fpName, passphrase, hdPath) + require.ErrorIs(t, err, types.ErrFinalityProviderAlreadyExisted) }) } @@ -57,7 +57,7 @@ func FuzzCreateRandomnessPairList(f *testing.F) { f.Fuzz(func(t *testing.T, seed int64) { r := rand.New(rand.NewSource(seed)) - valName := testutil.GenRandomHexStr(r, 4) + fpName := testutil.GenRandomHexStr(r, 4) homeDir := filepath.Join(t.TempDir(), "eots-home") eotsCfg := testutil.GenEOTSConfig(r, t) defer func() { @@ -68,18 +68,18 @@ func FuzzCreateRandomnessPairList(f *testing.F) { lm, err := eotsmanager.NewLocalEOTSManager(homeDir, eotsCfg, zap.NewNop()) require.NoError(t, err) - valPk, err := lm.CreateKey(valName, passphrase, hdPath) + fpPk, err := lm.CreateKey(fpName, passphrase, hdPath) require.NoError(t, err) chainID := datagen.GenRandomByteArray(r, 10) startHeight := datagen.RandomInt(r, 100) num := r.Intn(10) + 1 - pubRandList, err := lm.CreateRandomnessPairList(valPk, chainID, startHeight, uint32(num), passphrase) + pubRandList, err := lm.CreateRandomnessPairList(fpPk, chainID, startHeight, uint32(num), passphrase) require.NoError(t, err) require.Len(t, pubRandList, num) for i := 0; i < num; i++ { - sig, err := lm.SignEOTS(valPk, chainID, datagen.GenRandomByteArray(r, 32), startHeight+uint64(i), passphrase) + sig, err := lm.SignEOTS(fpPk, chainID, datagen.GenRandomByteArray(r, 32), startHeight+uint64(i), passphrase) require.NoError(t, err) require.NotNil(t, sig) } diff --git a/eotsmanager/proto/eotsmanager.pb.go b/eotsmanager/proto/eotsmanager.pb.go index 7b295d37..844ed8e6 100644 --- a/eotsmanager/proto/eotsmanager.pb.go +++ b/eotsmanager/proto/eotsmanager.pb.go @@ -788,11 +788,11 @@ var file_eotsmanager_proto_rawDesc = []byte{ 0x6e, 0x53, 0x63, 0x68, 0x6e, 0x6f, 0x72, 0x72, 0x53, 0x69, 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x53, 0x69, 0x67, 0x6e, 0x53, 0x63, 0x68, 0x6e, 0x6f, 0x72, 0x72, 0x53, 0x69, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, - 0x65, 0x42, 0x39, 0x5a, 0x37, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, + 0x65, 0x42, 0x41, 0x5a, 0x3f, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x61, 0x62, 0x79, 0x6c, 0x6f, 0x6e, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x2f, 0x62, 0x74, 0x63, - 0x2d, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x2f, 0x65, 0x6f, 0x74, 0x73, 0x6d, - 0x61, 0x6e, 0x61, 0x67, 0x65, 0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x33, + 0x2d, 0x66, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x2d, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, + 0x65, 0x72, 0x2f, 0x65, 0x6f, 0x74, 0x73, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x72, 0x2f, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/eotsmanager/proto/eotsmanager.proto b/eotsmanager/proto/eotsmanager.proto index f85e0347..866a9de0 100644 --- a/eotsmanager/proto/eotsmanager.proto +++ b/eotsmanager/proto/eotsmanager.proto @@ -2,7 +2,7 @@ syntax = "proto3"; package proto; -option go_package = "github.com/babylonchain/btc-validator/eotsmanager/proto"; +option go_package = "github.com/babylonchain/btc-finality-provider/eotsmanager/proto"; service EOTSManager { rpc Ping (PingRequest) returns (PingResponse); diff --git a/eotsmanager/service/rpcserver.go b/eotsmanager/service/rpcserver.go index ee7e0fc3..b8cc4990 100644 --- a/eotsmanager/service/rpcserver.go +++ b/eotsmanager/service/rpcserver.go @@ -5,11 +5,11 @@ import ( "google.golang.org/grpc" - "github.com/babylonchain/btc-validator/eotsmanager" - "github.com/babylonchain/btc-validator/eotsmanager/proto" + "github.com/babylonchain/finality-provider/eotsmanager" + "github.com/babylonchain/finality-provider/eotsmanager/proto" ) -// rpcServer is the main RPC server for the BTC-Validator daemon that handles +// rpcServer is the main RPC server for the EOTS daemon that handles // gRPC incoming requests. type rpcServer struct { proto.UnimplementedEOTSManagerServer diff --git a/eotsmanager/service/server.go b/eotsmanager/service/server.go index c475e2c8..f16008c8 100644 --- a/eotsmanager/service/server.go +++ b/eotsmanager/service/server.go @@ -10,8 +10,8 @@ import ( "go.uber.org/zap" "google.golang.org/grpc" - "github.com/babylonchain/btc-validator/eotsmanager" - "github.com/babylonchain/btc-validator/eotsmanager/config" + "github.com/babylonchain/finality-provider/eotsmanager" + "github.com/babylonchain/finality-provider/eotsmanager/config" ) // Server is the main daemon construct for the EOTS manager server. It handles diff --git a/eotsmanager/types/errors.go b/eotsmanager/types/errors.go index d5419969..2d2879fd 100644 --- a/eotsmanager/types/errors.go +++ b/eotsmanager/types/errors.go @@ -3,5 +3,5 @@ package types import "errors" var ( - ErrValidatorAlreadyExisted = errors.New("the validator has already existed") + ErrFinalityProviderAlreadyExisted = errors.New("the finality provider has already existed") ) diff --git a/validator/Makefile b/finality-provider/Makefile similarity index 100% rename from validator/Makefile rename to finality-provider/Makefile diff --git a/validator/cmd/valcli/daemoncmd.go b/finality-provider/cmd/fpcli/daemoncmd.go similarity index 53% rename from validator/cmd/valcli/daemoncmd.go rename to finality-provider/cmd/fpcli/daemoncmd.go index a1cc6f71..c3a9fdff 100644 --- a/validator/cmd/valcli/daemoncmd.go +++ b/finality-provider/cmd/fpcli/daemoncmd.go @@ -11,21 +11,21 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/urfave/cli" - valcfg "github.com/babylonchain/btc-validator/validator/config" - dc "github.com/babylonchain/btc-validator/validator/service/client" + fpcfg "github.com/babylonchain/finality-provider/finality-provider/config" + dc "github.com/babylonchain/finality-provider/finality-provider/service/client" ) const ( - valdDaemonAddressFlag = "daemon-address" - keyNameFlag = "key-name" - valBTCPkFlag = "btc-pk" - blockHeightFlag = "height" - appHashFlag = "app-hash" - passphraseFlag = "passphrase" - hdPathFlag = "hd-path" - chainIdFlag = "chain-id" - defaultPassphrase = "" - defaultHdPath = "" + fpdDaemonAddressFlag = "daemon-address" + keyNameFlag = "key-name" + fpBTCPkFlag = "btc-pk" + blockHeightFlag = "height" + appHashFlag = "app-hash" + passphraseFlag = "passphrase" + hdPathFlag = "hd-path" + chainIdFlag = "chain-id" + defaultPassphrase = "" + defaultHdPath = "" // flags for description monikerFlag = "moniker" @@ -38,8 +38,8 @@ const ( ) var ( - defaultValdDaemonAddress = "127.0.0.1:" + strconv.Itoa(valcfg.DefaultRPCPort) - defaultAppHashStr = "fd903d9baeb3ab1c734ee003de75f676c5a9a8d0574647e5385834d57d3e79ec" + defaultFpdDaemonAddress = "127.0.0.1:" + strconv.Itoa(fpcfg.DefaultRPCPort) + defaultAppHashStr = "fd903d9baeb3ab1c734ee003de75f676c5a9a8d0574647e5385834d57d3e79ec" ) var getDaemonInfoCmd = cli.Command{ @@ -48,17 +48,17 @@ var getDaemonInfoCmd = cli.Command{ Usage: "Get information of the running daemon.", Flags: []cli.Flag{ cli.StringFlag{ - Name: valdDaemonAddressFlag, - Usage: "Full address of the validator daemon in format tcp://:", - Value: defaultValdDaemonAddress, + Name: fpdDaemonAddressFlag, + Usage: "Full address of the finality provider daemon in format tcp://:", + Value: defaultFpdDaemonAddress, }, }, Action: getInfo, } func getInfo(ctx *cli.Context) error { - daemonAddress := ctx.String(valdDaemonAddressFlag) - client, cleanUp, err := dc.NewValidatorServiceGRpcClient(daemonAddress) + daemonAddress := ctx.String(fpdDaemonAddressFlag) + client, cleanUp, err := dc.NewFinalityProviderServiceGRpcClient(daemonAddress) if err != nil { return err } @@ -75,19 +75,19 @@ func getInfo(ctx *cli.Context) error { return nil } -var createValDaemonCmd = cli.Command{ - Name: "create-validator", - ShortName: "cv", - Usage: "Create a Bitcoin validator object and save it in database.", +var createFpDaemonCmd = cli.Command{ + Name: "create-finality-provider", + ShortName: "cfp", + Usage: "Create a finality provider object and save it in database.", Flags: []cli.Flag{ cli.StringFlag{ - Name: valdDaemonAddressFlag, - Usage: "Full address of the validator daemon in format tcp://:", - Value: defaultValdDaemonAddress, + Name: fpdDaemonAddressFlag, + Usage: "Full address of the finality provider daemon in format tcp://:", + Value: defaultFpdDaemonAddress, }, cli.StringFlag{ Name: keyNameFlag, - Usage: "The unique name of the validator key", + Usage: "The unique name of the finality provider key", Required: true, }, cli.StringFlag{ @@ -107,12 +107,12 @@ var createValDaemonCmd = cli.Command{ }, cli.StringFlag{ Name: commissionRateFlag, - Usage: "The commission rate for the validator, e.g., 0.05", + Usage: "The commission rate for the finality provider, e.g., 0.05", Value: "0.05", }, cli.StringFlag{ Name: monikerFlag, - Usage: "A human-readable name for the validator", + Usage: "A human-readable name for the finality provider", Value: "", }, cli.StringFlag{ @@ -136,11 +136,11 @@ var createValDaemonCmd = cli.Command{ Value: "", }, }, - Action: createValDaemon, + Action: createFpDaemon, } -func createValDaemon(ctx *cli.Context) error { - daemonAddress := ctx.String(valdDaemonAddressFlag) +func createFpDaemon(ctx *cli.Context) error { + daemonAddress := ctx.String(fpdDaemonAddressFlag) commissionRate, err := math.LegacyNewDecFromStr(ctx.String(commissionRateFlag)) if err != nil { @@ -152,13 +152,13 @@ func createValDaemon(ctx *cli.Context) error { return err } - client, cleanUp, err := dc.NewValidatorServiceGRpcClient(daemonAddress) + client, cleanUp, err := dc.NewFinalityProviderServiceGRpcClient(daemonAddress) if err != nil { return err } defer cleanUp() - info, err := client.CreateValidator( + info, err := client.CreateFinalityProvider( context.Background(), ctx.String(keyNameFlag), ctx.String(chainIdFlag), @@ -190,29 +190,29 @@ func getDescriptionFromContext(ctx *cli.Context) (stakingtypes.Description, erro return description.EnsureLength() } -var lsValDaemonCmd = cli.Command{ - Name: "list-validators", +var lsFpDaemonCmd = cli.Command{ + Name: "list-finality-providers", ShortName: "ls", - Usage: "List validators stored in the database.", + Usage: "List finality providers stored in the database.", Flags: []cli.Flag{ cli.StringFlag{ - Name: valdDaemonAddressFlag, - Usage: "Full address of the validator daemon in format tcp://:", - Value: defaultValdDaemonAddress, + Name: fpdDaemonAddressFlag, + Usage: "Full address of the finality provider daemon in format tcp://:", + Value: defaultFpdDaemonAddress, }, }, - Action: lsValDaemon, + Action: lsFpDaemon, } -func lsValDaemon(ctx *cli.Context) error { - daemonAddress := ctx.String(valdDaemonAddressFlag) - rpcClient, cleanUp, err := dc.NewValidatorServiceGRpcClient(daemonAddress) +func lsFpDaemon(ctx *cli.Context) error { + daemonAddress := ctx.String(fpdDaemonAddressFlag) + rpcClient, cleanUp, err := dc.NewFinalityProviderServiceGRpcClient(daemonAddress) if err != nil { return err } defer cleanUp() - resp, err := rpcClient.QueryValidatorList(context.Background()) + resp, err := rpcClient.QueryFinalityProviderList(context.Background()) if err != nil { return err } @@ -222,39 +222,39 @@ func lsValDaemon(ctx *cli.Context) error { return nil } -var valInfoDaemonCmd = cli.Command{ - Name: "validator-info", - ShortName: "vi", - Usage: "Show the information of the validator.", +var fpInfoDaemonCmd = cli.Command{ + Name: "finality-provider-info", + ShortName: "fpi", + Usage: "Show the information of the finality provider.", Flags: []cli.Flag{ cli.StringFlag{ - Name: valdDaemonAddressFlag, - Usage: "Full address of the validator daemon in format tcp://:", - Value: defaultValdDaemonAddress, + Name: fpdDaemonAddressFlag, + Usage: "Full address of the finality provider daemon in format tcp://:", + Value: defaultFpdDaemonAddress, }, cli.StringFlag{ - Name: valBTCPkFlag, + Name: fpBTCPkFlag, Usage: "The hex string of the BTC public key", Required: true, }, }, - Action: valInfoDaemon, + Action: fpInfoDaemon, } -func valInfoDaemon(ctx *cli.Context) error { - daemonAddress := ctx.String(valdDaemonAddressFlag) - rpcClient, cleanUp, err := dc.NewValidatorServiceGRpcClient(daemonAddress) +func fpInfoDaemon(ctx *cli.Context) error { + daemonAddress := ctx.String(fpdDaemonAddressFlag) + rpcClient, cleanUp, err := dc.NewFinalityProviderServiceGRpcClient(daemonAddress) if err != nil { return err } defer cleanUp() - valPk, err := bbntypes.NewBIP340PubKeyFromHex(ctx.String(valBTCPkFlag)) + fpPk, err := bbntypes.NewBIP340PubKeyFromHex(ctx.String(fpBTCPkFlag)) if err != nil { return err } - resp, err := rpcClient.QueryValidatorInfo(context.Background(), valPk) + resp, err := rpcClient.QueryFinalityProviderInfo(context.Background(), fpPk) if err != nil { return err } @@ -264,20 +264,20 @@ func valInfoDaemon(ctx *cli.Context) error { return nil } -var registerValDaemonCmd = cli.Command{ - Name: "register-validator", - ShortName: "rv", - Usage: "Register a created Bitcoin validator to Babylon.", - UsageText: fmt.Sprintf("register-validator --%s [key-name]", keyNameFlag), +var registerFpDaemonCmd = cli.Command{ + Name: "register-finality-provider", + ShortName: "rfp", + Usage: "Register a created finality provider to Babylon.", + UsageText: fmt.Sprintf("register-finality-provider --%s [key-name]", keyNameFlag), Flags: []cli.Flag{ cli.StringFlag{ - Name: valdDaemonAddressFlag, - Usage: "Full address of the validator daemon in format tcp://:", - Value: defaultValdDaemonAddress, + Name: fpdDaemonAddressFlag, + Usage: "Full address of the finality provider daemon in format tcp://:", + Value: defaultFpdDaemonAddress, }, cli.StringFlag{ - Name: valBTCPkFlag, - Usage: "The hex string of the validator BTC public key", + Name: fpBTCPkFlag, + Usage: "The hex string of the finality provider BTC public key", Required: true, }, cli.StringFlag{ @@ -286,24 +286,24 @@ var registerValDaemonCmd = cli.Command{ Value: defaultPassphrase, }, }, - Action: registerVal, + Action: registerFp, } -func registerVal(ctx *cli.Context) error { - valPkStr := ctx.String(valBTCPkFlag) - valPk, err := bbntypes.NewBIP340PubKeyFromHex(valPkStr) +func registerFp(ctx *cli.Context) error { + fpPkStr := ctx.String(fpBTCPkFlag) + fpPk, err := bbntypes.NewBIP340PubKeyFromHex(fpPkStr) if err != nil { return fmt.Errorf("invalid BTC public key: %w", err) } - daemonAddress := ctx.String(valdDaemonAddressFlag) - rpcClient, cleanUp, err := dc.NewValidatorServiceGRpcClient(daemonAddress) + daemonAddress := ctx.String(fpdDaemonAddressFlag) + rpcClient, cleanUp, err := dc.NewFinalityProviderServiceGRpcClient(daemonAddress) if err != nil { return err } defer cleanUp() - res, err := rpcClient.RegisterValidator(context.Background(), valPk, ctx.String(passphraseFlag)) + res, err := rpcClient.RegisterFinalityProvider(context.Background(), fpPk, ctx.String(passphraseFlag)) if err != nil { return err } @@ -319,15 +319,15 @@ var addFinalitySigDaemonCmd = cli.Command{ Name: "add-finality-sig", ShortName: "afs", Usage: "Send a finality signature to the consumer chain. This command should only be used for presentation/testing purposes", - UsageText: fmt.Sprintf("add-finality-sig --%s [btc_pk_hex]", valBTCPkFlag), + UsageText: fmt.Sprintf("add-finality-sig --%s [btc_pk_hex]", fpBTCPkFlag), Flags: []cli.Flag{ cli.StringFlag{ - Name: valdDaemonAddressFlag, - Usage: "Full address of the validator daemon in format tcp://:", - Value: defaultValdDaemonAddress, + Name: fpdDaemonAddressFlag, + Usage: "Full address of the finality provider daemon in format tcp://:", + Value: defaultFpdDaemonAddress, }, cli.StringFlag{ - Name: valBTCPkFlag, + Name: fpBTCPkFlag, Usage: "The hex string of the BTC public key", Required: true, }, @@ -346,14 +346,14 @@ var addFinalitySigDaemonCmd = cli.Command{ } func addFinalitySig(ctx *cli.Context) error { - daemonAddress := ctx.String(valdDaemonAddressFlag) - rpcClient, cleanUp, err := dc.NewValidatorServiceGRpcClient(daemonAddress) + daemonAddress := ctx.String(fpdDaemonAddressFlag) + rpcClient, cleanUp, err := dc.NewFinalityProviderServiceGRpcClient(daemonAddress) if err != nil { return err } defer cleanUp() - valPk, err := bbntypes.NewBIP340PubKeyFromHex(ctx.String(valBTCPkFlag)) + fpPk, err := bbntypes.NewBIP340PubKeyFromHex(ctx.String(fpBTCPkFlag)) if err != nil { return err } @@ -364,7 +364,7 @@ func addFinalitySig(ctx *cli.Context) error { } res, err := rpcClient.AddFinalitySignature( - context.Background(), valPk.MarshalHex(), ctx.Uint64(blockHeightFlag), lch) + context.Background(), fpPk.MarshalHex(), ctx.Uint64(blockHeightFlag), lch) if err != nil { return err } diff --git a/validator/cmd/valcli/main.go b/finality-provider/cmd/fpcli/main.go similarity index 75% rename from validator/cmd/valcli/main.go rename to finality-provider/cmd/fpcli/main.go index e101e79a..906f1d96 100644 --- a/validator/cmd/valcli/main.go +++ b/finality-provider/cmd/fpcli/main.go @@ -3,14 +3,14 @@ package main import ( "encoding/json" "fmt" - "github.com/babylonchain/btc-validator/config" + "github.com/babylonchain/finality-provider/config" "os" "github.com/urfave/cli" ) func fatal(err error) { - fmt.Fprintf(os.Stderr, "[btc-validator] %v\n", err) + fmt.Fprintf(os.Stderr, "[fpd] %v\n", err) os.Exit(1) } @@ -31,8 +31,8 @@ const ( func main() { app := cli.NewApp() - app.Name = "valcli" - app.Usage = "Control plane for the Bitcoin Validator Daemon (vald)." + app.Name = "fpcli" + app.Usage = "Control plane for the Finality Provider Daemon (fpd)." app.Flags = []cli.Flag{ cli.StringFlag{ Name: dbTypeFlag, @@ -48,10 +48,10 @@ func main() { app.Commands = append(app.Commands, getDaemonInfoCmd, - createValDaemonCmd, - lsValDaemonCmd, - valInfoDaemonCmd, - registerValDaemonCmd, + createFpDaemonCmd, + lsFpDaemonCmd, + fpInfoDaemonCmd, + registerFpDaemonCmd, addFinalitySigDaemonCmd, ) diff --git a/validator/cmd/vald/flags.go b/finality-provider/cmd/fpd/flags.go similarity index 76% rename from validator/cmd/vald/flags.go rename to finality-provider/cmd/fpd/flags.go index e34735b4..687cfa4e 100644 --- a/validator/cmd/vald/flags.go +++ b/finality-provider/cmd/fpd/flags.go @@ -4,7 +4,7 @@ const ( homeFlag = "home" forceFlag = "force" passphraseFlag = "passphrase" - valPkFlag = "validator-pk" + fpPkFlag = "finality-provider-pk" defaultPassphrase = "" ) diff --git a/validator/cmd/vald/init.go b/finality-provider/cmd/fpd/init.go similarity index 69% rename from validator/cmd/vald/init.go rename to finality-provider/cmd/fpd/init.go index ec8e08c6..99d3cc0b 100644 --- a/validator/cmd/vald/init.go +++ b/finality-provider/cmd/fpd/init.go @@ -2,8 +2,8 @@ package main import ( "fmt" - "github.com/babylonchain/btc-validator/util" - valcfg "github.com/babylonchain/btc-validator/validator/config" + fpcfg "github.com/babylonchain/finality-provider/finality-provider/config" + "github.com/babylonchain/finality-provider/util" "github.com/jessevdk/go-flags" "github.com/urfave/cli" "path/filepath" @@ -11,12 +11,12 @@ import ( var initCommand = cli.Command{ Name: "init", - Usage: "Initialize a validator home directory", + Usage: "Initialize a finality-provider home directory", Flags: []cli.Flag{ cli.StringFlag{ Name: homeFlag, Usage: "Path to where the home directory will be initialized", - Value: valcfg.DefaultValdDir, + Value: fpcfg.DefaultFpdDir, }, cli.BoolFlag{ Name: forceFlag, @@ -44,13 +44,13 @@ func initHome(c *cli.Context) error { return err } // Create log directory - logDir := valcfg.LogDir(homePath) + logDir := fpcfg.LogDir(homePath) if err := util.MakeDirectory(logDir); err != nil { return err } - defaultConfig := valcfg.DefaultConfigWithHome(homePath) + defaultConfig := fpcfg.DefaultConfigWithHome(homePath) fileParser := flags.NewParser(&defaultConfig, flags.Default) - return flags.NewIniParser(fileParser).WriteFile(valcfg.ConfigFile(homePath), flags.IniIncludeComments|flags.IniIncludeDefaults) + return flags.NewIniParser(fileParser).WriteFile(fpcfg.ConfigFile(homePath), flags.IniIncludeComments|flags.IniIncludeDefaults) } diff --git a/validator/cmd/vald/main.go b/finality-provider/cmd/fpd/main.go similarity index 67% rename from validator/cmd/vald/main.go rename to finality-provider/cmd/fpd/main.go index b2923474..569b0521 100644 --- a/validator/cmd/vald/main.go +++ b/finality-provider/cmd/fpd/main.go @@ -8,14 +8,14 @@ import ( ) func fatal(err error) { - fmt.Fprintf(os.Stderr, "[btc-validator] %v\n", err) + fmt.Fprintf(os.Stderr, "[btc-finality-provider] %v\n", err) os.Exit(1) } func main() { app := cli.NewApp() - app.Name = "vald" - app.Usage = "BTC Validator Daemon (vald)." + app.Name = "fpd" + app.Usage = "Finality Provider Daemon (fpd)." app.Commands = append(app.Commands, startCommand, initCommand) if err := app.Run(os.Args); err != nil { diff --git a/finality-provider/cmd/fpd/start.go b/finality-provider/cmd/fpd/start.go new file mode 100644 index 00000000..dbc46524 --- /dev/null +++ b/finality-provider/cmd/fpd/start.go @@ -0,0 +1,89 @@ +package main + +import ( + "fmt" + "github.com/babylonchain/babylon/types" + "github.com/babylonchain/finality-provider/log" + "github.com/babylonchain/finality-provider/util" + "github.com/lightningnetwork/lnd/signal" + "github.com/urfave/cli" + "path/filepath" + + fpcfg "github.com/babylonchain/finality-provider/finality-provider/config" + "github.com/babylonchain/finality-provider/finality-provider/service" +) + +var startCommand = cli.Command{ + Name: "start", + Usage: "fpd start", + Description: "Start the finality-provider app. Note that eotsd should be started beforehand", + Flags: []cli.Flag{ + cli.StringFlag{ + Name: passphraseFlag, + Usage: "The pass phrase used to decrypt the private key", + Value: defaultPassphrase, + }, + cli.StringFlag{ + Name: homeFlag, + Usage: "The path to the finality-provider home directory", + Value: fpcfg.DefaultFpdDir, + }, + cli.StringFlag{ + Name: fpPkFlag, + Usage: "The public key of the finality-provider to start", + }, + }, + Action: start, +} + +func start(ctx *cli.Context) error { + homePath, err := filepath.Abs(ctx.String(homeFlag)) + if err != nil { + return err + } + homePath = util.CleanAndExpandPath(homePath) + passphrase := ctx.String(passphraseFlag) + fpPkStr := ctx.String(fpPkFlag) + + cfg, err := fpcfg.LoadConfig(homePath) + if err != nil { + return fmt.Errorf("failed to load configuration: %w", err) + } + + logger, err := log.NewRootLoggerWithFile(fpcfg.LogFile(homePath), cfg.LogLevel) + if err != nil { + return fmt.Errorf("failed to initialize the logger") + } + + fpApp, err := service.NewFinalityProviderAppFromConfig(homePath, cfg, logger) + if err != nil { + return fmt.Errorf("failed to create finality-provider app: %v", err) + } + + // only start the app without starting any finality-provider instance + // as there might be no finality-provider registered yet + if err := fpApp.Start(); err != nil { + return fmt.Errorf("failed to start the finality-provider app: %w", err) + } + + if fpPkStr != "" { + // start the finality-provider instance with the given public key + fpPk, err := types.NewBIP340PubKeyFromHex(fpPkStr) + if err != nil { + return fmt.Errorf("invalid finality-provider public key %s: %w", fpPkStr, err) + } + if err := fpApp.StartHandlingFinalityProvider(fpPk, passphrase); err != nil { + return fmt.Errorf("failed to start the finality-provider instance %s: %w", fpPkStr, err) + } + } + + // Hook interceptor for os signals. + shutdownInterceptor, err := signal.Intercept() + if err != nil { + return err + } + + fpServer := service.NewFinalityProviderServer(cfg, logger, fpApp, shutdownInterceptor) + + return fpServer.RunUntilShutdown() +} diff --git a/validator/config/config.go b/finality-provider/config/config.go similarity index 88% rename from validator/config/config.go rename to finality-provider/config/config.go index 8d695be1..b666703e 100644 --- a/validator/config/config.go +++ b/finality-provider/config/config.go @@ -1,4 +1,4 @@ -package valcfg +package fpcfg import ( "fmt" @@ -7,25 +7,25 @@ import ( "strconv" "time" - "github.com/babylonchain/btc-validator/util" + "github.com/babylonchain/finality-provider/util" "github.com/btcsuite/btcd/btcutil" "github.com/btcsuite/btcd/chaincfg" "github.com/jessevdk/go-flags" - "github.com/babylonchain/btc-validator/config" + "github.com/babylonchain/finality-provider/config" - eotscfg "github.com/babylonchain/btc-validator/eotsmanager/config" + eotscfg "github.com/babylonchain/finality-provider/eotsmanager/config" ) const ( defaultChainName = "babylon" defaultLogLevel = "info" defaultLogDirname = "logs" - defaultLogFilename = "vald.log" - defaultValidatorKeyName = "btc-validator" + defaultLogFilename = "fpd.log" + defaultFinalityProviderKeyName = "finality-provider" DefaultRPCPort = 15812 - defaultConfigFileName = "vald.conf" + defaultConfigFileName = "fpd.conf" defaultNumPubRand = 100 defaultNumPubRandMax = 100 defaultMinRandHeightGap = 10 @@ -39,22 +39,22 @@ const ( defaultMaxSubmissionRetries = 20 defaultBitcoinNetwork = "simnet" defaultDataDirname = "data" - defaultDBPath = "bbolt-vald.db" - defaultMaxNumValidators = 3 + defaultDBPath = "bbolt-fpd.db" + defaultMaxNumFinalityProviders = 3 ) var ( // C:\Users\\AppData\Local\ on Windows - // ~/.vald on Linux - // ~/Library/Application Support/Vald on MacOS - DefaultValdDir = btcutil.AppDataDir("vald", false) + // ~/.fpd on Linux + // ~/Library/Application Support/Fpd on MacOS + DefaultFpdDir = btcutil.AppDataDir("fpd", false) defaultBTCNetParams = chaincfg.SimNetParams defaultEOTSManagerAddress = "127.0.0.1:" + strconv.Itoa(eotscfg.DefaultRPCPort) defaultRpcListener = "localhost:" + strconv.Itoa(DefaultRPCPort) ) -// Config is the main config for the vald cli command +// Config is the main config for the fpd cli command type Config struct { LogLevel string `long:"loglevel" description:"Logging level for all subsystems" choice:"trace" choice:"debug" choice:"info" choice:"warn" choice:"error" choice:"fatal"` // ChainName and ChainID (if any) of the chain config identify a consumer chain @@ -62,7 +62,7 @@ type Config struct { NumPubRand uint64 `long:"numPubRand" description:"The number of Schnorr public randomness for each commitment"` NumPubRandMax uint64 `long:"numpubrandmax" description:"The upper bound of the number of Schnorr public randomness for each commitment"` MinRandHeightGap uint64 `long:"minrandheightgap" description:"The minimum gap between the last committed rand height and the current Babylon block height"` - StatusUpdateInterval time.Duration `long:"statusupdateinterval" description:"The interval between each update of validator status"` + StatusUpdateInterval time.Duration `long:"statusupdateinterval" description:"The interval between each update of finality-provider status"` RandomnessCommitInterval time.Duration `long:"randomnesscommitinterval" description:"The interval between each attempt to commit public randomness"` SubmissionRetryInterval time.Duration `long:"submissionretryinterval" description:"The interval between each attempt to submit finality signature or public randomness after a failure"` UnbondingSigSubmissionInterval time.Duration `long:"unbondingsigsubmissioninterval" description:"The interval between each attempt to check and submit unbonding signature"` @@ -71,7 +71,7 @@ type Config struct { FastSyncLimit uint64 `long:"fastsynclimit" description:"The maximum number of blocks to catch up for each fast sync"` FastSyncGap uint64 `long:"fastsyncgap" description:"The block gap that will trigger the fast sync"` EOTSManagerAddress string `long:"eotsmanageraddress" description:"The address of the remote EOTS manager; Empty if the EOTS manager is running locally"` - MaxNumValidators uint32 `long:"maxnumvalidators" description:"The maximum number of validator instances running concurrently within the daemon"` + MaxNumFinalityProviders uint32 `long:"maxnumfinalityproviders" description:"The maximum number of finality-provider instances running concurrently within the daemon"` BitcoinNetwork string `long:"bitcoinnetwork" description:"Bitcoin network to run on" choise:"mainnet" choice:"regtest" choice:"testnet" choice:"simnet" choice:"signet"` @@ -88,7 +88,7 @@ type Config struct { func DefaultConfigWithHome(homePath string) Config { bbnCfg := config.DefaultBBNConfig() - bbnCfg.Key = defaultValidatorKeyName + bbnCfg.Key = defaultFinalityProviderKeyName bbnCfg.KeyDirectory = homePath dbCfg := config.DefaultDatabaseConfig() pollerCfg := DefaultChainPollerConfig() @@ -113,7 +113,7 @@ func DefaultConfigWithHome(homePath string) Config { BTCNetParams: defaultBTCNetParams, EOTSManagerAddress: defaultEOTSManagerAddress, RpcListener: defaultRpcListener, - MaxNumValidators: defaultMaxNumValidators, + MaxNumFinalityProviders: defaultMaxNumFinalityProviders, } if err := cfg.Validate(); err != nil { @@ -124,7 +124,7 @@ func DefaultConfigWithHome(homePath string) Config { } func DefaultConfig() Config { - return DefaultConfigWithHome(DefaultValdDir) + return DefaultConfigWithHome(DefaultFpdDir) } func ConfigFile(homePath string) string { diff --git a/validator/config/poller.go b/finality-provider/config/poller.go similarity index 98% rename from validator/config/poller.go rename to finality-provider/config/poller.go index b0d29ea8..1ee1fee1 100644 --- a/validator/config/poller.go +++ b/finality-provider/config/poller.go @@ -1,4 +1,4 @@ -package valcfg +package fpcfg import "time" diff --git a/validator/proto/.clang-format b/finality-provider/proto/.clang-format similarity index 100% rename from validator/proto/.clang-format rename to finality-provider/proto/.clang-format diff --git a/validator/proto/buf.gen.yaml b/finality-provider/proto/buf.gen.yaml similarity index 100% rename from validator/proto/buf.gen.yaml rename to finality-provider/proto/buf.gen.yaml diff --git a/validator/proto/buf.lock b/finality-provider/proto/buf.lock similarity index 100% rename from validator/proto/buf.lock rename to finality-provider/proto/buf.lock diff --git a/validator/proto/buf.yaml b/finality-provider/proto/buf.yaml similarity index 92% rename from validator/proto/buf.yaml rename to finality-provider/proto/buf.yaml index 4b16d8ad..0e7c3e91 100644 --- a/validator/proto/buf.yaml +++ b/finality-provider/proto/buf.yaml @@ -1,5 +1,5 @@ version: v1 -name: buf.build/babylonchain/btc-validator +name: buf.build/babylonchain/btc-finality-provider deps: - buf.build/cosmos/cosmos-sdk:v0.47.0 - buf.build/cosmos/cosmos-proto:1935555c206d4afb9e94615dfd0fad31 diff --git a/finality-provider/proto/finality_providers.go b/finality-provider/proto/finality_providers.go new file mode 100644 index 00000000..d43dcb46 --- /dev/null +++ b/finality-provider/proto/finality_providers.go @@ -0,0 +1,45 @@ +package proto + +import ( + "encoding/hex" + "fmt" + + bbn "github.com/babylonchain/babylon/types" + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" +) + +func (sfp *StoreFinalityProvider) GetBabylonPK() *secp256k1.PubKey { + return &secp256k1.PubKey{ + Key: sfp.BabylonPk, + } +} + +func (sfp *StoreFinalityProvider) GetBabylonPkHexString() string { + return hex.EncodeToString(sfp.BabylonPk) +} + +func (sfp *StoreFinalityProvider) MustGetBTCPK() *btcec.PublicKey { + btcPubKey, err := schnorr.ParsePubKey(sfp.BtcPk) + if err != nil { + panic(fmt.Errorf("failed to parse BTC PK: %w", err)) + } + return btcPubKey +} + +func (sfp *StoreFinalityProvider) MustGetBIP340BTCPK() *bbn.BIP340PubKey { + btcPK := sfp.MustGetBTCPK() + return bbn.NewBIP340PubKeyFromBTCPK(btcPK) +} + +func NewFinalityProviderInfo(sfp *StoreFinalityProvider) *FinalityProviderInfo { + return &FinalityProviderInfo{ + BabylonPkHex: sfp.GetBabylonPkHexString(), + BtcPkHex: sfp.MustGetBIP340BTCPK().MarshalHex(), + Description: sfp.Description, + LastVotedHeight: sfp.LastVotedHeight, + LastCommittedHeight: sfp.LastCommittedHeight, + Status: sfp.Status, + } +} diff --git a/finality-provider/proto/finality_providers.pb.go b/finality-provider/proto/finality_providers.pb.go new file mode 100644 index 00000000..a0e64a01 --- /dev/null +++ b/finality-provider/proto/finality_providers.pb.go @@ -0,0 +1,1574 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.28.0 +// protoc (unknown) +// source: finality_providers.proto + +package proto + +import ( + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/cosmos-sdk/x/staking/types" + _ "github.com/cosmos/gogoproto/gogoproto" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// FinalityProviderStatus is the status of a finality provider +// a FinalityProvider object has 4 states: +// - Created - created and managed by finality provider client, not registered to +// babylon yet +// - Registered - created and registered to Babylon, but not voting yet (No +// delegated stake) +// - Active - created and registered to Babylon with stake to vote +// - Inactive - created and registered to Babylon with no stake to vote. +// Finality Provider was already active. +// Valid State Transactions: +// - Created -> Registered +// - Registered -> Active +// - Active -> Inactive +// - Inactive -> Active +type FinalityProviderStatus int32 + +const ( + // CREATED defines a finality provider that is awaiting registration + FinalityProviderStatus_CREATED FinalityProviderStatus = 0 + // REGISTERED defines a finality provider that has been registered + // to Babylon but has no delegated stake + FinalityProviderStatus_REGISTERED FinalityProviderStatus = 1 + // ACTIVE defines a finality provider that is delegated to vote + FinalityProviderStatus_ACTIVE FinalityProviderStatus = 2 + // INACTIVE defines a finality provider whose delegations are reduced to zero but not slashed + FinalityProviderStatus_INACTIVE FinalityProviderStatus = 3 + // SLASHED defines a finality provider that has been slashed + FinalityProviderStatus_SLASHED FinalityProviderStatus = 4 +) + +// Enum value maps for FinalityProviderStatus. +var ( + FinalityProviderStatus_name = map[int32]string{ + 0: "CREATED", + 1: "REGISTERED", + 2: "ACTIVE", + 3: "INACTIVE", + 4: "SLASHED", + } + FinalityProviderStatus_value = map[string]int32{ + "CREATED": 0, + "REGISTERED": 1, + "ACTIVE": 2, + "INACTIVE": 3, + "SLASHED": 4, + } +) + +func (x FinalityProviderStatus) Enum() *FinalityProviderStatus { + p := new(FinalityProviderStatus) + *p = x + return p +} + +func (x FinalityProviderStatus) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (FinalityProviderStatus) Descriptor() protoreflect.EnumDescriptor { + return file_finality_providers_proto_enumTypes[0].Descriptor() +} + +func (FinalityProviderStatus) Type() protoreflect.EnumType { + return &file_finality_providers_proto_enumTypes[0] +} + +func (x FinalityProviderStatus) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use FinalityProviderStatus.Descriptor instead. +func (FinalityProviderStatus) EnumDescriptor() ([]byte, []int) { + return file_finality_providers_proto_rawDescGZIP(), []int{0} +} + +type GetInfoRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields +} + +func (x *GetInfoRequest) Reset() { + *x = GetInfoRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_finality_providers_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GetInfoRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetInfoRequest) ProtoMessage() {} + +func (x *GetInfoRequest) ProtoReflect() protoreflect.Message { + mi := &file_finality_providers_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetInfoRequest.ProtoReflect.Descriptor instead. +func (*GetInfoRequest) Descriptor() ([]byte, []int) { + return file_finality_providers_proto_rawDescGZIP(), []int{0} +} + +type GetInfoResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Version string `protobuf:"bytes,1,opt,name=version,proto3" json:"version,omitempty"` +} + +func (x *GetInfoResponse) Reset() { + *x = GetInfoResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_finality_providers_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GetInfoResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetInfoResponse) ProtoMessage() {} + +func (x *GetInfoResponse) ProtoReflect() protoreflect.Message { + mi := &file_finality_providers_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetInfoResponse.ProtoReflect.Descriptor instead. +func (*GetInfoResponse) Descriptor() ([]byte, []int) { + return file_finality_providers_proto_rawDescGZIP(), []int{1} +} + +func (x *GetInfoResponse) GetVersion() string { + if x != nil { + return x.Version + } + return "" +} + +type CreateFinalityProviderRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // key_name is the identifier key in keyring + KeyName string `protobuf:"bytes,1,opt,name=key_name,json=keyName,proto3" json:"key_name,omitempty"` + // passphrase is used to encrypt the keys + Passphrase string `protobuf:"bytes,2,opt,name=passphrase,proto3" json:"passphrase,omitempty"` + // hd_path is the hd path for private key derivation + HdPath string `protobuf:"bytes,3,opt,name=hd_path,json=hdPath,proto3" json:"hd_path,omitempty"` + // chain_id is the identifier of the consumer chain that the finality provider connected to + ChainId string `protobuf:"bytes,4,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + // description defines the description terms for the finality provider + Description []byte `protobuf:"bytes,5,opt,name=description,proto3" json:"description,omitempty"` + // commission defines the commission rate for the finality provider + Commission string `protobuf:"bytes,6,opt,name=commission,proto3" json:"commission,omitempty"` +} + +func (x *CreateFinalityProviderRequest) Reset() { + *x = CreateFinalityProviderRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_finality_providers_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *CreateFinalityProviderRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CreateFinalityProviderRequest) ProtoMessage() {} + +func (x *CreateFinalityProviderRequest) ProtoReflect() protoreflect.Message { + mi := &file_finality_providers_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CreateFinalityProviderRequest.ProtoReflect.Descriptor instead. +func (*CreateFinalityProviderRequest) Descriptor() ([]byte, []int) { + return file_finality_providers_proto_rawDescGZIP(), []int{2} +} + +func (x *CreateFinalityProviderRequest) GetKeyName() string { + if x != nil { + return x.KeyName + } + return "" +} + +func (x *CreateFinalityProviderRequest) GetPassphrase() string { + if x != nil { + return x.Passphrase + } + return "" +} + +func (x *CreateFinalityProviderRequest) GetHdPath() string { + if x != nil { + return x.HdPath + } + return "" +} + +func (x *CreateFinalityProviderRequest) GetChainId() string { + if x != nil { + return x.ChainId + } + return "" +} + +func (x *CreateFinalityProviderRequest) GetDescription() []byte { + if x != nil { + return x.Description + } + return nil +} + +func (x *CreateFinalityProviderRequest) GetCommission() string { + if x != nil { + return x.Commission + } + return "" +} + +type CreateFinalityProviderResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // btc_pk is the hex string of BTC secp256k1 public key of the finality provider encoded in BIP-340 spec + BtcPk string `protobuf:"bytes,1,opt,name=btc_pk,json=btcPk,proto3" json:"btc_pk,omitempty"` +} + +func (x *CreateFinalityProviderResponse) Reset() { + *x = CreateFinalityProviderResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_finality_providers_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *CreateFinalityProviderResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CreateFinalityProviderResponse) ProtoMessage() {} + +func (x *CreateFinalityProviderResponse) ProtoReflect() protoreflect.Message { + mi := &file_finality_providers_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CreateFinalityProviderResponse.ProtoReflect.Descriptor instead. +func (*CreateFinalityProviderResponse) Descriptor() ([]byte, []int) { + return file_finality_providers_proto_rawDescGZIP(), []int{3} +} + +func (x *CreateFinalityProviderResponse) GetBtcPk() string { + if x != nil { + return x.BtcPk + } + return "" +} + +type RegisterFinalityProviderRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // btc_pk is hex string of the BTC secp256k1 public key of the finality provider encoded in BIP-340 spec + BtcPk string `protobuf:"bytes,1,opt,name=btc_pk,json=btcPk,proto3" json:"btc_pk,omitempty"` + // passphrase is used to encrypt the keys + Passphrase string `protobuf:"bytes,2,opt,name=passphrase,proto3" json:"passphrase,omitempty"` +} + +func (x *RegisterFinalityProviderRequest) Reset() { + *x = RegisterFinalityProviderRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_finality_providers_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *RegisterFinalityProviderRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RegisterFinalityProviderRequest) ProtoMessage() {} + +func (x *RegisterFinalityProviderRequest) ProtoReflect() protoreflect.Message { + mi := &file_finality_providers_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RegisterFinalityProviderRequest.ProtoReflect.Descriptor instead. +func (*RegisterFinalityProviderRequest) Descriptor() ([]byte, []int) { + return file_finality_providers_proto_rawDescGZIP(), []int{4} +} + +func (x *RegisterFinalityProviderRequest) GetBtcPk() string { + if x != nil { + return x.BtcPk + } + return "" +} + +func (x *RegisterFinalityProviderRequest) GetPassphrase() string { + if x != nil { + return x.Passphrase + } + return "" +} + +type RegisterFinalityProviderResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // hash of the successful Babylon registration transaction + TxHash string `protobuf:"bytes,1,opt,name=tx_hash,json=txHash,proto3" json:"tx_hash,omitempty"` +} + +func (x *RegisterFinalityProviderResponse) Reset() { + *x = RegisterFinalityProviderResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_finality_providers_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *RegisterFinalityProviderResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RegisterFinalityProviderResponse) ProtoMessage() {} + +func (x *RegisterFinalityProviderResponse) ProtoReflect() protoreflect.Message { + mi := &file_finality_providers_proto_msgTypes[5] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RegisterFinalityProviderResponse.ProtoReflect.Descriptor instead. +func (*RegisterFinalityProviderResponse) Descriptor() ([]byte, []int) { + return file_finality_providers_proto_rawDescGZIP(), []int{5} +} + +func (x *RegisterFinalityProviderResponse) GetTxHash() string { + if x != nil { + return x.TxHash + } + return "" +} + +type AddFinalitySignatureRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // btc_pk is hex string of the BTC secp256k1 public key of the finality provider encoded in BIP-340 spec + BtcPk string `protobuf:"bytes,1,opt,name=btc_pk,json=btcPk,proto3" json:"btc_pk,omitempty"` + // height is the height of the Babylon block + Height uint64 `protobuf:"varint,2,opt,name=height,proto3" json:"height,omitempty"` + // app_hash is the AppHash of the Babylon block + AppHash []byte `protobuf:"bytes,3,opt,name=app_hash,json=appHash,proto3" json:"app_hash,omitempty"` +} + +func (x *AddFinalitySignatureRequest) Reset() { + *x = AddFinalitySignatureRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_finality_providers_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *AddFinalitySignatureRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddFinalitySignatureRequest) ProtoMessage() {} + +func (x *AddFinalitySignatureRequest) ProtoReflect() protoreflect.Message { + mi := &file_finality_providers_proto_msgTypes[6] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddFinalitySignatureRequest.ProtoReflect.Descriptor instead. +func (*AddFinalitySignatureRequest) Descriptor() ([]byte, []int) { + return file_finality_providers_proto_rawDescGZIP(), []int{6} +} + +func (x *AddFinalitySignatureRequest) GetBtcPk() string { + if x != nil { + return x.BtcPk + } + return "" +} + +func (x *AddFinalitySignatureRequest) GetHeight() uint64 { + if x != nil { + return x.Height + } + return 0 +} + +func (x *AddFinalitySignatureRequest) GetAppHash() []byte { + if x != nil { + return x.AppHash + } + return nil +} + +type AddFinalitySignatureResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // hash of the successful Babylon finality signature submission transaction + TxHash string `protobuf:"bytes,1,opt,name=tx_hash,json=txHash,proto3" json:"tx_hash,omitempty"` + // the hex string of the extracted Bitcoin secp256k1 private key + ExtractedSkHex string `protobuf:"bytes,2,opt,name=extracted_sk_hex,json=extractedSkHex,proto3" json:"extracted_sk_hex,omitempty"` + // the hex string of the local Bitcoin secp256k1 private key + LocalSkHex string `protobuf:"bytes,3,opt,name=local_sk_hex,json=localSkHex,proto3" json:"local_sk_hex,omitempty"` +} + +func (x *AddFinalitySignatureResponse) Reset() { + *x = AddFinalitySignatureResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_finality_providers_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *AddFinalitySignatureResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddFinalitySignatureResponse) ProtoMessage() {} + +func (x *AddFinalitySignatureResponse) ProtoReflect() protoreflect.Message { + mi := &file_finality_providers_proto_msgTypes[7] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddFinalitySignatureResponse.ProtoReflect.Descriptor instead. +func (*AddFinalitySignatureResponse) Descriptor() ([]byte, []int) { + return file_finality_providers_proto_rawDescGZIP(), []int{7} +} + +func (x *AddFinalitySignatureResponse) GetTxHash() string { + if x != nil { + return x.TxHash + } + return "" +} + +func (x *AddFinalitySignatureResponse) GetExtractedSkHex() string { + if x != nil { + return x.ExtractedSkHex + } + return "" +} + +func (x *AddFinalitySignatureResponse) GetLocalSkHex() string { + if x != nil { + return x.LocalSkHex + } + return "" +} + +type QueryFinalityProviderRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // btc_pk is hex string of the BTC secp256k1 public key of the finality provider encoded in BIP-340 spec + BtcPk string `protobuf:"bytes,1,opt,name=btc_pk,json=btcPk,proto3" json:"btc_pk,omitempty"` +} + +func (x *QueryFinalityProviderRequest) Reset() { + *x = QueryFinalityProviderRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_finality_providers_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *QueryFinalityProviderRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*QueryFinalityProviderRequest) ProtoMessage() {} + +func (x *QueryFinalityProviderRequest) ProtoReflect() protoreflect.Message { + mi := &file_finality_providers_proto_msgTypes[8] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use QueryFinalityProviderRequest.ProtoReflect.Descriptor instead. +func (*QueryFinalityProviderRequest) Descriptor() ([]byte, []int) { + return file_finality_providers_proto_rawDescGZIP(), []int{8} +} + +func (x *QueryFinalityProviderRequest) GetBtcPk() string { + if x != nil { + return x.BtcPk + } + return "" +} + +type QueryFinalityProviderResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + FinalityProvider *FinalityProviderInfo `protobuf:"bytes,1,opt,name=finality_provider,json=finalityProvider,proto3" json:"finality_provider,omitempty"` +} + +func (x *QueryFinalityProviderResponse) Reset() { + *x = QueryFinalityProviderResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_finality_providers_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *QueryFinalityProviderResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*QueryFinalityProviderResponse) ProtoMessage() {} + +func (x *QueryFinalityProviderResponse) ProtoReflect() protoreflect.Message { + mi := &file_finality_providers_proto_msgTypes[9] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use QueryFinalityProviderResponse.ProtoReflect.Descriptor instead. +func (*QueryFinalityProviderResponse) Descriptor() ([]byte, []int) { + return file_finality_providers_proto_rawDescGZIP(), []int{9} +} + +func (x *QueryFinalityProviderResponse) GetFinalityProvider() *FinalityProviderInfo { + if x != nil { + return x.FinalityProvider + } + return nil +} + +type QueryFinalityProviderListRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields +} + +func (x *QueryFinalityProviderListRequest) Reset() { + *x = QueryFinalityProviderListRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_finality_providers_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *QueryFinalityProviderListRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*QueryFinalityProviderListRequest) ProtoMessage() {} + +func (x *QueryFinalityProviderListRequest) ProtoReflect() protoreflect.Message { + mi := &file_finality_providers_proto_msgTypes[10] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use QueryFinalityProviderListRequest.ProtoReflect.Descriptor instead. +func (*QueryFinalityProviderListRequest) Descriptor() ([]byte, []int) { + return file_finality_providers_proto_rawDescGZIP(), []int{10} +} + +type QueryFinalityProviderListResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + FinalityProviders []*FinalityProviderInfo `protobuf:"bytes,1,rep,name=finality_providers,json=finalityProviders,proto3" json:"finality_providers,omitempty"` // TODO add pagination in case the list gets large +} + +func (x *QueryFinalityProviderListResponse) Reset() { + *x = QueryFinalityProviderListResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_finality_providers_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *QueryFinalityProviderListResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*QueryFinalityProviderListResponse) ProtoMessage() {} + +func (x *QueryFinalityProviderListResponse) ProtoReflect() protoreflect.Message { + mi := &file_finality_providers_proto_msgTypes[11] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use QueryFinalityProviderListResponse.ProtoReflect.Descriptor instead. +func (*QueryFinalityProviderListResponse) Descriptor() ([]byte, []int) { + return file_finality_providers_proto_rawDescGZIP(), []int{11} +} + +func (x *QueryFinalityProviderListResponse) GetFinalityProviders() []*FinalityProviderInfo { + if x != nil { + return x.FinalityProviders + } + return nil +} + +type StoreFinalityProvider struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // babylon_pk is the Babylon secp256k1 PK of this finality provider + BabylonPk []byte `protobuf:"bytes,1,opt,name=babylon_pk,json=babylonPk,proto3" json:"babylon_pk,omitempty"` + // btc_pk is the BTC secp256k1 PK of the finality provider encoded in BIP-340 spec + BtcPk []byte `protobuf:"bytes,2,opt,name=btc_pk,json=btcPk,proto3" json:"btc_pk,omitempty"` + // description defines the description terms for the finality provider + Description []byte `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"` + // commission defines the commission rate for the finality provider + Commission string `protobuf:"bytes,4,opt,name=commission,proto3" json:"commission,omitempty"` + // pop is the proof of possession of babylon_pk and btc_pk + Pop *ProofOfPossession `protobuf:"bytes,5,opt,name=pop,proto3" json:"pop,omitempty"` + // key_name is the identifier of the keyring + KeyName string `protobuf:"bytes,6,opt,name=key_name,json=keyName,proto3" json:"key_name,omitempty"` + // chain_id is the identifier of the consumer chain that the finality provider connected to + ChainId string `protobuf:"bytes,7,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + // last_voted_height defines the height of the last voted Babylon block + LastVotedHeight uint64 `protobuf:"varint,8,opt,name=last_voted_height,json=lastVotedHeight,proto3" json:"last_voted_height,omitempty"` + // last_committed_height defines the height of the last Babylon block + // to which the finality provider committed a randomness pair + LastCommittedHeight uint64 `protobuf:"varint,9,opt,name=last_committed_height,json=lastCommittedHeight,proto3" json:"last_committed_height,omitempty"` + // last_processed_height defines the height of the last successfully processed block + // even though the vote is not cast + LastProcessedHeight uint64 `protobuf:"varint,10,opt,name=last_processed_height,json=lastProcessedHeight,proto3" json:"last_processed_height,omitempty"` + // status defines the current finality provider status + Status FinalityProviderStatus `protobuf:"varint,11,opt,name=status,proto3,enum=proto.FinalityProviderStatus" json:"status,omitempty"` +} + +func (x *StoreFinalityProvider) Reset() { + *x = StoreFinalityProvider{} + if protoimpl.UnsafeEnabled { + mi := &file_finality_providers_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *StoreFinalityProvider) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*StoreFinalityProvider) ProtoMessage() {} + +func (x *StoreFinalityProvider) ProtoReflect() protoreflect.Message { + mi := &file_finality_providers_proto_msgTypes[12] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use StoreFinalityProvider.ProtoReflect.Descriptor instead. +func (*StoreFinalityProvider) Descriptor() ([]byte, []int) { + return file_finality_providers_proto_rawDescGZIP(), []int{12} +} + +func (x *StoreFinalityProvider) GetBabylonPk() []byte { + if x != nil { + return x.BabylonPk + } + return nil +} + +func (x *StoreFinalityProvider) GetBtcPk() []byte { + if x != nil { + return x.BtcPk + } + return nil +} + +func (x *StoreFinalityProvider) GetDescription() []byte { + if x != nil { + return x.Description + } + return nil +} + +func (x *StoreFinalityProvider) GetCommission() string { + if x != nil { + return x.Commission + } + return "" +} + +func (x *StoreFinalityProvider) GetPop() *ProofOfPossession { + if x != nil { + return x.Pop + } + return nil +} + +func (x *StoreFinalityProvider) GetKeyName() string { + if x != nil { + return x.KeyName + } + return "" +} + +func (x *StoreFinalityProvider) GetChainId() string { + if x != nil { + return x.ChainId + } + return "" +} + +func (x *StoreFinalityProvider) GetLastVotedHeight() uint64 { + if x != nil { + return x.LastVotedHeight + } + return 0 +} + +func (x *StoreFinalityProvider) GetLastCommittedHeight() uint64 { + if x != nil { + return x.LastCommittedHeight + } + return 0 +} + +func (x *StoreFinalityProvider) GetLastProcessedHeight() uint64 { + if x != nil { + return x.LastProcessedHeight + } + return 0 +} + +func (x *StoreFinalityProvider) GetStatus() FinalityProviderStatus { + if x != nil { + return x.Status + } + return FinalityProviderStatus_CREATED +} + +// FinalityProviderInfo is the basic information of a finality provider mainly for external usage +type FinalityProviderInfo struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // babylon_pk_hex is the hex string of the Babylon secp256k1 PK of this finality provider + BabylonPkHex string `protobuf:"bytes,1,opt,name=babylon_pk_hex,json=babylonPkHex,proto3" json:"babylon_pk_hex,omitempty"` + // btc_pk_hex is the hex string of the BTC secp256k1 PK of the finality provider encoded in BIP-340 spec + BtcPkHex string `protobuf:"bytes,2,opt,name=btc_pk_hex,json=btcPkHex,proto3" json:"btc_pk_hex,omitempty"` + // description defines the description terms for the finality provider + Description []byte `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"` + // commission defines the commission rate for the finality provider + Commission string `protobuf:"bytes,4,opt,name=commission,proto3" json:"commission,omitempty"` + // last_voted_height defines the height of the last voted Babylon block + LastVotedHeight uint64 `protobuf:"varint,5,opt,name=last_voted_height,json=lastVotedHeight,proto3" json:"last_voted_height,omitempty"` + // last_committed_height defines the height of the last Babylon block + // to which the finality provider committed a randomness pair + LastCommittedHeight uint64 `protobuf:"varint,6,opt,name=last_committed_height,json=lastCommittedHeight,proto3" json:"last_committed_height,omitempty"` + // status defines the current finality provider status + Status FinalityProviderStatus `protobuf:"varint,7,opt,name=status,proto3,enum=proto.FinalityProviderStatus" json:"status,omitempty"` +} + +func (x *FinalityProviderInfo) Reset() { + *x = FinalityProviderInfo{} + if protoimpl.UnsafeEnabled { + mi := &file_finality_providers_proto_msgTypes[13] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *FinalityProviderInfo) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FinalityProviderInfo) ProtoMessage() {} + +func (x *FinalityProviderInfo) ProtoReflect() protoreflect.Message { + mi := &file_finality_providers_proto_msgTypes[13] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FinalityProviderInfo.ProtoReflect.Descriptor instead. +func (*FinalityProviderInfo) Descriptor() ([]byte, []int) { + return file_finality_providers_proto_rawDescGZIP(), []int{13} +} + +func (x *FinalityProviderInfo) GetBabylonPkHex() string { + if x != nil { + return x.BabylonPkHex + } + return "" +} + +func (x *FinalityProviderInfo) GetBtcPkHex() string { + if x != nil { + return x.BtcPkHex + } + return "" +} + +func (x *FinalityProviderInfo) GetDescription() []byte { + if x != nil { + return x.Description + } + return nil +} + +func (x *FinalityProviderInfo) GetCommission() string { + if x != nil { + return x.Commission + } + return "" +} + +func (x *FinalityProviderInfo) GetLastVotedHeight() uint64 { + if x != nil { + return x.LastVotedHeight + } + return 0 +} + +func (x *FinalityProviderInfo) GetLastCommittedHeight() uint64 { + if x != nil { + return x.LastCommittedHeight + } + return 0 +} + +func (x *FinalityProviderInfo) GetStatus() FinalityProviderStatus { + if x != nil { + return x.Status + } + return FinalityProviderStatus_CREATED +} + +// ProofOfPossession is the proof of possession that a Babylon secp256k1 +// secret key and a Bitcoin secp256k1 secret key are held by the same +// person +type ProofOfPossession struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // babylon_sig is the signature generated via sign(sk_babylon, pk_btc) + BabylonSig []byte `protobuf:"bytes,1,opt,name=babylon_sig,json=babylonSig,proto3" json:"babylon_sig,omitempty"` + // btc_sig is the signature generated via sign(sk_btc, babylon_sig) + // the signature follows encoding in BIP-340 spec + BtcSig []byte `protobuf:"bytes,2,opt,name=btc_sig,json=btcSig,proto3" json:"btc_sig,omitempty"` +} + +func (x *ProofOfPossession) Reset() { + *x = ProofOfPossession{} + if protoimpl.UnsafeEnabled { + mi := &file_finality_providers_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ProofOfPossession) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ProofOfPossession) ProtoMessage() {} + +func (x *ProofOfPossession) ProtoReflect() protoreflect.Message { + mi := &file_finality_providers_proto_msgTypes[14] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ProofOfPossession.ProtoReflect.Descriptor instead. +func (*ProofOfPossession) Descriptor() ([]byte, []int) { + return file_finality_providers_proto_rawDescGZIP(), []int{14} +} + +func (x *ProofOfPossession) GetBabylonSig() []byte { + if x != nil { + return x.BabylonSig + } + return nil +} + +func (x *ProofOfPossession) GetBtcSig() []byte { + if x != nil { + return x.BtcSig + } + return nil +} + +type SchnorrRandPair struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + PubRand []byte `protobuf:"bytes,1,opt,name=pub_rand,json=pubRand,proto3" json:"pub_rand,omitempty"` + SecRand []byte `protobuf:"bytes,2,opt,name=sec_rand,json=secRand,proto3" json:"sec_rand,omitempty"` +} + +func (x *SchnorrRandPair) Reset() { + *x = SchnorrRandPair{} + if protoimpl.UnsafeEnabled { + mi := &file_finality_providers_proto_msgTypes[15] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SchnorrRandPair) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SchnorrRandPair) ProtoMessage() {} + +func (x *SchnorrRandPair) ProtoReflect() protoreflect.Message { + mi := &file_finality_providers_proto_msgTypes[15] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SchnorrRandPair.ProtoReflect.Descriptor instead. +func (*SchnorrRandPair) Descriptor() ([]byte, []int) { + return file_finality_providers_proto_rawDescGZIP(), []int{15} +} + +func (x *SchnorrRandPair) GetPubRand() []byte { + if x != nil { + return x.PubRand + } + return nil +} + +func (x *SchnorrRandPair) GetSecRand() []byte { + if x != nil { + return x.SecRand + } + return nil +} + +var File_finality_providers_proto protoreflect.FileDescriptor + +var file_finality_providers_proto_rawDesc = []byte{ + 0x0a, 0x18, 0x66, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x5f, 0x70, 0x72, 0x6f, 0x76, 0x69, + 0x64, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x05, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x1a, 0x14, 0x67, 0x6f, 0x67, 0x6f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x67, + 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x24, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, + 0x73, 0x74, 0x61, 0x6b, 0x69, 0x6e, 0x67, 0x2f, 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, + 0x73, 0x74, 0x61, 0x6b, 0x69, 0x6e, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x19, 0x63, + 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x73, 0x6d, + 0x6f, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x10, 0x0a, 0x0e, 0x47, 0x65, 0x74, 0x49, + 0x6e, 0x66, 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x2b, 0x0a, 0x0f, 0x47, 0x65, + 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, + 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, + 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0xf5, 0x01, 0x0a, 0x1d, 0x43, 0x72, 0x65, 0x61, + 0x74, 0x65, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, + 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x6b, 0x65, 0x79, + 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6b, 0x65, 0x79, + 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1e, 0x0a, 0x0a, 0x70, 0x61, 0x73, 0x73, 0x70, 0x68, 0x72, 0x61, + 0x73, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x70, 0x61, 0x73, 0x73, 0x70, 0x68, + 0x72, 0x61, 0x73, 0x65, 0x12, 0x17, 0x0a, 0x07, 0x68, 0x64, 0x5f, 0x70, 0x61, 0x74, 0x68, 0x18, + 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x68, 0x64, 0x50, 0x61, 0x74, 0x68, 0x12, 0x19, 0x0a, + 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, + 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x64, + 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x43, 0x0a, 0x0a, 0x63, 0x6f, + 0x6d, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x42, 0x23, + 0xc8, 0xde, 0x1f, 0x00, 0xda, 0xde, 0x1f, 0x1b, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x73, 0x64, + 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x6d, 0x61, 0x74, 0x68, 0x2e, 0x4c, 0x65, 0x67, 0x61, 0x63, 0x79, + 0x44, 0x65, 0x63, 0x52, 0x0a, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x22, + 0x37, 0x0a, 0x1e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, + 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x12, 0x15, 0x0a, 0x06, 0x62, 0x74, 0x63, 0x5f, 0x70, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x05, 0x62, 0x74, 0x63, 0x50, 0x6b, 0x22, 0x58, 0x0a, 0x1f, 0x52, 0x65, 0x67, 0x69, + 0x73, 0x74, 0x65, 0x72, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, + 0x69, 0x64, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x15, 0x0a, 0x06, 0x62, + 0x74, 0x63, 0x5f, 0x70, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x62, 0x74, 0x63, + 0x50, 0x6b, 0x12, 0x1e, 0x0a, 0x0a, 0x70, 0x61, 0x73, 0x73, 0x70, 0x68, 0x72, 0x61, 0x73, 0x65, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x70, 0x61, 0x73, 0x73, 0x70, 0x68, 0x72, 0x61, + 0x73, 0x65, 0x22, 0x3b, 0x0a, 0x20, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x46, 0x69, + 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x17, 0x0a, 0x07, 0x74, 0x78, 0x5f, 0x68, 0x61, 0x73, + 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x74, 0x78, 0x48, 0x61, 0x73, 0x68, 0x22, + 0x67, 0x0a, 0x1b, 0x41, 0x64, 0x64, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x53, 0x69, + 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x15, + 0x0a, 0x06, 0x62, 0x74, 0x63, 0x5f, 0x70, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, + 0x62, 0x74, 0x63, 0x50, 0x6b, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x19, 0x0a, + 0x08, 0x61, 0x70, 0x70, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, + 0x07, 0x61, 0x70, 0x70, 0x48, 0x61, 0x73, 0x68, 0x22, 0x83, 0x01, 0x0a, 0x1c, 0x41, 0x64, 0x64, + 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, + 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x17, 0x0a, 0x07, 0x74, 0x78, 0x5f, + 0x68, 0x61, 0x73, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x74, 0x78, 0x48, 0x61, + 0x73, 0x68, 0x12, 0x28, 0x0a, 0x10, 0x65, 0x78, 0x74, 0x72, 0x61, 0x63, 0x74, 0x65, 0x64, 0x5f, + 0x73, 0x6b, 0x5f, 0x68, 0x65, 0x78, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x65, 0x78, + 0x74, 0x72, 0x61, 0x63, 0x74, 0x65, 0x64, 0x53, 0x6b, 0x48, 0x65, 0x78, 0x12, 0x20, 0x0a, 0x0c, + 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x5f, 0x73, 0x6b, 0x5f, 0x68, 0x65, 0x78, 0x18, 0x03, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x0a, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x53, 0x6b, 0x48, 0x65, 0x78, 0x22, 0x35, + 0x0a, 0x1c, 0x51, 0x75, 0x65, 0x72, 0x79, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, + 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x15, + 0x0a, 0x06, 0x62, 0x74, 0x63, 0x5f, 0x70, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, + 0x62, 0x74, 0x63, 0x50, 0x6b, 0x22, 0x69, 0x0a, 0x1d, 0x51, 0x75, 0x65, 0x72, 0x79, 0x46, 0x69, + 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x48, 0x0a, 0x11, 0x66, 0x69, 0x6e, 0x61, 0x6c, 0x69, + 0x74, 0x79, 0x5f, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x1b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, + 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x10, + 0x66, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, + 0x22, 0x22, 0x0a, 0x20, 0x51, 0x75, 0x65, 0x72, 0x79, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, + 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x22, 0x6f, 0x0a, 0x21, 0x51, 0x75, 0x65, 0x72, 0x79, 0x46, 0x69, 0x6e, + 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x4c, 0x69, 0x73, + 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4a, 0x0a, 0x12, 0x66, 0x69, 0x6e, + 0x61, 0x6c, 0x69, 0x74, 0x79, 0x5f, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x73, 0x18, + 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x46, 0x69, + 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x49, 0x6e, + 0x66, 0x6f, 0x52, 0x11, 0x66, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, + 0x69, 0x64, 0x65, 0x72, 0x73, 0x22, 0xe1, 0x03, 0x0a, 0x15, 0x53, 0x74, 0x6f, 0x72, 0x65, 0x46, + 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x12, + 0x1d, 0x0a, 0x0a, 0x62, 0x61, 0x62, 0x79, 0x6c, 0x6f, 0x6e, 0x5f, 0x70, 0x6b, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x0c, 0x52, 0x09, 0x62, 0x61, 0x62, 0x79, 0x6c, 0x6f, 0x6e, 0x50, 0x6b, 0x12, 0x15, + 0x0a, 0x06, 0x62, 0x74, 0x63, 0x5f, 0x70, 0x6b, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, + 0x62, 0x74, 0x63, 0x50, 0x6b, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, + 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, + 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x43, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x6d, 0x69, + 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x42, 0x23, 0xc8, 0xde, 0x1f, + 0x00, 0xda, 0xde, 0x1f, 0x1b, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, 0x69, + 0x6f, 0x2f, 0x6d, 0x61, 0x74, 0x68, 0x2e, 0x4c, 0x65, 0x67, 0x61, 0x63, 0x79, 0x44, 0x65, 0x63, + 0x52, 0x0a, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x2a, 0x0a, 0x03, + 0x70, 0x6f, 0x70, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x2e, 0x50, 0x72, 0x6f, 0x6f, 0x66, 0x4f, 0x66, 0x50, 0x6f, 0x73, 0x73, 0x65, 0x73, 0x73, + 0x69, 0x6f, 0x6e, 0x52, 0x03, 0x70, 0x6f, 0x70, 0x12, 0x19, 0x0a, 0x08, 0x6b, 0x65, 0x79, 0x5f, + 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6b, 0x65, 0x79, 0x4e, + 0x61, 0x6d, 0x65, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, + 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x2a, + 0x0a, 0x11, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x76, 0x6f, 0x74, 0x65, 0x64, 0x5f, 0x68, 0x65, 0x69, + 0x67, 0x68, 0x74, 0x18, 0x08, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, 0x6c, 0x61, 0x73, 0x74, 0x56, + 0x6f, 0x74, 0x65, 0x64, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x32, 0x0a, 0x15, 0x6c, 0x61, + 0x73, 0x74, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x74, 0x65, 0x64, 0x5f, 0x68, 0x65, 0x69, + 0x67, 0x68, 0x74, 0x18, 0x09, 0x20, 0x01, 0x28, 0x04, 0x52, 0x13, 0x6c, 0x61, 0x73, 0x74, 0x43, + 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x74, 0x65, 0x64, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x32, + 0x0a, 0x15, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x65, 0x64, + 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x04, 0x52, 0x13, 0x6c, + 0x61, 0x73, 0x74, 0x50, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x65, 0x64, 0x48, 0x65, 0x69, 0x67, + 0x68, 0x74, 0x12, 0x35, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x0b, 0x20, 0x01, + 0x28, 0x0e, 0x32, 0x1d, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x46, 0x69, 0x6e, 0x61, 0x6c, + 0x69, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x53, 0x74, 0x61, 0x74, 0x75, + 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0xd8, 0x02, 0x0a, 0x14, 0x46, 0x69, + 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x49, 0x6e, + 0x66, 0x6f, 0x12, 0x24, 0x0a, 0x0e, 0x62, 0x61, 0x62, 0x79, 0x6c, 0x6f, 0x6e, 0x5f, 0x70, 0x6b, + 0x5f, 0x68, 0x65, 0x78, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x62, 0x61, 0x62, 0x79, + 0x6c, 0x6f, 0x6e, 0x50, 0x6b, 0x48, 0x65, 0x78, 0x12, 0x1c, 0x0a, 0x0a, 0x62, 0x74, 0x63, 0x5f, + 0x70, 0x6b, 0x5f, 0x68, 0x65, 0x78, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x62, 0x74, + 0x63, 0x50, 0x6b, 0x48, 0x65, 0x78, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, + 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x64, 0x65, 0x73, + 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x43, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x6d, + 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x42, 0x23, 0xc8, 0xde, + 0x1f, 0x00, 0xda, 0xde, 0x1f, 0x1b, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, + 0x69, 0x6f, 0x2f, 0x6d, 0x61, 0x74, 0x68, 0x2e, 0x4c, 0x65, 0x67, 0x61, 0x63, 0x79, 0x44, 0x65, + 0x63, 0x52, 0x0a, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x2a, 0x0a, + 0x11, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x76, 0x6f, 0x74, 0x65, 0x64, 0x5f, 0x68, 0x65, 0x69, 0x67, + 0x68, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, 0x6c, 0x61, 0x73, 0x74, 0x56, 0x6f, + 0x74, 0x65, 0x64, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x32, 0x0a, 0x15, 0x6c, 0x61, 0x73, + 0x74, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x74, 0x65, 0x64, 0x5f, 0x68, 0x65, 0x69, 0x67, + 0x68, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x04, 0x52, 0x13, 0x6c, 0x61, 0x73, 0x74, 0x43, 0x6f, + 0x6d, 0x6d, 0x69, 0x74, 0x74, 0x65, 0x64, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x35, 0x0a, + 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1d, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, + 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, + 0x61, 0x74, 0x75, 0x73, 0x22, 0x4d, 0x0a, 0x11, 0x50, 0x72, 0x6f, 0x6f, 0x66, 0x4f, 0x66, 0x50, + 0x6f, 0x73, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x1f, 0x0a, 0x0b, 0x62, 0x61, 0x62, + 0x79, 0x6c, 0x6f, 0x6e, 0x5f, 0x73, 0x69, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0a, + 0x62, 0x61, 0x62, 0x79, 0x6c, 0x6f, 0x6e, 0x53, 0x69, 0x67, 0x12, 0x17, 0x0a, 0x07, 0x62, 0x74, + 0x63, 0x5f, 0x73, 0x69, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x62, 0x74, 0x63, + 0x53, 0x69, 0x67, 0x22, 0x47, 0x0a, 0x0f, 0x53, 0x63, 0x68, 0x6e, 0x6f, 0x72, 0x72, 0x52, 0x61, + 0x6e, 0x64, 0x50, 0x61, 0x69, 0x72, 0x12, 0x19, 0x0a, 0x08, 0x70, 0x75, 0x62, 0x5f, 0x72, 0x61, + 0x6e, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x70, 0x75, 0x62, 0x52, 0x61, 0x6e, + 0x64, 0x12, 0x19, 0x0a, 0x08, 0x73, 0x65, 0x63, 0x5f, 0x72, 0x61, 0x6e, 0x64, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x0c, 0x52, 0x07, 0x73, 0x65, 0x63, 0x52, 0x61, 0x6e, 0x64, 0x2a, 0xa6, 0x01, 0x0a, + 0x16, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, + 0x72, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x43, 0x52, 0x45, 0x41, 0x54, + 0x45, 0x44, 0x10, 0x00, 0x1a, 0x0b, 0x8a, 0x9d, 0x20, 0x07, 0x43, 0x52, 0x45, 0x41, 0x54, 0x45, + 0x44, 0x12, 0x1e, 0x0a, 0x0a, 0x52, 0x45, 0x47, 0x49, 0x53, 0x54, 0x45, 0x52, 0x45, 0x44, 0x10, + 0x01, 0x1a, 0x0e, 0x8a, 0x9d, 0x20, 0x0a, 0x52, 0x45, 0x47, 0x49, 0x53, 0x54, 0x45, 0x52, 0x45, + 0x44, 0x12, 0x16, 0x0a, 0x06, 0x41, 0x43, 0x54, 0x49, 0x56, 0x45, 0x10, 0x02, 0x1a, 0x0a, 0x8a, + 0x9d, 0x20, 0x06, 0x41, 0x43, 0x54, 0x49, 0x56, 0x45, 0x12, 0x1a, 0x0a, 0x08, 0x49, 0x4e, 0x41, + 0x43, 0x54, 0x49, 0x56, 0x45, 0x10, 0x03, 0x1a, 0x0c, 0x8a, 0x9d, 0x20, 0x08, 0x49, 0x4e, 0x41, + 0x43, 0x54, 0x49, 0x56, 0x45, 0x12, 0x18, 0x0a, 0x07, 0x53, 0x4c, 0x41, 0x53, 0x48, 0x45, 0x44, + 0x10, 0x04, 0x1a, 0x0b, 0x8a, 0x9d, 0x20, 0x07, 0x53, 0x4c, 0x41, 0x53, 0x48, 0x45, 0x44, 0x1a, + 0x04, 0x88, 0xa3, 0x1e, 0x00, 0x32, 0xd6, 0x04, 0x0a, 0x11, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, + 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x73, 0x12, 0x38, 0x0a, 0x07, 0x47, + 0x65, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x12, 0x15, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x47, + 0x65, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x47, 0x65, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x65, 0x0a, 0x16, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x46, + 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x12, + 0x24, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x46, 0x69, + 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x25, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x43, 0x72, + 0x65, 0x61, 0x74, 0x65, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, + 0x69, 0x64, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x6b, 0x0a, 0x18, + 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, + 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x12, 0x26, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, + 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x1a, 0x27, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, + 0x72, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, + 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x5f, 0x0a, 0x14, 0x41, 0x64, 0x64, + 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, + 0x65, 0x12, 0x22, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x41, 0x64, 0x64, 0x46, 0x69, 0x6e, + 0x61, 0x6c, 0x69, 0x74, 0x79, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x23, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x41, 0x64, + 0x64, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, + 0x72, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x62, 0x0a, 0x15, 0x51, 0x75, + 0x65, 0x72, 0x79, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, + 0x64, 0x65, 0x72, 0x12, 0x23, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x51, 0x75, 0x65, 0x72, + 0x79, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, + 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x24, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x2e, 0x51, 0x75, 0x65, 0x72, 0x79, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, + 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x6e, + 0x0a, 0x19, 0x51, 0x75, 0x65, 0x72, 0x79, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, + 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x27, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x2e, 0x51, 0x75, 0x65, 0x72, 0x79, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, + 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x1a, 0x28, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x51, 0x75, 0x65, + 0x72, 0x79, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x64, + 0x65, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x43, + 0x5a, 0x41, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x61, 0x62, + 0x79, 0x6c, 0x6f, 0x6e, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x2f, 0x66, 0x69, 0x6e, 0x61, 0x6c, 0x69, + 0x74, 0x79, 0x2d, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x2f, 0x66, 0x69, 0x6e, 0x61, + 0x6c, 0x69, 0x74, 0x79, 0x2d, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x72, 0x2f, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_finality_providers_proto_rawDescOnce sync.Once + file_finality_providers_proto_rawDescData = file_finality_providers_proto_rawDesc +) + +func file_finality_providers_proto_rawDescGZIP() []byte { + file_finality_providers_proto_rawDescOnce.Do(func() { + file_finality_providers_proto_rawDescData = protoimpl.X.CompressGZIP(file_finality_providers_proto_rawDescData) + }) + return file_finality_providers_proto_rawDescData +} + +var file_finality_providers_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_finality_providers_proto_msgTypes = make([]protoimpl.MessageInfo, 16) +var file_finality_providers_proto_goTypes = []interface{}{ + (FinalityProviderStatus)(0), // 0: proto.FinalityProviderStatus + (*GetInfoRequest)(nil), // 1: proto.GetInfoRequest + (*GetInfoResponse)(nil), // 2: proto.GetInfoResponse + (*CreateFinalityProviderRequest)(nil), // 3: proto.CreateFinalityProviderRequest + (*CreateFinalityProviderResponse)(nil), // 4: proto.CreateFinalityProviderResponse + (*RegisterFinalityProviderRequest)(nil), // 5: proto.RegisterFinalityProviderRequest + (*RegisterFinalityProviderResponse)(nil), // 6: proto.RegisterFinalityProviderResponse + (*AddFinalitySignatureRequest)(nil), // 7: proto.AddFinalitySignatureRequest + (*AddFinalitySignatureResponse)(nil), // 8: proto.AddFinalitySignatureResponse + (*QueryFinalityProviderRequest)(nil), // 9: proto.QueryFinalityProviderRequest + (*QueryFinalityProviderResponse)(nil), // 10: proto.QueryFinalityProviderResponse + (*QueryFinalityProviderListRequest)(nil), // 11: proto.QueryFinalityProviderListRequest + (*QueryFinalityProviderListResponse)(nil), // 12: proto.QueryFinalityProviderListResponse + (*StoreFinalityProvider)(nil), // 13: proto.StoreFinalityProvider + (*FinalityProviderInfo)(nil), // 14: proto.FinalityProviderInfo + (*ProofOfPossession)(nil), // 15: proto.ProofOfPossession + (*SchnorrRandPair)(nil), // 16: proto.SchnorrRandPair +} +var file_finality_providers_proto_depIdxs = []int32{ + 14, // 0: proto.QueryFinalityProviderResponse.finality_provider:type_name -> proto.FinalityProviderInfo + 14, // 1: proto.QueryFinalityProviderListResponse.finality_providers:type_name -> proto.FinalityProviderInfo + 15, // 2: proto.StoreFinalityProvider.pop:type_name -> proto.ProofOfPossession + 0, // 3: proto.StoreFinalityProvider.status:type_name -> proto.FinalityProviderStatus + 0, // 4: proto.FinalityProviderInfo.status:type_name -> proto.FinalityProviderStatus + 1, // 5: proto.FinalityProviders.GetInfo:input_type -> proto.GetInfoRequest + 3, // 6: proto.FinalityProviders.CreateFinalityProvider:input_type -> proto.CreateFinalityProviderRequest + 5, // 7: proto.FinalityProviders.RegisterFinalityProvider:input_type -> proto.RegisterFinalityProviderRequest + 7, // 8: proto.FinalityProviders.AddFinalitySignature:input_type -> proto.AddFinalitySignatureRequest + 9, // 9: proto.FinalityProviders.QueryFinalityProvider:input_type -> proto.QueryFinalityProviderRequest + 11, // 10: proto.FinalityProviders.QueryFinalityProviderList:input_type -> proto.QueryFinalityProviderListRequest + 2, // 11: proto.FinalityProviders.GetInfo:output_type -> proto.GetInfoResponse + 4, // 12: proto.FinalityProviders.CreateFinalityProvider:output_type -> proto.CreateFinalityProviderResponse + 6, // 13: proto.FinalityProviders.RegisterFinalityProvider:output_type -> proto.RegisterFinalityProviderResponse + 8, // 14: proto.FinalityProviders.AddFinalitySignature:output_type -> proto.AddFinalitySignatureResponse + 10, // 15: proto.FinalityProviders.QueryFinalityProvider:output_type -> proto.QueryFinalityProviderResponse + 12, // 16: proto.FinalityProviders.QueryFinalityProviderList:output_type -> proto.QueryFinalityProviderListResponse + 11, // [11:17] is the sub-list for method output_type + 5, // [5:11] is the sub-list for method input_type + 5, // [5:5] is the sub-list for extension type_name + 5, // [5:5] is the sub-list for extension extendee + 0, // [0:5] is the sub-list for field type_name +} + +func init() { file_finality_providers_proto_init() } +func file_finality_providers_proto_init() { + if File_finality_providers_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_finality_providers_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GetInfoRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_finality_providers_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GetInfoResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_finality_providers_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CreateFinalityProviderRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_finality_providers_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CreateFinalityProviderResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_finality_providers_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*RegisterFinalityProviderRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_finality_providers_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*RegisterFinalityProviderResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_finality_providers_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*AddFinalitySignatureRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_finality_providers_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*AddFinalitySignatureResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_finality_providers_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*QueryFinalityProviderRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_finality_providers_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*QueryFinalityProviderResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_finality_providers_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*QueryFinalityProviderListRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_finality_providers_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*QueryFinalityProviderListResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_finality_providers_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*StoreFinalityProvider); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_finality_providers_proto_msgTypes[13].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*FinalityProviderInfo); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_finality_providers_proto_msgTypes[14].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ProofOfPossession); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_finality_providers_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*SchnorrRandPair); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_finality_providers_proto_rawDesc, + NumEnums: 1, + NumMessages: 16, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_finality_providers_proto_goTypes, + DependencyIndexes: file_finality_providers_proto_depIdxs, + EnumInfos: file_finality_providers_proto_enumTypes, + MessageInfos: file_finality_providers_proto_msgTypes, + }.Build() + File_finality_providers_proto = out.File + file_finality_providers_proto_rawDesc = nil + file_finality_providers_proto_goTypes = nil + file_finality_providers_proto_depIdxs = nil +} diff --git a/validator/proto/validators.proto b/finality-provider/proto/finality_providers.proto similarity index 59% rename from validator/proto/validators.proto rename to finality-provider/proto/finality_providers.proto index 66aa0531..0ef3b8a7 100644 --- a/validator/proto/validators.proto +++ b/finality-provider/proto/finality_providers.proto @@ -6,31 +6,32 @@ import "gogoproto/gogo.proto"; import "cosmos/staking/v1beta1/staking.proto"; import "cosmos_proto/cosmos.proto"; -option go_package = "github.com/babylonchain/btc-validator/validator/proto"; +option go_package = "github.com/babylonchain/finality-provider/finality-provider/proto"; -service BtcValidators { +service FinalityProviders { // GetInfo returns the information of the daemon rpc GetInfo (GetInfoRequest) returns (GetInfoResponse); - // CreateValidator generates and saves a validator object - rpc CreateValidator (CreateValidatorRequest) - returns (CreateValidatorResponse); + // CreateFinalityProvider generates and saves a finality provider object + rpc CreateFinalityProvider (CreateFinalityProviderRequest) + returns (CreateFinalityProviderResponse); - // RegisterValidator sends a transactions to Babylon to register a BTC - // validator - rpc RegisterValidator (RegisterValidatorRequest) - returns (RegisterValidatorResponse); + // RegisterFinalityProvider sends a transactions to Babylon to register a BTC + // finality provider + rpc RegisterFinalityProvider (RegisterFinalityProviderRequest) + returns (RegisterFinalityProviderResponse); // AddFinalitySignature sends a transactions to Babylon to add a Finality // signature for a block rpc AddFinalitySignature(AddFinalitySignatureRequest) returns (AddFinalitySignatureResponse); - // QueryValidator queries the validator - rpc QueryValidator (QueryValidatorRequest) returns (QueryValidatorResponse); - // QueryValidatorList queries a list of validators - rpc QueryValidatorList (QueryValidatorListRequest) - returns (QueryValidatorListResponse); + // QueryFinalityProvider queries the finality provider + rpc QueryFinalityProvider (QueryFinalityProviderRequest) returns (QueryFinalityProviderResponse); + + // QueryFinalityProviderList queries a list of finality providers + rpc QueryFinalityProviderList (QueryFinalityProviderListRequest) + returns (QueryFinalityProviderListResponse); } message GetInfoRequest { @@ -40,43 +41,43 @@ message GetInfoResponse { string version = 1; } -message CreateValidatorRequest { +message CreateFinalityProviderRequest { // key_name is the identifier key in keyring string key_name = 1; // passphrase is used to encrypt the keys string passphrase = 2; // hd_path is the hd path for private key derivation string hd_path = 3; - // chain_id is the identifier of the consumer chain that the validator connected to + // chain_id is the identifier of the consumer chain that the finality provider connected to string chain_id = 4; - // description defines the description terms for the validator + // description defines the description terms for the finality provider bytes description = 5; - // commission defines the commission rate for the validator + // commission defines the commission rate for the finality provider string commission = 6 [ (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", (gogoproto.nullable) = false ]; } -message CreateValidatorResponse { - // btc_pk is the hex string of BTC secp256k1 public key of the validator encoded in BIP-340 spec +message CreateFinalityProviderResponse { + // btc_pk is the hex string of BTC secp256k1 public key of the finality provider encoded in BIP-340 spec string btc_pk = 1; } -message RegisterValidatorRequest { - // btc_pk is hex string of the BTC secp256k1 public key of the validator encoded in BIP-340 spec +message RegisterFinalityProviderRequest { + // btc_pk is hex string of the BTC secp256k1 public key of the finality provider encoded in BIP-340 spec string btc_pk = 1; // passphrase is used to encrypt the keys string passphrase = 2; } -message RegisterValidatorResponse { +message RegisterFinalityProviderResponse { // hash of the successful Babylon registration transaction string tx_hash = 1; } message AddFinalitySignatureRequest { - // btc_pk is hex string of the BTC secp256k1 public key of the validator encoded in BIP-340 spec + // btc_pk is hex string of the BTC secp256k1 public key of the finality provider encoded in BIP-340 spec string btc_pk = 1; // height is the height of the Babylon block uint64 height = 2; @@ -93,32 +94,32 @@ message AddFinalitySignatureResponse { string local_sk_hex = 3; } -message QueryValidatorRequest { - // btc_pk is hex string of the BTC secp256k1 public key of the validator encoded in BIP-340 spec +message QueryFinalityProviderRequest { + // btc_pk is hex string of the BTC secp256k1 public key of the finality provider encoded in BIP-340 spec string btc_pk = 1; } -message QueryValidatorResponse { - ValidatorInfo validator = 1; +message QueryFinalityProviderResponse { + FinalityProviderInfo finality_provider = 1; } -message QueryValidatorListRequest { +message QueryFinalityProviderListRequest { // TODO add pagination in case the list gets large } -message QueryValidatorListResponse { - repeated ValidatorInfo validators = 1; +message QueryFinalityProviderListResponse { + repeated FinalityProviderInfo finality_providers = 1; // TODO add pagination in case the list gets large } -message StoreValidator { - // babylon_pk is the Babylon secp256k1 PK of this BTC validator +message StoreFinalityProvider { + // babylon_pk is the Babylon secp256k1 PK of this finality provider bytes babylon_pk = 1; - // btc_pk is the BTC secp256k1 PK of the validator encoded in BIP-340 spec + // btc_pk is the BTC secp256k1 PK of the finality provider encoded in BIP-340 spec bytes btc_pk = 2; - // description defines the description terms for the validator + // description defines the description terms for the finality provider bytes description = 3; - // commission defines the commission rate for the validator + // commission defines the commission rate for the finality provider string commission = 4 [ (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", (gogoproto.nullable) = false @@ -127,29 +128,29 @@ message StoreValidator { ProofOfPossession pop = 5; // key_name is the identifier of the keyring string key_name = 6; - // chain_id is the identifier of the consumer chain that the validator connected to + // chain_id is the identifier of the consumer chain that the finality provider connected to string chain_id = 7; // last_voted_height defines the height of the last voted Babylon block uint64 last_voted_height = 8; // last_committed_height defines the height of the last Babylon block - // to which the validator committed a randomness pair + // to which the finality provider committed a randomness pair uint64 last_committed_height = 9; // last_processed_height defines the height of the last successfully processed block // even though the vote is not cast uint64 last_processed_height = 10; - // status defines the current validator status - ValidatorStatus status = 11; + // status defines the current finality provider status + FinalityProviderStatus status = 11; } -// ValidatorInfo is the basic information of a validator mainly for external usage -message ValidatorInfo { - // babylon_pk_hex is the hex string of the Babylon secp256k1 PK of this BTC validator +// FinalityProviderInfo is the basic information of a finality provider mainly for external usage +message FinalityProviderInfo { + // babylon_pk_hex is the hex string of the Babylon secp256k1 PK of this finality provider string babylon_pk_hex = 1; - // btc_pk_hex is the hex string of the BTC secp256k1 PK of the validator encoded in BIP-340 spec + // btc_pk_hex is the hex string of the BTC secp256k1 PK of the finality provider encoded in BIP-340 spec string btc_pk_hex = 2; - // description defines the description terms for the validator + // description defines the description terms for the finality provider bytes description = 3; - // commission defines the commission rate for the validator + // commission defines the commission rate for the finality provider string commission = 4 [ (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec", (gogoproto.nullable) = false @@ -157,10 +158,10 @@ message ValidatorInfo { // last_voted_height defines the height of the last voted Babylon block uint64 last_voted_height = 5; // last_committed_height defines the height of the last Babylon block - // to which the validator committed a randomness pair + // to which the finality provider committed a randomness pair uint64 last_committed_height = 6; - // status defines the current validator status - ValidatorStatus status = 7; + // status defines the current finality provider status + FinalityProviderStatus status = 7; } // ProofOfPossession is the proof of possession that a Babylon secp256k1 @@ -179,32 +180,32 @@ message SchnorrRandPair { bytes sec_rand = 2; } -// ValidatorStatus is the status of a BTC validator -// a Validator object has 4 states: -// - Created - created and managed by validator client, not registered to +// FinalityProviderStatus is the status of a finality provider +// a FinalityProvider object has 4 states: +// - Created - created and managed by finality provider client, not registered to // babylon yet // - Registered - created and registered to Babylon, but not voting yet (No // delegated stake) // - Active - created and registered to Babylon with stake to vote // - Inactive - created and registered to Babylon with no stake to vote. -// Validator was already active. +// Finality Provider was already active. // Valid State Transactions: // - Created -> Registered // - Registered -> Active // - Active -> Inactive // - Inactive -> Active -enum ValidatorStatus { +enum FinalityProviderStatus { option (gogoproto.goproto_enum_prefix) = false; - // CREATED defines a validator that is awaiting registration + // CREATED defines a finality provider that is awaiting registration CREATED = 0 [(gogoproto.enumvalue_customname) = "CREATED"]; - // REGISTERED defines a validator that has been registered + // REGISTERED defines a finality provider that has been registered // to Babylon but has no delegated stake REGISTERED = 1 [(gogoproto.enumvalue_customname) = "REGISTERED"]; - // ACTIVE defines a validator that is delegated to vote + // ACTIVE defines a finality provider that is delegated to vote ACTIVE = 2 [(gogoproto.enumvalue_customname) = "ACTIVE"]; - // INACTIVE defines a validator whose delegations are reduced to zero but not slashed + // INACTIVE defines a finality provider whose delegations are reduced to zero but not slashed INACTIVE = 3 [(gogoproto.enumvalue_customname) = "INACTIVE"]; - // SLASHED defines a validator that has been slashed + // SLASHED defines a finality provider that has been slashed SLASHED = 4 [(gogoproto.enumvalue_customname) = "SLASHED"]; } diff --git a/finality-provider/proto/finality_providers_grpc.pb.go b/finality-provider/proto/finality_providers_grpc.pb.go new file mode 100644 index 00000000..e8a27819 --- /dev/null +++ b/finality-provider/proto/finality_providers_grpc.pb.go @@ -0,0 +1,310 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.3.0 +// - protoc (unknown) +// source: finality_providers.proto + +package proto + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.32.0 or later. +const _ = grpc.SupportPackageIsVersion7 + +const ( + FinalityProviders_GetInfo_FullMethodName = "/proto.FinalityProviders/GetInfo" + FinalityProviders_CreateFinalityProvider_FullMethodName = "/proto.FinalityProviders/CreateFinalityProvider" + FinalityProviders_RegisterFinalityProvider_FullMethodName = "/proto.FinalityProviders/RegisterFinalityProvider" + FinalityProviders_AddFinalitySignature_FullMethodName = "/proto.FinalityProviders/AddFinalitySignature" + FinalityProviders_QueryFinalityProvider_FullMethodName = "/proto.FinalityProviders/QueryFinalityProvider" + FinalityProviders_QueryFinalityProviderList_FullMethodName = "/proto.FinalityProviders/QueryFinalityProviderList" +) + +// FinalityProvidersClient is the client API for FinalityProviders service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type FinalityProvidersClient interface { + // GetInfo returns the information of the daemon + GetInfo(ctx context.Context, in *GetInfoRequest, opts ...grpc.CallOption) (*GetInfoResponse, error) + // CreateFinalityProvider generates and saves a finality provider object + CreateFinalityProvider(ctx context.Context, in *CreateFinalityProviderRequest, opts ...grpc.CallOption) (*CreateFinalityProviderResponse, error) + // RegisterFinalityProvider sends a transactions to Babylon to register a BTC + // finality provider + RegisterFinalityProvider(ctx context.Context, in *RegisterFinalityProviderRequest, opts ...grpc.CallOption) (*RegisterFinalityProviderResponse, error) + // AddFinalitySignature sends a transactions to Babylon to add a Finality + // signature for a block + AddFinalitySignature(ctx context.Context, in *AddFinalitySignatureRequest, opts ...grpc.CallOption) (*AddFinalitySignatureResponse, error) + // QueryFinalityProvider queries the finality provider + QueryFinalityProvider(ctx context.Context, in *QueryFinalityProviderRequest, opts ...grpc.CallOption) (*QueryFinalityProviderResponse, error) + // QueryFinalityProviderList queries a list of finality providers + QueryFinalityProviderList(ctx context.Context, in *QueryFinalityProviderListRequest, opts ...grpc.CallOption) (*QueryFinalityProviderListResponse, error) +} + +type finalityProvidersClient struct { + cc grpc.ClientConnInterface +} + +func NewFinalityProvidersClient(cc grpc.ClientConnInterface) FinalityProvidersClient { + return &finalityProvidersClient{cc} +} + +func (c *finalityProvidersClient) GetInfo(ctx context.Context, in *GetInfoRequest, opts ...grpc.CallOption) (*GetInfoResponse, error) { + out := new(GetInfoResponse) + err := c.cc.Invoke(ctx, FinalityProviders_GetInfo_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *finalityProvidersClient) CreateFinalityProvider(ctx context.Context, in *CreateFinalityProviderRequest, opts ...grpc.CallOption) (*CreateFinalityProviderResponse, error) { + out := new(CreateFinalityProviderResponse) + err := c.cc.Invoke(ctx, FinalityProviders_CreateFinalityProvider_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *finalityProvidersClient) RegisterFinalityProvider(ctx context.Context, in *RegisterFinalityProviderRequest, opts ...grpc.CallOption) (*RegisterFinalityProviderResponse, error) { + out := new(RegisterFinalityProviderResponse) + err := c.cc.Invoke(ctx, FinalityProviders_RegisterFinalityProvider_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *finalityProvidersClient) AddFinalitySignature(ctx context.Context, in *AddFinalitySignatureRequest, opts ...grpc.CallOption) (*AddFinalitySignatureResponse, error) { + out := new(AddFinalitySignatureResponse) + err := c.cc.Invoke(ctx, FinalityProviders_AddFinalitySignature_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *finalityProvidersClient) QueryFinalityProvider(ctx context.Context, in *QueryFinalityProviderRequest, opts ...grpc.CallOption) (*QueryFinalityProviderResponse, error) { + out := new(QueryFinalityProviderResponse) + err := c.cc.Invoke(ctx, FinalityProviders_QueryFinalityProvider_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *finalityProvidersClient) QueryFinalityProviderList(ctx context.Context, in *QueryFinalityProviderListRequest, opts ...grpc.CallOption) (*QueryFinalityProviderListResponse, error) { + out := new(QueryFinalityProviderListResponse) + err := c.cc.Invoke(ctx, FinalityProviders_QueryFinalityProviderList_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// FinalityProvidersServer is the server API for FinalityProviders service. +// All implementations must embed UnimplementedFinalityProvidersServer +// for forward compatibility +type FinalityProvidersServer interface { + // GetInfo returns the information of the daemon + GetInfo(context.Context, *GetInfoRequest) (*GetInfoResponse, error) + // CreateFinalityProvider generates and saves a finality provider object + CreateFinalityProvider(context.Context, *CreateFinalityProviderRequest) (*CreateFinalityProviderResponse, error) + // RegisterFinalityProvider sends a transactions to Babylon to register a BTC + // finality provider + RegisterFinalityProvider(context.Context, *RegisterFinalityProviderRequest) (*RegisterFinalityProviderResponse, error) + // AddFinalitySignature sends a transactions to Babylon to add a Finality + // signature for a block + AddFinalitySignature(context.Context, *AddFinalitySignatureRequest) (*AddFinalitySignatureResponse, error) + // QueryFinalityProvider queries the finality provider + QueryFinalityProvider(context.Context, *QueryFinalityProviderRequest) (*QueryFinalityProviderResponse, error) + // QueryFinalityProviderList queries a list of finality providers + QueryFinalityProviderList(context.Context, *QueryFinalityProviderListRequest) (*QueryFinalityProviderListResponse, error) + mustEmbedUnimplementedFinalityProvidersServer() +} + +// UnimplementedFinalityProvidersServer must be embedded to have forward compatible implementations. +type UnimplementedFinalityProvidersServer struct { +} + +func (UnimplementedFinalityProvidersServer) GetInfo(context.Context, *GetInfoRequest) (*GetInfoResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetInfo not implemented") +} +func (UnimplementedFinalityProvidersServer) CreateFinalityProvider(context.Context, *CreateFinalityProviderRequest) (*CreateFinalityProviderResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method CreateFinalityProvider not implemented") +} +func (UnimplementedFinalityProvidersServer) RegisterFinalityProvider(context.Context, *RegisterFinalityProviderRequest) (*RegisterFinalityProviderResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method RegisterFinalityProvider not implemented") +} +func (UnimplementedFinalityProvidersServer) AddFinalitySignature(context.Context, *AddFinalitySignatureRequest) (*AddFinalitySignatureResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method AddFinalitySignature not implemented") +} +func (UnimplementedFinalityProvidersServer) QueryFinalityProvider(context.Context, *QueryFinalityProviderRequest) (*QueryFinalityProviderResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method QueryFinalityProvider not implemented") +} +func (UnimplementedFinalityProvidersServer) QueryFinalityProviderList(context.Context, *QueryFinalityProviderListRequest) (*QueryFinalityProviderListResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method QueryFinalityProviderList not implemented") +} +func (UnimplementedFinalityProvidersServer) mustEmbedUnimplementedFinalityProvidersServer() {} + +// UnsafeFinalityProvidersServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to FinalityProvidersServer will +// result in compilation errors. +type UnsafeFinalityProvidersServer interface { + mustEmbedUnimplementedFinalityProvidersServer() +} + +func RegisterFinalityProvidersServer(s grpc.ServiceRegistrar, srv FinalityProvidersServer) { + s.RegisterService(&FinalityProviders_ServiceDesc, srv) +} + +func _FinalityProviders_GetInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetInfoRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(FinalityProvidersServer).GetInfo(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: FinalityProviders_GetInfo_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(FinalityProvidersServer).GetInfo(ctx, req.(*GetInfoRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _FinalityProviders_CreateFinalityProvider_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(CreateFinalityProviderRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(FinalityProvidersServer).CreateFinalityProvider(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: FinalityProviders_CreateFinalityProvider_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(FinalityProvidersServer).CreateFinalityProvider(ctx, req.(*CreateFinalityProviderRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _FinalityProviders_RegisterFinalityProvider_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RegisterFinalityProviderRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(FinalityProvidersServer).RegisterFinalityProvider(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: FinalityProviders_RegisterFinalityProvider_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(FinalityProvidersServer).RegisterFinalityProvider(ctx, req.(*RegisterFinalityProviderRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _FinalityProviders_AddFinalitySignature_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AddFinalitySignatureRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(FinalityProvidersServer).AddFinalitySignature(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: FinalityProviders_AddFinalitySignature_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(FinalityProvidersServer).AddFinalitySignature(ctx, req.(*AddFinalitySignatureRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _FinalityProviders_QueryFinalityProvider_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryFinalityProviderRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(FinalityProvidersServer).QueryFinalityProvider(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: FinalityProviders_QueryFinalityProvider_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(FinalityProvidersServer).QueryFinalityProvider(ctx, req.(*QueryFinalityProviderRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _FinalityProviders_QueryFinalityProviderList_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryFinalityProviderListRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(FinalityProvidersServer).QueryFinalityProviderList(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: FinalityProviders_QueryFinalityProviderList_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(FinalityProvidersServer).QueryFinalityProviderList(ctx, req.(*QueryFinalityProviderListRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// FinalityProviders_ServiceDesc is the grpc.ServiceDesc for FinalityProviders service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var FinalityProviders_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "proto.FinalityProviders", + HandlerType: (*FinalityProvidersServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "GetInfo", + Handler: _FinalityProviders_GetInfo_Handler, + }, + { + MethodName: "CreateFinalityProvider", + Handler: _FinalityProviders_CreateFinalityProvider_Handler, + }, + { + MethodName: "RegisterFinalityProvider", + Handler: _FinalityProviders_RegisterFinalityProvider_Handler, + }, + { + MethodName: "AddFinalitySignature", + Handler: _FinalityProviders_AddFinalitySignature_Handler, + }, + { + MethodName: "QueryFinalityProvider", + Handler: _FinalityProviders_QueryFinalityProvider_Handler, + }, + { + MethodName: "QueryFinalityProviderList", + Handler: _FinalityProviders_QueryFinalityProviderList_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "finality_providers.proto", +} diff --git a/validator/proto/scripts/protocgen.sh b/finality-provider/proto/scripts/protocgen.sh similarity index 100% rename from validator/proto/scripts/protocgen.sh rename to finality-provider/proto/scripts/protocgen.sh diff --git a/finality-provider/service/app.go b/finality-provider/service/app.go new file mode 100644 index 00000000..42f7eb48 --- /dev/null +++ b/finality-provider/service/app.go @@ -0,0 +1,467 @@ +package service + +import ( + "encoding/hex" + "fmt" + "github.com/babylonchain/finality-provider/util" + "strings" + "sync" + + sdkmath "cosmossdk.io/math" + bbntypes "github.com/babylonchain/babylon/types" + bstypes "github.com/babylonchain/babylon/x/btcstaking/types" + "github.com/btcsuite/btcd/btcec/v2" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + "go.uber.org/zap" + + fpkr "github.com/babylonchain/finality-provider/keyring" + + "github.com/babylonchain/finality-provider/clientcontroller" + "github.com/babylonchain/finality-provider/eotsmanager" + "github.com/babylonchain/finality-provider/eotsmanager/client" + fpcfg "github.com/babylonchain/finality-provider/finality-provider/config" + "github.com/babylonchain/finality-provider/finality-provider/proto" + + fpstore "github.com/babylonchain/finality-provider/finality-provider/store" +) + +type FinalityProviderApp struct { + startOnce sync.Once + stopOnce sync.Once + + wg sync.WaitGroup + quit chan struct{} + + sentWg sync.WaitGroup + sentQuit chan struct{} + + eventWg sync.WaitGroup + eventQuit chan struct{} + + cc clientcontroller.ClientController + kr keyring.Keyring + fps *fpstore.FinalityProviderStore + config *fpcfg.Config + logger *zap.Logger + input *strings.Reader + + fpManager *FinalityProviderManager + eotsManager eotsmanager.EOTSManager + + createFinalityProviderRequestChan chan *createFinalityProviderRequest + registerFinalityProviderRequestChan chan *registerFinalityProviderRequest + finalityProviderRegisteredEventChan chan *finalityProviderRegisteredEvent +} + +func NewFinalityProviderAppFromConfig( + homePath string, + config *fpcfg.Config, + logger *zap.Logger, +) (*FinalityProviderApp, error) { + cc, err := clientcontroller.NewClientController(config.ChainName, config.BabylonConfig, &config.BTCNetParams, logger) + if err != nil { + return nil, fmt.Errorf("failed to create rpc client for the consumer chain %s: %v", config.ChainName, err) + } + + // if the EOTSManagerAddress is empty, run a local EOTS manager; + // otherwise connect a remote one with a gRPC client + em, err := client.NewEOTSManagerGRpcClient(config.EOTSManagerAddress) + if err != nil { + return nil, fmt.Errorf("failed to create EOTS manager client: %w", err) + } + // TODO add retry mechanism and ping to ensure the EOTS manager daemon is healthy + logger.Info("successfully connected to a remote EOTS manager", zap.String("address", config.EOTSManagerAddress)) + + return NewFinalityProviderApp(homePath, config, cc, em, logger) +} + +func NewFinalityProviderApp( + homePath string, + config *fpcfg.Config, + cc clientcontroller.ClientController, + em eotsmanager.EOTSManager, + logger *zap.Logger, +) (*FinalityProviderApp, error) { + fpStore, err := initStore(homePath, config) + if err != nil { + return nil, fmt.Errorf("failed to load store: %w", err) + } + + input := strings.NewReader("") + kr, err := fpkr.CreateKeyring( + config.BabylonConfig.KeyDirectory, + config.BabylonConfig.ChainID, + config.BabylonConfig.KeyringBackend, + input, + ) + if err != nil { + return nil, fmt.Errorf("failed to create keyring: %w", err) + } + + fpm, err := NewFinalityProviderManager(fpStore, config, cc, em, logger) + if err != nil { + return nil, fmt.Errorf("failed to create finality-provider manager: %w", err) + } + + return &FinalityProviderApp{ + cc: cc, + fps: fpStore, + kr: kr, + config: config, + logger: logger, + input: input, + fpManager: fpm, + eotsManager: em, + quit: make(chan struct{}), + sentQuit: make(chan struct{}), + eventQuit: make(chan struct{}), + createFinalityProviderRequestChan: make(chan *createFinalityProviderRequest), + registerFinalityProviderRequestChan: make(chan *registerFinalityProviderRequest), + finalityProviderRegisteredEventChan: make(chan *finalityProviderRegisteredEvent), + }, nil +} + +func initStore(homePath string, cfg *fpcfg.Config) (*fpstore.FinalityProviderStore, error) { + // Create the directory that will store the data + if err := util.MakeDirectory(fpcfg.DataDir(homePath)); err != nil { + return nil, err + } + + return fpstore.NewFinalityProviderStore(fpcfg.DBPath(homePath), cfg.DatabaseConfig.Name, cfg.DatabaseConfig.Backend) +} + +func (app *FinalityProviderApp) GetConfig() *fpcfg.Config { + return app.config +} + +func (app *FinalityProviderApp) GetFinalityProviderStore() *fpstore.FinalityProviderStore { + return app.fps +} + +func (app *FinalityProviderApp) GetKeyring() keyring.Keyring { + return app.kr +} + +func (app *FinalityProviderApp) GetInput() *strings.Reader { + return app.input +} + +func (app *FinalityProviderApp) ListFinalityProviderInstances() []*FinalityProviderInstance { + return app.fpManager.ListFinalityProviderInstances() +} + +// GetFinalityProviderInstance returns the finality-provider instance with the given Babylon public key +func (app *FinalityProviderApp) GetFinalityProviderInstance(fpPk *bbntypes.BIP340PubKey) (*FinalityProviderInstance, error) { + return app.fpManager.GetFinalityProviderInstance(fpPk) +} + +func (app *FinalityProviderApp) RegisterFinalityProvider(fpPkStr string) (*RegisterFinalityProviderResponse, error) { + fpPk, err := bbntypes.NewBIP340PubKeyFromHex(fpPkStr) + if err != nil { + return nil, err + } + + fp, err := app.fps.GetStoreFinalityProvider(fpPk.MustMarshal()) + if err != nil { + return nil, err + } + + if fp.Status != proto.FinalityProviderStatus_CREATED { + return nil, fmt.Errorf("finality-provider is already registered") + } + + btcSig, err := bbntypes.NewBIP340Signature(fp.Pop.BtcSig) + if err != nil { + return nil, err + } + + pop := &bstypes.ProofOfPossession{ + BabylonSig: fp.Pop.BabylonSig, + BtcSig: btcSig.MustMarshal(), + BtcSigType: bstypes.BTCSigType_BIP340, + } + + commissionRate, err := sdkmath.LegacyNewDecFromStr(fp.Commission) + if err != nil { + return nil, err + } + + request := ®isterFinalityProviderRequest{ + bbnPubKey: fp.GetBabylonPK(), + btcPubKey: fp.MustGetBIP340BTCPK(), + pop: pop, + description: fp.Description, + commission: &commissionRate, + errResponse: make(chan error, 1), + successResponse: make(chan *RegisterFinalityProviderResponse, 1), + } + + app.registerFinalityProviderRequestChan <- request + + select { + case err := <-request.errResponse: + return nil, err + case successResponse := <-request.successResponse: + return successResponse, nil + case <-app.quit: + return nil, fmt.Errorf("finality-provider app is shutting down") + } +} + +// StartHandlingFinalityProvider starts a finality-provider instance with the given Babylon public key +// Note: this should be called right after the finality-provider is registered +func (app *FinalityProviderApp) StartHandlingFinalityProvider(fpPk *bbntypes.BIP340PubKey, passphrase string) error { + return app.fpManager.StartFinalityProvider(fpPk, passphrase) +} + +// NOTE: this is not safe in production, so only used for testing purpose +func (app *FinalityProviderApp) getFpPrivKey(fpPk []byte) (*btcec.PrivateKey, error) { + record, err := app.eotsManager.KeyRecord(fpPk, "") + if err != nil { + return nil, err + } + + return record.PrivKey, nil +} + +// Start starts only the finality-provider daemon without any finality-provider instances +func (app *FinalityProviderApp) Start() error { + var startErr error + app.startOnce.Do(func() { + app.logger.Info("Starting FinalityProviderApp") + + app.eventWg.Add(1) + go app.eventLoop() + + app.sentWg.Add(1) + go app.registrationLoop() + }) + + return startErr +} + +func (app *FinalityProviderApp) Stop() error { + var stopErr error + app.stopOnce.Do(func() { + app.logger.Info("Stopping FinalityProviderApp") + + // Always stop the submission loop first to not generate additional events and actions + app.logger.Debug("Stopping submission loop") + close(app.quit) + app.wg.Wait() + + app.logger.Debug("Stopping finality providers") + if err := app.fpManager.Stop(); err != nil { + stopErr = err + return + } + + app.logger.Debug("Sent to Babylon loop stopped") + close(app.sentQuit) + app.sentWg.Wait() + + app.logger.Debug("Stopping main eventLoop") + close(app.eventQuit) + app.eventWg.Wait() + + // Closing db as last to avoid anybody to write do db + app.logger.Debug("Stopping data store") + if err := app.fps.Close(); err != nil { + stopErr = err + return + } + + app.logger.Debug("Stopping EOTS manager") + if err := app.eotsManager.Close(); err != nil { + stopErr = err + return + } + + app.logger.Debug("FinalityProviderApp successfully stopped") + + }) + return stopErr +} + +func (app *FinalityProviderApp) CreateFinalityProvider( + keyName, chainID, passPhrase, hdPath string, + description []byte, + commission *sdkmath.LegacyDec, +) (*CreateFinalityProviderResult, error) { + + req := &createFinalityProviderRequest{ + keyName: keyName, + chainID: chainID, + passPhrase: passPhrase, + hdPath: hdPath, + description: description, + commission: commission, + errResponse: make(chan error, 1), + successResponse: make(chan *createFinalityProviderResponse, 1), + } + + app.createFinalityProviderRequestChan <- req + + select { + case err := <-req.errResponse: + return nil, err + case successResponse := <-req.successResponse: + return &CreateFinalityProviderResult{ + FpPk: successResponse.FpPk, + }, nil + case <-app.quit: + return nil, fmt.Errorf("finality-provider app is shutting down") + } +} + +func (app *FinalityProviderApp) handleCreateFinalityProviderRequest(req *createFinalityProviderRequest) (*createFinalityProviderResponse, error) { + fpPkBytes, err := app.eotsManager.CreateKey(req.keyName, req.passPhrase, req.hdPath) + if err != nil { + return nil, err + } + + fpPk, err := bbntypes.NewBIP340PubKey(fpPkBytes) + if err != nil { + return nil, err + } + + kr, err := fpkr.NewChainKeyringControllerWithKeyring(app.kr, req.keyName, app.input) + if err != nil { + return nil, err + } + + keyPair, err := kr.CreateChainKey(req.passPhrase, req.hdPath) + if err != nil { + return nil, fmt.Errorf("failed to create chain key for the finality-provider: %w", err) + } + pk := &secp256k1.PubKey{Key: keyPair.PublicKey.SerializeCompressed()} + + fpRecord, err := app.eotsManager.KeyRecord(fpPk.MustMarshal(), req.passPhrase) + if err != nil { + return nil, fmt.Errorf("failed to get finality-provider record: %w", err) + } + + pop, err := kr.CreatePop(fpRecord.PrivKey, req.passPhrase) + if err != nil { + return nil, fmt.Errorf("failed to create proof-of-possession of the finality-provider: %w", err) + } + + fp := fpstore.NewStoreFinalityProvider(pk, fpPk, req.keyName, req.chainID, pop, req.description, req.commission) + + if err := app.fps.SaveFinalityProvider(fp); err != nil { + return nil, fmt.Errorf("failed to save finality-provider: %w", err) + } + + app.logger.Info("successfully created a finality-provider", + zap.String("btc_pk", fpPk.MarshalHex()), + zap.String("key_name", req.keyName), + ) + + return &createFinalityProviderResponse{ + FpPk: fpPk, + }, nil +} + +// main event loop for the finality-provider app +func (app *FinalityProviderApp) eventLoop() { + defer app.eventWg.Done() + + for { + select { + case req := <-app.createFinalityProviderRequestChan: + res, err := app.handleCreateFinalityProviderRequest(req) + if err != nil { + req.errResponse <- err + continue + } + + req.successResponse <- &createFinalityProviderResponse{FpPk: res.FpPk} + + case ev := <-app.finalityProviderRegisteredEventChan: + fpStored, err := app.fps.GetStoreFinalityProvider(ev.btcPubKey.MustMarshal()) + if err != nil { + // we always check if the finality-provider is in the DB before sending the registration request + app.logger.Fatal( + "registered finality-provider not found in DB", + zap.String("pk", ev.btcPubKey.MarshalHex()), + zap.Error(err), + ) + } + + // change the status of the finality-provider to registered + err = app.fps.SetFinalityProviderStatus(fpStored, proto.FinalityProviderStatus_REGISTERED) + if err != nil { + app.logger.Fatal("failed to set finality-provider status to REGISTERED", + zap.String("pk", ev.btcPubKey.MarshalHex()), + zap.Error(err), + ) + } + + // return to the caller + ev.successResponse <- &RegisterFinalityProviderResponse{ + bbnPubKey: fpStored.GetBabylonPK(), + btcPubKey: fpStored.MustGetBIP340BTCPK(), + TxHash: ev.txHash, + } + + case <-app.eventQuit: + app.logger.Debug("exiting main event loop") + return + } + } +} + +func (app *FinalityProviderApp) registrationLoop() { + defer app.sentWg.Done() + for { + select { + case req := <-app.registerFinalityProviderRequestChan: + // we won't do any retries here to not block the loop for more important messages. + // Most probably it fails due so some user error so we just return the error to the user. + // TODO: need to start passing context here to be able to cancel the request in case of app quiting + popBytes, err := req.pop.Marshal() + if err != nil { + req.errResponse <- err + continue + } + + res, err := app.cc.RegisterFinalityProvider( + req.bbnPubKey.Key, + req.btcPubKey.MustToBTCPK(), + popBytes, + req.commission, + req.description, + ) + + if err != nil { + app.logger.Error( + "failed to register finality-provider", + zap.String("pk", req.btcPubKey.MarshalHex()), + zap.Error(err), + ) + req.errResponse <- err + continue + } + + app.logger.Info( + "successfully registered finality-provider on babylon", + zap.String("btc_pk", req.btcPubKey.MarshalHex()), + zap.String("babylon_pk", hex.EncodeToString(req.bbnPubKey.Key)), + zap.String("txHash", res.TxHash), + ) + + app.finalityProviderRegisteredEventChan <- &finalityProviderRegisteredEvent{ + btcPubKey: req.btcPubKey, + bbnPubKey: req.bbnPubKey, + txHash: res.TxHash, + // pass the channel to the event so that we can send the response to the user which requested + // the registration + successResponse: req.successResponse, + } + case <-app.sentQuit: + app.logger.Debug("exiting registration loop") + return + } + } +} diff --git a/validator/service/app_test.go b/finality-provider/service/app_test.go similarity index 60% rename from validator/service/app_test.go rename to finality-provider/service/app_test.go index 1dee92ed..1852fcd9 100644 --- a/validator/service/app_test.go +++ b/finality-provider/service/app_test.go @@ -12,11 +12,11 @@ import ( "github.com/stretchr/testify/require" "go.uber.org/zap" - "github.com/babylonchain/btc-validator/eotsmanager" - "github.com/babylonchain/btc-validator/testutil" - "github.com/babylonchain/btc-validator/types" - "github.com/babylonchain/btc-validator/validator/proto" - "github.com/babylonchain/btc-validator/validator/service" + "github.com/babylonchain/finality-provider/eotsmanager" + "github.com/babylonchain/finality-provider/finality-provider/proto" + "github.com/babylonchain/finality-provider/finality-provider/service" + "github.com/babylonchain/finality-provider/testutil" + "github.com/babylonchain/finality-provider/types" ) var ( @@ -24,7 +24,7 @@ var ( hdPath = "" ) -func FuzzRegisterValidator(f *testing.F) { +func FuzzRegisterFinalityProvider(f *testing.F) { testutil.AddRandomSeedsToFuzzer(f, 10) f.Fuzz(func(t *testing.T, seed int64) { r := rand.New(rand.NewSource(seed)) @@ -47,14 +47,14 @@ func FuzzRegisterValidator(f *testing.F) { mockClientController.EXPECT().QueryLatestFinalizedBlocks(gomock.Any()).Return(nil, nil).AnyTimes() // Create randomized config - valHomeDir := filepath.Join(t.TempDir(), "val-home") - valCfg := testutil.GenValConfig(r, t, valHomeDir) - valCfg.PollerConfig.AutoChainScanningMode = false - valCfg.PollerConfig.StaticChainScanningStartHeight = randomStartingHeight - app, err := service.NewValidatorApp(valHomeDir, valCfg, mockClientController, em, logger) + fpHomeDir := filepath.Join(t.TempDir(), "fp-home") + fpCfg := testutil.GenFpConfig(r, t, fpHomeDir) + fpCfg.PollerConfig.AutoChainScanningMode = false + fpCfg.PollerConfig.StaticChainScanningStartHeight = randomStartingHeight + app, err := service.NewFinalityProviderApp(fpHomeDir, fpCfg, mockClientController, em, logger) require.NoError(t, err) defer func() { - err = os.RemoveAll(valHomeDir) + err = os.RemoveAll(fpHomeDir) require.NoError(t, err) }() @@ -65,13 +65,13 @@ func FuzzRegisterValidator(f *testing.F) { require.NoError(t, err) }() - // create a validator object and save it to db - validator := testutil.GenStoredValidator(r, t, app, passphrase, hdPath) + // create a finality-provider object and save it to db + fp := testutil.GenStoredFinalityProvider(r, t, app, passphrase, hdPath) btcSig := new(bbntypes.BIP340Signature) - err = btcSig.Unmarshal(validator.Pop.BtcSig) + err = btcSig.Unmarshal(fp.Pop.BtcSig) require.NoError(t, err) pop := &bstypes.ProofOfPossession{ - BabylonSig: validator.Pop.BabylonSig, + BabylonSig: fp.Pop.BabylonSig, BtcSig: btcSig.MustMarshal(), BtcSigType: bstypes.BTCSigType_BIP340, } @@ -80,23 +80,23 @@ func FuzzRegisterValidator(f *testing.F) { txHash := testutil.GenRandomHexStr(r, 32) mockClientController.EXPECT(). - RegisterValidator( - validator.GetBabylonPK().Key, - validator.MustGetBIP340BTCPK().MustToBTCPK(), + RegisterFinalityProvider( + fp.GetBabylonPK().Key, + fp.MustGetBIP340BTCPK().MustToBTCPK(), popBytes, testutil.ZeroCommissionRate(), testutil.EmptyDescription(), ).Return(&types.TxResponse{TxHash: txHash}, nil).AnyTimes() - res, err := app.RegisterValidator(validator.MustGetBIP340BTCPK().MarshalHex()) + res, err := app.RegisterFinalityProvider(fp.MustGetBIP340BTCPK().MarshalHex()) require.NoError(t, err) require.Equal(t, txHash, res.TxHash) - err = app.StartHandlingValidator(validator.MustGetBIP340BTCPK(), passphrase) + err = app.StartHandlingFinalityProvider(fp.MustGetBIP340BTCPK(), passphrase) require.NoError(t, err) - valAfterReg, err := app.GetValidatorInstance(validator.MustGetBIP340BTCPK()) + fpAfterReg, err := app.GetFinalityProviderInstance(fp.MustGetBIP340BTCPK()) require.NoError(t, err) - require.Equal(t, valAfterReg.GetStoreValidator().Status, proto.ValidatorStatus_REGISTERED) + require.Equal(t, fpAfterReg.GetStoreFinalityProvider().Status, proto.FinalityProviderStatus_REGISTERED) }) } diff --git a/validator/service/chain_poller.go b/finality-provider/service/chain_poller.go similarity index 97% rename from validator/service/chain_poller.go rename to finality-provider/service/chain_poller.go index 51b3c137..856a6d45 100644 --- a/validator/service/chain_poller.go +++ b/finality-provider/service/chain_poller.go @@ -8,9 +8,9 @@ import ( "github.com/avast/retry-go/v4" "go.uber.org/zap" - "github.com/babylonchain/btc-validator/clientcontroller" - "github.com/babylonchain/btc-validator/types" - cfg "github.com/babylonchain/btc-validator/validator/config" + "github.com/babylonchain/finality-provider/clientcontroller" + cfg "github.com/babylonchain/finality-provider/finality-provider/config" + "github.com/babylonchain/finality-provider/types" ) var ( diff --git a/finality-provider/service/client/rpcclient.go b/finality-provider/service/client/rpcclient.go new file mode 100644 index 00000000..afd68858 --- /dev/null +++ b/finality-provider/service/client/rpcclient.go @@ -0,0 +1,122 @@ +package client + +import ( + "context" + "fmt" + + sdkmath "cosmossdk.io/math" + bbntypes "github.com/babylonchain/babylon/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + + "github.com/babylonchain/finality-provider/finality-provider/proto" +) + +type FinalityProviderServiceGRpcClient struct { + client proto.FinalityProvidersClient +} + +func NewFinalityProviderServiceGRpcClient(remoteAddr string) (*FinalityProviderServiceGRpcClient, func(), error) { + conn, err := grpc.Dial(remoteAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + return nil, nil, fmt.Errorf("failed to build gRPC connection to %s: %w", remoteAddr, err) + } + + cleanUp := func() { + conn.Close() + } + + return &FinalityProviderServiceGRpcClient{ + client: proto.NewFinalityProvidersClient(conn), + }, cleanUp, nil +} + +func (c *FinalityProviderServiceGRpcClient) GetInfo(ctx context.Context) (*proto.GetInfoResponse, error) { + req := &proto.GetInfoRequest{} + res, err := c.client.GetInfo(ctx, req) + if err != nil { + return nil, err + } + + return res, nil +} + +func (c *FinalityProviderServiceGRpcClient) RegisterFinalityProvider( + ctx context.Context, + fpPk *bbntypes.BIP340PubKey, + passphrase string, +) (*proto.RegisterFinalityProviderResponse, error) { + + req := &proto.RegisterFinalityProviderRequest{BtcPk: fpPk.MarshalHex(), Passphrase: passphrase} + res, err := c.client.RegisterFinalityProvider(ctx, req) + if err != nil { + return nil, err + } + + return res, nil +} + +func (c *FinalityProviderServiceGRpcClient) CreateFinalityProvider( + ctx context.Context, + keyName, chainID, passphrase, hdPath string, + description types.Description, + commission *sdkmath.LegacyDec, +) (*proto.CreateFinalityProviderResponse, error) { + + descBytes, err := description.Marshal() + if err != nil { + return nil, err + } + + req := &proto.CreateFinalityProviderRequest{ + KeyName: keyName, + ChainId: chainID, + Passphrase: passphrase, + HdPath: hdPath, + Description: descBytes, + Commission: commission.String(), + } + + res, err := c.client.CreateFinalityProvider(ctx, req) + if err != nil { + return nil, err + } + + return res, nil +} + +func (c *FinalityProviderServiceGRpcClient) AddFinalitySignature(ctx context.Context, fpPk string, height uint64, lch []byte) (*proto.AddFinalitySignatureResponse, error) { + req := &proto.AddFinalitySignatureRequest{ + BtcPk: fpPk, + Height: height, + AppHash: lch, + } + + res, err := c.client.AddFinalitySignature(ctx, req) + if err != nil { + return nil, err + } + + return res, nil +} + +func (c *FinalityProviderServiceGRpcClient) QueryFinalityProviderList(ctx context.Context) (*proto.QueryFinalityProviderListResponse, error) { + req := &proto.QueryFinalityProviderListRequest{} + res, err := c.client.QueryFinalityProviderList(ctx, req) + if err != nil { + return nil, err + } + + return res, nil +} + +func (c *FinalityProviderServiceGRpcClient) QueryFinalityProviderInfo(ctx context.Context, fpPk *bbntypes.BIP340PubKey) (*proto.QueryFinalityProviderResponse, error) { + req := &proto.QueryFinalityProviderRequest{BtcPk: fpPk.MarshalHex()} + res, err := c.client.QueryFinalityProvider(ctx, req) + if err != nil { + return nil, err + } + + return res, nil +} diff --git a/validator/service/fastsync.go b/finality-provider/service/fastsync.go similarity index 74% rename from validator/service/fastsync.go rename to finality-provider/service/fastsync.go index 0a7e7c82..d070109a 100644 --- a/validator/service/fastsync.go +++ b/finality-provider/service/fastsync.go @@ -5,7 +5,7 @@ import ( "go.uber.org/zap" - "github.com/babylonchain/btc-validator/types" + "github.com/babylonchain/finality-provider/types" ) type FastSyncResult struct { @@ -17,11 +17,11 @@ type FastSyncResult struct { // FastSync attempts to send a batch of finality signatures // from the maximum of the last voted height and the last finalized height // to the current height -func (v *ValidatorInstance) FastSync(startHeight, endHeight uint64) (*FastSyncResult, error) { - if v.inSync.Swap(true) { - return nil, fmt.Errorf("the validator has already been in fast sync") +func (fp *FinalityProviderInstance) FastSync(startHeight, endHeight uint64) (*FastSyncResult, error) { + if fp.inSync.Swap(true) { + return nil, fmt.Errorf("the finality-provider has already been in fast sync") } - defer v.inSync.Store(false) + defer fp.inSync.Store(false) if startHeight > endHeight { return nil, fmt.Errorf("the start height %v should not be higher than the end height %v", @@ -33,7 +33,7 @@ func (v *ValidatorInstance) FastSync(startHeight, endHeight uint64) (*FastSyncRe // we may need several rounds to catch-up as we need to limit // the catch-up distance for each round to avoid memory overflow for startHeight <= endHeight { - blocks, err := v.cc.QueryBlocks(startHeight, endHeight, v.cfg.FastSyncLimit) + blocks, err := fp.cc.QueryBlocks(startHeight, endHeight, fp.cfg.FastSyncLimit) if err != nil { return nil, err } @@ -49,7 +49,7 @@ func (v *ValidatorInstance) FastSync(startHeight, endHeight uint64) (*FastSyncRe // have gaps during sync catchUpBlocks := make([]*types.BlockInfo, 0, len(blocks)) for _, b := range blocks { - should, err := v.shouldSubmitFinalitySignature(b) + should, err := fp.shouldSubmitFinalitySignature(b) if err != nil { // stop catch-up when critical errors occur return nil, err @@ -71,22 +71,22 @@ func (v *ValidatorInstance) FastSync(startHeight, endHeight uint64) (*FastSyncRe syncedHeight = catchUpBlocks[len(catchUpBlocks)-1].Height - res, err := v.SubmitBatchFinalitySignatures(catchUpBlocks) + res, err := fp.SubmitBatchFinalitySignatures(catchUpBlocks) if err != nil { return nil, err } responses = append(responses, res) - v.logger.Debug( - "the validator is catching up by sending finality signatures in a batch", - zap.String("pk", v.GetBtcPkHex()), + fp.logger.Debug( + "the finality-provider is catching up by sending finality signatures in a batch", + zap.String("pk", fp.GetBtcPkHex()), zap.Uint64("start_height", catchUpBlocks[0].Height), zap.Uint64("synced_height", syncedHeight), ) } - v.MustSetLastProcessedHeight(endHeight) + fp.MustSetLastProcessedHeight(endHeight) return &FastSyncResult{ Responses: responses, diff --git a/validator/service/fastsync_test.go b/finality-provider/service/fastsync_test.go similarity index 66% rename from validator/service/fastsync_test.go rename to finality-provider/service/fastsync_test.go index 74d43bb9..a0ca1583 100644 --- a/validator/service/fastsync_test.go +++ b/finality-provider/service/fastsync_test.go @@ -7,8 +7,8 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" - "github.com/babylonchain/btc-validator/testutil" - "github.com/babylonchain/btc-validator/types" + "github.com/babylonchain/finality-provider/testutil" + "github.com/babylonchain/finality-provider/types" ) func FuzzFastSync(f *testing.F) { @@ -21,20 +21,20 @@ func FuzzFastSync(f *testing.F) { currentHeight := finalizedHeight + uint64(r.Int63n(10)+1) startingBlock := &types.BlockInfo{Height: randomStartingHeight, Hash: testutil.GenRandomByteArray(r, 32)} mockClientController := testutil.PrepareMockedClientController(t, r, randomStartingHeight, currentHeight, &types.StakingParams{}) - app, storeValidator, cleanUp := startValidatorAppWithRegisteredValidator(t, r, mockClientController, randomStartingHeight) + app, storeFp, cleanUp := startFinalityProviderAppWithRegisteredFp(t, r, mockClientController, randomStartingHeight) defer cleanUp() - valIns, err := app.GetValidatorInstance(storeValidator.MustGetBIP340BTCPK()) + fpIns, err := app.GetFinalityProviderInstance(storeFp.MustGetBIP340BTCPK()) require.NoError(t, err) // commit public randomness expectedTxHash := testutil.GenRandomHexStr(r, 32) mockClientController.EXPECT(). - CommitPubRandList(valIns.MustGetBtcPk(), startingBlock.Height+1, gomock.Any(), gomock.Any()). + CommitPubRandList(fpIns.MustGetBtcPk(), startingBlock.Height+1, gomock.Any(), gomock.Any()). Return(&types.TxResponse{TxHash: expectedTxHash}, nil).AnyTimes() - res, err := valIns.CommitPubRand(startingBlock) + res, err := fpIns.CommitPubRand(startingBlock) require.NoError(t, err) require.Equal(t, expectedTxHash, res.TxHash) - mockClientController.EXPECT().QueryValidatorVotingPower(storeValidator.MustGetBTCPK(), gomock.Any()). + mockClientController.EXPECT().QueryFinalityProviderVotingPower(storeFp.MustGetBTCPK(), gomock.Any()). Return(uint64(1), nil).AnyTimes() // fast sync @@ -44,13 +44,13 @@ func FuzzFastSync(f *testing.F) { mockClientController.EXPECT().QueryLatestFinalizedBlocks(uint64(1)).Return([]*types.BlockInfo{finalizedBlock}, nil).AnyTimes() mockClientController.EXPECT().QueryBlocks(finalizedHeight+1, currentHeight, uint64(10)). Return(catchUpBlocks, nil) - mockClientController.EXPECT().SubmitBatchFinalitySigs(valIns.MustGetBtcPk(), catchUpBlocks, gomock.Any()). + mockClientController.EXPECT().SubmitBatchFinalitySigs(fpIns.MustGetBtcPk(), catchUpBlocks, gomock.Any()). Return(&types.TxResponse{TxHash: expectedTxHash}, nil).AnyTimes() - result, err := valIns.FastSync(finalizedHeight+1, currentHeight) + result, err := fpIns.FastSync(finalizedHeight+1, currentHeight) require.NoError(t, err) require.NotNil(t, result) require.Equal(t, expectedTxHash, result.Responses[0].TxHash) - require.Equal(t, currentHeight, valIns.GetLastVotedHeight()) - require.Equal(t, currentHeight, valIns.GetLastProcessedHeight()) + require.Equal(t, currentHeight, fpIns.GetLastVotedHeight()) + require.Equal(t, currentHeight, fpIns.GetLastProcessedHeight()) }) } diff --git a/validator/service/validator_instance.go b/finality-provider/service/fp_instance.go similarity index 54% rename from validator/service/validator_instance.go rename to finality-provider/service/fp_instance.go index 7ec9322d..ce9f74b5 100644 --- a/validator/service/validator_instance.go +++ b/finality-provider/service/fp_instance.go @@ -17,20 +17,20 @@ import ( "go.uber.org/atomic" "go.uber.org/zap" - "github.com/babylonchain/btc-validator/clientcontroller" - "github.com/babylonchain/btc-validator/eotsmanager" - "github.com/babylonchain/btc-validator/types" - valcfg "github.com/babylonchain/btc-validator/validator/config" - "github.com/babylonchain/btc-validator/validator/proto" - valstore "github.com/babylonchain/btc-validator/validator/store" + "github.com/babylonchain/finality-provider/clientcontroller" + "github.com/babylonchain/finality-provider/eotsmanager" + fpcfg "github.com/babylonchain/finality-provider/finality-provider/config" + "github.com/babylonchain/finality-provider/finality-provider/proto" + fpstore "github.com/babylonchain/finality-provider/finality-provider/store" + "github.com/babylonchain/finality-provider/types" ) -type ValidatorInstance struct { +type FinalityProviderInstance struct { bbnPk *secp256k1.PubKey btcPk *bbntypes.BIP340PubKey - state *valState - cfg *valcfg.Config + state *fpState + cfg *fpcfg.Config logger *zap.Logger em eotsmanager.EOTSManager @@ -51,34 +51,34 @@ type ValidatorInstance struct { quit chan struct{} } -// NewValidatorInstance returns a ValidatorInstance instance with the given Babylon public key -// the validator should be registered before -func NewValidatorInstance( - valPk *bbntypes.BIP340PubKey, - cfg *valcfg.Config, - s *valstore.ValidatorStore, +// NewFinalityProviderInstance returns a FinalityProviderInstance instance with the given Babylon public key +// the finality-provider should be registered before +func NewFinalityProviderInstance( + fpPk *bbntypes.BIP340PubKey, + cfg *fpcfg.Config, + s *fpstore.FinalityProviderStore, cc clientcontroller.ClientController, em eotsmanager.EOTSManager, passphrase string, errChan chan<- *CriticalError, logger *zap.Logger, -) (*ValidatorInstance, error) { - v, err := s.GetStoreValidator(valPk.MustMarshal()) +) (*FinalityProviderInstance, error) { + sfp, err := s.GetStoreFinalityProvider(fpPk.MustMarshal()) if err != nil { - return nil, fmt.Errorf("failed to retrive the validator %s from DB: %w", v.GetBabylonPkHexString(), err) + return nil, fmt.Errorf("failed to retrive the finality-provider %s from DB: %w", sfp.GetBabylonPkHexString(), err) } - // ensure the validator has been registered - if v.Status < proto.ValidatorStatus_REGISTERED { - return nil, fmt.Errorf("the validator %s has not been registered", v.KeyName) + // ensure the finality-provider has been registered + if sfp.Status < proto.FinalityProviderStatus_REGISTERED { + return nil, fmt.Errorf("the finality-provider %s has not been registered", sfp.KeyName) } - return &ValidatorInstance{ - btcPk: v.MustGetBIP340BTCPK(), - bbnPk: v.GetBabylonPK(), - state: &valState{ - v: v, - s: s, + return &FinalityProviderInstance{ + btcPk: sfp.MustGetBIP340BTCPK(), + bbnPk: sfp.GetBabylonPK(), + state: &fpState{ + fp: sfp, + s: s, }, cfg: cfg, logger: logger, @@ -92,57 +92,57 @@ func NewValidatorInstance( }, nil } -func (v *ValidatorInstance) Start() error { - if v.isStarted.Swap(true) { - return fmt.Errorf("the validator instance %s is already started", v.GetBtcPkHex()) +func (fp *FinalityProviderInstance) Start() error { + if fp.isStarted.Swap(true) { + return fmt.Errorf("the finality-provider instance %s is already started", fp.GetBtcPkHex()) } - v.logger.Info("Starting validator instance", zap.String("pk", v.GetBtcPkHex())) + fp.logger.Info("Starting finality-provider instance", zap.String("pk", fp.GetBtcPkHex())) - startHeight, err := v.bootstrap() + startHeight, err := fp.bootstrap() if err != nil { - return fmt.Errorf("failed to bootstrap the validator %s: %w", v.GetBtcPkHex(), err) + return fmt.Errorf("failed to bootstrap the finality-provider %s: %w", fp.GetBtcPkHex(), err) } - v.logger.Info("the validator %s has been bootstrapped", - zap.String("pk", v.GetBtcPkHex()), zap.Uint64("height", startHeight)) + fp.logger.Info("the finality-provider %s has been bootstrapped", + zap.String("pk", fp.GetBtcPkHex()), zap.Uint64("height", startHeight)) - poller := NewChainPoller(v.logger, v.cfg.PollerConfig, v.cc) + poller := NewChainPoller(fp.logger, fp.cfg.PollerConfig, fp.cc) if err := poller.Start(startHeight + 1); err != nil { return fmt.Errorf("failed to start the poller: %w", err) } - v.poller = poller + fp.poller = poller - v.laggingTargetChan = make(chan *types.BlockInfo, 1) + fp.laggingTargetChan = make(chan *types.BlockInfo, 1) - v.quit = make(chan struct{}) + fp.quit = make(chan struct{}) - v.wg.Add(1) - go v.finalitySigSubmissionLoop() - v.wg.Add(1) - go v.randomnessCommitmentLoop() - v.wg.Add(1) - go v.checkLaggingLoop() + fp.wg.Add(1) + go fp.finalitySigSubmissionLoop() + fp.wg.Add(1) + go fp.randomnessCommitmentLoop() + fp.wg.Add(1) + go fp.checkLaggingLoop() return nil } -func (v *ValidatorInstance) bootstrap() (uint64, error) { - latestBlock, err := v.getLatestBlockWithRetry() +func (fp *FinalityProviderInstance) bootstrap() (uint64, error) { + latestBlock, err := fp.getLatestBlockWithRetry() if err != nil { return 0, err } - if v.checkLagging(latestBlock) { - _, err := v.tryFastSync(latestBlock) + if fp.checkLagging(latestBlock) { + _, err := fp.tryFastSync(latestBlock) if err != nil { return 0, err } } - startHeight, err := v.getPollerStartingHeight() + startHeight, err := fp.getPollerStartingHeight() if err != nil { return 0, err } @@ -150,222 +150,222 @@ func (v *ValidatorInstance) bootstrap() (uint64, error) { return startHeight, nil } -func (v *ValidatorInstance) Stop() error { - if !v.isStarted.Swap(false) { - return fmt.Errorf("the validator %s has already stopped", v.GetBtcPkHex()) +func (fp *FinalityProviderInstance) Stop() error { + if !fp.isStarted.Swap(false) { + return fmt.Errorf("the finality-provider %s has already stopped", fp.GetBtcPkHex()) } - if err := v.poller.Stop(); err != nil { + if err := fp.poller.Stop(); err != nil { return fmt.Errorf("failed to stop the poller: %w", err) } - v.logger.Info("stopping validator instance", zap.String("pk", v.GetBtcPkHex())) + fp.logger.Info("stopping finality-provider instance", zap.String("pk", fp.GetBtcPkHex())) - close(v.quit) - v.wg.Wait() + close(fp.quit) + fp.wg.Wait() - v.logger.Info("the validator instance %s is successfully stopped", zap.String("pk", v.GetBtcPkHex())) + fp.logger.Info("the finality-provider instance %s is successfully stopped", zap.String("pk", fp.GetBtcPkHex())) return nil } -func (v *ValidatorInstance) IsRunning() bool { - return v.isStarted.Load() +func (fp *FinalityProviderInstance) IsRunning() bool { + return fp.isStarted.Load() } -func (v *ValidatorInstance) finalitySigSubmissionLoop() { - defer v.wg.Done() +func (fp *FinalityProviderInstance) finalitySigSubmissionLoop() { + defer fp.wg.Done() for { select { - case b := <-v.poller.GetBlockInfoChan(): - v.logger.Debug( - "the validator received a new block, start processing", - zap.String("pk", v.GetBtcPkHex()), + case b := <-fp.poller.GetBlockInfoChan(): + fp.logger.Debug( + "the finality-provider received a new block, start processing", + zap.String("pk", fp.GetBtcPkHex()), zap.Uint64("height", b.Height), ) - if b.Height <= v.GetLastProcessedHeight() { - v.logger.Debug( + if b.Height <= fp.GetLastProcessedHeight() { + fp.logger.Debug( "the block has been processed before, skip processing", zap.Uint64("height", b.Height), - zap.Uint64("last_processed_height", v.GetLastProcessedHeight()), - zap.Uint64("last_voted_height", v.GetLastVotedHeight()), + zap.Uint64("last_processed_height", fp.GetLastProcessedHeight()), + zap.Uint64("last_voted_height", fp.GetLastVotedHeight()), ) continue } // use the copy of the block to avoid the impact to other receivers nextBlock := *b - should, err := v.shouldSubmitFinalitySignature(&nextBlock) + should, err := fp.shouldSubmitFinalitySignature(&nextBlock) if err != nil { - v.reportCriticalErr(err) + fp.reportCriticalErr(err) continue } if !should { - v.MustSetLastProcessedHeight(nextBlock.Height) + fp.MustSetLastProcessedHeight(nextBlock.Height) continue } - res, err := v.retrySubmitFinalitySignatureUntilBlockFinalized(&nextBlock) + res, err := fp.retrySubmitFinalitySignatureUntilBlockFinalized(&nextBlock) if err != nil { - v.reportCriticalErr(err) + fp.reportCriticalErr(err) continue } if res == nil { - v.reportCriticalErr(fmt.Errorf("received an empty response when submitting finality sig")) + fp.reportCriticalErr(fmt.Errorf("received an empty response when submitting finality sig")) continue } - v.logger.Info( + fp.logger.Info( "successfully submitted a finality signature to the consumer chain", - zap.String("pk", v.GetBtcPkHex()), + zap.String("pk", fp.GetBtcPkHex()), zap.Uint64("height", b.Height), zap.String("tx_hash", res.TxHash), ) - case targetBlock := <-v.laggingTargetChan: - res, err := v.tryFastSync(targetBlock) - v.isLagging.Store(false) + case targetBlock := <-fp.laggingTargetChan: + res, err := fp.tryFastSync(targetBlock) + fp.isLagging.Store(false) if err != nil { - if errors.Is(err, bstypes.ErrBTCValAlreadySlashed) { - v.reportCriticalErr(err) + if errors.Is(err, bstypes.ErrFpAlreadySlashed) { + fp.reportCriticalErr(err) continue } - v.logger.Debug( + fp.logger.Debug( "failed to sync up, will try again later", - zap.String("pk", v.GetBtcPkHex()), + zap.String("pk", fp.GetBtcPkHex()), zap.Error(err), ) continue } // response might be nil if sync is not needed if res != nil { - v.logger.Info( + fp.logger.Info( "fast sync is finished", - zap.String("pk", v.GetBtcPkHex()), + zap.String("pk", fp.GetBtcPkHex()), zap.Uint64("synced_height", res.SyncedHeight), zap.Uint64("last_processed_height", res.LastProcessedHeight), ) // set the poller to fetch blocks that have not been processed - v.poller.SetNextHeightAndClearBuffer(v.GetLastProcessedHeight() + 1) + fp.poller.SetNextHeightAndClearBuffer(fp.GetLastProcessedHeight() + 1) } - case <-v.quit: - v.logger.Info("the finality signature submission loop is closing") + case <-fp.quit: + fp.logger.Info("the finality signature submission loop is closing") return } } } -func (v *ValidatorInstance) randomnessCommitmentLoop() { - defer v.wg.Done() +func (fp *FinalityProviderInstance) randomnessCommitmentLoop() { + defer fp.wg.Done() - commitRandTicker := time.NewTicker(v.cfg.RandomnessCommitInterval) + commitRandTicker := time.NewTicker(fp.cfg.RandomnessCommitInterval) defer commitRandTicker.Stop() for { select { case <-commitRandTicker.C: - tipBlock, err := v.getLatestBlockWithRetry() + tipBlock, err := fp.getLatestBlockWithRetry() if err != nil { - v.reportCriticalErr(err) + fp.reportCriticalErr(err) continue } - txRes, err := v.retryCommitPubRandUntilBlockFinalized(tipBlock) + txRes, err := fp.retryCommitPubRandUntilBlockFinalized(tipBlock) if err != nil { - v.reportCriticalErr(err) + fp.reportCriticalErr(err) continue } // txRes could be nil if no need to commit more randomness if txRes != nil { - v.logger.Info( + fp.logger.Info( "successfully committed public randomness to the consumer chain", - zap.String("pk", v.GetBtcPkHex()), - zap.Uint64("last_committed_height", v.GetLastCommittedHeight()), + zap.String("pk", fp.GetBtcPkHex()), + zap.Uint64("last_committed_height", fp.GetLastCommittedHeight()), zap.String("tx_hash", txRes.TxHash), ) } - case <-v.quit: - v.logger.Info("the randomness commitment loop is closing") + case <-fp.quit: + fp.logger.Info("the randomness commitment loop is closing") return } } } -func (v *ValidatorInstance) checkLaggingLoop() { - defer v.wg.Done() +func (fp *FinalityProviderInstance) checkLaggingLoop() { + defer fp.wg.Done() - if v.cfg.FastSyncInterval == 0 { - v.logger.Info("the fast sync is disabled") + if fp.cfg.FastSyncInterval == 0 { + fp.logger.Info("the fast sync is disabled") return } - fastSyncTicker := time.NewTicker(v.cfg.FastSyncInterval) + fastSyncTicker := time.NewTicker(fp.cfg.FastSyncInterval) defer fastSyncTicker.Stop() for { select { case <-fastSyncTicker.C: - if v.isLagging.Load() { + if fp.isLagging.Load() { // we are in fast sync mode, skip do not do checks continue } - latestBlock, err := v.getLatestBlockWithRetry() + latestBlock, err := fp.getLatestBlockWithRetry() if err != nil { - v.logger.Debug( + fp.logger.Debug( "failed to get the latest block of the consumer chain", - zap.String("pk", v.GetBtcPkHex()), + zap.String("pk", fp.GetBtcPkHex()), zap.Error(err), ) continue } - if v.checkLagging(latestBlock) { - v.isLagging.Store(true) - v.laggingTargetChan <- latestBlock + if fp.checkLagging(latestBlock) { + fp.isLagging.Store(true) + fp.laggingTargetChan <- latestBlock } - case <-v.quit: - v.logger.Debug("the fast sync loop is closing") + case <-fp.quit: + fp.logger.Debug("the fast sync loop is closing") return } } } -func (v *ValidatorInstance) tryFastSync(targetBlock *types.BlockInfo) (*FastSyncResult, error) { - if v.inSync.Load() { - return nil, fmt.Errorf("the validator %s is already in sync", v.GetBtcPkHex()) +func (fp *FinalityProviderInstance) tryFastSync(targetBlock *types.BlockInfo) (*FastSyncResult, error) { + if fp.inSync.Load() { + return nil, fmt.Errorf("the finality-provider %s is already in sync", fp.GetBtcPkHex()) } - if v.GetLastCommittedHeight() <= v.GetLastVotedHeight() { - if err := v.SetLastProcessedHeight(targetBlock.Height); err != nil { + if fp.GetLastCommittedHeight() <= fp.GetLastVotedHeight() { + if err := fp.SetLastProcessedHeight(targetBlock.Height); err != nil { return nil, err } - v.logger.Debug( + fp.logger.Debug( "insufficient public randomness, jumping to the latest block", - zap.String("pk", v.GetBtcPkHex()), + zap.String("pk", fp.GetBtcPkHex()), zap.Uint64("target_height", targetBlock.Height), ) return nil, nil } // get the last finalized height - lastFinalizedBlocks, err := v.cc.QueryLatestFinalizedBlocks(1) + lastFinalizedBlocks, err := fp.cc.QueryLatestFinalizedBlocks(1) if err != nil { return nil, err } if lastFinalizedBlocks == nil { - v.logger.Debug( + fp.logger.Debug( "no finalized blocks yet, no need to catch up", - zap.String("pk", v.GetBtcPkHex()), + zap.String("pk", fp.GetBtcPkHex()), zap.Uint64("height", targetBlock.Height), ) return nil, nil } lastFinalizedHeight := lastFinalizedBlocks[0].Height - lastProcessedHeight := v.GetLastProcessedHeight() + lastProcessedHeight := fp.GetLastProcessedHeight() // get the startHeight from the maximum of the lastVotedHeight and // the lastFinalizedHeight plus 1 @@ -380,49 +380,49 @@ func (v *ValidatorInstance) tryFastSync(targetBlock *types.BlockInfo) (*FastSync return nil, fmt.Errorf("the start height %v should not be higher than the current block %v", startHeight, targetBlock.Height) } - v.logger.Debug("the validator is entering fast sync") + fp.logger.Debug("the finality-provider is entering fast sync") - return v.FastSync(startHeight, targetBlock.Height) + return fp.FastSync(startHeight, targetBlock.Height) } // shouldSubmitFinalitySignature checks all the conditions that a finality should not be sent: -// 1. the validator does not have voting power on the given block -// 2. the last committed height is lower than the block height as this indicates the validator +// 1. the finality-provider does not have voting power on the given block +// 2. the last committed height is lower than the block height as this indicates the finality-provider // does not have the corresponding public randomness -// 3. the block height is lower than the last voted height as this indicates that the validator +// 3. the block height is lower than the last voted height as this indicates that the finality-provider // does not need to send finality signature over this block -func (v *ValidatorInstance) shouldSubmitFinalitySignature(b *types.BlockInfo) (bool, error) { +func (fp *FinalityProviderInstance) shouldSubmitFinalitySignature(b *types.BlockInfo) (bool, error) { // check last voted height - if v.GetLastVotedHeight() >= b.Height { - v.logger.Debug( + if fp.GetLastVotedHeight() >= b.Height { + fp.logger.Debug( "the block has been voted before, skip voting", - zap.String("pk", v.GetBtcPkHex()), + zap.String("pk", fp.GetBtcPkHex()), zap.Uint64("block_height", b.Height), - zap.Uint64("last_voted_height", v.GetLastVotedHeight()), + zap.Uint64("last_voted_height", fp.GetLastVotedHeight()), ) return false, nil } // check last committed height - if v.GetLastCommittedHeight() < b.Height { - v.logger.Debug( + if fp.GetLastCommittedHeight() < b.Height { + fp.logger.Debug( "public rand is not committed, skip voting", - zap.String("pk", v.GetBtcPkHex()), + zap.String("pk", fp.GetBtcPkHex()), zap.Uint64("block_height", b.Height), - zap.Uint64("last_committed_height", v.GetLastCommittedHeight()), + zap.Uint64("last_committed_height", fp.GetLastCommittedHeight()), ) return false, nil } - power, err := v.GetVotingPowerWithRetry(b.Height) + power, err := fp.GetVotingPowerWithRetry(b.Height) if err != nil { return false, err } if power == 0 { - v.logger.Debug( - "the validator does not have voting power, skip voting", - zap.String("pk", v.GetBtcPkHex()), + fp.logger.Debug( + "the finality-provider does not have voting power, skip voting", + zap.String("pk", fp.GetBtcPkHex()), zap.Uint64("block_height", b.Height), ) return false, nil @@ -431,42 +431,42 @@ func (v *ValidatorInstance) shouldSubmitFinalitySignature(b *types.BlockInfo) (b return true, nil } -func (v *ValidatorInstance) reportCriticalErr(err error) { - v.criticalErrChan <- &CriticalError{ - err: err, - valBtcPk: v.GetBtcPkBIP340(), +func (fp *FinalityProviderInstance) reportCriticalErr(err error) { + fp.criticalErrChan <- &CriticalError{ + err: err, + fpBtcPk: fp.GetBtcPkBIP340(), } } // checkLagging returns true if the lasted voted height is behind by a configured gap -func (v *ValidatorInstance) checkLagging(currentBlock *types.BlockInfo) bool { - return currentBlock.Height >= v.GetLastProcessedHeight()+v.cfg.FastSyncGap +func (fp *FinalityProviderInstance) checkLagging(currentBlock *types.BlockInfo) bool { + return currentBlock.Height >= fp.GetLastProcessedHeight()+fp.cfg.FastSyncGap } // retrySubmitFinalitySignatureUntilBlockFinalized periodically tries to submit finality signature until success or the block is finalized // error will be returned if maximum retries have been reached or the query to the consumer chain fails -func (v *ValidatorInstance) retrySubmitFinalitySignatureUntilBlockFinalized(targetBlock *types.BlockInfo) (*types.TxResponse, error) { +func (fp *FinalityProviderInstance) retrySubmitFinalitySignatureUntilBlockFinalized(targetBlock *types.BlockInfo) (*types.TxResponse, error) { var failedCycles uint32 // we break the for loop if the block is finalized or the signature is successfully submitted // error will be returned if maximum retries have been reached or the query to the consumer chain fails for { // error will be returned if max retries have been reached - res, err := v.SubmitFinalitySignature(targetBlock) + res, err := fp.SubmitFinalitySignature(targetBlock) if err != nil { if clientcontroller.IsUnrecoverable(err) { return nil, err } - v.logger.Debug( + fp.logger.Debug( "failed to submit finality signature to the consumer chain", - zap.String("pk", v.GetBtcPkHex()), + zap.String("pk", fp.GetBtcPkHex()), zap.Uint32("current_failures", failedCycles), zap.Uint64("target_block_height", targetBlock.Height), zap.Error(err), ) failedCycles += 1 - if failedCycles > uint32(v.cfg.MaxSubmissionRetries) { + if failedCycles > uint32(fp.cfg.MaxSubmissionRetries) { return nil, fmt.Errorf("reached max failed cycles with err: %w", err) } } else { @@ -474,30 +474,30 @@ func (v *ValidatorInstance) retrySubmitFinalitySignatureUntilBlockFinalized(targ return res, nil } select { - case <-time.After(v.cfg.SubmissionRetryInterval): + case <-time.After(fp.cfg.SubmissionRetryInterval): // periodically query the index block to be later checked whether it is Finalized - finalized, err := v.checkBlockFinalization(targetBlock.Height) + finalized, err := fp.checkBlockFinalization(targetBlock.Height) if err != nil { return nil, fmt.Errorf("failed to query block finalization at height %v: %w", targetBlock.Height, err) } if finalized { - v.logger.Debug( + fp.logger.Debug( "the block is already finalized, skip submission", - zap.String("pk", v.GetBtcPkHex()), + zap.String("pk", fp.GetBtcPkHex()), zap.Uint64("target_height", targetBlock.Height), ) return nil, nil } - case <-v.quit: - v.logger.Debug("the validator instance is closing", zap.String("pk", v.GetBtcPkHex())) + case <-fp.quit: + fp.logger.Debug("the finality-provider instance is closing", zap.String("pk", fp.GetBtcPkHex())) return nil, nil } } } -func (v *ValidatorInstance) checkBlockFinalization(height uint64) (bool, error) { - b, err := v.cc.QueryBlock(height) +func (fp *FinalityProviderInstance) checkBlockFinalization(height uint64) (bool, error) { + b, err := fp.cc.QueryBlock(height) if err != nil { return false, err } @@ -507,28 +507,28 @@ func (v *ValidatorInstance) checkBlockFinalization(height uint64) (bool, error) // retryCommitPubRandUntilBlockFinalized periodically tries to commit public rand until success or the block is finalized // error will be returned if maximum retries have been reached or the query to the consumer chain fails -func (v *ValidatorInstance) retryCommitPubRandUntilBlockFinalized(targetBlock *types.BlockInfo) (*types.TxResponse, error) { +func (fp *FinalityProviderInstance) retryCommitPubRandUntilBlockFinalized(targetBlock *types.BlockInfo) (*types.TxResponse, error) { var failedCycles uint32 // we break the for loop if the block is finalized or the public rand is successfully committed // error will be returned if maximum retries have been reached or the query to the consumer chain fails for { // error will be returned if max retries have been reached - res, err := v.CommitPubRand(targetBlock) + res, err := fp.CommitPubRand(targetBlock) if err != nil { if clientcontroller.IsUnrecoverable(err) { return nil, err } - v.logger.Debug( + fp.logger.Debug( "failed to commit public randomness to the consumer chain", - zap.String("pk", v.GetBtcPkHex()), + zap.String("pk", fp.GetBtcPkHex()), zap.Uint32("current_failures", failedCycles), zap.Uint64("target_block_height", targetBlock.Height), zap.Error(err), ) failedCycles += 1 - if failedCycles > uint32(v.cfg.MaxSubmissionRetries) { + if failedCycles > uint32(fp.cfg.MaxSubmissionRetries) { return nil, fmt.Errorf("reached max failed cycles with err: %w", err) } } else { @@ -536,48 +536,48 @@ func (v *ValidatorInstance) retryCommitPubRandUntilBlockFinalized(targetBlock *t return res, nil } select { - case <-time.After(v.cfg.SubmissionRetryInterval): + case <-time.After(fp.cfg.SubmissionRetryInterval): // periodically query the index block to be later checked whether it is Finalized - finalized, err := v.checkBlockFinalization(targetBlock.Height) + finalized, err := fp.checkBlockFinalization(targetBlock.Height) if err != nil { return nil, fmt.Errorf("failed to query block finalization at height %v: %w", targetBlock.Height, err) } if finalized { - v.logger.Debug( + fp.logger.Debug( "the block is already finalized, skip submission", - zap.String("pk", v.GetBtcPkHex()), + zap.String("pk", fp.GetBtcPkHex()), zap.Uint64("target_height", targetBlock.Height), ) return nil, nil } - case <-v.quit: - v.logger.Debug("the validator instance is closing", zap.String("pk", v.GetBtcPkHex())) + case <-fp.quit: + fp.logger.Debug("the finality-provider instance is closing", zap.String("pk", fp.GetBtcPkHex())) return nil, nil } } } // CommitPubRand generates a list of Schnorr rand pairs, -// commits the public randomness for the managed validators, +// commits the public randomness for the managed finality providers, // and save the randomness pair to DB -func (v *ValidatorInstance) CommitPubRand(tipBlock *types.BlockInfo) (*types.TxResponse, error) { - lastCommittedHeight := v.GetLastCommittedHeight() +func (fp *FinalityProviderInstance) CommitPubRand(tipBlock *types.BlockInfo) (*types.TxResponse, error) { + lastCommittedHeight := fp.GetLastCommittedHeight() var startHeight uint64 if lastCommittedHeight == uint64(0) { - // the validator has never submitted public rand before + // the finality-provider has never submitted public rand before startHeight = tipBlock.Height + 1 // should not use subtraction because they are in the type of uint64 - } else if lastCommittedHeight < v.cfg.MinRandHeightGap+tipBlock.Height { + } else if lastCommittedHeight < fp.cfg.MinRandHeightGap+tipBlock.Height { // we are running out of the randomness startHeight = lastCommittedHeight + 1 } else { - v.logger.Debug( - "the validator has sufficient public randomness, skip committing more", - zap.String("pk", v.GetBtcPkHex()), + fp.logger.Debug( + "the finality-provider has sufficient public randomness, skip committing more", + zap.String("pk", fp.GetBtcPkHex()), zap.Uint64("block_height", tipBlock.Height), - zap.Uint64("last_committed_height", v.GetLastCommittedHeight()), + zap.Uint64("last_committed_height", fp.GetLastCommittedHeight()), ) return nil, nil } @@ -588,14 +588,14 @@ func (v *ValidatorInstance) CommitPubRand(tipBlock *types.BlockInfo) (*types.TxR // for safety reason as the same randomness must not be used twice // TODO: should consider an implementation that deterministically create // randomness without saving it - pubRandList, err := v.createPubRandList(startHeight) + pubRandList, err := fp.createPubRandList(startHeight) if err != nil { return nil, fmt.Errorf("failed to generate randomness: %w", err) } // get the message hash for signing msg := &ftypes.MsgCommitPubRandList{ - ValBtcPk: v.btcPk, + FpBtcPk: fp.btcPk, StartHeight: startHeight, PubRandList: pubRandList, } @@ -604,8 +604,8 @@ func (v *ValidatorInstance) CommitPubRand(tipBlock *types.BlockInfo) (*types.TxR return nil, fmt.Errorf("failed to sign the commit public randomness message: %w", err) } - // sign the message hash using the validator's BTC private key - schnorrSig, err := v.em.SignSchnorrSig(v.btcPk.MustMarshal(), hash, v.passphrase) + // sign the message hash using the finality-provider's BTC private key + schnorrSig, err := fp.em.SignSchnorrSig(fp.btcPk.MustMarshal(), hash, fp.passphrase) if err != nil { return nil, fmt.Errorf("failed to sign the Schnorr signature: %w", err) } @@ -614,26 +614,26 @@ func (v *ValidatorInstance) CommitPubRand(tipBlock *types.BlockInfo) (*types.TxR for _, r := range pubRandList { pubRandByteList = append(pubRandByteList, r.ToFieldVal()) } - res, err := v.cc.CommitPubRandList(v.MustGetBtcPk(), startHeight, pubRandByteList, schnorrSig) + res, err := fp.cc.CommitPubRandList(fp.MustGetBtcPk(), startHeight, pubRandByteList, schnorrSig) if err != nil { - // TODO Add retry. check issue: https://github.com/babylonchain/btc-validator/issues/34 + // TODO Add retry. check issue: https://github.com/babylonchain/finality-provider/issues/34 return nil, fmt.Errorf("failed to commit public randomness to the consumer chain: %w", err) } newLastCommittedHeight := startHeight + uint64(len(pubRandList)-1) - v.MustSetLastCommittedHeight(newLastCommittedHeight) + fp.MustSetLastCommittedHeight(newLastCommittedHeight) return res, nil } -func (v *ValidatorInstance) createPubRandList(startHeight uint64) ([]bbntypes.SchnorrPubRand, error) { - pubRandList, err := v.em.CreateRandomnessPairList( - v.btcPk.MustMarshal(), - v.GetChainID(), +func (fp *FinalityProviderInstance) createPubRandList(startHeight uint64) ([]bbntypes.SchnorrPubRand, error) { + pubRandList, err := fp.em.CreateRandomnessPairList( + fp.btcPk.MustMarshal(), + fp.GetChainID(), startHeight, - uint32(v.cfg.NumPubRand), - v.passphrase, + uint32(fp.cfg.NumPubRand), + fp.passphrase, ) if err != nil { return nil, err @@ -648,34 +648,34 @@ func (v *ValidatorInstance) createPubRandList(startHeight uint64) ([]bbntypes.Sc } // SubmitFinalitySignature builds and sends a finality signature over the given block to the consumer chain -func (v *ValidatorInstance) SubmitFinalitySignature(b *types.BlockInfo) (*types.TxResponse, error) { - eotsSig, err := v.signEotsSig(b) +func (fp *FinalityProviderInstance) SubmitFinalitySignature(b *types.BlockInfo) (*types.TxResponse, error) { + eotsSig, err := fp.signEotsSig(b) if err != nil { return nil, err } // send finality signature to the consumer chain - res, err := v.cc.SubmitFinalitySig(v.MustGetBtcPk(), b.Height, b.Hash, eotsSig.ToModNScalar()) + res, err := fp.cc.SubmitFinalitySig(fp.MustGetBtcPk(), b.Height, b.Hash, eotsSig.ToModNScalar()) if err != nil { return nil, fmt.Errorf("failed to send finality signature to the consumer chain: %w", err) } // update DB - v.MustUpdateStateAfterFinalitySigSubmission(b.Height) + fp.MustUpdateStateAfterFinalitySigSubmission(b.Height) return res, nil } // SubmitBatchFinalitySignatures builds and sends a finality signature over the given block to the consumer chain // NOTE: the input blocks should be in the ascending order of height -func (v *ValidatorInstance) SubmitBatchFinalitySignatures(blocks []*types.BlockInfo) (*types.TxResponse, error) { +func (fp *FinalityProviderInstance) SubmitBatchFinalitySignatures(blocks []*types.BlockInfo) (*types.TxResponse, error) { if len(blocks) == 0 { return nil, fmt.Errorf("should not submit batch finality signature with zero block") } sigs := make([]*btcec.ModNScalar, 0, len(blocks)) for _, b := range blocks { - eotsSig, err := v.signEotsSig(b) + eotsSig, err := fp.signEotsSig(b) if err != nil { return nil, err } @@ -683,27 +683,27 @@ func (v *ValidatorInstance) SubmitBatchFinalitySignatures(blocks []*types.BlockI } // send finality signature to the consumer chain - res, err := v.cc.SubmitBatchFinalitySigs(v.MustGetBtcPk(), blocks, sigs) + res, err := fp.cc.SubmitBatchFinalitySigs(fp.MustGetBtcPk(), blocks, sigs) if err != nil { return nil, fmt.Errorf("failed to send a batch of finality signatures to the consumer chain: %w", err) } // update DB highBlock := blocks[len(blocks)-1] - v.MustUpdateStateAfterFinalitySigSubmission(highBlock.Height) + fp.MustUpdateStateAfterFinalitySigSubmission(highBlock.Height) return res, nil } -func (v *ValidatorInstance) signEotsSig(b *types.BlockInfo) (*bbntypes.SchnorrEOTSSig, error) { +func (fp *FinalityProviderInstance) signEotsSig(b *types.BlockInfo) (*bbntypes.SchnorrEOTSSig, error) { // build proper finality signature request msg := &ftypes.MsgAddFinalitySig{ - ValBtcPk: v.btcPk, + FpBtcPk: fp.btcPk, BlockHeight: b.Height, BlockAppHash: b.Hash, } msgToSign := msg.MsgToSign() - sig, err := v.em.SignEOTS(v.btcPk.MustMarshal(), v.GetChainID(), msgToSign, b.Height, v.passphrase) + sig, err := fp.em.SignEOTS(fp.btcPk.MustMarshal(), fp.GetChainID(), msgToSign, b.Height, fp.passphrase) if err != nil { return nil, fmt.Errorf("failed to sign EOTS: %w", err) } @@ -714,20 +714,20 @@ func (v *ValidatorInstance) signEotsSig(b *types.BlockInfo) (*bbntypes.SchnorrEO // TestSubmitFinalitySignatureAndExtractPrivKey is exposed for presentation/testing purpose to allow manual sending finality signature // this API is the same as SubmitFinalitySignature except that we don't constraint the voting height and update status // Note: this should not be used in the submission loop -func (v *ValidatorInstance) TestSubmitFinalitySignatureAndExtractPrivKey(b *types.BlockInfo) (*types.TxResponse, *btcec.PrivateKey, error) { +func (fp *FinalityProviderInstance) TestSubmitFinalitySignatureAndExtractPrivKey(b *types.BlockInfo) (*types.TxResponse, *btcec.PrivateKey, error) { // check last committed height - if v.GetLastCommittedHeight() < b.Height { - return nil, nil, fmt.Errorf("the validator's last committed height %v is lower than the current block height %v", - v.GetLastCommittedHeight(), b.Height) + if fp.GetLastCommittedHeight() < b.Height { + return nil, nil, fmt.Errorf("the finality-provider's last committed height %v is lower than the current block height %v", + fp.GetLastCommittedHeight(), b.Height) } - eotsSig, err := v.signEotsSig(b) + eotsSig, err := fp.signEotsSig(b) if err != nil { return nil, nil, err } // send finality signature to the consumer chain - res, err := v.cc.SubmitFinalitySig(v.MustGetBtcPk(), b.Height, b.Hash, eotsSig.ToModNScalar()) + res, err := fp.cc.SubmitFinalitySig(fp.MustGetBtcPk(), b.Height, b.Hash, eotsSig.ToModNScalar()) if err != nil { return nil, nil, fmt.Errorf("failed to send finality signature to the consumer chain: %w", err) } @@ -735,9 +735,9 @@ func (v *ValidatorInstance) TestSubmitFinalitySignatureAndExtractPrivKey(b *type // try to extract the private key var privKey *btcec.PrivateKey for _, ev := range res.Events { - if strings.Contains(ev.EventType, "EventSlashedBTCValidator") { + if strings.Contains(ev.EventType, "EventSlashedFinalityProvider") { evidenceStr := ev.Attributes["evidence"] - v.logger.Debug("found slashing evidence") + fp.logger.Debug("found slashing evidence") var evidence ftypes.Evidence if err := jsonpb.UnmarshalString(evidenceStr, &evidence); err != nil { return nil, nil, fmt.Errorf("failed to decode evidence bytes to evidence: %s", err.Error()) @@ -753,9 +753,9 @@ func (v *ValidatorInstance) TestSubmitFinalitySignatureAndExtractPrivKey(b *type return res, privKey, nil } -func (v *ValidatorInstance) getPollerStartingHeight() (uint64, error) { - if !v.cfg.PollerConfig.AutoChainScanningMode { - return v.cfg.PollerConfig.StaticChainScanningStartHeight, nil +func (fp *FinalityProviderInstance) getPollerStartingHeight() (uint64, error) { + if !fp.cfg.PollerConfig.AutoChainScanningMode { + return fp.cfg.PollerConfig.StaticChainScanningStartHeight, nil } // Set initial block to the maximum of @@ -763,12 +763,12 @@ func (v *ValidatorInstance) getPollerStartingHeight() (uint64, error) { // - the latest Babylon finalised height // The above is to ensure that: // - // (1) Any validator that is eligible to vote for a block, + // (1) Any finality-provider that is eligible to vote for a block, // doesn't miss submitting a vote for it. - // (2) The validators do not submit signatures for any already + // (2) The finality providers do not submit signatures for any already // finalised blocks. - initialBlockToGet := v.GetLastProcessedHeight() - latestFinalisedBlock, err := v.latestFinalizedBlocksWithRetry(1) + initialBlockToGet := fp.GetLastProcessedHeight() + latestFinalisedBlock, err := fp.latestFinalizedBlocksWithRetry(1) if err != nil { return 0, err } @@ -785,17 +785,17 @@ func (v *ValidatorInstance) getPollerStartingHeight() (uint64, error) { return initialBlockToGet, nil } -func (v *ValidatorInstance) latestFinalizedBlocksWithRetry(count uint64) ([]*types.BlockInfo, error) { +func (fp *FinalityProviderInstance) latestFinalizedBlocksWithRetry(count uint64) ([]*types.BlockInfo, error) { var response []*types.BlockInfo if err := retry.Do(func() error { - latestFinalisedBlock, err := v.cc.QueryLatestFinalizedBlocks(count) + latestFinalisedBlock, err := fp.cc.QueryLatestFinalizedBlocks(count) if err != nil { return err } response = latestFinalisedBlock return nil }, RtyAtt, RtyDel, RtyErr, retry.OnRetry(func(n uint, err error) { - v.logger.Debug( + fp.logger.Debug( "failed to query babylon for the latest finalised blocks", zap.Uint("attempt", n+1), zap.Uint("max_attempts", RtyAttNum), @@ -807,20 +807,20 @@ func (v *ValidatorInstance) latestFinalizedBlocksWithRetry(count uint64) ([]*typ return response, nil } -func (v *ValidatorInstance) getLatestBlockWithRetry() (*types.BlockInfo, error) { +func (fp *FinalityProviderInstance) getLatestBlockWithRetry() (*types.BlockInfo, error) { var ( latestBlock *types.BlockInfo err error ) if err := retry.Do(func() error { - latestBlock, err = v.cc.QueryBestBlock() + latestBlock, err = fp.cc.QueryBestBlock() if err != nil { return err } return nil }, RtyAtt, RtyDel, RtyErr, retry.OnRetry(func(n uint, err error) { - v.logger.Debug( + fp.logger.Debug( "failed to query the consumer chain for the latest block", zap.Uint("attempt", n+1), zap.Uint("max_attempts", RtyAttNum), @@ -833,20 +833,20 @@ func (v *ValidatorInstance) getLatestBlockWithRetry() (*types.BlockInfo, error) return latestBlock, nil } -func (v *ValidatorInstance) GetVotingPowerWithRetry(height uint64) (uint64, error) { +func (fp *FinalityProviderInstance) GetVotingPowerWithRetry(height uint64) (uint64, error) { var ( power uint64 err error ) if err := retry.Do(func() error { - power, err = v.cc.QueryValidatorVotingPower(v.MustGetBtcPk(), height) + power, err = fp.cc.QueryFinalityProviderVotingPower(fp.MustGetBtcPk(), height) if err != nil { return err } return nil }, RtyAtt, RtyDel, RtyErr, retry.OnRetry(func(n uint, err error) { - v.logger.Debug( + fp.logger.Debug( "failed to query the voting power", zap.Uint("attempt", n+1), zap.Uint("max_attempts", RtyAttNum), @@ -859,21 +859,21 @@ func (v *ValidatorInstance) GetVotingPowerWithRetry(height uint64) (uint64, erro return power, nil } -func (v *ValidatorInstance) GetValidatorSlashedWithRetry() (bool, error) { +func (fp *FinalityProviderInstance) GetFinalityProviderSlashedWithRetry() (bool, error) { var ( slashed bool err error ) if err := retry.Do(func() error { - slashed, err = v.cc.QueryValidatorSlashed(v.MustGetBtcPk()) + slashed, err = fp.cc.QueryFinalityProviderSlashed(fp.MustGetBtcPk()) if err != nil { return err } return nil }, RtyAtt, RtyDel, RtyErr, retry.OnRetry(func(n uint, err error) { - v.logger.Debug( - "failed to query the validator", + fp.logger.Debug( + "failed to query the finality-provider", zap.Uint("attempt", n+1), zap.Uint("max_attempts", RtyAttNum), zap.Error(err), diff --git a/validator/service/validator_instance_test.go b/finality-provider/service/fp_instance_test.go similarity index 55% rename from validator/service/validator_instance_test.go rename to finality-provider/service/fp_instance_test.go index 1e92f2fc..6cf19ac7 100644 --- a/validator/service/validator_instance_test.go +++ b/finality-provider/service/fp_instance_test.go @@ -10,12 +10,12 @@ import ( "github.com/stretchr/testify/require" "go.uber.org/zap" - "github.com/babylonchain/btc-validator/clientcontroller" - "github.com/babylonchain/btc-validator/eotsmanager" - "github.com/babylonchain/btc-validator/testutil" - "github.com/babylonchain/btc-validator/types" - "github.com/babylonchain/btc-validator/validator/proto" - "github.com/babylonchain/btc-validator/validator/service" + "github.com/babylonchain/finality-provider/clientcontroller" + "github.com/babylonchain/finality-provider/eotsmanager" + "github.com/babylonchain/finality-provider/finality-provider/proto" + "github.com/babylonchain/finality-provider/finality-provider/service" + "github.com/babylonchain/finality-provider/testutil" + "github.com/babylonchain/finality-provider/types" ) func FuzzCommitPubRandList(f *testing.F) { @@ -28,24 +28,24 @@ func FuzzCommitPubRandList(f *testing.F) { startingBlock := &types.BlockInfo{Height: randomStartingHeight, Hash: testutil.GenRandomByteArray(r, 32)} mockClientController := testutil.PrepareMockedClientController(t, r, randomStartingHeight, currentHeight, &types.StakingParams{}) mockClientController.EXPECT().QueryLatestFinalizedBlocks(gomock.Any()).Return(nil, nil).AnyTimes() - app, storeValidator, cleanUp := startValidatorAppWithRegisteredValidator(t, r, mockClientController, randomStartingHeight) + app, storeFp, cleanUp := startFinalityProviderAppWithRegisteredFp(t, r, mockClientController, randomStartingHeight) defer cleanUp() - mockClientController.EXPECT().QueryValidatorVotingPower(storeValidator.MustGetBTCPK(), gomock.Any()). + mockClientController.EXPECT().QueryFinalityProviderVotingPower(storeFp.MustGetBTCPK(), gomock.Any()). Return(uint64(0), nil).AnyTimes() - valIns, err := app.GetValidatorInstance(storeValidator.MustGetBIP340BTCPK()) + fpIns, err := app.GetFinalityProviderInstance(storeFp.MustGetBIP340BTCPK()) require.NoError(t, err) expectedTxHash := testutil.GenRandomHexStr(r, 32) mockClientController.EXPECT(). - CommitPubRandList(valIns.MustGetBtcPk(), startingBlock.Height+1, gomock.Any(), gomock.Any()). + CommitPubRandList(fpIns.MustGetBtcPk(), startingBlock.Height+1, gomock.Any(), gomock.Any()). Return(&types.TxResponse{TxHash: expectedTxHash}, nil).AnyTimes() - res, err := valIns.CommitPubRand(startingBlock) + res, err := fpIns.CommitPubRand(startingBlock) require.NoError(t, err) require.Equal(t, expectedTxHash, res.TxHash) // check the last_committed_height numPubRand := app.GetConfig().NumPubRand - require.Equal(t, startingBlock.Height+numPubRand, valIns.GetStoreValidator().LastCommittedHeight) + require.Equal(t, startingBlock.Height+numPubRand, fpIns.GetStoreFinalityProvider().LastCommittedHeight) }) } @@ -59,22 +59,22 @@ func FuzzSubmitFinalitySig(f *testing.F) { startingBlock := &types.BlockInfo{Height: randomStartingHeight, Hash: testutil.GenRandomByteArray(r, 32)} mockClientController := testutil.PrepareMockedClientController(t, r, randomStartingHeight, currentHeight, &types.StakingParams{}) mockClientController.EXPECT().QueryLatestFinalizedBlocks(gomock.Any()).Return(nil, nil).AnyTimes() - app, storeValidator, cleanUp := startValidatorAppWithRegisteredValidator(t, r, mockClientController, randomStartingHeight) + app, storeFp, cleanUp := startFinalityProviderAppWithRegisteredFp(t, r, mockClientController, randomStartingHeight) defer cleanUp() - mockClientController.EXPECT().QueryValidatorVotingPower(storeValidator.MustGetBTCPK(), gomock.Any()). + mockClientController.EXPECT().QueryFinalityProviderVotingPower(storeFp.MustGetBTCPK(), gomock.Any()). Return(uint64(0), nil).AnyTimes() - valIns, err := app.GetValidatorInstance(storeValidator.MustGetBIP340BTCPK()) + fpIns, err := app.GetFinalityProviderInstance(storeFp.MustGetBIP340BTCPK()) require.NoError(t, err) // commit public randomness expectedTxHash := testutil.GenRandomHexStr(r, 32) mockClientController.EXPECT(). - CommitPubRandList(valIns.MustGetBtcPk(), startingBlock.Height+1, gomock.Any(), gomock.Any()). + CommitPubRandList(fpIns.MustGetBtcPk(), startingBlock.Height+1, gomock.Any(), gomock.Any()). Return(&types.TxResponse{TxHash: expectedTxHash}, nil).AnyTimes() - res, err := valIns.CommitPubRand(startingBlock) + res, err := fpIns.CommitPubRand(startingBlock) require.NoError(t, err) require.Equal(t, expectedTxHash, res.TxHash) - mockClientController.EXPECT().QueryValidatorVotingPower(storeValidator.MustGetBTCPK(), gomock.Any()). + mockClientController.EXPECT().QueryFinalityProviderVotingPower(storeFp.MustGetBTCPK(), gomock.Any()). Return(uint64(1), nil).AnyTimes() // submit finality sig @@ -84,19 +84,19 @@ func FuzzSubmitFinalitySig(f *testing.F) { } expectedTxHash = testutil.GenRandomHexStr(r, 32) mockClientController.EXPECT(). - SubmitFinalitySig(valIns.MustGetBtcPk(), nextBlock.Height, nextBlock.Hash, gomock.Any()). + SubmitFinalitySig(fpIns.MustGetBtcPk(), nextBlock.Height, nextBlock.Hash, gomock.Any()). Return(&types.TxResponse{TxHash: expectedTxHash}, nil).AnyTimes() - providerRes, err := valIns.SubmitFinalitySignature(nextBlock) + providerRes, err := fpIns.SubmitFinalitySignature(nextBlock) require.NoError(t, err) require.Equal(t, expectedTxHash, providerRes.TxHash) // check the last_voted_height - require.Equal(t, nextBlock.Height, valIns.GetLastVotedHeight()) - require.Equal(t, nextBlock.Height, valIns.GetLastProcessedHeight()) + require.Equal(t, nextBlock.Height, fpIns.GetLastVotedHeight()) + require.Equal(t, nextBlock.Height, fpIns.GetLastProcessedHeight()) }) } -func startValidatorAppWithRegisteredValidator(t *testing.T, r *rand.Rand, cc clientcontroller.ClientController, startingHeight uint64) (*service.ValidatorApp, *proto.StoreValidator, func()) { +func startFinalityProviderAppWithRegisteredFp(t *testing.T, r *rand.Rand, cc clientcontroller.ClientController, startingHeight uint64) (*service.FinalityProviderApp, *proto.StoreFinalityProvider, func()) { logger := zap.NewNop() // create an EOTS manager eotsHomeDir := filepath.Join(t.TempDir(), "eots-home") @@ -104,22 +104,22 @@ func startValidatorAppWithRegisteredValidator(t *testing.T, r *rand.Rand, cc cli em, err := eotsmanager.NewLocalEOTSManager(eotsHomeDir, eotsCfg, logger) require.NoError(t, err) - // create validator app with randomized config - valHomeDir := filepath.Join(t.TempDir(), "val-home") - valCfg := testutil.GenValConfig(r, t, valHomeDir) - valCfg.NumPubRand = uint64(25) - valCfg.PollerConfig.AutoChainScanningMode = false - valCfg.PollerConfig.StaticChainScanningStartHeight = startingHeight - app, err := service.NewValidatorApp(valHomeDir, valCfg, cc, em, logger) + // create finality-provider app with randomized config + fpHomeDir := filepath.Join(t.TempDir(), "fp-home") + fpCfg := testutil.GenFpConfig(r, t, fpHomeDir) + fpCfg.NumPubRand = uint64(25) + fpCfg.PollerConfig.AutoChainScanningMode = false + fpCfg.PollerConfig.StaticChainScanningStartHeight = startingHeight + app, err := service.NewFinalityProviderApp(fpHomeDir, fpCfg, cc, em, logger) require.NoError(t, err) err = app.Start() require.NoError(t, err) - // create registered validator - validator := testutil.GenStoredValidator(r, t, app, passphrase, hdPath) - err = app.GetValidatorStore().SetValidatorStatus(validator, proto.ValidatorStatus_REGISTERED) + // create registered finality-provider + fp := testutil.GenStoredFinalityProvider(r, t, app, passphrase, hdPath) + err = app.GetFinalityProviderStore().SetFinalityProviderStatus(fp, proto.FinalityProviderStatus_REGISTERED) require.NoError(t, err) - err = app.StartHandlingValidator(validator.MustGetBIP340BTCPK(), passphrase) + err = app.StartHandlingFinalityProvider(fp.MustGetBIP340BTCPK(), passphrase) require.NoError(t, err) cleanUp := func() { @@ -127,9 +127,9 @@ func startValidatorAppWithRegisteredValidator(t *testing.T, r *rand.Rand, cc cli require.NoError(t, err) err = os.RemoveAll(eotsHomeDir) require.NoError(t, err) - err = os.RemoveAll(valHomeDir) + err = os.RemoveAll(fpHomeDir) require.NoError(t, err) } - return app, validator, cleanUp + return app, fp, cleanUp } diff --git a/finality-provider/service/fp_manager.go b/finality-provider/service/fp_manager.go new file mode 100644 index 00000000..c1d176b4 --- /dev/null +++ b/finality-provider/service/fp_manager.go @@ -0,0 +1,344 @@ +package service + +import ( + "errors" + "fmt" + "sync" + "time" + + "github.com/avast/retry-go/v4" + bbntypes "github.com/babylonchain/babylon/types" + btcstakingtypes "github.com/babylonchain/babylon/x/btcstaking/types" + "go.uber.org/atomic" + "go.uber.org/zap" + + "github.com/babylonchain/finality-provider/clientcontroller" + "github.com/babylonchain/finality-provider/eotsmanager" + fpcfg "github.com/babylonchain/finality-provider/finality-provider/config" + "github.com/babylonchain/finality-provider/finality-provider/proto" + fpstore "github.com/babylonchain/finality-provider/finality-provider/store" + "github.com/babylonchain/finality-provider/types" +) + +const instanceTerminatingMsg = "terminating the finality-provider instance due to critical error" + +type CriticalError struct { + err error + fpBtcPk *bbntypes.BIP340PubKey +} + +func (ce *CriticalError) Error() string { + return fmt.Sprintf("critical err on finality-provider %s: %s", ce.fpBtcPk.MarshalHex(), ce.err.Error()) +} + +type FinalityProviderManager struct { + isStarted *atomic.Bool + + mu sync.Mutex + wg sync.WaitGroup + + // running finality-provider instances map keyed by the hex string of the BTC public key + fpis map[string]*FinalityProviderInstance + + // needed for initiating finality-provider instances + fps *fpstore.FinalityProviderStore + config *fpcfg.Config + cc clientcontroller.ClientController + em eotsmanager.EOTSManager + logger *zap.Logger + + criticalErrChan chan *CriticalError + + quit chan struct{} +} + +func NewFinalityProviderManager(fps *fpstore.FinalityProviderStore, + config *fpcfg.Config, + cc clientcontroller.ClientController, + em eotsmanager.EOTSManager, + logger *zap.Logger, +) (*FinalityProviderManager, error) { + return &FinalityProviderManager{ + fpis: make(map[string]*FinalityProviderInstance), + criticalErrChan: make(chan *CriticalError), + isStarted: atomic.NewBool(false), + fps: fps, + config: config, + cc: cc, + em: em, + logger: logger, + quit: make(chan struct{}), + }, nil +} + +// monitorCriticalErr takes actions when it receives critical errors from a finality-provider instance +// if the finality-provider is slashed, it will be terminated and the program keeps running in case +// new finality providers join +// otherwise, the program will panic +func (fpm *FinalityProviderManager) monitorCriticalErr() { + defer fpm.wg.Done() + + var criticalErr *CriticalError + for { + select { + case criticalErr = <-fpm.criticalErrChan: + fpi, err := fpm.GetFinalityProviderInstance(criticalErr.fpBtcPk) + if err != nil { + panic(fmt.Errorf("failed to get the finality-provider instance: %w", err)) + } + if errors.Is(criticalErr.err, btcstakingtypes.ErrFpAlreadySlashed) { + fpm.setFinalityProviderSlashed(fpi) + fpm.logger.Debug("the finality-provider has been slashed", + zap.String("pk", criticalErr.fpBtcPk.MarshalHex())) + continue + } + fpi.logger.Fatal(instanceTerminatingMsg, + zap.String("pk", criticalErr.fpBtcPk.MarshalHex()), zap.Error(criticalErr.err)) + case <-fpm.quit: + return + } + } +} + +// monitorStatusUpdate periodically check the status of each managed finality providers and update +// it accordingly. We update the status by querying the latest voting power and the slashed_height. +// In particular, we perform the following status transitions (REGISTERED, ACTIVE, INACTIVE, SLASHED): +// 1. if power == 0 and slashed_height == 0, if status == ACTIVE, change to INACTIVE, otherwise remain the same +// 2. if power == 0 and slashed_height > 0, set status to SLASHED and stop and remove the finality-provider instance +// 3. if power > 0 (slashed_height must > 0), set status to ACTIVE +// NOTE: once error occurs, we log and continue as the status update is not critical to the entire program +func (fpm *FinalityProviderManager) monitorStatusUpdate() { + defer fpm.wg.Done() + + if fpm.config.StatusUpdateInterval == 0 { + fpm.logger.Info("the status update is disabled") + return + } + + statusUpdateTicker := time.NewTicker(fpm.config.StatusUpdateInterval) + defer statusUpdateTicker.Stop() + + for { + select { + case <-statusUpdateTicker.C: + latestBlock, err := fpm.getLatestBlockWithRetry() + if err != nil { + fpm.logger.Debug("failed to get the latest block", zap.Error(err)) + continue + } + fpis := fpm.ListFinalityProviderInstances() + for _, fpi := range fpis { + oldStatus := fpi.GetStatus() + power, err := fpi.GetVotingPowerWithRetry(latestBlock.Height) + if err != nil { + fpm.logger.Debug( + "failed to get the voting power", + zap.String("fp_btc_pk", fpi.GetBtcPkHex()), + zap.Uint64("height", latestBlock.Height), + zap.Error(err), + ) + continue + } + // power > 0 (slashed_height must > 0), set status to ACTIVE + if power > 0 { + if oldStatus != proto.FinalityProviderStatus_ACTIVE { + fpi.MustSetStatus(proto.FinalityProviderStatus_ACTIVE) + fpm.logger.Debug( + "the finality-provider status is changed to ACTIVE", + zap.String("fp_btc_pk", fpi.GetBtcPkHex()), + zap.String("old_status", oldStatus.String()), + zap.Uint64("power", power), + ) + } + continue + } + slashed, err := fpi.GetFinalityProviderSlashedWithRetry() + if err != nil { + fpm.logger.Debug( + "failed to get the slashed height", + zap.String("fp_btc_pk", fpi.GetBtcPkHex()), + zap.Error(err), + ) + continue + } + // power == 0 and slashed == true, set status to SLASHED and stop and remove the finality-provider instance + if slashed { + fpm.setFinalityProviderSlashed(fpi) + fpm.logger.Debug( + "the finality-provider is slashed", + zap.String("fp_btc_pk", fpi.GetBtcPkHex()), + zap.String("old_status", oldStatus.String()), + ) + continue + } + // power == 0 and slashed_height == 0, change to INACTIVE if the current status is ACTIVE + if oldStatus == proto.FinalityProviderStatus_ACTIVE { + fpi.MustSetStatus(proto.FinalityProviderStatus_INACTIVE) + fpm.logger.Debug( + "the finality-provider status is changed to INACTIVE", + zap.String("fp_btc_pk", fpi.GetBtcPkHex()), + zap.String("old_status", oldStatus.String()), + ) + } + } + case <-fpm.quit: + return + } + } +} + +func (fpm *FinalityProviderManager) setFinalityProviderSlashed(fpi *FinalityProviderInstance) { + fpi.MustSetStatus(proto.FinalityProviderStatus_SLASHED) + if err := fpm.removeFinalityProviderInstance(fpi.GetBtcPkBIP340()); err != nil { + panic(fmt.Errorf("failed to terminate a slashed finality-provider %s: %w", fpi.GetBtcPkHex(), err)) + } +} + +func (fpm *FinalityProviderManager) StartFinalityProvider(fpPk *bbntypes.BIP340PubKey, passphrase string) error { + if !fpm.isStarted.Load() { + fpm.isStarted.Store(true) + + fpm.wg.Add(1) + go fpm.monitorCriticalErr() + + fpm.wg.Add(1) + go fpm.monitorStatusUpdate() + } + + if fpm.numOfRunningFinalityProviders() >= int(fpm.config.MaxNumFinalityProviders) { + return fmt.Errorf("reaching maximum number of running finality providers %v", fpm.config.MaxNumFinalityProviders) + } + + if err := fpm.addFinalityProviderInstance(fpPk, passphrase); err != nil { + return err + } + + return nil +} + +func (fpm *FinalityProviderManager) Stop() error { + if !fpm.isStarted.Swap(false) { + return fmt.Errorf("the finality-provider manager has already stopped") + } + + var stopErr error + + for _, fpi := range fpm.fpis { + if !fpi.IsRunning() { + continue + } + if err := fpi.Stop(); err != nil { + stopErr = err + break + } + } + + close(fpm.quit) + fpm.wg.Wait() + + return stopErr +} + +func (fpm *FinalityProviderManager) ListFinalityProviderInstances() []*FinalityProviderInstance { + fpm.mu.Lock() + defer fpm.mu.Unlock() + + fpisList := make([]*FinalityProviderInstance, 0, len(fpm.fpis)) + for _, fpi := range fpm.fpis { + fpisList = append(fpisList, fpi) + } + + return fpisList +} + +func (fpm *FinalityProviderManager) GetFinalityProviderInstance(fpPk *bbntypes.BIP340PubKey) (*FinalityProviderInstance, error) { + fpm.mu.Lock() + defer fpm.mu.Unlock() + + keyHex := fpPk.MarshalHex() + v, exists := fpm.fpis[keyHex] + if !exists { + return nil, fmt.Errorf("cannot find the finality-provider instance with PK: %s", keyHex) + } + + return v, nil +} + +func (fpm *FinalityProviderManager) removeFinalityProviderInstance(fpPk *bbntypes.BIP340PubKey) error { + fpm.mu.Lock() + defer fpm.mu.Unlock() + + keyHex := fpPk.MarshalHex() + fpi, exists := fpm.fpis[keyHex] + if !exists { + return fmt.Errorf("cannot find the finality-provider instance with PK: %s", keyHex) + } + if fpi.IsRunning() { + if err := fpi.Stop(); err != nil { + return fmt.Errorf("failed to stop the finality-provider instance %s", keyHex) + } + } + + delete(fpm.fpis, keyHex) + return nil +} + +func (fpm *FinalityProviderManager) numOfRunningFinalityProviders() int { + fpm.mu.Lock() + defer fpm.mu.Unlock() + + return len(fpm.fpis) +} + +// addFinalityProviderInstance creates a finality-provider instance, starts it and adds it into the finality-provider manager +func (fpm *FinalityProviderManager) addFinalityProviderInstance( + pk *bbntypes.BIP340PubKey, + passphrase string, +) error { + fpm.mu.Lock() + defer fpm.mu.Unlock() + + pkHex := pk.MarshalHex() + if _, exists := fpm.fpis[pkHex]; exists { + return fmt.Errorf("finality-provider instance already exists") + } + + fpIns, err := NewFinalityProviderInstance(pk, fpm.config, fpm.fps, fpm.cc, fpm.em, passphrase, fpm.criticalErrChan, fpm.logger) + if err != nil { + return fmt.Errorf("failed to create finality-provider %s instance: %w", pkHex, err) + } + + if err := fpIns.Start(); err != nil { + return fmt.Errorf("failed to start finality-provider %s instance: %w", pkHex, err) + } + + fpm.fpis[pkHex] = fpIns + + return nil +} + +func (fpm *FinalityProviderManager) getLatestBlockWithRetry() (*types.BlockInfo, error) { + var ( + latestBlock *types.BlockInfo + err error + ) + + if err := retry.Do(func() error { + latestBlock, err = fpm.cc.QueryBestBlock() + if err != nil { + return err + } + return nil + }, RtyAtt, RtyDel, RtyErr, retry.OnRetry(func(n uint, err error) { + fpm.logger.Debug( + "failed to query the consumer chain for the latest block", + zap.Uint("attempt", n+1), + zap.Uint("max_attempts", RtyAttNum), + zap.Error(err), + ) + })); err != nil { + return nil, err + } + + return latestBlock, nil +} diff --git a/validator/service/validator_manager_test.go b/finality-provider/service/fp_manager_test.go similarity index 50% rename from validator/service/validator_manager_test.go rename to finality-provider/service/fp_manager_test.go index 94831315..841cecd7 100644 --- a/validator/service/validator_manager_test.go +++ b/finality-provider/service/fp_manager_test.go @@ -1,8 +1,8 @@ package service_test import ( - "github.com/babylonchain/btc-validator/util" - valcfg "github.com/babylonchain/btc-validator/validator/config" + fpcfg "github.com/babylonchain/finality-provider/finality-provider/config" + "github.com/babylonchain/finality-provider/util" "math/rand" "os" "path/filepath" @@ -12,22 +12,22 @@ import ( "go.uber.org/zap" - "github.com/babylonchain/btc-validator/keyring" + "github.com/babylonchain/finality-provider/keyring" "github.com/babylonchain/babylon/testutil/datagen" bbntypes "github.com/babylonchain/babylon/types" + fpstore "github.com/babylonchain/finality-provider/finality-provider/store" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" - "github.com/babylonchain/btc-validator/clientcontroller" - "github.com/babylonchain/btc-validator/eotsmanager" - "github.com/babylonchain/btc-validator/testutil" - "github.com/babylonchain/btc-validator/testutil/mocks" - "github.com/babylonchain/btc-validator/types" - "github.com/babylonchain/btc-validator/validator/proto" - "github.com/babylonchain/btc-validator/validator/service" - valstore "github.com/babylonchain/btc-validator/validator/store" + "github.com/babylonchain/finality-provider/clientcontroller" + "github.com/babylonchain/finality-provider/eotsmanager" + "github.com/babylonchain/finality-provider/finality-provider/proto" + "github.com/babylonchain/finality-provider/finality-provider/service" + "github.com/babylonchain/finality-provider/testutil" + "github.com/babylonchain/finality-provider/testutil/mocks" + "github.com/babylonchain/finality-provider/types" ) var ( @@ -42,7 +42,7 @@ func FuzzStatusUpdate(f *testing.F) { ctl := gomock.NewController(t) mockClientController := mocks.NewMockClientController(ctl) - vm, valPk, cleanUp := newValidatorManagerWithRegisteredValidator(t, r, mockClientController) + vm, fpPk, cleanUp := newFinalityProviderManagerWithRegisteredFp(t, r, mockClientController) defer cleanUp() // setup mocks @@ -59,39 +59,39 @@ func FuzzStatusUpdate(f *testing.F) { mockClientController.EXPECT().QueryBlock(gomock.Any()).Return(currentBlockRes, nil).AnyTimes() votingPower := uint64(r.Intn(2)) - mockClientController.EXPECT().QueryValidatorVotingPower(gomock.Any(), currentHeight).Return(votingPower, nil).AnyTimes() + mockClientController.EXPECT().QueryFinalityProviderVotingPower(gomock.Any(), currentHeight).Return(votingPower, nil).AnyTimes() var slashedHeight uint64 if votingPower == 0 { - mockClientController.EXPECT().QueryValidatorSlashed(gomock.Any()).Return(true, nil).AnyTimes() + mockClientController.EXPECT().QueryFinalityProviderSlashed(gomock.Any()).Return(true, nil).AnyTimes() } - err := vm.StartValidator(valPk, passphrase) + err := vm.StartFinalityProvider(fpPk, passphrase) require.NoError(t, err) - valIns := vm.ListValidatorInstances()[0] - // stop the validator as we are testing static functionalities - err = valIns.Stop() + fpIns := vm.ListFinalityProviderInstances()[0] + // stop the finality-provider as we are testing static functionalities + err = fpIns.Stop() require.NoError(t, err) if votingPower > 0 { - waitForStatus(t, valIns, proto.ValidatorStatus_ACTIVE) + waitForStatus(t, fpIns, proto.FinalityProviderStatus_ACTIVE) } else { - if slashedHeight == 0 && valIns.GetStatus() == proto.ValidatorStatus_ACTIVE { - waitForStatus(t, valIns, proto.ValidatorStatus_INACTIVE) + if slashedHeight == 0 && fpIns.GetStatus() == proto.FinalityProviderStatus_ACTIVE { + waitForStatus(t, fpIns, proto.FinalityProviderStatus_INACTIVE) } else if slashedHeight > 0 { - waitForStatus(t, valIns, proto.ValidatorStatus_SLASHED) + waitForStatus(t, fpIns, proto.FinalityProviderStatus_SLASHED) } } }) } -func waitForStatus(t *testing.T, valIns *service.ValidatorInstance, s proto.ValidatorStatus) { +func waitForStatus(t *testing.T, fpIns *service.FinalityProviderInstance, s proto.FinalityProviderStatus) { require.Eventually(t, func() bool { - return valIns.GetStatus() == s + return fpIns.GetStatus() == s }, eventuallyWaitTimeOut, eventuallyPollTime) } -func newValidatorManagerWithRegisteredValidator(t *testing.T, r *rand.Rand, cc clientcontroller.ClientController) (*service.ValidatorManager, *bbntypes.BIP340PubKey, func()) { +func newFinalityProviderManagerWithRegisteredFp(t *testing.T, r *rand.Rand, cc clientcontroller.ClientController) (*service.FinalityProviderManager, *bbntypes.BIP340PubKey, func()) { logger := zap.NewNop() // create an EOTS manager eotsHomeDir := filepath.Join(t.TempDir(), "eots-home") @@ -99,31 +99,31 @@ func newValidatorManagerWithRegisteredValidator(t *testing.T, r *rand.Rand, cc c em, err := eotsmanager.NewLocalEOTSManager(eotsHomeDir, eotsCfg, logger) require.NoError(t, err) - // create validator app with randomized config - valHomeDir := filepath.Join(t.TempDir(), "val-home") - valCfg := testutil.GenValConfig(r, t, valHomeDir) - valCfg.StatusUpdateInterval = 10 * time.Millisecond + // create finality-provider app with randomized config + fpHomeDir := filepath.Join(t.TempDir(), "fp-home") + fpCfg := testutil.GenFpConfig(r, t, fpHomeDir) + fpCfg.StatusUpdateInterval = 10 * time.Millisecond input := strings.NewReader("") kr, err := keyring.CreateKeyring( - valCfg.BabylonConfig.KeyDirectory, - valCfg.BabylonConfig.ChainID, - valCfg.BabylonConfig.KeyringBackend, + fpCfg.BabylonConfig.KeyDirectory, + fpCfg.BabylonConfig.ChainID, + fpCfg.BabylonConfig.KeyringBackend, input, ) require.NoError(t, err) - err = util.MakeDirectory(valcfg.DataDir(valHomeDir)) + err = util.MakeDirectory(fpcfg.DataDir(fpHomeDir)) require.NoError(t, err) - valStore, err := valstore.NewValidatorStore( - valcfg.DBPath(valHomeDir), - valCfg.DatabaseConfig.Name, - valCfg.DatabaseConfig.Backend, + fpStore, err := fpstore.NewFinalityProviderStore( + fpcfg.DBPath(fpHomeDir), + fpCfg.DatabaseConfig.Name, + fpCfg.DatabaseConfig.Backend, ) require.NoError(t, err) - vm, err := service.NewValidatorManager(valStore, valCfg, cc, em, logger) + vm, err := service.NewFinalityProviderManager(fpStore, fpCfg, cc, em, logger) require.NoError(t, err) - // create registered validator + // create registered finality-provider keyName := datagen.GenRandomHexStr(r, 10) chainID := datagen.GenRandomHexStr(r, 10) kc, err := keyring.NewChainKeyringControllerWithKeyring(kr, keyName, input) @@ -135,14 +135,14 @@ func newValidatorManagerWithRegisteredValidator(t *testing.T, r *rand.Rand, cc c keyPair, err := kc.CreateChainKey(passphrase, hdPath) require.NoError(t, err) bbnPk := &secp256k1.PubKey{Key: keyPair.PublicKey.SerializeCompressed()} - valRecord, err := em.KeyRecord(btcPk.MustMarshal(), passphrase) + fpRecord, err := em.KeyRecord(btcPk.MustMarshal(), passphrase) require.NoError(t, err) - pop, err := kc.CreatePop(valRecord.PrivKey, passphrase) + pop, err := kc.CreatePop(fpRecord.PrivKey, passphrase) require.NoError(t, err) - storedValidator := valstore.NewStoreValidator(bbnPk, btcPk, keyName, chainID, pop, testutil.EmptyDescription(), testutil.ZeroCommissionRate()) - storedValidator.Status = proto.ValidatorStatus_REGISTERED - err = valStore.SaveValidator(storedValidator) + storedFp := fpstore.NewStoreFinalityProvider(bbnPk, btcPk, keyName, chainID, pop, testutil.EmptyDescription(), testutil.ZeroCommissionRate()) + storedFp.Status = proto.FinalityProviderStatus_REGISTERED + err = fpStore.SaveFinalityProvider(storedFp) require.NoError(t, err) cleanUp := func() { @@ -150,7 +150,7 @@ func newValidatorManagerWithRegisteredValidator(t *testing.T, r *rand.Rand, cc c require.NoError(t, err) err = os.RemoveAll(eotsHomeDir) require.NoError(t, err) - err = os.RemoveAll(valHomeDir) + err = os.RemoveAll(fpHomeDir) require.NoError(t, err) } diff --git a/finality-provider/service/rpcserver.go b/finality-provider/service/rpcserver.go new file mode 100644 index 00000000..77438fb8 --- /dev/null +++ b/finality-provider/service/rpcserver.go @@ -0,0 +1,210 @@ +package service + +import ( + "context" + "encoding/hex" + "fmt" + "sync" + "sync/atomic" + + "cosmossdk.io/math" + bbntypes "github.com/babylonchain/babylon/types" + "google.golang.org/grpc" + + "github.com/babylonchain/finality-provider/finality-provider/proto" + "github.com/babylonchain/finality-provider/types" + "github.com/babylonchain/finality-provider/version" +) + +// rpcServer is the main RPC server for the Finality Provider daemon that handles +// gRPC incoming requests. +type rpcServer struct { + started int32 + shutdown int32 + + proto.UnimplementedFinalityProvidersServer + + app *FinalityProviderApp + + quit chan struct{} + wg sync.WaitGroup +} + +// newRPCServer creates a new RPC sever from the set of input dependencies. +func newRPCServer( + fpa *FinalityProviderApp, +) *rpcServer { + + return &rpcServer{ + quit: make(chan struct{}), + app: fpa, + } +} + +// Start signals that the RPC server starts accepting requests. +func (r *rpcServer) Start() error { + if atomic.AddInt32(&r.started, 1) != 1 { + return nil + } + + return nil +} + +// Stop signals that the RPC server should attempt a graceful shutdown and +// cancel any outstanding requests. +func (r *rpcServer) Stop() error { + if atomic.AddInt32(&r.shutdown, 1) != 1 { + return nil + } + + close(r.quit) + + r.wg.Wait() + + return nil +} + +// RegisterWithGrpcServer registers the rpcServer with the passed root gRPC +// server. +func (r *rpcServer) RegisterWithGrpcServer(grpcServer *grpc.Server) error { + // Register the main RPC server. + proto.RegisterFinalityProvidersServer(grpcServer, r) + return nil +} + +// GetInfo returns general information relating to the active daemon +func (r *rpcServer) GetInfo(context.Context, *proto.GetInfoRequest) (*proto.GetInfoResponse, error) { + + return &proto.GetInfoResponse{ + Version: version.Version(), + }, nil +} + +// CreateFinalityProvider generates a finality-provider object and saves it in the database +func (r *rpcServer) CreateFinalityProvider(ctx context.Context, req *proto.CreateFinalityProviderRequest) ( + *proto.CreateFinalityProviderResponse, error) { + + commissionRate, err := math.LegacyNewDecFromStr(req.Commission) + if err != nil { + return nil, err + } + + result, err := r.app.CreateFinalityProvider( + req.KeyName, + req.ChainId, + req.Passphrase, + req.HdPath, + req.Description, + &commissionRate, + ) + + if err != nil { + return nil, err + } + + return &proto.CreateFinalityProviderResponse{ + BtcPk: result.FpPk.MarshalHex(), + }, nil + +} + +// RegisterFinalityProvider sends a transactions to Babylon to register a BTC finality-provider +func (r *rpcServer) RegisterFinalityProvider(ctx context.Context, req *proto.RegisterFinalityProviderRequest) ( + *proto.RegisterFinalityProviderResponse, error) { + + txRes, err := r.app.RegisterFinalityProvider(req.BtcPk) + if err != nil { + return nil, fmt.Errorf("failed to register the finality-provider to Babylon: %w", err) + } + + // the finality-provider instance should be started right after registration + if err := r.app.StartHandlingFinalityProvider(txRes.btcPubKey, req.Passphrase); err != nil { + return nil, fmt.Errorf("failed to start the registered finality-provider %s: %w", hex.EncodeToString(txRes.bbnPubKey.Key), err) + } + + return &proto.RegisterFinalityProviderResponse{TxHash: txRes.TxHash}, nil +} + +// AddFinalitySignature adds a manually constructed finality signature to Babylon +// NOTE: this is only used for presentation/testing purposes +func (r *rpcServer) AddFinalitySignature(ctx context.Context, req *proto.AddFinalitySignatureRequest) ( + *proto.AddFinalitySignatureResponse, error) { + + fpPk, err := bbntypes.NewBIP340PubKeyFromHex(req.BtcPk) + if err != nil { + return nil, err + } + + fpi, err := r.app.GetFinalityProviderInstance(fpPk) + if err != nil { + return nil, err + } + + b := &types.BlockInfo{ + Height: req.Height, + Hash: req.AppHash, + } + + txRes, privKey, err := fpi.TestSubmitFinalitySignatureAndExtractPrivKey(b) + if err != nil { + return nil, err + } + + res := &proto.AddFinalitySignatureResponse{TxHash: txRes.TxHash} + + // if privKey is not empty, then this BTC finality-provider + // has voted for a fork and will be slashed + if privKey != nil { + localPrivKey, err := r.app.getFpPrivKey(fpPk.MustMarshal()) + res.ExtractedSkHex = privKey.Key.String() + if err != nil { + return nil, err + } + localSkHex := localPrivKey.Key.String() + localSkNegateHex := localPrivKey.Key.Negate().String() + if res.ExtractedSkHex == localSkHex { + res.LocalSkHex = localSkHex + } else if res.ExtractedSkHex == localSkNegateHex { + res.LocalSkHex = localSkNegateHex + } else { + return nil, fmt.Errorf("the finality-provider's BTC private key is extracted but does not match the local key,"+ + "extrated: %s, local: %s, local-negated: %s", + res.ExtractedSkHex, localSkHex, localSkNegateHex) + } + } + + return res, nil +} + +// QueryFinalityProvider queries the information of the finality-provider +func (r *rpcServer) QueryFinalityProvider(ctx context.Context, req *proto.QueryFinalityProviderRequest) ( + *proto.QueryFinalityProviderResponse, error) { + + fpPk, err := bbntypes.NewBIP340PubKeyFromHex(req.BtcPk) + if err != nil { + return nil, err + } + fp, err := r.app.GetFinalityProviderInstance(fpPk) + if err != nil { + return nil, err + } + + fpInfo := proto.NewFinalityProviderInfo(fp.GetStoreFinalityProvider()) + + return &proto.QueryFinalityProviderResponse{FinalityProvider: fpInfo}, nil +} + +// QueryFinalityProviderList queries the information of a list of finality providers +func (r *rpcServer) QueryFinalityProviderList(ctx context.Context, req *proto.QueryFinalityProviderListRequest) ( + *proto.QueryFinalityProviderListResponse, error) { + + fps := r.app.ListFinalityProviderInstances() + + fpsInfo := make([]*proto.FinalityProviderInfo, len(fps)) + for i, fp := range fps { + fpInfo := proto.NewFinalityProviderInfo(fp.GetStoreFinalityProvider()) + fpsInfo[i] = fpInfo + } + + return &proto.QueryFinalityProviderListResponse{FinalityProviders: fpsInfo}, nil +} diff --git a/validator/service/server.go b/finality-provider/service/server.go similarity index 83% rename from validator/service/server.go rename to finality-provider/service/server.go index 85ed5fee..5b4dbf58 100644 --- a/validator/service/server.go +++ b/finality-provider/service/server.go @@ -10,16 +10,16 @@ import ( "go.uber.org/zap" "google.golang.org/grpc" - valcfg "github.com/babylonchain/btc-validator/validator/config" + fpcfg "github.com/babylonchain/finality-provider/finality-provider/config" ) -// Server is the main daemon construct for the BTC-Validator server. It handles +// Server is the main daemon construct for the Finality Provider server. It handles // spinning up the RPC sever, the database, and any other components that the // Taproot Asset server needs to function. type Server struct { started int32 - cfg *valcfg.Config + cfg *fpcfg.Config logger *zap.Logger rpcServer *rpcServer @@ -28,12 +28,12 @@ type Server struct { quit chan struct{} } -// NewValidatorServer creates a new server with the given config. -func NewValidatorServer(cfg *valcfg.Config, l *zap.Logger, v *ValidatorApp, sig signal.Interceptor) *Server { +// NewFinalityproviderServer creates a new server with the given config. +func NewFinalityProviderServer(cfg *fpcfg.Config, l *zap.Logger, fpa *FinalityProviderApp, sig signal.Interceptor) *Server { return &Server{ cfg: cfg, logger: l, - rpcServer: newRPCServer(v), + rpcServer: newRPCServer(fpa), interceptor: sig, quit: make(chan struct{}, 1), } @@ -72,7 +72,7 @@ func (s *Server) RunUntilShutdown() error { return fmt.Errorf("failed to start gRPC listener: %v", err) } - s.logger.Info("BTC Validator Daemon is fully active!") + s.logger.Info("Finality Provider Daemon is fully active!") // Wait for shutdown signal from either a graceful server stop or from // the interrupt handler. diff --git a/finality-provider/service/types.go b/finality-provider/service/types.go new file mode 100644 index 00000000..59ebf46e --- /dev/null +++ b/finality-provider/service/types.go @@ -0,0 +1,200 @@ +package service + +import ( + "sync" + + sdkmath "cosmossdk.io/math" + bbntypes "github.com/babylonchain/babylon/types" + btcstakingtypes "github.com/babylonchain/babylon/x/btcstaking/types" + "github.com/btcsuite/btcd/btcec/v2" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + "go.uber.org/zap" + + "github.com/babylonchain/finality-provider/finality-provider/proto" + fpstore "github.com/babylonchain/finality-provider/finality-provider/store" +) + +type createFinalityProviderResponse struct { + FpPk *bbntypes.BIP340PubKey +} +type createFinalityProviderRequest struct { + keyName string + passPhrase string + hdPath string + chainID string + description []byte + commission *sdkmath.LegacyDec + errResponse chan error + successResponse chan *createFinalityProviderResponse +} + +type registerFinalityProviderRequest struct { + bbnPubKey *secp256k1.PubKey + btcPubKey *bbntypes.BIP340PubKey + // TODO we should have our own representation of PoP + pop *btcstakingtypes.ProofOfPossession + description []byte + commission *sdkmath.LegacyDec + errResponse chan error + successResponse chan *RegisterFinalityProviderResponse +} + +type finalityProviderRegisteredEvent struct { + bbnPubKey *secp256k1.PubKey + btcPubKey *bbntypes.BIP340PubKey + txHash string + successResponse chan *RegisterFinalityProviderResponse +} + +type RegisterFinalityProviderResponse struct { + bbnPubKey *secp256k1.PubKey + btcPubKey *bbntypes.BIP340PubKey + TxHash string +} + +type CreateFinalityProviderResult struct { + FpPk *bbntypes.BIP340PubKey +} + +type fpState struct { + mu sync.Mutex + fp *proto.StoreFinalityProvider + s *fpstore.FinalityProviderStore +} + +func (fps *fpState) getStoreFinalityProvider() *proto.StoreFinalityProvider { + fps.mu.Lock() + defer fps.mu.Unlock() + return fps.fp +} + +func (fps *fpState) setStatus(s proto.FinalityProviderStatus) error { + fps.mu.Lock() + fps.fp.Status = s + fps.mu.Unlock() + return fps.s.UpdateFinalityProvider(fps.fp) +} + +func (fps *fpState) setLastProcessedHeight(height uint64) error { + fps.mu.Lock() + fps.fp.LastProcessedHeight = height + fps.mu.Unlock() + return fps.s.UpdateFinalityProvider(fps.fp) +} + +func (fps *fpState) setLastCommittedHeight(height uint64) error { + fps.mu.Lock() + fps.fp.LastCommittedHeight = height + fps.mu.Unlock() + return fps.s.UpdateFinalityProvider(fps.fp) +} + +func (fps *fpState) setLastProcessedAndVotedHeight(height uint64) error { + fps.mu.Lock() + fps.fp.LastVotedHeight = height + fps.fp.LastProcessedHeight = height + fps.mu.Unlock() + return fps.s.UpdateFinalityProvider(fps.fp) +} + +func (fp *FinalityProviderInstance) GetStoreFinalityProvider() *proto.StoreFinalityProvider { + return fp.state.getStoreFinalityProvider() +} + +func (fp *FinalityProviderInstance) GetBabylonPk() *secp256k1.PubKey { + return fp.state.getStoreFinalityProvider().GetBabylonPK() +} + +func (fp *FinalityProviderInstance) GetBabylonPkHex() string { + return fp.state.getStoreFinalityProvider().GetBabylonPkHexString() +} + +func (fp *FinalityProviderInstance) GetBtcPkBIP340() *bbntypes.BIP340PubKey { + return fp.state.getStoreFinalityProvider().MustGetBIP340BTCPK() +} + +func (fp *FinalityProviderInstance) MustGetBtcPk() *btcec.PublicKey { + return fp.state.getStoreFinalityProvider().MustGetBTCPK() +} + +func (fp *FinalityProviderInstance) GetBtcPkHex() string { + return fp.GetBtcPkBIP340().MarshalHex() +} + +func (fp *FinalityProviderInstance) GetStatus() proto.FinalityProviderStatus { + return fp.state.getStoreFinalityProvider().Status +} + +func (fp *FinalityProviderInstance) GetLastVotedHeight() uint64 { + return fp.state.getStoreFinalityProvider().LastVotedHeight +} + +func (fp *FinalityProviderInstance) GetLastProcessedHeight() uint64 { + return fp.state.getStoreFinalityProvider().LastProcessedHeight +} + +func (fp *FinalityProviderInstance) GetLastCommittedHeight() uint64 { + return fp.state.getStoreFinalityProvider().LastCommittedHeight +} + +func (fp *FinalityProviderInstance) GetChainID() []byte { + return []byte(fp.state.getStoreFinalityProvider().ChainId) +} + +func (fp *FinalityProviderInstance) SetStatus(s proto.FinalityProviderStatus) error { + return fp.state.setStatus(s) +} + +func (fp *FinalityProviderInstance) MustSetStatus(s proto.FinalityProviderStatus) { + if err := fp.SetStatus(s); err != nil { + fp.logger.Fatal("failed to set finality-provider status", + zap.String("pk", fp.GetBtcPkHex()), zap.String("status", s.String())) + } +} + +func (fp *FinalityProviderInstance) SetLastProcessedHeight(height uint64) error { + return fp.state.setLastProcessedHeight(height) +} + +func (fp *FinalityProviderInstance) MustSetLastProcessedHeight(height uint64) { + if err := fp.SetLastProcessedHeight(height); err != nil { + fp.logger.Fatal("failed to set last processed height", + zap.String("pk", fp.GetBtcPkHex()), zap.Uint64("last_processed_height", height)) + } +} + +func (fp *FinalityProviderInstance) SetLastCommittedHeight(height uint64) error { + return fp.state.setLastCommittedHeight(height) +} + +func (fp *FinalityProviderInstance) MustSetLastCommittedHeight(height uint64) { + if err := fp.SetLastCommittedHeight(height); err != nil { + fp.logger.Fatal("failed to set last committed height", + zap.String("pk", fp.GetBtcPkHex()), zap.Uint64("last_committed_height", height)) + } +} + +func (fp *FinalityProviderInstance) updateStateAfterFinalitySigSubmission(height uint64) error { + return fp.state.setLastProcessedAndVotedHeight(height) +} + +func (fp *FinalityProviderInstance) MustUpdateStateAfterFinalitySigSubmission(height uint64) { + if err := fp.updateStateAfterFinalitySigSubmission(height); err != nil { + fp.logger.Fatal("failed to update state after finality signature submitted", + zap.String("pk", fp.GetBtcPkHex()), zap.Uint64("height", height)) + } +} + +func (fp *FinalityProviderInstance) getEOTSPrivKey() (*btcec.PrivateKey, error) { + record, err := fp.em.KeyRecord(fp.btcPk.MustMarshal(), fp.passphrase) + if err != nil { + return nil, err + } + + return record.PrivKey, nil +} + +// only used for testing purposes +func (fp *FinalityProviderInstance) BtcPrivKey() (*btcec.PrivateKey, error) { + return fp.getEOTSPrivKey() +} diff --git a/finality-provider/store/fpstore.go b/finality-provider/store/fpstore.go new file mode 100644 index 00000000..feaa6088 --- /dev/null +++ b/finality-provider/store/fpstore.go @@ -0,0 +1,210 @@ +package store + +import ( + "fmt" + "math" + + sdkmath "cosmossdk.io/math" + "github.com/babylonchain/babylon/types" + bstypes "github.com/babylonchain/babylon/x/btcstaking/types" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + gproto "google.golang.org/protobuf/proto" + + "github.com/babylonchain/finality-provider/finality-provider/proto" + "github.com/babylonchain/finality-provider/store" +) + +const ( + fpPrefix = "finality-provider" +) + +func NewStoreFinalityProvider(babylonPk *secp256k1.PubKey, btcPk *types.BIP340PubKey, keyName, chainID string, pop *bstypes.ProofOfPossession, des []byte, com *sdkmath.LegacyDec) *proto.StoreFinalityProvider { + return &proto.StoreFinalityProvider{ + KeyName: keyName, + BabylonPk: babylonPk.Bytes(), + BtcPk: btcPk.MustMarshal(), + Pop: &proto.ProofOfPossession{ + BabylonSig: pop.BabylonSig, + BtcSig: pop.BtcSig, + }, + ChainId: chainID, + Status: proto.FinalityProviderStatus_CREATED, + Description: des, + Commission: com.String(), + } +} + +type FinalityProviderStore struct { + s store.Store +} + +func NewFinalityProviderStore(dbPath string, dbName string, dbBackend string) (*FinalityProviderStore, error) { + s, err := openStore(dbPath, dbName, dbBackend) + if err != nil { + return nil, err + } + + return &FinalityProviderStore{s: s}, nil +} + +func getFinalityProviderKey(pk []byte) []byte { + return append([]byte(fpPrefix), pk...) +} + +func (vs *FinalityProviderStore) getFinalityProviderListKey() []byte { + return []byte(fpPrefix) +} + +func (vs *FinalityProviderStore) SaveFinalityProvider(fp *proto.StoreFinalityProvider) error { + k := getFinalityProviderKey(fp.BtcPk) + v, err := gproto.Marshal(fp) + if err != nil { + return fmt.Errorf("failed to marshal the created finality-provider object: %w", err) + } + + if err := vs.s.Put(k, v); err != nil { + return fmt.Errorf("failed to save the created finality-provider object: %w", err) + } + + return nil +} + +func (vs *FinalityProviderStore) UpdateFinalityProvider(fp *proto.StoreFinalityProvider) error { + k := getFinalityProviderKey(fp.BtcPk) + exists, err := vs.s.Exists(k) + if err != nil { + return err + } + if !exists { + return fmt.Errorf("the finality-provider does not exist") + } + + v, err := gproto.Marshal(fp) + if err != nil { + return err + } + + if err := vs.s.Put(k, v); err != nil { + return err + } + + return nil +} + +func (vs *FinalityProviderStore) SetFinalityProviderStatus(fp *proto.StoreFinalityProvider, status proto.FinalityProviderStatus) error { + fp.Status = status + return vs.UpdateFinalityProvider(fp) +} + +func (vs *FinalityProviderStore) GetStoreFinalityProvider(pk []byte) (*proto.StoreFinalityProvider, error) { + k := getFinalityProviderKey(pk) + fpBytes, err := vs.s.Get(k) + if err != nil { + return nil, err + } + + fp := new(proto.StoreFinalityProvider) + err = gproto.Unmarshal(fpBytes, fp) + if err != nil { + panic(fmt.Errorf("unable to unmarshal finality-provider object: %w", err)) + } + + return fp, nil +} + +func (vs *FinalityProviderStore) ListFinalityProviders() ([]*proto.StoreFinalityProvider, error) { + k := vs.getFinalityProviderListKey() + fpsBytes, err := vs.s.List(k) + if err != nil { + return nil, err + } + + fpsList := make([]*proto.StoreFinalityProvider, len(fpsBytes)) + for i := 0; i < len(fpsBytes); i++ { + fp := new(proto.StoreFinalityProvider) + err := gproto.Unmarshal(fpsBytes[i].Value, fp) + if err != nil { + panic(fmt.Errorf("failed to unmarshal finality-provider from the database: %w", err)) + } + fpsList[i] = fp + } + + return fpsList, nil +} + +// ListRegisteredFinalityProviders returns a list of finality providers whose status is more than CREATED +// but less than SLASHED +func (vs *FinalityProviderStore) ListRegisteredFinalityProviders() ([]*proto.StoreFinalityProvider, error) { + k := vs.getFinalityProviderListKey() + fpsBytes, err := vs.s.List(k) + if err != nil { + return nil, err + } + + fpsList := make([]*proto.StoreFinalityProvider, 0) + for i := 0; i < len(fpsBytes); i++ { + fp := new(proto.StoreFinalityProvider) + err := gproto.Unmarshal(fpsBytes[i].Value, fp) + if err != nil { + panic(fmt.Errorf("failed to unmarshal finality-provider from the database: %w", err)) + } + if fp.Status > proto.FinalityProviderStatus_CREATED && fp.Status < proto.FinalityProviderStatus_SLASHED { + fpsList = append(fpsList, fp) + } + } + + return fpsList, nil +} + +func (vs *FinalityProviderStore) GetEarliestActiveFinalityProviderVotedHeight() (uint64, error) { + registeredFps, err := vs.ListRegisteredFinalityProviders() + if err != nil { + return 0, err + } + + if len(registeredFps) == 0 { + return 0, nil + } + + earliestHeight := uint64(math.MaxUint64) + activeFpsCnt := 0 + for _, fp := range registeredFps { + // Note there might be a delay between the finality-provider being active on Babylon + // and this program capturing that. However, given that we only care + // about the `LastVotedHeight` of the finality-provider, other parts of the program + // ensure that when this value is set, the finality-provider is stored as ACTIVE. + // TODO: Another option would be to query here for the + // active status of each finality-provider although this might prove inefficient. + if fp.Status != proto.FinalityProviderStatus_ACTIVE { + continue + } + activeFpsCnt += 1 + if earliestHeight > fp.LastVotedHeight { + earliestHeight = fp.LastVotedHeight + } + } + // If there are no active finality providers, return 0 + if activeFpsCnt == 0 { + return 0, nil + } + return earliestHeight, nil +} + +func (vs *FinalityProviderStore) Close() error { + if err := vs.s.Close(); err != nil { + return err + } + + return nil +} + +// openStore returns a Store instance with the given db type, path and name +// currently, we only support bbolt +func openStore(dbPath string, dbName string, dbBackend string) (store.Store, error) { + switch dbBackend { + case "bbolt": + return store.NewBboltStore(dbPath, dbName) + default: + return nil, fmt.Errorf("unsupported database type") + } +} diff --git a/finality-provider/store/fpstore_test.go b/finality-provider/store/fpstore_test.go new file mode 100644 index 00000000..a8c39a2b --- /dev/null +++ b/finality-provider/store/fpstore_test.go @@ -0,0 +1,45 @@ +package store_test + +import ( + "math/rand" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" + + fpstore "github.com/babylonchain/finality-provider/finality-provider/store" + "github.com/babylonchain/finality-provider/testutil" +) + +// FuzzFinalityProvidersStore tests save and list finality providers properly +func FuzzFinalityProvidersStore(f *testing.F) { + testutil.AddRandomSeedsToFuzzer(f, 10) + f.Fuzz(func(t *testing.T, seed int64) { + r := rand.New(rand.NewSource(seed)) + + dbPath := filepath.Join(t.TempDir(), "db") + dbcfg := testutil.GenDBConfig(r, t) + vs, err := fpstore.NewFinalityProviderStore(dbPath, dbcfg.Name, dbcfg.Backend) + require.NoError(t, err) + + defer func() { + err := os.RemoveAll(dbPath) + require.NoError(t, err) + }() + + fp := testutil.GenRandomFinalityProvider(r, t) + err = vs.SaveFinalityProvider(fp) + require.NoError(t, err) + + fpList, err := vs.ListFinalityProviders() + require.NoError(t, err) + require.Equal(t, fp.BtcPk, fpList[0].BtcPk) + + actualFp, err := vs.GetStoreFinalityProvider(fp.BtcPk) + require.NoError(t, err) + require.Equal(t, fp.BabylonPk, actualFp.BabylonPk) + require.Equal(t, fp.BtcPk, actualFp.BtcPk) + require.Equal(t, fp.KeyName, actualFp.KeyName) + }) +} diff --git a/go.mod b/go.mod index 13bfb2bc..3763a9de 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module github.com/babylonchain/btc-validator +module github.com/babylonchain/finality-provider go 1.21 @@ -238,8 +238,8 @@ require ( ) replace ( - github.com/babylonchain/babylon => github.com/babylonchain/babylon-private v0.0.0-20231212092759-3504554e618b - github.com/babylonchain/rpc-client => github.com/babylonchain/rpc-client-private v0.7.0-rc0.0.20231128092309-ad2ef0696dc1 + github.com/babylonchain/babylon => github.com/babylonchain/babylon-private v0.0.0-20231213105136-11792cad8a84 + github.com/babylonchain/rpc-client => github.com/babylonchain/rpc-client-private v0.7.0-rc0.0.20231214053715-9de58555773a github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.3-alpha.regen.1 github.com/syndtr/goleveldb => github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 ) diff --git a/go.sum b/go.sum index 6b5dd0af..5ce19912 100644 --- a/go.sum +++ b/go.sum @@ -279,10 +279,10 @@ github.com/aws/aws-sdk-go v1.44.122/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX github.com/aws/aws-sdk-go v1.44.312 h1:llrElfzeqG/YOLFFKjg1xNpZCFJ2xraIi3PqSuP+95k= github.com/aws/aws-sdk-go v1.44.312/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI= github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g= -github.com/babylonchain/babylon-private v0.0.0-20231212092759-3504554e618b h1:FAadQ5l5ORQa/P8IRRtHXibK7g7MHOzhKxmvObY42OI= -github.com/babylonchain/babylon-private v0.0.0-20231212092759-3504554e618b/go.mod h1:6wqL7SJBWltXMNXgFsvavB1bR5Fft0yChfRLamBtrAY= -github.com/babylonchain/rpc-client-private v0.7.0-rc0.0.20231128092309-ad2ef0696dc1 h1:Cf1aNeXcSfZczocNxZZ1mM+KU4NDopzaIyi1fSoezxo= -github.com/babylonchain/rpc-client-private v0.7.0-rc0.0.20231128092309-ad2ef0696dc1/go.mod h1:M/tRKH7cc0gpAqCEpHTiaYob/6xoTD4v3A4FZQ3Y3ks= +github.com/babylonchain/babylon-private v0.0.0-20231213105136-11792cad8a84 h1:fFlLF+rl6Buwb3eYgIoUQ4JkYdNMMTk9ihoznTTw2hk= +github.com/babylonchain/babylon-private v0.0.0-20231213105136-11792cad8a84/go.mod h1:6wqL7SJBWltXMNXgFsvavB1bR5Fft0yChfRLamBtrAY= +github.com/babylonchain/rpc-client-private v0.7.0-rc0.0.20231214053715-9de58555773a h1:IwntCUOlcsczQfl4P72ckqGf09coMdM42LvAG1aM+mg= +github.com/babylonchain/rpc-client-private v0.7.0-rc0.0.20231214053715-9de58555773a/go.mod h1:dnUVCa5yHq2giiSpBpXx7W3CbJuuMabvQi3hG81AAtM= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= diff --git a/itest/e2e_test.go b/itest/e2e_test.go index fc08cf60..cfb11d4b 100644 --- a/itest/e2e_test.go +++ b/itest/e2e_test.go @@ -4,16 +4,16 @@ package e2etest import ( + "github.com/btcsuite/btcd/btcec/v2" "math/rand" "testing" "time" "github.com/babylonchain/babylon/testutil/datagen" - "github.com/btcsuite/btcd/btcec/v2" "github.com/stretchr/testify/require" - "github.com/babylonchain/btc-validator/types" - "github.com/babylonchain/btc-validator/validator/service" + "github.com/babylonchain/finality-provider/finality-provider/service" + "github.com/babylonchain/finality-provider/types" ) var ( @@ -21,110 +21,110 @@ var ( stakingAmount = int64(20000) ) -// TestValidatorLifeCycle tests the whole life cycle of a validator +// TestFinalityProviderLifeCycle tests the whole life cycle of a finality-provider // creation -> registration -> randomness commitment -> // activation with BTC delegation and Covenant sig -> // vote submission -> block finalization -func TestValidatorLifeCycle(t *testing.T) { - tm, valInsList := StartManagerWithValidator(t, 1) +func TestFinalityProviderLifeCycle(t *testing.T) { + tm, fpInsList := StartManagerWithFinalityProvider(t, 1) defer tm.Stop(t) - valIns := valInsList[0] + fpIns := fpInsList[0] params := tm.GetParams(t) // check the public randomness is committed - tm.WaitForValPubRandCommitted(t, valIns) + tm.WaitForFpPubRandCommitted(t, fpIns) // send a BTC delegation - _ = tm.InsertBTCDelegation(t, []*btcec.PublicKey{valIns.MustGetBtcPk()}, stakingTime, stakingAmount, params) + _ = tm.InsertBTCDelegation(t, []*btcec.PublicKey{fpIns.MustGetBtcPk()}, stakingTime, stakingAmount, params) // check the BTC delegation is pending _ = tm.WaitForNPendingDels(t, 1) // check the BTC delegation is active - _ = tm.WaitForValNActiveDels(t, valIns.GetBtcPkBIP340(), 1) + _ = tm.WaitForFpNActiveDels(t, fpIns.GetBtcPkBIP340(), 1) // check the last voted block is finalized - lastVotedHeight := tm.WaitForValVoteCast(t, valIns) + lastVotedHeight := tm.WaitForFpVoteCast(t, fpIns) tm.CheckBlockFinalization(t, lastVotedHeight, 1) t.Logf("the block at height %v is finalized", lastVotedHeight) } -// TestDoubleSigning tests the attack scenario where the validator +// TestDoubleSigning tests the attack scenario where the finality-provider // sends a finality vote over a conflicting block // in this case, the BTC private key should be extracted by Babylon func TestDoubleSigning(t *testing.T) { - tm, valInsList := StartManagerWithValidator(t, 1) + tm, fpInsList := StartManagerWithFinalityProvider(t, 1) defer tm.Stop(t) - valIns := valInsList[0] + fpIns := fpInsList[0] params := tm.GetParams(t) // check the public randomness is committed - tm.WaitForValPubRandCommitted(t, valIns) + tm.WaitForFpPubRandCommitted(t, fpIns) // send a BTC delegation - _ = tm.InsertBTCDelegation(t, []*btcec.PublicKey{valIns.MustGetBtcPk()}, stakingTime, stakingAmount, params) + _ = tm.InsertBTCDelegation(t, []*btcec.PublicKey{fpIns.MustGetBtcPk()}, stakingTime, stakingAmount, params) // check the BTC delegation is pending _ = tm.WaitForNPendingDels(t, 1) // check the BTC delegation is active - _ = tm.WaitForValNActiveDels(t, valIns.GetBtcPkBIP340(), 1) + _ = tm.WaitForFpNActiveDels(t, fpIns.GetBtcPkBIP340(), 1) // check the last voted block is finalized - lastVotedHeight := tm.WaitForValVoteCast(t, valIns) + lastVotedHeight := tm.WaitForFpVoteCast(t, fpIns) tm.CheckBlockFinalization(t, lastVotedHeight, 1) t.Logf("the block at height %v is finalized", lastVotedHeight) finalizedBlocks := tm.WaitForNFinalizedBlocks(t, 1) // attack: manually submit a finality vote over a conflicting block - // to trigger the extraction of validator's private key + // to trigger the extraction of finality-provider's private key r := rand.New(rand.NewSource(time.Now().UnixNano())) b := &types.BlockInfo{ Height: finalizedBlocks[0].Height, Hash: datagen.GenRandomAppHash(r), } - _, extractedKey, err := valIns.TestSubmitFinalitySignatureAndExtractPrivKey(b) + _, extractedKey, err := fpIns.TestSubmitFinalitySignatureAndExtractPrivKey(b) require.NoError(t, err) require.NotNil(t, extractedKey) - localKey := tm.GetValPrivKey(t, valIns.GetBtcPkBIP340().MustMarshal()) + localKey := tm.GetFpPrivKey(t, fpIns.GetBtcPkBIP340().MustMarshal()) require.True(t, localKey.Key.Equals(&extractedKey.Key) || localKey.Key.Negate().Equals(&extractedKey.Key)) t.Logf("the equivocation attack is successful") } -// TestMultipleValidators tests starting with multiple validators -func TestMultipleValidators(t *testing.T) { +// TestMultipleFinalityProviders tests starting with multiple finality providers +func TestMultipleFinalityProviders(t *testing.T) { n := 3 - tm, valInstances := StartManagerWithValidator(t, n) + tm, fpInstances := StartManagerWithFinalityProvider(t, n) defer tm.Stop(t) params := tm.GetParams(t) - // submit BTC delegations for each validator - for _, valIns := range valInstances { + // submit BTC delegations for each finality-provider + for _, fpIns := range fpInstances { tm.Wg.Add(1) - go func(v *service.ValidatorInstance) { + go func(fpi *service.FinalityProviderInstance) { defer tm.Wg.Done() // check the public randomness is committed - tm.WaitForValPubRandCommitted(t, v) + tm.WaitForFpPubRandCommitted(t, fpi) // send a BTC delegation - _ = tm.InsertBTCDelegation(t, []*btcec.PublicKey{v.MustGetBtcPk()}, stakingTime, stakingAmount, params) - }(valIns) + _ = tm.InsertBTCDelegation(t, []*btcec.PublicKey{fpi.MustGetBtcPk()}, stakingTime, stakingAmount, params) + }(fpIns) } tm.Wg.Wait() - for _, valIns := range valInstances { + for _, fpIns := range fpInstances { tm.Wg.Add(1) - go func(v *service.ValidatorInstance) { + go func(fpi *service.FinalityProviderInstance) { defer tm.Wg.Done() - _ = tm.WaitForValNActiveDels(t, v.GetBtcPkBIP340(), 1) - }(valIns) + _ = tm.WaitForFpNActiveDels(t, fpi.GetBtcPkBIP340(), 1) + }(fpIns) } tm.Wg.Wait() @@ -132,28 +132,28 @@ func TestMultipleValidators(t *testing.T) { _ = tm.WaitForNFinalizedBlocks(t, 1) } -// TestFastSync tests the fast sync process where the validator is terminated and restarted with fast sync +// TestFastSync tests the fast sync process where the finality-provider is terminated and restarted with fast sync func TestFastSync(t *testing.T) { - tm, valInsList := StartManagerWithValidator(t, 1) + tm, fpInsList := StartManagerWithFinalityProvider(t, 1) defer tm.Stop(t) - valIns := valInsList[0] + fpIns := fpInsList[0] params := tm.GetParams(t) // check the public randomness is committed - tm.WaitForValPubRandCommitted(t, valIns) + tm.WaitForFpPubRandCommitted(t, fpIns) // send a BTC delegation - _ = tm.InsertBTCDelegation(t, []*btcec.PublicKey{valIns.MustGetBtcPk()}, stakingTime, stakingAmount, params) + _ = tm.InsertBTCDelegation(t, []*btcec.PublicKey{fpIns.MustGetBtcPk()}, stakingTime, stakingAmount, params) // check the BTC delegation is pending _ = tm.WaitForNPendingDels(t, 1) - _ = tm.WaitForValNActiveDels(t, valIns.GetBtcPkBIP340(), 1) + _ = tm.WaitForFpNActiveDels(t, fpIns.GetBtcPkBIP340(), 1) // check the last voted block is finalized - lastVotedHeight := tm.WaitForValVoteCast(t, valIns) + lastVotedHeight := tm.WaitForFpVoteCast(t, fpIns) tm.CheckBlockFinalization(t, lastVotedHeight, 1) t.Logf("the block at height %v is finalized", lastVotedHeight) @@ -162,9 +162,9 @@ func TestFastSync(t *testing.T) { finalizedBlocks = tm.WaitForNFinalizedBlocks(t, 1) n := 3 - // stop the validator for a few blocks then restart to trigger the fast sync - tm.ValConfig.FastSyncGap = uint64(n) - tm.StopAndRestartValidatorAfterNBlocks(t, n, valIns) + // stop the finality-provider for a few blocks then restart to trigger the fast sync + tm.FpConfig.FastSyncGap = uint64(n) + tm.StopAndRestartFpAfterNBlocks(t, n, fpIns) // check there are n+1 blocks finalized finalizedBlocks = tm.WaitForNFinalizedBlocks(t, n+1) diff --git a/itest/eotsmanager_handler.go b/itest/eotsmanager_handler.go index 0a041c97..2c644500 100644 --- a/itest/eotsmanager_handler.go +++ b/itest/eotsmanager_handler.go @@ -7,9 +7,9 @@ import ( "github.com/stretchr/testify/require" "go.uber.org/zap" - "github.com/babylonchain/btc-validator/eotsmanager" - "github.com/babylonchain/btc-validator/eotsmanager/config" - "github.com/babylonchain/btc-validator/eotsmanager/service" + "github.com/babylonchain/finality-provider/eotsmanager" + "github.com/babylonchain/finality-provider/eotsmanager/config" + "github.com/babylonchain/finality-provider/eotsmanager/service" ) type EOTSServerHandler struct { diff --git a/itest/test_manager.go b/itest/test_manager.go index 7c1aaa58..4da76eae 100644 --- a/itest/test_manager.go +++ b/itest/test_manager.go @@ -1,6 +1,7 @@ package e2etest import ( + "github.com/btcsuite/btcd/btcec/v2" "math/rand" "os" "path/filepath" @@ -16,7 +17,6 @@ import ( btcctypes "github.com/babylonchain/babylon/x/btccheckpoint/types" btclctypes "github.com/babylonchain/babylon/x/btclightclient/types" bstypes "github.com/babylonchain/babylon/x/btcstaking/types" - "github.com/btcsuite/btcd/btcec/v2" "github.com/btcsuite/btcd/chaincfg" "github.com/btcsuite/btcd/wire" "github.com/cosmos/cosmos-sdk/crypto/keyring" @@ -25,14 +25,14 @@ import ( "github.com/stretchr/testify/require" "go.uber.org/zap" - "github.com/babylonchain/btc-validator/clientcontroller" - "github.com/babylonchain/btc-validator/covenant" - covcfg "github.com/babylonchain/btc-validator/covenant/config" - "github.com/babylonchain/btc-validator/eotsmanager/client" - eotsconfig "github.com/babylonchain/btc-validator/eotsmanager/config" - "github.com/babylonchain/btc-validator/types" - valcfg "github.com/babylonchain/btc-validator/validator/config" - "github.com/babylonchain/btc-validator/validator/service" + "github.com/babylonchain/finality-provider/clientcontroller" + "github.com/babylonchain/finality-provider/covenant" + covcfg "github.com/babylonchain/finality-provider/covenant/config" + "github.com/babylonchain/finality-provider/eotsmanager/client" + eotsconfig "github.com/babylonchain/finality-provider/eotsmanager/config" + fpcfg "github.com/babylonchain/finality-provider/finality-provider/config" + "github.com/babylonchain/finality-provider/finality-provider/service" + "github.com/babylonchain/finality-provider/types" ) var ( @@ -40,7 +40,7 @@ var ( eventuallyPollTime = 500 * time.Millisecond btcNetworkParams = &chaincfg.SimNetParams - valNamePrefix = "test-val-" + fpNamePrefix = "test-fp-" monikerPrefix = "moniker-" covenantKeyName = "covenant-key" chainID = "chain-test" @@ -53,10 +53,10 @@ type TestManager struct { BabylonHandler *BabylonNodeHandler EOTSServerHandler *EOTSServerHandler CovenantEmulator *covenant.CovenantEmulator - ValConfig *valcfg.Config + FpConfig *fpcfg.Config EOTSConfig *eotsconfig.Config CovenanConfig *covcfg.Config - Va *service.ValidatorApp + Fpa *service.FinalityProviderApp EOTSClient *client.EOTSManagerGRpcClient BabylonClient *clientcontroller.BabylonController baseDir string @@ -71,7 +71,7 @@ type TestDelegationData struct { StakingTx *wire.MsgTx StakingTxInfo *btcctypes.TransactionInfo DelegatorSig *bbntypes.BIP340Signature - ValidatorPks []*btcec.PublicKey + FpPks []*btcec.PublicKey SlashingAddr string ChangeAddr string @@ -80,7 +80,7 @@ type TestDelegationData struct { } func StartManager(t *testing.T) *TestManager { - testDir, err := tempDirWithName("vale2etest") + testDir, err := tempDirWithName("fpe2etest") require.NoError(t, err) logger := zap.NewNop() @@ -96,8 +96,8 @@ func StartManager(t *testing.T) *TestManager { bh := NewBabylonNodeHandler(t, bbntypes.NewBIP340PubKeyFromBTCPK(covKeyPair.PublicKey)) err = bh.Start() require.NoError(t, err) - valHomeDir := filepath.Join(testDir, "val-home") - cfg := defaultValidatorConfig(bh.GetNodeDataDir(), valHomeDir) + fpHomeDir := filepath.Join(testDir, "fp-home") + cfg := defaultFpConfig(bh.GetNodeDataDir(), fpHomeDir) bc, err := clientcontroller.NewBabylonController(cfg.BabylonConfig, &cfg.BTCNetParams, logger) require.NoError(t, err) @@ -109,10 +109,10 @@ func StartManager(t *testing.T) *TestManager { eotsCli, err := client.NewEOTSManagerGRpcClient(cfg.EOTSManagerAddress) require.NoError(t, err) - // 4. prepare validator - valApp, err := service.NewValidatorApp(valHomeDir, cfg, bc, eotsCli, logger) + // 4. prepare finality-provider + fpApp, err := service.NewFinalityProviderApp(fpHomeDir, cfg, bc, eotsCli, logger) require.NoError(t, err) - err = valApp.Start() + err = fpApp.Start() require.NoError(t, err) // 5. prepare covenant emulator @@ -124,9 +124,9 @@ func StartManager(t *testing.T) *TestManager { tm := &TestManager{ BabylonHandler: bh, EOTSServerHandler: eh, - ValConfig: cfg, + FpConfig: cfg, EOTSConfig: eotsCfg, - Va: valApp, + Fpa: fpApp, CovenantEmulator: ce, CovenanConfig: covenantConfig, EOTSClient: eotsCli, @@ -150,44 +150,44 @@ func (tm *TestManager) WaitForServicesStart(t *testing.T) { t.Logf("Babylon node is started") } -func StartManagerWithValidator(t *testing.T, n int) (*TestManager, []*service.ValidatorInstance) { +func StartManagerWithFinalityProvider(t *testing.T, n int) (*TestManager, []*service.FinalityProviderInstance) { tm := StartManager(t) - app := tm.Va + app := tm.Fpa for i := 0; i < n; i++ { - valName := valNamePrefix + strconv.Itoa(i) + fpName := fpNamePrefix + strconv.Itoa(i) moniker := monikerPrefix + strconv.Itoa(i) commission := sdkmath.LegacyZeroDec() desc, err := newDescription(moniker).Marshal() require.NoError(t, err) - res, err := app.CreateValidator(valName, chainID, passphrase, hdPath, desc, &commission) + res, err := app.CreateFinalityProvider(fpName, chainID, passphrase, hdPath, desc, &commission) require.NoError(t, err) - _, err = app.RegisterValidator(res.ValPk.MarshalHex()) + _, err = app.RegisterFinalityProvider(res.FpPk.MarshalHex()) require.NoError(t, err) - err = app.StartHandlingValidator(res.ValPk, passphrase) + err = app.StartHandlingFinalityProvider(res.FpPk, passphrase) require.NoError(t, err) - valIns, err := app.GetValidatorInstance(res.ValPk) + fpIns, err := app.GetFinalityProviderInstance(res.FpPk) require.NoError(t, err) - require.True(t, valIns.IsRunning()) + require.True(t, fpIns.IsRunning()) require.NoError(t, err) - // check validators on Babylon side + // check finality providers on Babylon side require.Eventually(t, func() bool { - vals, err := tm.BabylonClient.QueryValidators() + fps, err := tm.BabylonClient.QueryFinalityProviders() if err != nil { - t.Logf("failed to query validtors from Babylon %s", err.Error()) + t.Logf("failed to query finality providers from Babylon %s", err.Error()) return false } - if len(vals) != i+1 { + if len(fps) != i+1 { return false } - for _, v := range vals { - if !strings.Contains(v.Description.Moniker, monikerPrefix) { + for _, fp := range fps { + if !strings.Contains(fp.Description.Moniker, monikerPrefix) { return false } - if !v.Commission.Equal(sdkmath.LegacyZeroDec()) { + if !fp.Commission.Equal(sdkmath.LegacyZeroDec()) { return false } } @@ -196,16 +196,16 @@ func StartManagerWithValidator(t *testing.T, n int) (*TestManager, []*service.Va }, eventuallyWaitTimeOut, eventuallyPollTime) } - valInsList := app.ListValidatorInstances() - require.Equal(t, n, len(valInsList)) + fpInsList := app.ListFinalityProviderInstances() + require.Equal(t, n, len(fpInsList)) - t.Logf("the test manager is running with %v validator(s)", len(valInsList)) + t.Logf("the test manager is running with %v finality-provider(s)", len(fpInsList)) - return tm, valInsList + return tm, fpInsList } func (tm *TestManager) Stop(t *testing.T) { - err := tm.Va.Stop() + err := tm.Fpa.Stop() require.NoError(t, err) err = tm.CovenantEmulator.Stop() require.NoError(t, err) @@ -216,21 +216,21 @@ func (tm *TestManager) Stop(t *testing.T) { tm.EOTSServerHandler.Stop() } -func (tm *TestManager) WaitForValRegistered(t *testing.T, bbnPk *secp256k1.PubKey) { +func (tm *TestManager) WaitForFpRegistered(t *testing.T, bbnPk *secp256k1.PubKey) { require.Eventually(t, func() bool { - queriedValidators, err := tm.BabylonClient.QueryValidators() + queriedFps, err := tm.BabylonClient.QueryFinalityProviders() if err != nil { return false } - return len(queriedValidators) == 1 && queriedValidators[0].BabylonPk.Equals(bbnPk) + return len(queriedFps) == 1 && queriedFps[0].BabylonPk.Equals(bbnPk) }, eventuallyWaitTimeOut, eventuallyPollTime) - t.Logf("the validator is successfully registered") + t.Logf("the finality-provider is successfully registered") } -func (tm *TestManager) WaitForValPubRandCommitted(t *testing.T, valIns *service.ValidatorInstance) { +func (tm *TestManager) WaitForFpPubRandCommitted(t *testing.T, fpIns *service.FinalityProviderInstance) { require.Eventually(t, func() bool { - return valIns.GetLastCommittedHeight() > 0 + return fpIns.GetLastCommittedHeight() > 0 }, eventuallyWaitTimeOut, eventuallyPollTime) t.Logf("public randomness is successfully committed") @@ -256,14 +256,14 @@ func (tm *TestManager) WaitForNPendingDels(t *testing.T, n int) []*types.Delegat return dels } -func (tm *TestManager) WaitForValNActiveDels(t *testing.T, btcPk *bbntypes.BIP340PubKey, n int) []*types.Delegation { +func (tm *TestManager) WaitForFpNActiveDels(t *testing.T, btcPk *bbntypes.BIP340PubKey, n int) []*types.Delegation { var dels []*types.Delegation currentBtcTip, err := tm.BabylonClient.QueryBtcLightClientTip() require.NoError(t, err) params, err := tm.BabylonClient.QueryStakingParams() require.NoError(t, err) require.Eventually(t, func() bool { - dels, err = tm.BabylonClient.QueryBTCValidatorDelegations(btcPk, 1000) + dels, err = tm.BabylonClient.QueryFinalityProviderDelegations(btcPk, 1000) if err != nil { return false } @@ -271,7 +271,7 @@ func (tm *TestManager) WaitForValNActiveDels(t *testing.T, btcPk *bbntypes.BIP34 params.CovenantQuorum, bstypes.BTCDelegationStatus_ACTIVE) }, eventuallyWaitTimeOut, eventuallyPollTime) - t.Logf("the delegation is active, validators should start voting") + t.Logf("the delegation is active, finality providers should start voting") return dels } @@ -333,11 +333,11 @@ func (tm *TestManager) CheckBlockFinalization(t *testing.T, height uint64, num i }, eventuallyWaitTimeOut, eventuallyPollTime) } -func (tm *TestManager) WaitForValVoteCast(t *testing.T, valIns *service.ValidatorInstance) uint64 { +func (tm *TestManager) WaitForFpVoteCast(t *testing.T, fpIns *service.FinalityProviderInstance) uint64 { var lastVotedHeight uint64 require.Eventually(t, func() bool { - if valIns.GetLastVotedHeight() > 0 { - lastVotedHeight = valIns.GetLastVotedHeight() + if fpIns.GetLastVotedHeight() > 0 { + lastVotedHeight = fpIns.GetLastVotedHeight() return true } else { return false @@ -366,10 +366,10 @@ func (tm *TestManager) WaitForNFinalizedBlocks(t *testing.T, n int) []*types.Blo return blocks } -func (tm *TestManager) StopAndRestartValidatorAfterNBlocks(t *testing.T, n int, valIns *service.ValidatorInstance) { +func (tm *TestManager) StopAndRestartFpAfterNBlocks(t *testing.T, n int, fpIns *service.FinalityProviderInstance) { blockBeforeStop, err := tm.BabylonClient.QueryBestBlock() require.NoError(t, err) - err = valIns.Stop() + err = fpIns.Stop() require.NoError(t, err) require.Eventually(t, func() bool { @@ -381,20 +381,20 @@ func (tm *TestManager) StopAndRestartValidatorAfterNBlocks(t *testing.T, n int, return headerAfterStop.Height >= uint64(n)+blockBeforeStop.Height }, eventuallyWaitTimeOut, eventuallyPollTime) - t.Log("restarting the validator instance") + t.Log("restarting the finality-provider instance") - tm.ValConfig.PollerConfig.AutoChainScanningMode = true - err = valIns.Start() + tm.FpConfig.PollerConfig.AutoChainScanningMode = true + err = fpIns.Start() require.NoError(t, err) } -func (tm *TestManager) GetValPrivKey(t *testing.T, valPk []byte) *btcec.PrivateKey { - record, err := tm.EOTSClient.KeyRecord(valPk, passphrase) +func (tm *TestManager) GetFpPrivKey(t *testing.T, fpPk []byte) *btcec.PrivateKey { + record, err := tm.EOTSClient.KeyRecord(fpPk, passphrase) require.NoError(t, err) return record.PrivKey } -func (tm *TestManager) InsertBTCDelegation(t *testing.T, validatorPks []*btcec.PublicKey, stakingTime uint16, stakingAmount int64, params *types.StakingParams) *TestDelegationData { +func (tm *TestManager) InsertBTCDelegation(t *testing.T, fpPks []*btcec.PublicKey, stakingTime uint16, stakingAmount int64, params *types.StakingParams) *TestDelegationData { r := rand.New(rand.NewSource(time.Now().UnixNano())) // delegator BTC key pairs, staking tx and slashing tx @@ -409,7 +409,7 @@ func (tm *TestManager) InsertBTCDelegation(t *testing.T, validatorPks []*btcec.P t, btcNetworkParams, delBtcPrivKey, - validatorPks, + fpPks, params.CovenantPks, params.CovenantQuorum, stakingTime, @@ -473,7 +473,7 @@ func (tm *TestManager) InsertBTCDelegation(t *testing.T, validatorPks []*btcec.P t, btcNetworkParams, delBtcPrivKey, - validatorPks, + fpPks, params.CovenantPks, params.CovenantQuorum, wire.NewOutPoint(&stakingTxHash, 0), @@ -504,7 +504,7 @@ func (tm *TestManager) InsertBTCDelegation(t *testing.T, validatorPks []*btcec.P _, err = tm.BabylonClient.CreateBTCDelegation( delBabylonPubKey.(*secp256k1.PubKey), bbntypes.NewBIP340PubKeyFromBTCPK(delBtcPubKey), - validatorPks, + fpPks, pop, uint32(stakingTime), stakingAmount, @@ -525,7 +525,7 @@ func (tm *TestManager) InsertBTCDelegation(t *testing.T, validatorPks []*btcec.P DelegatorKey: delBtcPubKey, DelegatorBabylonPrivKey: delBabylonPrivKey.(*secp256k1.PrivKey), DelegatorBabylonKey: delBabylonPubKey.(*secp256k1.PubKey), - ValidatorPks: validatorPks, + FpPks: fpPks, StakingTx: testStakingInfo.StakingTx, SlashingTx: testStakingInfo.SlashingTx, StakingTxInfo: txInfo, @@ -543,8 +543,8 @@ func (tm *TestManager) GetParams(t *testing.T) *types.StakingParams { return p } -func defaultValidatorConfig(keyringDir, homeDir string) *valcfg.Config { - cfg := valcfg.DefaultConfigWithHome(homeDir) +func defaultFpConfig(keyringDir, homeDir string) *fpcfg.Config { + cfg := fpcfg.DefaultConfigWithHome(homeDir) cfg.PollerConfig.AutoChainScanningMode = false // babylon configs for sending transactions diff --git a/keyring/keyring.go b/keyring/keyring.go index 920d0cfd..36b526b3 100644 --- a/keyring/keyring.go +++ b/keyring/keyring.go @@ -9,7 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/babylonchain/btc-validator/codec" + "github.com/babylonchain/finality-provider/codec" ) func CreateKeyring(keyringDir string, chainId string, backend string, input *strings.Reader) (keyring.Keyring, error) { @@ -45,7 +45,7 @@ func CreateClientCtx(keyringDir string, chainId string) (client.Context, error) if err != nil { return client.Context{}, err } - keyringDir = path.Join(homeDir, ".btc-validator") + keyringDir = path.Join(homeDir, ".finality-provider") } return client.Context{}. diff --git a/keyring/keyringcontroller.go b/keyring/keyringcontroller.go index d8d40d34..f5d141af 100644 --- a/keyring/keyringcontroller.go +++ b/keyring/keyringcontroller.go @@ -11,7 +11,7 @@ import ( sdksecp256k1 "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" "github.com/cosmos/go-bip39" - "github.com/babylonchain/btc-validator/types" + "github.com/babylonchain/finality-provider/types" ) const ( @@ -20,8 +20,8 @@ const ( ) type ChainKeyringController struct { - kr keyring.Keyring - valName string + kr keyring.Keyring + fpName string // input is to send passphrase to kr input *strings.Reader } @@ -48,9 +48,9 @@ func NewChainKeyringController(ctx client.Context, name, keyringBackend string) } return &ChainKeyringController{ - valName: name, - kr: kr, - input: inputReader, + fpName: name, + kr: kr, + input: inputReader, }, nil } @@ -60,9 +60,9 @@ func NewChainKeyringControllerWithKeyring(kr keyring.Keyring, name string, input } return &ChainKeyringController{ - kr: kr, - valName: name, - input: input, + kr: kr, + fpName: name, + input: input, }, nil } @@ -89,11 +89,11 @@ func (kc *ChainKeyringController) CreateChainKey(passphrase, hdPath string) (*ty } // TODO use a better way to remind the user to keep it - fmt.Printf("Generated mnemonic for the validator %s is:\n%s\n", kc.valName, mnemonic) + fmt.Printf("Generated mnemonic for the finality provider %s is:\n%s\n", kc.fpName, mnemonic) // we need to repeat the passphrase to mock the reentry kc.input.Reset(passphrase + "\n" + passphrase) - record, err := kc.kr.NewAccount(kc.valName, mnemonic, passphrase, hdPath, algo) + record, err := kc.kr.NewAccount(kc.fpName, mnemonic, passphrase, hdPath, algo) if err != nil { return nil, err } @@ -123,7 +123,7 @@ func (kc *ChainKeyringController) CreatePop(btcPrivKey *btcec.PrivateKey, passph func (kc *ChainKeyringController) GetChainPrivKey(passphrase string) (*sdksecp256k1.PrivKey, error) { kc.input.Reset(passphrase) - k, err := kc.kr.Key(kc.valName) + k, err := kc.kr.Key(kc.fpName) if err != nil { return nil, fmt.Errorf("failed to get private key: %w", err) } diff --git a/keyring/keyringcontroller_test.go b/keyring/keyringcontroller_test.go index 1c88b9ef..1a8c6e57 100644 --- a/keyring/keyringcontroller_test.go +++ b/keyring/keyringcontroller_test.go @@ -7,7 +7,7 @@ import ( "path/filepath" "testing" - valstore "github.com/babylonchain/btc-validator/validator/store" + fpstore "github.com/babylonchain/finality-provider/finality-provider/store" "github.com/babylonchain/babylon/types" "github.com/btcsuite/btcd/chaincfg" @@ -15,10 +15,10 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" "github.com/stretchr/testify/require" - valkr "github.com/babylonchain/btc-validator/keyring" + fpkr "github.com/babylonchain/finality-provider/keyring" - "github.com/babylonchain/btc-validator/eotsmanager" - "github.com/babylonchain/btc-validator/testutil" + "github.com/babylonchain/finality-provider/eotsmanager" + "github.com/babylonchain/finality-provider/testutil" ) var ( @@ -36,7 +36,7 @@ func FuzzCreatePoP(f *testing.F) { sdkCtx := testutil.GenSdkContext(r, t) chainID := testutil.GenRandomHexStr(r, 4) - kc, err := valkr.NewChainKeyringController(sdkCtx, keyName, keyring.BackendTest) + kc, err := fpkr.NewChainKeyringController(sdkCtx, keyName, keyring.BackendTest) require.NoError(t, err) eotsHome := filepath.Join(t.TempDir(), "eots-home") @@ -55,14 +55,14 @@ func FuzzCreatePoP(f *testing.F) { keyPair, err := kc.CreateChainKey(passphrase, hdPath) require.NoError(t, err) bbnPk := &secp256k1.PubKey{Key: keyPair.PublicKey.SerializeCompressed()} - valRecord, err := em.KeyRecord(btcPk.MustMarshal(), passphrase) + fpRecord, err := em.KeyRecord(btcPk.MustMarshal(), passphrase) require.NoError(t, err) - pop, err := kc.CreatePop(valRecord.PrivKey, passphrase) + pop, err := kc.CreatePop(fpRecord.PrivKey, passphrase) require.NoError(t, err) - validator := valstore.NewStoreValidator(bbnPk, btcPk, keyName, chainID, pop, testutil.EmptyDescription(), testutil.ZeroCommissionRate()) + fp := fpstore.NewStoreFinalityProvider(bbnPk, btcPk, keyName, chainID, pop, testutil.EmptyDescription(), testutil.ZeroCommissionRate()) btcSig := new(types.BIP340Signature) - err = btcSig.Unmarshal(validator.Pop.BtcSig) + err = btcSig.Unmarshal(fp.Pop.BtcSig) require.NoError(t, err) err = pop.Verify(bbnPk, btcPk, &chaincfg.SimNetParams) require.NoError(t, err) diff --git a/log/log.go b/log/log.go index f8ed33a2..fd3643c4 100644 --- a/log/log.go +++ b/log/log.go @@ -2,7 +2,7 @@ package log import ( "fmt" - "github.com/babylonchain/btc-validator/util" + "github.com/babylonchain/finality-provider/util" "io" "os" "path/filepath" diff --git a/store/bbolt_test.go b/store/bbolt_test.go index 6ce9f922..7a407cee 100644 --- a/store/bbolt_test.go +++ b/store/bbolt_test.go @@ -6,8 +6,8 @@ import ( "github.com/stretchr/testify/require" - kvstore "github.com/babylonchain/btc-validator/store" - "github.com/babylonchain/btc-validator/testutil" + kvstore "github.com/babylonchain/finality-provider/store" + "github.com/babylonchain/finality-provider/testutil" ) // FuzzBboltStore tests store interfaces works properly. diff --git a/testutil/datagen.go b/testutil/datagen.go index 7cb5a75e..e842c53b 100644 --- a/testutil/datagen.go +++ b/testutil/datagen.go @@ -2,8 +2,8 @@ package testutil import ( "encoding/hex" - eotscfg "github.com/babylonchain/btc-validator/eotsmanager/config" - valcfg "github.com/babylonchain/btc-validator/validator/config" + eotscfg "github.com/babylonchain/finality-provider/eotsmanager/config" + fpcfg "github.com/babylonchain/finality-provider/finality-provider/config" "math/rand" "testing" "time" @@ -17,11 +17,11 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/stretchr/testify/require" - "github.com/babylonchain/btc-validator/codec" - "github.com/babylonchain/btc-validator/config" - "github.com/babylonchain/btc-validator/types" - "github.com/babylonchain/btc-validator/validator/proto" - "github.com/babylonchain/btc-validator/validator/service" + "github.com/babylonchain/finality-provider/codec" + "github.com/babylonchain/finality-provider/config" + "github.com/babylonchain/finality-provider/finality-provider/proto" + "github.com/babylonchain/finality-provider/finality-provider/service" + "github.com/babylonchain/finality-provider/types" ) func GenRandomByteArray(r *rand.Rand, length uint64) []byte { @@ -44,7 +44,7 @@ func AddRandomSeedsToFuzzer(f *testing.F, num uint) { } } -func GenRandomValidator(r *rand.Rand, t *testing.T) *proto.StoreValidator { +func GenRandomFinalityProvider(r *rand.Rand, t *testing.T) *proto.StoreFinalityProvider { // generate BTC key pair btcSK, btcPK, err := datagen.GenRandomBTCKeyPair(r) require.NoError(t, err) @@ -60,7 +60,7 @@ func GenRandomValidator(r *rand.Rand, t *testing.T) *proto.StoreValidator { err = pop.Verify(babylonPK, bip340PK, &chaincfg.SigNetParams) require.NoError(t, err) - return &proto.StoreValidator{ + return &proto.StoreFinalityProvider{ KeyName: GenRandomHexStr(r, 4), BabylonPk: babylonPK.Bytes(), BtcPk: bip340PK.MustMarshal(), @@ -122,19 +122,19 @@ func GenBlocks(r *rand.Rand, startHeight, endHeight uint64) []*types.BlockInfo { return blocks } -// GenStoredValidator generates a random validator from the keyring and store it in DB -func GenStoredValidator(r *rand.Rand, t *testing.T, app *service.ValidatorApp, passphrase, hdPath string) *proto.StoreValidator { +// GenStoredFinalityProvider generates a random finality-provider from the keyring and store it in DB +func GenStoredFinalityProvider(r *rand.Rand, t *testing.T, app *service.FinalityProviderApp, passphrase, hdPath string) *proto.StoreFinalityProvider { // generate keyring keyName := GenRandomHexStr(r, 4) chainID := GenRandomHexStr(r, 4) - res, err := app.CreateValidator(keyName, chainID, passphrase, hdPath, EmptyDescription(), ZeroCommissionRate()) + res, err := app.CreateFinalityProvider(keyName, chainID, passphrase, hdPath, EmptyDescription(), ZeroCommissionRate()) require.NoError(t, err) - storedVal, err := app.GetValidatorStore().GetStoreValidator(res.ValPk.MustMarshal()) + storedFp, err := app.GetFinalityProviderStore().GetStoreFinalityProvider(res.FpPk.MustMarshal()) require.NoError(t, err) - return storedVal + return storedFp } func GenDBConfig(r *rand.Rand, t *testing.T) *config.DatabaseConfig { @@ -154,11 +154,11 @@ func GenEOTSConfig(r *rand.Rand, t *testing.T) *eotscfg.Config { return &eotsCfg } -func GenValConfig(r *rand.Rand, t *testing.T, homeDir string) *valcfg.Config { - valCfg := valcfg.DefaultConfigWithHome(homeDir) - valCfg.DatabaseConfig = GenDBConfig(r, t) +func GenFpConfig(r *rand.Rand, t *testing.T, homeDir string) *fpcfg.Config { + fpCfg := fpcfg.DefaultConfigWithHome(homeDir) + fpCfg.DatabaseConfig = GenDBConfig(r, t) - return &valCfg + return &fpCfg } func GenSdkContext(r *rand.Rand, t *testing.T) client.Context { diff --git a/testutil/mocks/babylon.go b/testutil/mocks/babylon.go index c98901fe..21ffc81b 100644 --- a/testutil/mocks/babylon.go +++ b/testutil/mocks/babylon.go @@ -8,7 +8,7 @@ import ( reflect "reflect" math "cosmossdk.io/math" - types "github.com/babylonchain/btc-validator/types" + types "github.com/babylonchain/finality-provider/types" btcec "github.com/btcsuite/btcd/btcec/v2" schnorr "github.com/btcsuite/btcd/btcec/v2/schnorr" gomock "github.com/golang/mock/gomock" @@ -52,18 +52,18 @@ func (mr *MockClientControllerMockRecorder) Close() *gomock.Call { } // CommitPubRandList mocks base method. -func (m *MockClientController) CommitPubRandList(valPk *btcec.PublicKey, startHeight uint64, pubRandList []*btcec.FieldVal, sig *schnorr.Signature) (*types.TxResponse, error) { +func (m *MockClientController) CommitPubRandList(fpPk *btcec.PublicKey, startHeight uint64, pubRandList []*btcec.FieldVal, sig *schnorr.Signature) (*types.TxResponse, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CommitPubRandList", valPk, startHeight, pubRandList, sig) + ret := m.ctrl.Call(m, "CommitPubRandList", fpPk, startHeight, pubRandList, sig) ret0, _ := ret[0].(*types.TxResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // CommitPubRandList indicates an expected call of CommitPubRandList. -func (mr *MockClientControllerMockRecorder) CommitPubRandList(valPk, startHeight, pubRandList, sig interface{}) *gomock.Call { +func (mr *MockClientControllerMockRecorder) CommitPubRandList(fpPk, startHeight, pubRandList, sig interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CommitPubRandList", reflect.TypeOf((*MockClientController)(nil).CommitPubRandList), valPk, startHeight, pubRandList, sig) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CommitPubRandList", reflect.TypeOf((*MockClientController)(nil).CommitPubRandList), fpPk, startHeight, pubRandList, sig) } // QueryActivatedHeight mocks base method. @@ -126,6 +126,36 @@ func (mr *MockClientControllerMockRecorder) QueryBlocks(startHeight, endHeight, return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryBlocks", reflect.TypeOf((*MockClientController)(nil).QueryBlocks), startHeight, endHeight, limit) } +// QueryFinalityProviderSlashed mocks base method. +func (m *MockClientController) QueryFinalityProviderSlashed(fpPk *btcec.PublicKey) (bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "QueryFinalityProviderSlashed", fpPk) + ret0, _ := ret[0].(bool) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// QueryFinalityProviderSlashed indicates an expected call of QueryFinalityProviderSlashed. +func (mr *MockClientControllerMockRecorder) QueryFinalityProviderSlashed(fpPk interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryFinalityProviderSlashed", reflect.TypeOf((*MockClientController)(nil).QueryFinalityProviderSlashed), fpPk) +} + +// QueryFinalityProviderVotingPower mocks base method. +func (m *MockClientController) QueryFinalityProviderVotingPower(fpPk *btcec.PublicKey, blockHeight uint64) (uint64, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "QueryFinalityProviderVotingPower", fpPk, blockHeight) + ret0, _ := ret[0].(uint64) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// QueryFinalityProviderVotingPower indicates an expected call of QueryFinalityProviderVotingPower. +func (mr *MockClientControllerMockRecorder) QueryFinalityProviderVotingPower(fpPk, blockHeight interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryFinalityProviderVotingPower", reflect.TypeOf((*MockClientController)(nil).QueryFinalityProviderVotingPower), fpPk, blockHeight) +} + // QueryLatestFinalizedBlocks mocks base method. func (m *MockClientController) QueryLatestFinalizedBlocks(count uint64) ([]*types.BlockInfo, error) { m.ctrl.T.Helper() @@ -171,64 +201,34 @@ func (mr *MockClientControllerMockRecorder) QueryStakingParams() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryStakingParams", reflect.TypeOf((*MockClientController)(nil).QueryStakingParams)) } -// QueryValidatorSlashed mocks base method. -func (m *MockClientController) QueryValidatorSlashed(valPk *btcec.PublicKey) (bool, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "QueryValidatorSlashed", valPk) - ret0, _ := ret[0].(bool) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// QueryValidatorSlashed indicates an expected call of QueryValidatorSlashed. -func (mr *MockClientControllerMockRecorder) QueryValidatorSlashed(valPk interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryValidatorSlashed", reflect.TypeOf((*MockClientController)(nil).QueryValidatorSlashed), valPk) -} - -// QueryValidatorVotingPower mocks base method. -func (m *MockClientController) QueryValidatorVotingPower(valPk *btcec.PublicKey, blockHeight uint64) (uint64, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "QueryValidatorVotingPower", valPk, blockHeight) - ret0, _ := ret[0].(uint64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// QueryValidatorVotingPower indicates an expected call of QueryValidatorVotingPower. -func (mr *MockClientControllerMockRecorder) QueryValidatorVotingPower(valPk, blockHeight interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryValidatorVotingPower", reflect.TypeOf((*MockClientController)(nil).QueryValidatorVotingPower), valPk, blockHeight) -} - -// RegisterValidator mocks base method. -func (m *MockClientController) RegisterValidator(chainPk []byte, valPk *btcec.PublicKey, pop []byte, commission *math.LegacyDec, description []byte) (*types.TxResponse, error) { +// RegisterFinalityProvider mocks base method. +func (m *MockClientController) RegisterFinalityProvider(chainPk []byte, fpPk *btcec.PublicKey, pop []byte, commission *math.LegacyDec, description []byte) (*types.TxResponse, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "RegisterValidator", chainPk, valPk, pop, commission, description) + ret := m.ctrl.Call(m, "RegisterFinalityProvider", chainPk, fpPk, pop, commission, description) ret0, _ := ret[0].(*types.TxResponse) ret1, _ := ret[1].(error) return ret0, ret1 } -// RegisterValidator indicates an expected call of RegisterValidator. -func (mr *MockClientControllerMockRecorder) RegisterValidator(chainPk, valPk, pop, commission, description interface{}) *gomock.Call { +// RegisterFinalityProvider indicates an expected call of RegisterFinalityProvider. +func (mr *MockClientControllerMockRecorder) RegisterFinalityProvider(chainPk, fpPk, pop, commission, description interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterValidator", reflect.TypeOf((*MockClientController)(nil).RegisterValidator), chainPk, valPk, pop, commission, description) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterFinalityProvider", reflect.TypeOf((*MockClientController)(nil).RegisterFinalityProvider), chainPk, fpPk, pop, commission, description) } // SubmitBatchFinalitySigs mocks base method. -func (m *MockClientController) SubmitBatchFinalitySigs(valPk *btcec.PublicKey, blocks []*types.BlockInfo, sigs []*btcec.ModNScalar) (*types.TxResponse, error) { +func (m *MockClientController) SubmitBatchFinalitySigs(fpPk *btcec.PublicKey, blocks []*types.BlockInfo, sigs []*btcec.ModNScalar) (*types.TxResponse, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SubmitBatchFinalitySigs", valPk, blocks, sigs) + ret := m.ctrl.Call(m, "SubmitBatchFinalitySigs", fpPk, blocks, sigs) ret0, _ := ret[0].(*types.TxResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // SubmitBatchFinalitySigs indicates an expected call of SubmitBatchFinalitySigs. -func (mr *MockClientControllerMockRecorder) SubmitBatchFinalitySigs(valPk, blocks, sigs interface{}) *gomock.Call { +func (mr *MockClientControllerMockRecorder) SubmitBatchFinalitySigs(fpPk, blocks, sigs interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubmitBatchFinalitySigs", reflect.TypeOf((*MockClientController)(nil).SubmitBatchFinalitySigs), valPk, blocks, sigs) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubmitBatchFinalitySigs", reflect.TypeOf((*MockClientController)(nil).SubmitBatchFinalitySigs), fpPk, blocks, sigs) } // SubmitCovenantSigs mocks base method. @@ -247,60 +247,60 @@ func (mr *MockClientControllerMockRecorder) SubmitCovenantSigs(covPk, stakingTxH } // SubmitFinalitySig mocks base method. -func (m *MockClientController) SubmitFinalitySig(valPk *btcec.PublicKey, blockHeight uint64, blockHash []byte, sig *btcec.ModNScalar) (*types.TxResponse, error) { +func (m *MockClientController) SubmitFinalitySig(fpPk *btcec.PublicKey, blockHeight uint64, blockHash []byte, sig *btcec.ModNScalar) (*types.TxResponse, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SubmitFinalitySig", valPk, blockHeight, blockHash, sig) + ret := m.ctrl.Call(m, "SubmitFinalitySig", fpPk, blockHeight, blockHash, sig) ret0, _ := ret[0].(*types.TxResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // SubmitFinalitySig indicates an expected call of SubmitFinalitySig. -func (mr *MockClientControllerMockRecorder) SubmitFinalitySig(valPk, blockHeight, blockHash, sig interface{}) *gomock.Call { +func (mr *MockClientControllerMockRecorder) SubmitFinalitySig(fpPk, blockHeight, blockHash, sig interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubmitFinalitySig", reflect.TypeOf((*MockClientController)(nil).SubmitFinalitySig), valPk, blockHeight, blockHash, sig) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubmitFinalitySig", reflect.TypeOf((*MockClientController)(nil).SubmitFinalitySig), fpPk, blockHeight, blockHash, sig) } -// MockValidatorAPIs is a mock of ValidatorAPIs interface. -type MockValidatorAPIs struct { +// MockFinalityProviderAPIs is a mock of FinalityProviderAPIs interface. +type MockFinalityProviderAPIs struct { ctrl *gomock.Controller - recorder *MockValidatorAPIsMockRecorder + recorder *MockFinalityProviderAPIsMockRecorder } -// MockValidatorAPIsMockRecorder is the mock recorder for MockValidatorAPIs. -type MockValidatorAPIsMockRecorder struct { - mock *MockValidatorAPIs +// MockFinalityProviderAPIsMockRecorder is the mock recorder for MockFinalityProviderAPIs. +type MockFinalityProviderAPIsMockRecorder struct { + mock *MockFinalityProviderAPIs } -// NewMockValidatorAPIs creates a new mock instance. -func NewMockValidatorAPIs(ctrl *gomock.Controller) *MockValidatorAPIs { - mock := &MockValidatorAPIs{ctrl: ctrl} - mock.recorder = &MockValidatorAPIsMockRecorder{mock} +// NewMockFinalityProviderAPIs creates a new mock instance. +func NewMockFinalityProviderAPIs(ctrl *gomock.Controller) *MockFinalityProviderAPIs { + mock := &MockFinalityProviderAPIs{ctrl: ctrl} + mock.recorder = &MockFinalityProviderAPIsMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockValidatorAPIs) EXPECT() *MockValidatorAPIsMockRecorder { +func (m *MockFinalityProviderAPIs) EXPECT() *MockFinalityProviderAPIsMockRecorder { return m.recorder } // CommitPubRandList mocks base method. -func (m *MockValidatorAPIs) CommitPubRandList(valPk *btcec.PublicKey, startHeight uint64, pubRandList []*btcec.FieldVal, sig *schnorr.Signature) (*types.TxResponse, error) { +func (m *MockFinalityProviderAPIs) CommitPubRandList(fpPk *btcec.PublicKey, startHeight uint64, pubRandList []*btcec.FieldVal, sig *schnorr.Signature) (*types.TxResponse, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CommitPubRandList", valPk, startHeight, pubRandList, sig) + ret := m.ctrl.Call(m, "CommitPubRandList", fpPk, startHeight, pubRandList, sig) ret0, _ := ret[0].(*types.TxResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // CommitPubRandList indicates an expected call of CommitPubRandList. -func (mr *MockValidatorAPIsMockRecorder) CommitPubRandList(valPk, startHeight, pubRandList, sig interface{}) *gomock.Call { +func (mr *MockFinalityProviderAPIsMockRecorder) CommitPubRandList(fpPk, startHeight, pubRandList, sig interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CommitPubRandList", reflect.TypeOf((*MockValidatorAPIs)(nil).CommitPubRandList), valPk, startHeight, pubRandList, sig) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CommitPubRandList", reflect.TypeOf((*MockFinalityProviderAPIs)(nil).CommitPubRandList), fpPk, startHeight, pubRandList, sig) } // QueryActivatedHeight mocks base method. -func (m *MockValidatorAPIs) QueryActivatedHeight() (uint64, error) { +func (m *MockFinalityProviderAPIs) QueryActivatedHeight() (uint64, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "QueryActivatedHeight") ret0, _ := ret[0].(uint64) @@ -309,13 +309,13 @@ func (m *MockValidatorAPIs) QueryActivatedHeight() (uint64, error) { } // QueryActivatedHeight indicates an expected call of QueryActivatedHeight. -func (mr *MockValidatorAPIsMockRecorder) QueryActivatedHeight() *gomock.Call { +func (mr *MockFinalityProviderAPIsMockRecorder) QueryActivatedHeight() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryActivatedHeight", reflect.TypeOf((*MockValidatorAPIs)(nil).QueryActivatedHeight)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryActivatedHeight", reflect.TypeOf((*MockFinalityProviderAPIs)(nil).QueryActivatedHeight)) } // QueryBestBlock mocks base method. -func (m *MockValidatorAPIs) QueryBestBlock() (*types.BlockInfo, error) { +func (m *MockFinalityProviderAPIs) QueryBestBlock() (*types.BlockInfo, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "QueryBestBlock") ret0, _ := ret[0].(*types.BlockInfo) @@ -324,13 +324,13 @@ func (m *MockValidatorAPIs) QueryBestBlock() (*types.BlockInfo, error) { } // QueryBestBlock indicates an expected call of QueryBestBlock. -func (mr *MockValidatorAPIsMockRecorder) QueryBestBlock() *gomock.Call { +func (mr *MockFinalityProviderAPIsMockRecorder) QueryBestBlock() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryBestBlock", reflect.TypeOf((*MockValidatorAPIs)(nil).QueryBestBlock)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryBestBlock", reflect.TypeOf((*MockFinalityProviderAPIs)(nil).QueryBestBlock)) } // QueryBlock mocks base method. -func (m *MockValidatorAPIs) QueryBlock(height uint64) (*types.BlockInfo, error) { +func (m *MockFinalityProviderAPIs) QueryBlock(height uint64) (*types.BlockInfo, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "QueryBlock", height) ret0, _ := ret[0].(*types.BlockInfo) @@ -339,13 +339,13 @@ func (m *MockValidatorAPIs) QueryBlock(height uint64) (*types.BlockInfo, error) } // QueryBlock indicates an expected call of QueryBlock. -func (mr *MockValidatorAPIsMockRecorder) QueryBlock(height interface{}) *gomock.Call { +func (mr *MockFinalityProviderAPIsMockRecorder) QueryBlock(height interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryBlock", reflect.TypeOf((*MockValidatorAPIs)(nil).QueryBlock), height) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryBlock", reflect.TypeOf((*MockFinalityProviderAPIs)(nil).QueryBlock), height) } // QueryBlocks mocks base method. -func (m *MockValidatorAPIs) QueryBlocks(startHeight, endHeight, limit uint64) ([]*types.BlockInfo, error) { +func (m *MockFinalityProviderAPIs) QueryBlocks(startHeight, endHeight, limit uint64) ([]*types.BlockInfo, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "QueryBlocks", startHeight, endHeight, limit) ret0, _ := ret[0].([]*types.BlockInfo) @@ -354,99 +354,99 @@ func (m *MockValidatorAPIs) QueryBlocks(startHeight, endHeight, limit uint64) ([ } // QueryBlocks indicates an expected call of QueryBlocks. -func (mr *MockValidatorAPIsMockRecorder) QueryBlocks(startHeight, endHeight, limit interface{}) *gomock.Call { +func (mr *MockFinalityProviderAPIsMockRecorder) QueryBlocks(startHeight, endHeight, limit interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryBlocks", reflect.TypeOf((*MockValidatorAPIs)(nil).QueryBlocks), startHeight, endHeight, limit) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryBlocks", reflect.TypeOf((*MockFinalityProviderAPIs)(nil).QueryBlocks), startHeight, endHeight, limit) } -// QueryLatestFinalizedBlocks mocks base method. -func (m *MockValidatorAPIs) QueryLatestFinalizedBlocks(count uint64) ([]*types.BlockInfo, error) { +// QueryFinalityProviderSlashed mocks base method. +func (m *MockFinalityProviderAPIs) QueryFinalityProviderSlashed(fpPk *btcec.PublicKey) (bool, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "QueryLatestFinalizedBlocks", count) - ret0, _ := ret[0].([]*types.BlockInfo) + ret := m.ctrl.Call(m, "QueryFinalityProviderSlashed", fpPk) + ret0, _ := ret[0].(bool) ret1, _ := ret[1].(error) return ret0, ret1 } -// QueryLatestFinalizedBlocks indicates an expected call of QueryLatestFinalizedBlocks. -func (mr *MockValidatorAPIsMockRecorder) QueryLatestFinalizedBlocks(count interface{}) *gomock.Call { +// QueryFinalityProviderSlashed indicates an expected call of QueryFinalityProviderSlashed. +func (mr *MockFinalityProviderAPIsMockRecorder) QueryFinalityProviderSlashed(fpPk interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryLatestFinalizedBlocks", reflect.TypeOf((*MockValidatorAPIs)(nil).QueryLatestFinalizedBlocks), count) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryFinalityProviderSlashed", reflect.TypeOf((*MockFinalityProviderAPIs)(nil).QueryFinalityProviderSlashed), fpPk) } -// QueryValidatorSlashed mocks base method. -func (m *MockValidatorAPIs) QueryValidatorSlashed(valPk *btcec.PublicKey) (bool, error) { +// QueryFinalityProviderVotingPower mocks base method. +func (m *MockFinalityProviderAPIs) QueryFinalityProviderVotingPower(fpPk *btcec.PublicKey, blockHeight uint64) (uint64, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "QueryValidatorSlashed", valPk) - ret0, _ := ret[0].(bool) + ret := m.ctrl.Call(m, "QueryFinalityProviderVotingPower", fpPk, blockHeight) + ret0, _ := ret[0].(uint64) ret1, _ := ret[1].(error) return ret0, ret1 } -// QueryValidatorSlashed indicates an expected call of QueryValidatorSlashed. -func (mr *MockValidatorAPIsMockRecorder) QueryValidatorSlashed(valPk interface{}) *gomock.Call { +// QueryFinalityProviderVotingPower indicates an expected call of QueryFinalityProviderVotingPower. +func (mr *MockFinalityProviderAPIsMockRecorder) QueryFinalityProviderVotingPower(fpPk, blockHeight interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryValidatorSlashed", reflect.TypeOf((*MockValidatorAPIs)(nil).QueryValidatorSlashed), valPk) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryFinalityProviderVotingPower", reflect.TypeOf((*MockFinalityProviderAPIs)(nil).QueryFinalityProviderVotingPower), fpPk, blockHeight) } -// QueryValidatorVotingPower mocks base method. -func (m *MockValidatorAPIs) QueryValidatorVotingPower(valPk *btcec.PublicKey, blockHeight uint64) (uint64, error) { +// QueryLatestFinalizedBlocks mocks base method. +func (m *MockFinalityProviderAPIs) QueryLatestFinalizedBlocks(count uint64) ([]*types.BlockInfo, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "QueryValidatorVotingPower", valPk, blockHeight) - ret0, _ := ret[0].(uint64) + ret := m.ctrl.Call(m, "QueryLatestFinalizedBlocks", count) + ret0, _ := ret[0].([]*types.BlockInfo) ret1, _ := ret[1].(error) return ret0, ret1 } -// QueryValidatorVotingPower indicates an expected call of QueryValidatorVotingPower. -func (mr *MockValidatorAPIsMockRecorder) QueryValidatorVotingPower(valPk, blockHeight interface{}) *gomock.Call { +// QueryLatestFinalizedBlocks indicates an expected call of QueryLatestFinalizedBlocks. +func (mr *MockFinalityProviderAPIsMockRecorder) QueryLatestFinalizedBlocks(count interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryValidatorVotingPower", reflect.TypeOf((*MockValidatorAPIs)(nil).QueryValidatorVotingPower), valPk, blockHeight) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryLatestFinalizedBlocks", reflect.TypeOf((*MockFinalityProviderAPIs)(nil).QueryLatestFinalizedBlocks), count) } -// RegisterValidator mocks base method. -func (m *MockValidatorAPIs) RegisterValidator(chainPk []byte, valPk *btcec.PublicKey, pop []byte, commission *math.LegacyDec, description []byte) (*types.TxResponse, error) { +// RegisterFinalityProvider mocks base method. +func (m *MockFinalityProviderAPIs) RegisterFinalityProvider(chainPk []byte, fpPk *btcec.PublicKey, pop []byte, commission *math.LegacyDec, description []byte) (*types.TxResponse, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "RegisterValidator", chainPk, valPk, pop, commission, description) + ret := m.ctrl.Call(m, "RegisterFinalityProvider", chainPk, fpPk, pop, commission, description) ret0, _ := ret[0].(*types.TxResponse) ret1, _ := ret[1].(error) return ret0, ret1 } -// RegisterValidator indicates an expected call of RegisterValidator. -func (mr *MockValidatorAPIsMockRecorder) RegisterValidator(chainPk, valPk, pop, commission, description interface{}) *gomock.Call { +// RegisterFinalityProvider indicates an expected call of RegisterFinalityProvider. +func (mr *MockFinalityProviderAPIsMockRecorder) RegisterFinalityProvider(chainPk, fpPk, pop, commission, description interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterValidator", reflect.TypeOf((*MockValidatorAPIs)(nil).RegisterValidator), chainPk, valPk, pop, commission, description) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterFinalityProvider", reflect.TypeOf((*MockFinalityProviderAPIs)(nil).RegisterFinalityProvider), chainPk, fpPk, pop, commission, description) } // SubmitBatchFinalitySigs mocks base method. -func (m *MockValidatorAPIs) SubmitBatchFinalitySigs(valPk *btcec.PublicKey, blocks []*types.BlockInfo, sigs []*btcec.ModNScalar) (*types.TxResponse, error) { +func (m *MockFinalityProviderAPIs) SubmitBatchFinalitySigs(fpPk *btcec.PublicKey, blocks []*types.BlockInfo, sigs []*btcec.ModNScalar) (*types.TxResponse, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SubmitBatchFinalitySigs", valPk, blocks, sigs) + ret := m.ctrl.Call(m, "SubmitBatchFinalitySigs", fpPk, blocks, sigs) ret0, _ := ret[0].(*types.TxResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // SubmitBatchFinalitySigs indicates an expected call of SubmitBatchFinalitySigs. -func (mr *MockValidatorAPIsMockRecorder) SubmitBatchFinalitySigs(valPk, blocks, sigs interface{}) *gomock.Call { +func (mr *MockFinalityProviderAPIsMockRecorder) SubmitBatchFinalitySigs(fpPk, blocks, sigs interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubmitBatchFinalitySigs", reflect.TypeOf((*MockValidatorAPIs)(nil).SubmitBatchFinalitySigs), valPk, blocks, sigs) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubmitBatchFinalitySigs", reflect.TypeOf((*MockFinalityProviderAPIs)(nil).SubmitBatchFinalitySigs), fpPk, blocks, sigs) } // SubmitFinalitySig mocks base method. -func (m *MockValidatorAPIs) SubmitFinalitySig(valPk *btcec.PublicKey, blockHeight uint64, blockHash []byte, sig *btcec.ModNScalar) (*types.TxResponse, error) { +func (m *MockFinalityProviderAPIs) SubmitFinalitySig(fpPk *btcec.PublicKey, blockHeight uint64, blockHash []byte, sig *btcec.ModNScalar) (*types.TxResponse, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SubmitFinalitySig", valPk, blockHeight, blockHash, sig) + ret := m.ctrl.Call(m, "SubmitFinalitySig", fpPk, blockHeight, blockHash, sig) ret0, _ := ret[0].(*types.TxResponse) ret1, _ := ret[1].(error) return ret0, ret1 } // SubmitFinalitySig indicates an expected call of SubmitFinalitySig. -func (mr *MockValidatorAPIsMockRecorder) SubmitFinalitySig(valPk, blockHeight, blockHash, sig interface{}) *gomock.Call { +func (mr *MockFinalityProviderAPIsMockRecorder) SubmitFinalitySig(fpPk, blockHeight, blockHash, sig interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubmitFinalitySig", reflect.TypeOf((*MockValidatorAPIs)(nil).SubmitFinalitySig), valPk, blockHeight, blockHash, sig) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubmitFinalitySig", reflect.TypeOf((*MockFinalityProviderAPIs)(nil).SubmitFinalitySig), fpPk, blockHeight, blockHash, sig) } // MockCovenantAPIs is a mock of CovenantAPIs interface. diff --git a/testutil/store.go b/testutil/store.go index 67b13631..8232282a 100644 --- a/testutil/store.go +++ b/testutil/store.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/require" - kvstore "github.com/babylonchain/btc-validator/store" + kvstore "github.com/babylonchain/finality-provider/store" ) func CreateStore(r *rand.Rand, t *testing.T) (kvstore.Store, string) { diff --git a/testutil/utils.go b/testutil/utils.go index a9235e6f..ca3b8808 100644 --- a/testutil/utils.go +++ b/testutil/utils.go @@ -7,8 +7,8 @@ import ( sdkmath "cosmossdk.io/math" "github.com/golang/mock/gomock" - "github.com/babylonchain/btc-validator/testutil/mocks" - "github.com/babylonchain/btc-validator/types" + "github.com/babylonchain/finality-provider/testutil/mocks" + "github.com/babylonchain/finality-provider/types" ) func EmptyDescription() []byte { diff --git a/tools/go.mod b/tools/go.mod index 9c318e5a..5cc29ef9 100644 --- a/tools/go.mod +++ b/tools/go.mod @@ -1,4 +1,4 @@ -module github.com/babylonchain/btc-validator/tools +module github.com/babylonchain/finality-provider/tools go 1.21 @@ -212,7 +212,7 @@ require ( ) replace ( - github.com/babylonchain/babylon => github.com/babylonchain/babylon-private v0.0.0-20231212092759-3504554e618b + github.com/babylonchain/babylon => github.com/babylonchain/babylon-private v0.0.0-20231213105136-11792cad8a84 // Downgraded to stable version see: https://github.com/cosmos/cosmos-sdk/pull/14952 github.com/syndtr/goleveldb => github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 diff --git a/tools/go.sum b/tools/go.sum index 6b2e2198..52d832dd 100644 --- a/tools/go.sum +++ b/tools/go.sum @@ -272,8 +272,8 @@ github.com/aws/aws-sdk-go v1.44.122/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX github.com/aws/aws-sdk-go v1.44.224 h1:09CiaaF35nRmxrzWZ2uRq5v6Ghg/d2RiPjZnSgtt+RQ= github.com/aws/aws-sdk-go v1.44.224/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI= github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g= -github.com/babylonchain/babylon-private v0.0.0-20231212092759-3504554e618b h1:FAadQ5l5ORQa/P8IRRtHXibK7g7MHOzhKxmvObY42OI= -github.com/babylonchain/babylon-private v0.0.0-20231212092759-3504554e618b/go.mod h1:6wqL7SJBWltXMNXgFsvavB1bR5Fft0yChfRLamBtrAY= +github.com/babylonchain/babylon-private v0.0.0-20231213105136-11792cad8a84 h1:fFlLF+rl6Buwb3eYgIoUQ4JkYdNMMTk9ihoznTTw2hk= +github.com/babylonchain/babylon-private v0.0.0-20231213105136-11792cad8a84/go.mod h1:6wqL7SJBWltXMNXgFsvavB1bR5Fft0yChfRLamBtrAY= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= diff --git a/tools/tools.go b/tools/tools.go index 213715c3..752851fa 100644 --- a/tools/tools.go +++ b/tools/tools.go @@ -1,7 +1,7 @@ //go:build tools // +build tools -package btcvalidator +package finalityprovider import ( _ "github.com/babylonchain/babylon/cmd/babylond" diff --git a/types/delegation.go b/types/delegation.go index 92014754..c326c1d3 100644 --- a/types/delegation.go +++ b/types/delegation.go @@ -11,9 +11,9 @@ import ( type Delegation struct { // The Bitcoin secp256k1 PK of this BTC delegation BtcPk *btcec.PublicKey - // The Bitcoin secp256k1 PKs of the BTC validators that + // The Bitcoin secp256k1 PKs of the finality providers that // this BTC delegation delegates to - ValBtcPks []*btcec.PublicKey + FpBtcPks []*btcec.PublicKey // The start BTC height of the BTC delegation // it is the start BTC height of the timelock StartHeight uint64 @@ -48,7 +48,7 @@ func (d *Delegation) GetStakingTime() uint16 { diff := d.EndHeight - d.StartHeight if diff > math.MaxUint16 { - // In valid delegation, EndHeight is always greater than StartHeight and it is always uint16 value + // In a valid delegation, EndHeight is always greater than StartHeight and it is always uint16 value panic("invalid delegation in database") } @@ -65,7 +65,7 @@ type Undelegation struct { UnbondingTxHex string // The hex string of the slashing tx for unbonding transactions // It is partially signed by SK corresponding to btc_pk, but not signed by - // validator or covenant yet. + // finality provider or covenant yet. SlashingTxHex string // The signatures on the slashing tx by the covenant // (i.e., SK corresponding to covenant_pk in params) diff --git a/validator/cmd/vald/start.go b/validator/cmd/vald/start.go deleted file mode 100644 index 57ffe188..00000000 --- a/validator/cmd/vald/start.go +++ /dev/null @@ -1,89 +0,0 @@ -package main - -import ( - "fmt" - "github.com/babylonchain/babylon/types" - "github.com/babylonchain/btc-validator/log" - "github.com/babylonchain/btc-validator/util" - "github.com/lightningnetwork/lnd/signal" - "github.com/urfave/cli" - "path/filepath" - - valcfg "github.com/babylonchain/btc-validator/validator/config" - "github.com/babylonchain/btc-validator/validator/service" -) - -var startCommand = cli.Command{ - Name: "start", - Usage: "vald start", - Description: "Start the validator daemon. Note that eotsd should be started beforehand", - Flags: []cli.Flag{ - cli.StringFlag{ - Name: passphraseFlag, - Usage: "The pass phrase used to decrypt the private key", - Value: defaultPassphrase, - }, - cli.StringFlag{ - Name: homeFlag, - Usage: "The path to the validator home directory", - Value: valcfg.DefaultValdDir, - }, - cli.StringFlag{ - Name: valPkFlag, - Usage: "The public key of the validator to start", - }, - }, - Action: start, -} - -func start(ctx *cli.Context) error { - homePath, err := filepath.Abs(ctx.String(homeFlag)) - if err != nil { - return err - } - homePath = util.CleanAndExpandPath(homePath) - passphrase := ctx.String(passphraseFlag) - valPkStr := ctx.String(valPkFlag) - - cfg, err := valcfg.LoadConfig(homePath) - if err != nil { - return fmt.Errorf("failed to load configuration: %w", err) - } - - logger, err := log.NewRootLoggerWithFile(valcfg.LogFile(homePath), cfg.LogLevel) - if err != nil { - return fmt.Errorf("failed to initialize the logger") - } - - valApp, err := service.NewValidatorAppFromConfig(homePath, cfg, logger) - if err != nil { - return fmt.Errorf("failed to create validator app: %v", err) - } - - // only start the daemon without starting any validator instance - // as there might be no validator registered yet - if err := valApp.Start(); err != nil { - return fmt.Errorf("failed to start the validator daemon: %w", err) - } - - if valPkStr != "" { - // start the validator instance with the given public key - valPk, err := types.NewBIP340PubKeyFromHex(valPkStr) - if err != nil { - return fmt.Errorf("invalid validator public key %s: %w", valPkStr, err) - } - if err := valApp.StartHandlingValidator(valPk, passphrase); err != nil { - return fmt.Errorf("failed to start the validator instance %s: %w", valPkStr, err) - } - } - - // Hook interceptor for os signals. - shutdownInterceptor, err := signal.Intercept() - if err != nil { - return err - } - - valServer := service.NewValidatorServer(cfg, logger, valApp, shutdownInterceptor) - - return valServer.RunUntilShutdown() -} diff --git a/validator/proto/validators.go b/validator/proto/validators.go deleted file mode 100644 index 45128f06..00000000 --- a/validator/proto/validators.go +++ /dev/null @@ -1,45 +0,0 @@ -package proto - -import ( - "encoding/hex" - "fmt" - - bbn "github.com/babylonchain/babylon/types" - "github.com/btcsuite/btcd/btcec/v2" - "github.com/btcsuite/btcd/btcec/v2/schnorr" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" -) - -func (v *StoreValidator) GetBabylonPK() *secp256k1.PubKey { - return &secp256k1.PubKey{ - Key: v.BabylonPk, - } -} - -func (v *StoreValidator) GetBabylonPkHexString() string { - return hex.EncodeToString(v.BabylonPk) -} - -func (v *StoreValidator) MustGetBTCPK() *btcec.PublicKey { - btcPubKey, err := schnorr.ParsePubKey(v.BtcPk) - if err != nil { - panic(fmt.Errorf("failed to parse BTC PK: %w", err)) - } - return btcPubKey -} - -func (v *StoreValidator) MustGetBIP340BTCPK() *bbn.BIP340PubKey { - btcPK := v.MustGetBTCPK() - return bbn.NewBIP340PubKeyFromBTCPK(btcPK) -} - -func NewValidatorInfo(v *StoreValidator) *ValidatorInfo { - return &ValidatorInfo{ - BabylonPkHex: v.GetBabylonPkHexString(), - BtcPkHex: v.MustGetBIP340BTCPK().MarshalHex(), - Description: v.Description, - LastVotedHeight: v.LastVotedHeight, - LastCommittedHeight: v.LastCommittedHeight, - Status: v.Status, - } -} diff --git a/validator/proto/validators.pb.go b/validator/proto/validators.pb.go deleted file mode 100644 index 163e22e2..00000000 --- a/validator/proto/validators.pb.go +++ /dev/null @@ -1,1559 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.28.0 -// protoc (unknown) -// source: validators.proto - -package proto - -import ( - _ "github.com/cosmos/cosmos-proto" - _ "github.com/cosmos/cosmos-sdk/x/staking/types" - _ "github.com/cosmos/gogoproto/gogoproto" - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -// ValidatorStatus is the status of a BTC validator -// a Validator object has 4 states: -// - Created - created and managed by validator client, not registered to -// babylon yet -// - Registered - created and registered to Babylon, but not voting yet (No -// delegated stake) -// - Active - created and registered to Babylon with stake to vote -// - Inactive - created and registered to Babylon with no stake to vote. -// Validator was already active. -// Valid State Transactions: -// - Created -> Registered -// - Registered -> Active -// - Active -> Inactive -// - Inactive -> Active -type ValidatorStatus int32 - -const ( - // CREATED defines a validator that is awaiting registration - ValidatorStatus_CREATED ValidatorStatus = 0 - // REGISTERED defines a validator that has been registered - // to Babylon but has no delegated stake - ValidatorStatus_REGISTERED ValidatorStatus = 1 - // ACTIVE defines a validator that is delegated to vote - ValidatorStatus_ACTIVE ValidatorStatus = 2 - // INACTIVE defines a validator whose delegations are reduced to zero but not slashed - ValidatorStatus_INACTIVE ValidatorStatus = 3 - // SLASHED defines a validator that has been slashed - ValidatorStatus_SLASHED ValidatorStatus = 4 -) - -// Enum value maps for ValidatorStatus. -var ( - ValidatorStatus_name = map[int32]string{ - 0: "CREATED", - 1: "REGISTERED", - 2: "ACTIVE", - 3: "INACTIVE", - 4: "SLASHED", - } - ValidatorStatus_value = map[string]int32{ - "CREATED": 0, - "REGISTERED": 1, - "ACTIVE": 2, - "INACTIVE": 3, - "SLASHED": 4, - } -) - -func (x ValidatorStatus) Enum() *ValidatorStatus { - p := new(ValidatorStatus) - *p = x - return p -} - -func (x ValidatorStatus) String() string { - return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) -} - -func (ValidatorStatus) Descriptor() protoreflect.EnumDescriptor { - return file_validators_proto_enumTypes[0].Descriptor() -} - -func (ValidatorStatus) Type() protoreflect.EnumType { - return &file_validators_proto_enumTypes[0] -} - -func (x ValidatorStatus) Number() protoreflect.EnumNumber { - return protoreflect.EnumNumber(x) -} - -// Deprecated: Use ValidatorStatus.Descriptor instead. -func (ValidatorStatus) EnumDescriptor() ([]byte, []int) { - return file_validators_proto_rawDescGZIP(), []int{0} -} - -type GetInfoRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields -} - -func (x *GetInfoRequest) Reset() { - *x = GetInfoRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_validators_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *GetInfoRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*GetInfoRequest) ProtoMessage() {} - -func (x *GetInfoRequest) ProtoReflect() protoreflect.Message { - mi := &file_validators_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use GetInfoRequest.ProtoReflect.Descriptor instead. -func (*GetInfoRequest) Descriptor() ([]byte, []int) { - return file_validators_proto_rawDescGZIP(), []int{0} -} - -type GetInfoResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Version string `protobuf:"bytes,1,opt,name=version,proto3" json:"version,omitempty"` -} - -func (x *GetInfoResponse) Reset() { - *x = GetInfoResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_validators_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *GetInfoResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*GetInfoResponse) ProtoMessage() {} - -func (x *GetInfoResponse) ProtoReflect() protoreflect.Message { - mi := &file_validators_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use GetInfoResponse.ProtoReflect.Descriptor instead. -func (*GetInfoResponse) Descriptor() ([]byte, []int) { - return file_validators_proto_rawDescGZIP(), []int{1} -} - -func (x *GetInfoResponse) GetVersion() string { - if x != nil { - return x.Version - } - return "" -} - -type CreateValidatorRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // key_name is the identifier key in keyring - KeyName string `protobuf:"bytes,1,opt,name=key_name,json=keyName,proto3" json:"key_name,omitempty"` - // passphrase is used to encrypt the keys - Passphrase string `protobuf:"bytes,2,opt,name=passphrase,proto3" json:"passphrase,omitempty"` - // hd_path is the hd path for private key derivation - HdPath string `protobuf:"bytes,3,opt,name=hd_path,json=hdPath,proto3" json:"hd_path,omitempty"` - // chain_id is the identifier of the consumer chain that the validator connected to - ChainId string `protobuf:"bytes,4,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` - // description defines the description terms for the validator - Description []byte `protobuf:"bytes,5,opt,name=description,proto3" json:"description,omitempty"` - // commission defines the commission rate for the validator - Commission string `protobuf:"bytes,6,opt,name=commission,proto3" json:"commission,omitempty"` -} - -func (x *CreateValidatorRequest) Reset() { - *x = CreateValidatorRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_validators_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *CreateValidatorRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*CreateValidatorRequest) ProtoMessage() {} - -func (x *CreateValidatorRequest) ProtoReflect() protoreflect.Message { - mi := &file_validators_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use CreateValidatorRequest.ProtoReflect.Descriptor instead. -func (*CreateValidatorRequest) Descriptor() ([]byte, []int) { - return file_validators_proto_rawDescGZIP(), []int{2} -} - -func (x *CreateValidatorRequest) GetKeyName() string { - if x != nil { - return x.KeyName - } - return "" -} - -func (x *CreateValidatorRequest) GetPassphrase() string { - if x != nil { - return x.Passphrase - } - return "" -} - -func (x *CreateValidatorRequest) GetHdPath() string { - if x != nil { - return x.HdPath - } - return "" -} - -func (x *CreateValidatorRequest) GetChainId() string { - if x != nil { - return x.ChainId - } - return "" -} - -func (x *CreateValidatorRequest) GetDescription() []byte { - if x != nil { - return x.Description - } - return nil -} - -func (x *CreateValidatorRequest) GetCommission() string { - if x != nil { - return x.Commission - } - return "" -} - -type CreateValidatorResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // btc_pk is the hex string of BTC secp256k1 public key of the validator encoded in BIP-340 spec - BtcPk string `protobuf:"bytes,1,opt,name=btc_pk,json=btcPk,proto3" json:"btc_pk,omitempty"` -} - -func (x *CreateValidatorResponse) Reset() { - *x = CreateValidatorResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_validators_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *CreateValidatorResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*CreateValidatorResponse) ProtoMessage() {} - -func (x *CreateValidatorResponse) ProtoReflect() protoreflect.Message { - mi := &file_validators_proto_msgTypes[3] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use CreateValidatorResponse.ProtoReflect.Descriptor instead. -func (*CreateValidatorResponse) Descriptor() ([]byte, []int) { - return file_validators_proto_rawDescGZIP(), []int{3} -} - -func (x *CreateValidatorResponse) GetBtcPk() string { - if x != nil { - return x.BtcPk - } - return "" -} - -type RegisterValidatorRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // btc_pk is hex string of the BTC secp256k1 public key of the validator encoded in BIP-340 spec - BtcPk string `protobuf:"bytes,1,opt,name=btc_pk,json=btcPk,proto3" json:"btc_pk,omitempty"` - // passphrase is used to encrypt the keys - Passphrase string `protobuf:"bytes,2,opt,name=passphrase,proto3" json:"passphrase,omitempty"` -} - -func (x *RegisterValidatorRequest) Reset() { - *x = RegisterValidatorRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_validators_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *RegisterValidatorRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*RegisterValidatorRequest) ProtoMessage() {} - -func (x *RegisterValidatorRequest) ProtoReflect() protoreflect.Message { - mi := &file_validators_proto_msgTypes[4] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use RegisterValidatorRequest.ProtoReflect.Descriptor instead. -func (*RegisterValidatorRequest) Descriptor() ([]byte, []int) { - return file_validators_proto_rawDescGZIP(), []int{4} -} - -func (x *RegisterValidatorRequest) GetBtcPk() string { - if x != nil { - return x.BtcPk - } - return "" -} - -func (x *RegisterValidatorRequest) GetPassphrase() string { - if x != nil { - return x.Passphrase - } - return "" -} - -type RegisterValidatorResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // hash of the successful Babylon registration transaction - TxHash string `protobuf:"bytes,1,opt,name=tx_hash,json=txHash,proto3" json:"tx_hash,omitempty"` -} - -func (x *RegisterValidatorResponse) Reset() { - *x = RegisterValidatorResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_validators_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *RegisterValidatorResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*RegisterValidatorResponse) ProtoMessage() {} - -func (x *RegisterValidatorResponse) ProtoReflect() protoreflect.Message { - mi := &file_validators_proto_msgTypes[5] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use RegisterValidatorResponse.ProtoReflect.Descriptor instead. -func (*RegisterValidatorResponse) Descriptor() ([]byte, []int) { - return file_validators_proto_rawDescGZIP(), []int{5} -} - -func (x *RegisterValidatorResponse) GetTxHash() string { - if x != nil { - return x.TxHash - } - return "" -} - -type AddFinalitySignatureRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // btc_pk is hex string of the BTC secp256k1 public key of the validator encoded in BIP-340 spec - BtcPk string `protobuf:"bytes,1,opt,name=btc_pk,json=btcPk,proto3" json:"btc_pk,omitempty"` - // height is the height of the Babylon block - Height uint64 `protobuf:"varint,2,opt,name=height,proto3" json:"height,omitempty"` - // app_hash is the AppHash of the Babylon block - AppHash []byte `protobuf:"bytes,3,opt,name=app_hash,json=appHash,proto3" json:"app_hash,omitempty"` -} - -func (x *AddFinalitySignatureRequest) Reset() { - *x = AddFinalitySignatureRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_validators_proto_msgTypes[6] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *AddFinalitySignatureRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*AddFinalitySignatureRequest) ProtoMessage() {} - -func (x *AddFinalitySignatureRequest) ProtoReflect() protoreflect.Message { - mi := &file_validators_proto_msgTypes[6] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use AddFinalitySignatureRequest.ProtoReflect.Descriptor instead. -func (*AddFinalitySignatureRequest) Descriptor() ([]byte, []int) { - return file_validators_proto_rawDescGZIP(), []int{6} -} - -func (x *AddFinalitySignatureRequest) GetBtcPk() string { - if x != nil { - return x.BtcPk - } - return "" -} - -func (x *AddFinalitySignatureRequest) GetHeight() uint64 { - if x != nil { - return x.Height - } - return 0 -} - -func (x *AddFinalitySignatureRequest) GetAppHash() []byte { - if x != nil { - return x.AppHash - } - return nil -} - -type AddFinalitySignatureResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // hash of the successful Babylon finality signature submission transaction - TxHash string `protobuf:"bytes,1,opt,name=tx_hash,json=txHash,proto3" json:"tx_hash,omitempty"` - // the hex string of the extracted Bitcoin secp256k1 private key - ExtractedSkHex string `protobuf:"bytes,2,opt,name=extracted_sk_hex,json=extractedSkHex,proto3" json:"extracted_sk_hex,omitempty"` - // the hex string of the local Bitcoin secp256k1 private key - LocalSkHex string `protobuf:"bytes,3,opt,name=local_sk_hex,json=localSkHex,proto3" json:"local_sk_hex,omitempty"` -} - -func (x *AddFinalitySignatureResponse) Reset() { - *x = AddFinalitySignatureResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_validators_proto_msgTypes[7] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *AddFinalitySignatureResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*AddFinalitySignatureResponse) ProtoMessage() {} - -func (x *AddFinalitySignatureResponse) ProtoReflect() protoreflect.Message { - mi := &file_validators_proto_msgTypes[7] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use AddFinalitySignatureResponse.ProtoReflect.Descriptor instead. -func (*AddFinalitySignatureResponse) Descriptor() ([]byte, []int) { - return file_validators_proto_rawDescGZIP(), []int{7} -} - -func (x *AddFinalitySignatureResponse) GetTxHash() string { - if x != nil { - return x.TxHash - } - return "" -} - -func (x *AddFinalitySignatureResponse) GetExtractedSkHex() string { - if x != nil { - return x.ExtractedSkHex - } - return "" -} - -func (x *AddFinalitySignatureResponse) GetLocalSkHex() string { - if x != nil { - return x.LocalSkHex - } - return "" -} - -type QueryValidatorRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // btc_pk is hex string of the BTC secp256k1 public key of the validator encoded in BIP-340 spec - BtcPk string `protobuf:"bytes,1,opt,name=btc_pk,json=btcPk,proto3" json:"btc_pk,omitempty"` -} - -func (x *QueryValidatorRequest) Reset() { - *x = QueryValidatorRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_validators_proto_msgTypes[8] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *QueryValidatorRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*QueryValidatorRequest) ProtoMessage() {} - -func (x *QueryValidatorRequest) ProtoReflect() protoreflect.Message { - mi := &file_validators_proto_msgTypes[8] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use QueryValidatorRequest.ProtoReflect.Descriptor instead. -func (*QueryValidatorRequest) Descriptor() ([]byte, []int) { - return file_validators_proto_rawDescGZIP(), []int{8} -} - -func (x *QueryValidatorRequest) GetBtcPk() string { - if x != nil { - return x.BtcPk - } - return "" -} - -type QueryValidatorResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Validator *ValidatorInfo `protobuf:"bytes,1,opt,name=validator,proto3" json:"validator,omitempty"` -} - -func (x *QueryValidatorResponse) Reset() { - *x = QueryValidatorResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_validators_proto_msgTypes[9] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *QueryValidatorResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*QueryValidatorResponse) ProtoMessage() {} - -func (x *QueryValidatorResponse) ProtoReflect() protoreflect.Message { - mi := &file_validators_proto_msgTypes[9] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use QueryValidatorResponse.ProtoReflect.Descriptor instead. -func (*QueryValidatorResponse) Descriptor() ([]byte, []int) { - return file_validators_proto_rawDescGZIP(), []int{9} -} - -func (x *QueryValidatorResponse) GetValidator() *ValidatorInfo { - if x != nil { - return x.Validator - } - return nil -} - -type QueryValidatorListRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields -} - -func (x *QueryValidatorListRequest) Reset() { - *x = QueryValidatorListRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_validators_proto_msgTypes[10] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *QueryValidatorListRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*QueryValidatorListRequest) ProtoMessage() {} - -func (x *QueryValidatorListRequest) ProtoReflect() protoreflect.Message { - mi := &file_validators_proto_msgTypes[10] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use QueryValidatorListRequest.ProtoReflect.Descriptor instead. -func (*QueryValidatorListRequest) Descriptor() ([]byte, []int) { - return file_validators_proto_rawDescGZIP(), []int{10} -} - -type QueryValidatorListResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Validators []*ValidatorInfo `protobuf:"bytes,1,rep,name=validators,proto3" json:"validators,omitempty"` // TODO add pagination in case the list gets large -} - -func (x *QueryValidatorListResponse) Reset() { - *x = QueryValidatorListResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_validators_proto_msgTypes[11] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *QueryValidatorListResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*QueryValidatorListResponse) ProtoMessage() {} - -func (x *QueryValidatorListResponse) ProtoReflect() protoreflect.Message { - mi := &file_validators_proto_msgTypes[11] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use QueryValidatorListResponse.ProtoReflect.Descriptor instead. -func (*QueryValidatorListResponse) Descriptor() ([]byte, []int) { - return file_validators_proto_rawDescGZIP(), []int{11} -} - -func (x *QueryValidatorListResponse) GetValidators() []*ValidatorInfo { - if x != nil { - return x.Validators - } - return nil -} - -type StoreValidator struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // babylon_pk is the Babylon secp256k1 PK of this BTC validator - BabylonPk []byte `protobuf:"bytes,1,opt,name=babylon_pk,json=babylonPk,proto3" json:"babylon_pk,omitempty"` - // btc_pk is the BTC secp256k1 PK of the validator encoded in BIP-340 spec - BtcPk []byte `protobuf:"bytes,2,opt,name=btc_pk,json=btcPk,proto3" json:"btc_pk,omitempty"` - // description defines the description terms for the validator - Description []byte `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"` - // commission defines the commission rate for the validator - Commission string `protobuf:"bytes,4,opt,name=commission,proto3" json:"commission,omitempty"` - // pop is the proof of possession of babylon_pk and btc_pk - Pop *ProofOfPossession `protobuf:"bytes,5,opt,name=pop,proto3" json:"pop,omitempty"` - // key_name is the identifier of the keyring - KeyName string `protobuf:"bytes,6,opt,name=key_name,json=keyName,proto3" json:"key_name,omitempty"` - // chain_id is the identifier of the consumer chain that the validator connected to - ChainId string `protobuf:"bytes,7,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` - // last_voted_height defines the height of the last voted Babylon block - LastVotedHeight uint64 `protobuf:"varint,8,opt,name=last_voted_height,json=lastVotedHeight,proto3" json:"last_voted_height,omitempty"` - // last_committed_height defines the height of the last Babylon block - // to which the validator committed a randomness pair - LastCommittedHeight uint64 `protobuf:"varint,9,opt,name=last_committed_height,json=lastCommittedHeight,proto3" json:"last_committed_height,omitempty"` - // last_processed_height defines the height of the last successfully processed block - // even though the vote is not cast - LastProcessedHeight uint64 `protobuf:"varint,10,opt,name=last_processed_height,json=lastProcessedHeight,proto3" json:"last_processed_height,omitempty"` - // status defines the current validator status - Status ValidatorStatus `protobuf:"varint,11,opt,name=status,proto3,enum=proto.ValidatorStatus" json:"status,omitempty"` -} - -func (x *StoreValidator) Reset() { - *x = StoreValidator{} - if protoimpl.UnsafeEnabled { - mi := &file_validators_proto_msgTypes[12] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *StoreValidator) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*StoreValidator) ProtoMessage() {} - -func (x *StoreValidator) ProtoReflect() protoreflect.Message { - mi := &file_validators_proto_msgTypes[12] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use StoreValidator.ProtoReflect.Descriptor instead. -func (*StoreValidator) Descriptor() ([]byte, []int) { - return file_validators_proto_rawDescGZIP(), []int{12} -} - -func (x *StoreValidator) GetBabylonPk() []byte { - if x != nil { - return x.BabylonPk - } - return nil -} - -func (x *StoreValidator) GetBtcPk() []byte { - if x != nil { - return x.BtcPk - } - return nil -} - -func (x *StoreValidator) GetDescription() []byte { - if x != nil { - return x.Description - } - return nil -} - -func (x *StoreValidator) GetCommission() string { - if x != nil { - return x.Commission - } - return "" -} - -func (x *StoreValidator) GetPop() *ProofOfPossession { - if x != nil { - return x.Pop - } - return nil -} - -func (x *StoreValidator) GetKeyName() string { - if x != nil { - return x.KeyName - } - return "" -} - -func (x *StoreValidator) GetChainId() string { - if x != nil { - return x.ChainId - } - return "" -} - -func (x *StoreValidator) GetLastVotedHeight() uint64 { - if x != nil { - return x.LastVotedHeight - } - return 0 -} - -func (x *StoreValidator) GetLastCommittedHeight() uint64 { - if x != nil { - return x.LastCommittedHeight - } - return 0 -} - -func (x *StoreValidator) GetLastProcessedHeight() uint64 { - if x != nil { - return x.LastProcessedHeight - } - return 0 -} - -func (x *StoreValidator) GetStatus() ValidatorStatus { - if x != nil { - return x.Status - } - return ValidatorStatus_CREATED -} - -// ValidatorInfo is the basic information of a validator mainly for external usage -type ValidatorInfo struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // babylon_pk_hex is the hex string of the Babylon secp256k1 PK of this BTC validator - BabylonPkHex string `protobuf:"bytes,1,opt,name=babylon_pk_hex,json=babylonPkHex,proto3" json:"babylon_pk_hex,omitempty"` - // btc_pk_hex is the hex string of the BTC secp256k1 PK of the validator encoded in BIP-340 spec - BtcPkHex string `protobuf:"bytes,2,opt,name=btc_pk_hex,json=btcPkHex,proto3" json:"btc_pk_hex,omitempty"` - // description defines the description terms for the validator - Description []byte `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"` - // commission defines the commission rate for the validator - Commission string `protobuf:"bytes,4,opt,name=commission,proto3" json:"commission,omitempty"` - // last_voted_height defines the height of the last voted Babylon block - LastVotedHeight uint64 `protobuf:"varint,5,opt,name=last_voted_height,json=lastVotedHeight,proto3" json:"last_voted_height,omitempty"` - // last_committed_height defines the height of the last Babylon block - // to which the validator committed a randomness pair - LastCommittedHeight uint64 `protobuf:"varint,6,opt,name=last_committed_height,json=lastCommittedHeight,proto3" json:"last_committed_height,omitempty"` - // status defines the current validator status - Status ValidatorStatus `protobuf:"varint,7,opt,name=status,proto3,enum=proto.ValidatorStatus" json:"status,omitempty"` -} - -func (x *ValidatorInfo) Reset() { - *x = ValidatorInfo{} - if protoimpl.UnsafeEnabled { - mi := &file_validators_proto_msgTypes[13] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ValidatorInfo) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ValidatorInfo) ProtoMessage() {} - -func (x *ValidatorInfo) ProtoReflect() protoreflect.Message { - mi := &file_validators_proto_msgTypes[13] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ValidatorInfo.ProtoReflect.Descriptor instead. -func (*ValidatorInfo) Descriptor() ([]byte, []int) { - return file_validators_proto_rawDescGZIP(), []int{13} -} - -func (x *ValidatorInfo) GetBabylonPkHex() string { - if x != nil { - return x.BabylonPkHex - } - return "" -} - -func (x *ValidatorInfo) GetBtcPkHex() string { - if x != nil { - return x.BtcPkHex - } - return "" -} - -func (x *ValidatorInfo) GetDescription() []byte { - if x != nil { - return x.Description - } - return nil -} - -func (x *ValidatorInfo) GetCommission() string { - if x != nil { - return x.Commission - } - return "" -} - -func (x *ValidatorInfo) GetLastVotedHeight() uint64 { - if x != nil { - return x.LastVotedHeight - } - return 0 -} - -func (x *ValidatorInfo) GetLastCommittedHeight() uint64 { - if x != nil { - return x.LastCommittedHeight - } - return 0 -} - -func (x *ValidatorInfo) GetStatus() ValidatorStatus { - if x != nil { - return x.Status - } - return ValidatorStatus_CREATED -} - -// ProofOfPossession is the proof of possession that a Babylon secp256k1 -// secret key and a Bitcoin secp256k1 secret key are held by the same -// person -type ProofOfPossession struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // babylon_sig is the signature generated via sign(sk_babylon, pk_btc) - BabylonSig []byte `protobuf:"bytes,1,opt,name=babylon_sig,json=babylonSig,proto3" json:"babylon_sig,omitempty"` - // btc_sig is the signature generated via sign(sk_btc, babylon_sig) - // the signature follows encoding in BIP-340 spec - BtcSig []byte `protobuf:"bytes,2,opt,name=btc_sig,json=btcSig,proto3" json:"btc_sig,omitempty"` -} - -func (x *ProofOfPossession) Reset() { - *x = ProofOfPossession{} - if protoimpl.UnsafeEnabled { - mi := &file_validators_proto_msgTypes[14] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ProofOfPossession) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ProofOfPossession) ProtoMessage() {} - -func (x *ProofOfPossession) ProtoReflect() protoreflect.Message { - mi := &file_validators_proto_msgTypes[14] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ProofOfPossession.ProtoReflect.Descriptor instead. -func (*ProofOfPossession) Descriptor() ([]byte, []int) { - return file_validators_proto_rawDescGZIP(), []int{14} -} - -func (x *ProofOfPossession) GetBabylonSig() []byte { - if x != nil { - return x.BabylonSig - } - return nil -} - -func (x *ProofOfPossession) GetBtcSig() []byte { - if x != nil { - return x.BtcSig - } - return nil -} - -type SchnorrRandPair struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - PubRand []byte `protobuf:"bytes,1,opt,name=pub_rand,json=pubRand,proto3" json:"pub_rand,omitempty"` - SecRand []byte `protobuf:"bytes,2,opt,name=sec_rand,json=secRand,proto3" json:"sec_rand,omitempty"` -} - -func (x *SchnorrRandPair) Reset() { - *x = SchnorrRandPair{} - if protoimpl.UnsafeEnabled { - mi := &file_validators_proto_msgTypes[15] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *SchnorrRandPair) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*SchnorrRandPair) ProtoMessage() {} - -func (x *SchnorrRandPair) ProtoReflect() protoreflect.Message { - mi := &file_validators_proto_msgTypes[15] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use SchnorrRandPair.ProtoReflect.Descriptor instead. -func (*SchnorrRandPair) Descriptor() ([]byte, []int) { - return file_validators_proto_rawDescGZIP(), []int{15} -} - -func (x *SchnorrRandPair) GetPubRand() []byte { - if x != nil { - return x.PubRand - } - return nil -} - -func (x *SchnorrRandPair) GetSecRand() []byte { - if x != nil { - return x.SecRand - } - return nil -} - -var File_validators_proto protoreflect.FileDescriptor - -var file_validators_proto_rawDesc = []byte{ - 0x0a, 0x10, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x12, 0x05, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x14, 0x67, 0x6f, 0x67, 0x6f, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x67, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, - 0x24, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2f, 0x73, 0x74, 0x61, 0x6b, 0x69, 0x6e, 0x67, 0x2f, - 0x76, 0x31, 0x62, 0x65, 0x74, 0x61, 0x31, 0x2f, 0x73, 0x74, 0x61, 0x6b, 0x69, 0x6e, 0x67, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x19, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x5f, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x22, 0x10, 0x0a, 0x0e, 0x47, 0x65, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x22, 0x2b, 0x0a, 0x0f, 0x47, 0x65, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x65, 0x73, - 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, - 0xee, 0x01, 0x0a, 0x16, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, - 0x74, 0x6f, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x6b, 0x65, - 0x79, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6b, 0x65, - 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1e, 0x0a, 0x0a, 0x70, 0x61, 0x73, 0x73, 0x70, 0x68, 0x72, - 0x61, 0x73, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x70, 0x61, 0x73, 0x73, 0x70, - 0x68, 0x72, 0x61, 0x73, 0x65, 0x12, 0x17, 0x0a, 0x07, 0x68, 0x64, 0x5f, 0x70, 0x61, 0x74, 0x68, - 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x68, 0x64, 0x50, 0x61, 0x74, 0x68, 0x12, 0x19, - 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, - 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, - 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x43, 0x0a, 0x0a, 0x63, - 0x6f, 0x6d, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x42, - 0x23, 0xc8, 0xde, 0x1f, 0x00, 0xda, 0xde, 0x1f, 0x1b, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x73, - 0x64, 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x6d, 0x61, 0x74, 0x68, 0x2e, 0x4c, 0x65, 0x67, 0x61, 0x63, - 0x79, 0x44, 0x65, 0x63, 0x52, 0x0a, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, - 0x22, 0x30, 0x0a, 0x17, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, - 0x74, 0x6f, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x15, 0x0a, 0x06, 0x62, - 0x74, 0x63, 0x5f, 0x70, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x62, 0x74, 0x63, - 0x50, 0x6b, 0x22, 0x51, 0x0a, 0x18, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x56, 0x61, - 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x15, - 0x0a, 0x06, 0x62, 0x74, 0x63, 0x5f, 0x70, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, - 0x62, 0x74, 0x63, 0x50, 0x6b, 0x12, 0x1e, 0x0a, 0x0a, 0x70, 0x61, 0x73, 0x73, 0x70, 0x68, 0x72, - 0x61, 0x73, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x70, 0x61, 0x73, 0x73, 0x70, - 0x68, 0x72, 0x61, 0x73, 0x65, 0x22, 0x34, 0x0a, 0x19, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, - 0x72, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, - 0x73, 0x65, 0x12, 0x17, 0x0a, 0x07, 0x74, 0x78, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x06, 0x74, 0x78, 0x48, 0x61, 0x73, 0x68, 0x22, 0x67, 0x0a, 0x1b, 0x41, - 0x64, 0x64, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, - 0x75, 0x72, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x15, 0x0a, 0x06, 0x62, 0x74, - 0x63, 0x5f, 0x70, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x62, 0x74, 0x63, 0x50, - 0x6b, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x61, 0x70, 0x70, - 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x61, 0x70, 0x70, - 0x48, 0x61, 0x73, 0x68, 0x22, 0x83, 0x01, 0x0a, 0x1c, 0x41, 0x64, 0x64, 0x46, 0x69, 0x6e, 0x61, - 0x6c, 0x69, 0x74, 0x79, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x52, 0x65, 0x73, - 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x17, 0x0a, 0x07, 0x74, 0x78, 0x5f, 0x68, 0x61, 0x73, 0x68, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x74, 0x78, 0x48, 0x61, 0x73, 0x68, 0x12, 0x28, - 0x0a, 0x10, 0x65, 0x78, 0x74, 0x72, 0x61, 0x63, 0x74, 0x65, 0x64, 0x5f, 0x73, 0x6b, 0x5f, 0x68, - 0x65, 0x78, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x65, 0x78, 0x74, 0x72, 0x61, 0x63, - 0x74, 0x65, 0x64, 0x53, 0x6b, 0x48, 0x65, 0x78, 0x12, 0x20, 0x0a, 0x0c, 0x6c, 0x6f, 0x63, 0x61, - 0x6c, 0x5f, 0x73, 0x6b, 0x5f, 0x68, 0x65, 0x78, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, - 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x53, 0x6b, 0x48, 0x65, 0x78, 0x22, 0x2e, 0x0a, 0x15, 0x51, 0x75, - 0x65, 0x72, 0x79, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x12, 0x15, 0x0a, 0x06, 0x62, 0x74, 0x63, 0x5f, 0x70, 0x6b, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x05, 0x62, 0x74, 0x63, 0x50, 0x6b, 0x22, 0x4c, 0x0a, 0x16, 0x51, 0x75, - 0x65, 0x72, 0x79, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x73, 0x70, - 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x32, 0x0a, 0x09, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, - 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, - 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x09, 0x76, - 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x22, 0x1b, 0x0a, 0x19, 0x51, 0x75, 0x65, 0x72, - 0x79, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x52, 0x0a, 0x1a, 0x51, 0x75, 0x65, 0x72, 0x79, 0x56, 0x61, - 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x12, 0x34, 0x0a, 0x0a, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, - 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, - 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x0a, 0x76, - 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x73, 0x22, 0xd3, 0x03, 0x0a, 0x0e, 0x53, 0x74, - 0x6f, 0x72, 0x65, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x12, 0x1d, 0x0a, 0x0a, - 0x62, 0x61, 0x62, 0x79, 0x6c, 0x6f, 0x6e, 0x5f, 0x70, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, - 0x52, 0x09, 0x62, 0x61, 0x62, 0x79, 0x6c, 0x6f, 0x6e, 0x50, 0x6b, 0x12, 0x15, 0x0a, 0x06, 0x62, - 0x74, 0x63, 0x5f, 0x70, 0x6b, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x74, 0x63, - 0x50, 0x6b, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, - 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, - 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x43, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x73, 0x73, 0x69, - 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x42, 0x23, 0xc8, 0xde, 0x1f, 0x00, 0xda, 0xde, - 0x1f, 0x1b, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, 0x69, 0x6f, 0x2f, 0x6d, - 0x61, 0x74, 0x68, 0x2e, 0x4c, 0x65, 0x67, 0x61, 0x63, 0x79, 0x44, 0x65, 0x63, 0x52, 0x0a, 0x63, - 0x6f, 0x6d, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x2a, 0x0a, 0x03, 0x70, 0x6f, 0x70, - 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x50, - 0x72, 0x6f, 0x6f, 0x66, 0x4f, 0x66, 0x50, 0x6f, 0x73, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, - 0x52, 0x03, 0x70, 0x6f, 0x70, 0x12, 0x19, 0x0a, 0x08, 0x6b, 0x65, 0x79, 0x5f, 0x6e, 0x61, 0x6d, - 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6b, 0x65, 0x79, 0x4e, 0x61, 0x6d, 0x65, - 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x07, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x2a, 0x0a, 0x11, 0x6c, - 0x61, 0x73, 0x74, 0x5f, 0x76, 0x6f, 0x74, 0x65, 0x64, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, - 0x18, 0x08, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, 0x6c, 0x61, 0x73, 0x74, 0x56, 0x6f, 0x74, 0x65, - 0x64, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x32, 0x0a, 0x15, 0x6c, 0x61, 0x73, 0x74, 0x5f, - 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x74, 0x65, 0x64, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, - 0x18, 0x09, 0x20, 0x01, 0x28, 0x04, 0x52, 0x13, 0x6c, 0x61, 0x73, 0x74, 0x43, 0x6f, 0x6d, 0x6d, - 0x69, 0x74, 0x74, 0x65, 0x64, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x32, 0x0a, 0x15, 0x6c, - 0x61, 0x73, 0x74, 0x5f, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x65, 0x64, 0x5f, 0x68, 0x65, - 0x69, 0x67, 0x68, 0x74, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x04, 0x52, 0x13, 0x6c, 0x61, 0x73, 0x74, - 0x50, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x65, 0x64, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, - 0x2e, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x0e, 0x32, - 0x16, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, - 0x72, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, - 0xca, 0x02, 0x0a, 0x0d, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x49, 0x6e, 0x66, - 0x6f, 0x12, 0x24, 0x0a, 0x0e, 0x62, 0x61, 0x62, 0x79, 0x6c, 0x6f, 0x6e, 0x5f, 0x70, 0x6b, 0x5f, - 0x68, 0x65, 0x78, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x62, 0x61, 0x62, 0x79, 0x6c, - 0x6f, 0x6e, 0x50, 0x6b, 0x48, 0x65, 0x78, 0x12, 0x1c, 0x0a, 0x0a, 0x62, 0x74, 0x63, 0x5f, 0x70, - 0x6b, 0x5f, 0x68, 0x65, 0x78, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x62, 0x74, 0x63, - 0x50, 0x6b, 0x48, 0x65, 0x78, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, - 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, - 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x43, 0x0a, 0x0a, 0x63, 0x6f, 0x6d, 0x6d, 0x69, - 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x42, 0x23, 0xc8, 0xde, 0x1f, - 0x00, 0xda, 0xde, 0x1f, 0x1b, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0x73, 0x64, 0x6b, 0x2e, 0x69, - 0x6f, 0x2f, 0x6d, 0x61, 0x74, 0x68, 0x2e, 0x4c, 0x65, 0x67, 0x61, 0x63, 0x79, 0x44, 0x65, 0x63, - 0x52, 0x0a, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x2a, 0x0a, 0x11, - 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x76, 0x6f, 0x74, 0x65, 0x64, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, - 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, 0x6c, 0x61, 0x73, 0x74, 0x56, 0x6f, 0x74, - 0x65, 0x64, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x32, 0x0a, 0x15, 0x6c, 0x61, 0x73, 0x74, - 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x74, 0x65, 0x64, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, - 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x04, 0x52, 0x13, 0x6c, 0x61, 0x73, 0x74, 0x43, 0x6f, 0x6d, - 0x6d, 0x69, 0x74, 0x74, 0x65, 0x64, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x2e, 0x0a, 0x06, - 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x16, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x53, 0x74, - 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x4d, 0x0a, 0x11, - 0x50, 0x72, 0x6f, 0x6f, 0x66, 0x4f, 0x66, 0x50, 0x6f, 0x73, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, - 0x6e, 0x12, 0x1f, 0x0a, 0x0b, 0x62, 0x61, 0x62, 0x79, 0x6c, 0x6f, 0x6e, 0x5f, 0x73, 0x69, 0x67, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0a, 0x62, 0x61, 0x62, 0x79, 0x6c, 0x6f, 0x6e, 0x53, - 0x69, 0x67, 0x12, 0x17, 0x0a, 0x07, 0x62, 0x74, 0x63, 0x5f, 0x73, 0x69, 0x67, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x0c, 0x52, 0x06, 0x62, 0x74, 0x63, 0x53, 0x69, 0x67, 0x22, 0x47, 0x0a, 0x0f, 0x53, - 0x63, 0x68, 0x6e, 0x6f, 0x72, 0x72, 0x52, 0x61, 0x6e, 0x64, 0x50, 0x61, 0x69, 0x72, 0x12, 0x19, - 0x0a, 0x08, 0x70, 0x75, 0x62, 0x5f, 0x72, 0x61, 0x6e, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, - 0x52, 0x07, 0x70, 0x75, 0x62, 0x52, 0x61, 0x6e, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x73, 0x65, 0x63, - 0x5f, 0x72, 0x61, 0x6e, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x73, 0x65, 0x63, - 0x52, 0x61, 0x6e, 0x64, 0x2a, 0x9f, 0x01, 0x0a, 0x0f, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, - 0x6f, 0x72, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x43, 0x52, 0x45, 0x41, - 0x54, 0x45, 0x44, 0x10, 0x00, 0x1a, 0x0b, 0x8a, 0x9d, 0x20, 0x07, 0x43, 0x52, 0x45, 0x41, 0x54, - 0x45, 0x44, 0x12, 0x1e, 0x0a, 0x0a, 0x52, 0x45, 0x47, 0x49, 0x53, 0x54, 0x45, 0x52, 0x45, 0x44, - 0x10, 0x01, 0x1a, 0x0e, 0x8a, 0x9d, 0x20, 0x0a, 0x52, 0x45, 0x47, 0x49, 0x53, 0x54, 0x45, 0x52, - 0x45, 0x44, 0x12, 0x16, 0x0a, 0x06, 0x41, 0x43, 0x54, 0x49, 0x56, 0x45, 0x10, 0x02, 0x1a, 0x0a, - 0x8a, 0x9d, 0x20, 0x06, 0x41, 0x43, 0x54, 0x49, 0x56, 0x45, 0x12, 0x1a, 0x0a, 0x08, 0x49, 0x4e, - 0x41, 0x43, 0x54, 0x49, 0x56, 0x45, 0x10, 0x03, 0x1a, 0x0c, 0x8a, 0x9d, 0x20, 0x08, 0x49, 0x4e, - 0x41, 0x43, 0x54, 0x49, 0x56, 0x45, 0x12, 0x18, 0x0a, 0x07, 0x53, 0x4c, 0x41, 0x53, 0x48, 0x45, - 0x44, 0x10, 0x04, 0x1a, 0x0b, 0x8a, 0x9d, 0x20, 0x07, 0x53, 0x4c, 0x41, 0x53, 0x48, 0x45, 0x44, - 0x1a, 0x04, 0x88, 0xa3, 0x1e, 0x00, 0x32, 0xfe, 0x03, 0x0a, 0x0d, 0x42, 0x74, 0x63, 0x56, 0x61, - 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x73, 0x12, 0x38, 0x0a, 0x07, 0x47, 0x65, 0x74, 0x49, - 0x6e, 0x66, 0x6f, 0x12, 0x15, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x47, 0x65, 0x74, 0x49, - 0x6e, 0x66, 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x2e, 0x47, 0x65, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, - 0x73, 0x65, 0x12, 0x50, 0x0a, 0x0f, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x56, 0x61, 0x6c, 0x69, - 0x64, 0x61, 0x74, 0x6f, 0x72, 0x12, 0x1d, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x43, 0x72, - 0x65, 0x61, 0x74, 0x65, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x71, - 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x43, 0x72, 0x65, - 0x61, 0x74, 0x65, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x73, 0x70, - 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x56, 0x0a, 0x11, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, - 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x12, 0x1f, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, - 0x74, 0x6f, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x20, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x65, 0x72, 0x56, 0x61, 0x6c, 0x69, 0x64, - 0x61, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x5f, 0x0a, 0x14, - 0x41, 0x64, 0x64, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x53, 0x69, 0x67, 0x6e, 0x61, - 0x74, 0x75, 0x72, 0x65, 0x12, 0x22, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x41, 0x64, 0x64, - 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, - 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x23, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x2e, 0x41, 0x64, 0x64, 0x46, 0x69, 0x6e, 0x61, 0x6c, 0x69, 0x74, 0x79, 0x53, 0x69, 0x67, 0x6e, - 0x61, 0x74, 0x75, 0x72, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4d, 0x0a, - 0x0e, 0x51, 0x75, 0x65, 0x72, 0x79, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x12, - 0x1c, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x51, 0x75, 0x65, 0x72, 0x79, 0x56, 0x61, 0x6c, - 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x51, 0x75, 0x65, 0x72, 0x79, 0x56, 0x61, 0x6c, 0x69, 0x64, - 0x61, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x59, 0x0a, 0x12, - 0x51, 0x75, 0x65, 0x72, 0x79, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x4c, 0x69, - 0x73, 0x74, 0x12, 0x20, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x51, 0x75, 0x65, 0x72, 0x79, - 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x71, - 0x75, 0x65, 0x73, 0x74, 0x1a, 0x21, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x51, 0x75, 0x65, - 0x72, 0x79, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x52, - 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x37, 0x5a, 0x35, 0x67, 0x69, 0x74, 0x68, 0x75, - 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x61, 0x62, 0x79, 0x6c, 0x6f, 0x6e, 0x63, 0x68, 0x61, - 0x69, 0x6e, 0x2f, 0x62, 0x74, 0x63, 0x2d, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, - 0x2f, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} - -var ( - file_validators_proto_rawDescOnce sync.Once - file_validators_proto_rawDescData = file_validators_proto_rawDesc -) - -func file_validators_proto_rawDescGZIP() []byte { - file_validators_proto_rawDescOnce.Do(func() { - file_validators_proto_rawDescData = protoimpl.X.CompressGZIP(file_validators_proto_rawDescData) - }) - return file_validators_proto_rawDescData -} - -var file_validators_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_validators_proto_msgTypes = make([]protoimpl.MessageInfo, 16) -var file_validators_proto_goTypes = []interface{}{ - (ValidatorStatus)(0), // 0: proto.ValidatorStatus - (*GetInfoRequest)(nil), // 1: proto.GetInfoRequest - (*GetInfoResponse)(nil), // 2: proto.GetInfoResponse - (*CreateValidatorRequest)(nil), // 3: proto.CreateValidatorRequest - (*CreateValidatorResponse)(nil), // 4: proto.CreateValidatorResponse - (*RegisterValidatorRequest)(nil), // 5: proto.RegisterValidatorRequest - (*RegisterValidatorResponse)(nil), // 6: proto.RegisterValidatorResponse - (*AddFinalitySignatureRequest)(nil), // 7: proto.AddFinalitySignatureRequest - (*AddFinalitySignatureResponse)(nil), // 8: proto.AddFinalitySignatureResponse - (*QueryValidatorRequest)(nil), // 9: proto.QueryValidatorRequest - (*QueryValidatorResponse)(nil), // 10: proto.QueryValidatorResponse - (*QueryValidatorListRequest)(nil), // 11: proto.QueryValidatorListRequest - (*QueryValidatorListResponse)(nil), // 12: proto.QueryValidatorListResponse - (*StoreValidator)(nil), // 13: proto.StoreValidator - (*ValidatorInfo)(nil), // 14: proto.ValidatorInfo - (*ProofOfPossession)(nil), // 15: proto.ProofOfPossession - (*SchnorrRandPair)(nil), // 16: proto.SchnorrRandPair -} -var file_validators_proto_depIdxs = []int32{ - 14, // 0: proto.QueryValidatorResponse.validator:type_name -> proto.ValidatorInfo - 14, // 1: proto.QueryValidatorListResponse.validators:type_name -> proto.ValidatorInfo - 15, // 2: proto.StoreValidator.pop:type_name -> proto.ProofOfPossession - 0, // 3: proto.StoreValidator.status:type_name -> proto.ValidatorStatus - 0, // 4: proto.ValidatorInfo.status:type_name -> proto.ValidatorStatus - 1, // 5: proto.BtcValidators.GetInfo:input_type -> proto.GetInfoRequest - 3, // 6: proto.BtcValidators.CreateValidator:input_type -> proto.CreateValidatorRequest - 5, // 7: proto.BtcValidators.RegisterValidator:input_type -> proto.RegisterValidatorRequest - 7, // 8: proto.BtcValidators.AddFinalitySignature:input_type -> proto.AddFinalitySignatureRequest - 9, // 9: proto.BtcValidators.QueryValidator:input_type -> proto.QueryValidatorRequest - 11, // 10: proto.BtcValidators.QueryValidatorList:input_type -> proto.QueryValidatorListRequest - 2, // 11: proto.BtcValidators.GetInfo:output_type -> proto.GetInfoResponse - 4, // 12: proto.BtcValidators.CreateValidator:output_type -> proto.CreateValidatorResponse - 6, // 13: proto.BtcValidators.RegisterValidator:output_type -> proto.RegisterValidatorResponse - 8, // 14: proto.BtcValidators.AddFinalitySignature:output_type -> proto.AddFinalitySignatureResponse - 10, // 15: proto.BtcValidators.QueryValidator:output_type -> proto.QueryValidatorResponse - 12, // 16: proto.BtcValidators.QueryValidatorList:output_type -> proto.QueryValidatorListResponse - 11, // [11:17] is the sub-list for method output_type - 5, // [5:11] is the sub-list for method input_type - 5, // [5:5] is the sub-list for extension type_name - 5, // [5:5] is the sub-list for extension extendee - 0, // [0:5] is the sub-list for field type_name -} - -func init() { file_validators_proto_init() } -func file_validators_proto_init() { - if File_validators_proto != nil { - return - } - if !protoimpl.UnsafeEnabled { - file_validators_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetInfoRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_validators_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetInfoResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_validators_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*CreateValidatorRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_validators_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*CreateValidatorResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_validators_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*RegisterValidatorRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_validators_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*RegisterValidatorResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_validators_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*AddFinalitySignatureRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_validators_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*AddFinalitySignatureResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_validators_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*QueryValidatorRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_validators_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*QueryValidatorResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_validators_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*QueryValidatorListRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_validators_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*QueryValidatorListResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_validators_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*StoreValidator); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_validators_proto_msgTypes[13].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ValidatorInfo); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_validators_proto_msgTypes[14].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ProofOfPossession); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_validators_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SchnorrRandPair); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_validators_proto_rawDesc, - NumEnums: 1, - NumMessages: 16, - NumExtensions: 0, - NumServices: 1, - }, - GoTypes: file_validators_proto_goTypes, - DependencyIndexes: file_validators_proto_depIdxs, - EnumInfos: file_validators_proto_enumTypes, - MessageInfos: file_validators_proto_msgTypes, - }.Build() - File_validators_proto = out.File - file_validators_proto_rawDesc = nil - file_validators_proto_goTypes = nil - file_validators_proto_depIdxs = nil -} diff --git a/validator/proto/validators_grpc.pb.go b/validator/proto/validators_grpc.pb.go deleted file mode 100644 index 64ac1744..00000000 --- a/validator/proto/validators_grpc.pb.go +++ /dev/null @@ -1,310 +0,0 @@ -// Code generated by protoc-gen-go-grpc. DO NOT EDIT. -// versions: -// - protoc-gen-go-grpc v1.3.0 -// - protoc (unknown) -// source: validators.proto - -package proto - -import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.32.0 or later. -const _ = grpc.SupportPackageIsVersion7 - -const ( - BtcValidators_GetInfo_FullMethodName = "/proto.BtcValidators/GetInfo" - BtcValidators_CreateValidator_FullMethodName = "/proto.BtcValidators/CreateValidator" - BtcValidators_RegisterValidator_FullMethodName = "/proto.BtcValidators/RegisterValidator" - BtcValidators_AddFinalitySignature_FullMethodName = "/proto.BtcValidators/AddFinalitySignature" - BtcValidators_QueryValidator_FullMethodName = "/proto.BtcValidators/QueryValidator" - BtcValidators_QueryValidatorList_FullMethodName = "/proto.BtcValidators/QueryValidatorList" -) - -// BtcValidatorsClient is the client API for BtcValidators service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. -type BtcValidatorsClient interface { - // GetInfo returns the information of the daemon - GetInfo(ctx context.Context, in *GetInfoRequest, opts ...grpc.CallOption) (*GetInfoResponse, error) - // CreateValidator generates and saves a validator object - CreateValidator(ctx context.Context, in *CreateValidatorRequest, opts ...grpc.CallOption) (*CreateValidatorResponse, error) - // RegisterValidator sends a transactions to Babylon to register a BTC - // validator - RegisterValidator(ctx context.Context, in *RegisterValidatorRequest, opts ...grpc.CallOption) (*RegisterValidatorResponse, error) - // AddFinalitySignature sends a transactions to Babylon to add a Finality - // signature for a block - AddFinalitySignature(ctx context.Context, in *AddFinalitySignatureRequest, opts ...grpc.CallOption) (*AddFinalitySignatureResponse, error) - // QueryValidator queries the validator - QueryValidator(ctx context.Context, in *QueryValidatorRequest, opts ...grpc.CallOption) (*QueryValidatorResponse, error) - // QueryValidatorList queries a list of validators - QueryValidatorList(ctx context.Context, in *QueryValidatorListRequest, opts ...grpc.CallOption) (*QueryValidatorListResponse, error) -} - -type btcValidatorsClient struct { - cc grpc.ClientConnInterface -} - -func NewBtcValidatorsClient(cc grpc.ClientConnInterface) BtcValidatorsClient { - return &btcValidatorsClient{cc} -} - -func (c *btcValidatorsClient) GetInfo(ctx context.Context, in *GetInfoRequest, opts ...grpc.CallOption) (*GetInfoResponse, error) { - out := new(GetInfoResponse) - err := c.cc.Invoke(ctx, BtcValidators_GetInfo_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *btcValidatorsClient) CreateValidator(ctx context.Context, in *CreateValidatorRequest, opts ...grpc.CallOption) (*CreateValidatorResponse, error) { - out := new(CreateValidatorResponse) - err := c.cc.Invoke(ctx, BtcValidators_CreateValidator_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *btcValidatorsClient) RegisterValidator(ctx context.Context, in *RegisterValidatorRequest, opts ...grpc.CallOption) (*RegisterValidatorResponse, error) { - out := new(RegisterValidatorResponse) - err := c.cc.Invoke(ctx, BtcValidators_RegisterValidator_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *btcValidatorsClient) AddFinalitySignature(ctx context.Context, in *AddFinalitySignatureRequest, opts ...grpc.CallOption) (*AddFinalitySignatureResponse, error) { - out := new(AddFinalitySignatureResponse) - err := c.cc.Invoke(ctx, BtcValidators_AddFinalitySignature_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *btcValidatorsClient) QueryValidator(ctx context.Context, in *QueryValidatorRequest, opts ...grpc.CallOption) (*QueryValidatorResponse, error) { - out := new(QueryValidatorResponse) - err := c.cc.Invoke(ctx, BtcValidators_QueryValidator_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *btcValidatorsClient) QueryValidatorList(ctx context.Context, in *QueryValidatorListRequest, opts ...grpc.CallOption) (*QueryValidatorListResponse, error) { - out := new(QueryValidatorListResponse) - err := c.cc.Invoke(ctx, BtcValidators_QueryValidatorList_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// BtcValidatorsServer is the server API for BtcValidators service. -// All implementations must embed UnimplementedBtcValidatorsServer -// for forward compatibility -type BtcValidatorsServer interface { - // GetInfo returns the information of the daemon - GetInfo(context.Context, *GetInfoRequest) (*GetInfoResponse, error) - // CreateValidator generates and saves a validator object - CreateValidator(context.Context, *CreateValidatorRequest) (*CreateValidatorResponse, error) - // RegisterValidator sends a transactions to Babylon to register a BTC - // validator - RegisterValidator(context.Context, *RegisterValidatorRequest) (*RegisterValidatorResponse, error) - // AddFinalitySignature sends a transactions to Babylon to add a Finality - // signature for a block - AddFinalitySignature(context.Context, *AddFinalitySignatureRequest) (*AddFinalitySignatureResponse, error) - // QueryValidator queries the validator - QueryValidator(context.Context, *QueryValidatorRequest) (*QueryValidatorResponse, error) - // QueryValidatorList queries a list of validators - QueryValidatorList(context.Context, *QueryValidatorListRequest) (*QueryValidatorListResponse, error) - mustEmbedUnimplementedBtcValidatorsServer() -} - -// UnimplementedBtcValidatorsServer must be embedded to have forward compatible implementations. -type UnimplementedBtcValidatorsServer struct { -} - -func (UnimplementedBtcValidatorsServer) GetInfo(context.Context, *GetInfoRequest) (*GetInfoResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetInfo not implemented") -} -func (UnimplementedBtcValidatorsServer) CreateValidator(context.Context, *CreateValidatorRequest) (*CreateValidatorResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method CreateValidator not implemented") -} -func (UnimplementedBtcValidatorsServer) RegisterValidator(context.Context, *RegisterValidatorRequest) (*RegisterValidatorResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method RegisterValidator not implemented") -} -func (UnimplementedBtcValidatorsServer) AddFinalitySignature(context.Context, *AddFinalitySignatureRequest) (*AddFinalitySignatureResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method AddFinalitySignature not implemented") -} -func (UnimplementedBtcValidatorsServer) QueryValidator(context.Context, *QueryValidatorRequest) (*QueryValidatorResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method QueryValidator not implemented") -} -func (UnimplementedBtcValidatorsServer) QueryValidatorList(context.Context, *QueryValidatorListRequest) (*QueryValidatorListResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method QueryValidatorList not implemented") -} -func (UnimplementedBtcValidatorsServer) mustEmbedUnimplementedBtcValidatorsServer() {} - -// UnsafeBtcValidatorsServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to BtcValidatorsServer will -// result in compilation errors. -type UnsafeBtcValidatorsServer interface { - mustEmbedUnimplementedBtcValidatorsServer() -} - -func RegisterBtcValidatorsServer(s grpc.ServiceRegistrar, srv BtcValidatorsServer) { - s.RegisterService(&BtcValidators_ServiceDesc, srv) -} - -func _BtcValidators_GetInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetInfoRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(BtcValidatorsServer).GetInfo(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: BtcValidators_GetInfo_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BtcValidatorsServer).GetInfo(ctx, req.(*GetInfoRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _BtcValidators_CreateValidator_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(CreateValidatorRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(BtcValidatorsServer).CreateValidator(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: BtcValidators_CreateValidator_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BtcValidatorsServer).CreateValidator(ctx, req.(*CreateValidatorRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _BtcValidators_RegisterValidator_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(RegisterValidatorRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(BtcValidatorsServer).RegisterValidator(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: BtcValidators_RegisterValidator_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BtcValidatorsServer).RegisterValidator(ctx, req.(*RegisterValidatorRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _BtcValidators_AddFinalitySignature_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(AddFinalitySignatureRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(BtcValidatorsServer).AddFinalitySignature(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: BtcValidators_AddFinalitySignature_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BtcValidatorsServer).AddFinalitySignature(ctx, req.(*AddFinalitySignatureRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _BtcValidators_QueryValidator_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryValidatorRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(BtcValidatorsServer).QueryValidator(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: BtcValidators_QueryValidator_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BtcValidatorsServer).QueryValidator(ctx, req.(*QueryValidatorRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _BtcValidators_QueryValidatorList_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryValidatorListRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(BtcValidatorsServer).QueryValidatorList(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: BtcValidators_QueryValidatorList_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BtcValidatorsServer).QueryValidatorList(ctx, req.(*QueryValidatorListRequest)) - } - return interceptor(ctx, in, info, handler) -} - -// BtcValidators_ServiceDesc is the grpc.ServiceDesc for BtcValidators service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var BtcValidators_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "proto.BtcValidators", - HandlerType: (*BtcValidatorsServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "GetInfo", - Handler: _BtcValidators_GetInfo_Handler, - }, - { - MethodName: "CreateValidator", - Handler: _BtcValidators_CreateValidator_Handler, - }, - { - MethodName: "RegisterValidator", - Handler: _BtcValidators_RegisterValidator_Handler, - }, - { - MethodName: "AddFinalitySignature", - Handler: _BtcValidators_AddFinalitySignature_Handler, - }, - { - MethodName: "QueryValidator", - Handler: _BtcValidators_QueryValidator_Handler, - }, - { - MethodName: "QueryValidatorList", - Handler: _BtcValidators_QueryValidatorList_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "validators.proto", -} diff --git a/validator/service/app.go b/validator/service/app.go deleted file mode 100644 index 88551aeb..00000000 --- a/validator/service/app.go +++ /dev/null @@ -1,467 +0,0 @@ -package service - -import ( - "encoding/hex" - "fmt" - "github.com/babylonchain/btc-validator/util" - "strings" - "sync" - - sdkmath "cosmossdk.io/math" - bbntypes "github.com/babylonchain/babylon/types" - bstypes "github.com/babylonchain/babylon/x/btcstaking/types" - "github.com/btcsuite/btcd/btcec/v2" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - "go.uber.org/zap" - - valkr "github.com/babylonchain/btc-validator/keyring" - - "github.com/babylonchain/btc-validator/clientcontroller" - "github.com/babylonchain/btc-validator/eotsmanager" - "github.com/babylonchain/btc-validator/eotsmanager/client" - valcfg "github.com/babylonchain/btc-validator/validator/config" - "github.com/babylonchain/btc-validator/validator/proto" - - valstore "github.com/babylonchain/btc-validator/validator/store" -) - -type ValidatorApp struct { - startOnce sync.Once - stopOnce sync.Once - - wg sync.WaitGroup - quit chan struct{} - - sentWg sync.WaitGroup - sentQuit chan struct{} - - eventWg sync.WaitGroup - eventQuit chan struct{} - - cc clientcontroller.ClientController - kr keyring.Keyring - vs *valstore.ValidatorStore - config *valcfg.Config - logger *zap.Logger - input *strings.Reader - - validatorManager *ValidatorManager - eotsManager eotsmanager.EOTSManager - - createValidatorRequestChan chan *createValidatorRequest - registerValidatorRequestChan chan *registerValidatorRequest - validatorRegisteredEventChan chan *validatorRegisteredEvent -} - -func NewValidatorAppFromConfig( - homePath string, - config *valcfg.Config, - logger *zap.Logger, -) (*ValidatorApp, error) { - cc, err := clientcontroller.NewClientController(config.ChainName, config.BabylonConfig, &config.BTCNetParams, logger) - if err != nil { - return nil, fmt.Errorf("failed to create rpc client for the consumer chain %s: %v", config.ChainName, err) - } - - // if the EOTSManagerAddress is empty, run a local EOTS manager; - // otherwise connect a remote one with a gRPC client - em, err := client.NewEOTSManagerGRpcClient(config.EOTSManagerAddress) - if err != nil { - return nil, fmt.Errorf("failed to create EOTS manager client: %w", err) - } - // TODO add retry mechanism and ping to ensure the EOTS manager daemon is healthy - logger.Info("successfully connected to a remote EOTS manager", zap.String("address", config.EOTSManagerAddress)) - - return NewValidatorApp(homePath, config, cc, em, logger) -} - -func NewValidatorApp( - homePath string, - config *valcfg.Config, - cc clientcontroller.ClientController, - em eotsmanager.EOTSManager, - logger *zap.Logger, -) (*ValidatorApp, error) { - valStore, err := initStore(homePath, config) - if err != nil { - return nil, fmt.Errorf("failed to load store: %w", err) - } - - input := strings.NewReader("") - kr, err := valkr.CreateKeyring( - config.BabylonConfig.KeyDirectory, - config.BabylonConfig.ChainID, - config.BabylonConfig.KeyringBackend, - input, - ) - if err != nil { - return nil, fmt.Errorf("failed to create keyring: %w", err) - } - - vm, err := NewValidatorManager(valStore, config, cc, em, logger) - if err != nil { - return nil, fmt.Errorf("failed to create validator manager: %w", err) - } - - return &ValidatorApp{ - cc: cc, - vs: valStore, - kr: kr, - config: config, - logger: logger, - input: input, - validatorManager: vm, - eotsManager: em, - quit: make(chan struct{}), - sentQuit: make(chan struct{}), - eventQuit: make(chan struct{}), - createValidatorRequestChan: make(chan *createValidatorRequest), - registerValidatorRequestChan: make(chan *registerValidatorRequest), - validatorRegisteredEventChan: make(chan *validatorRegisteredEvent), - }, nil -} - -func initStore(homePath string, cfg *valcfg.Config) (*valstore.ValidatorStore, error) { - // Create the directory that will store the data - if err := util.MakeDirectory(valcfg.DataDir(homePath)); err != nil { - return nil, err - } - - return valstore.NewValidatorStore(valcfg.DBPath(homePath), cfg.DatabaseConfig.Name, cfg.DatabaseConfig.Backend) -} - -func (app *ValidatorApp) GetConfig() *valcfg.Config { - return app.config -} - -func (app *ValidatorApp) GetValidatorStore() *valstore.ValidatorStore { - return app.vs -} - -func (app *ValidatorApp) GetKeyring() keyring.Keyring { - return app.kr -} - -func (app *ValidatorApp) GetInput() *strings.Reader { - return app.input -} - -func (app *ValidatorApp) ListValidatorInstances() []*ValidatorInstance { - return app.validatorManager.ListValidatorInstances() -} - -// GetValidatorInstance returns the validator instance with the given Babylon public key -func (app *ValidatorApp) GetValidatorInstance(valPk *bbntypes.BIP340PubKey) (*ValidatorInstance, error) { - return app.validatorManager.GetValidatorInstance(valPk) -} - -func (app *ValidatorApp) RegisterValidator(valPkStr string) (*RegisterValidatorResponse, error) { - valPk, err := bbntypes.NewBIP340PubKeyFromHex(valPkStr) - if err != nil { - return nil, err - } - - validator, err := app.vs.GetStoreValidator(valPk.MustMarshal()) - if err != nil { - return nil, err - } - - if validator.Status != proto.ValidatorStatus_CREATED { - return nil, fmt.Errorf("validator is already registered") - } - - btcSig, err := bbntypes.NewBIP340Signature(validator.Pop.BtcSig) - if err != nil { - return nil, err - } - - pop := &bstypes.ProofOfPossession{ - BabylonSig: validator.Pop.BabylonSig, - BtcSig: btcSig.MustMarshal(), - BtcSigType: bstypes.BTCSigType_BIP340, - } - - commissionRate, err := sdkmath.LegacyNewDecFromStr(validator.Commission) - if err != nil { - return nil, err - } - - request := ®isterValidatorRequest{ - bbnPubKey: validator.GetBabylonPK(), - btcPubKey: validator.MustGetBIP340BTCPK(), - pop: pop, - description: validator.Description, - commission: &commissionRate, - errResponse: make(chan error, 1), - successResponse: make(chan *RegisterValidatorResponse, 1), - } - - app.registerValidatorRequestChan <- request - - select { - case err := <-request.errResponse: - return nil, err - case successResponse := <-request.successResponse: - return successResponse, nil - case <-app.quit: - return nil, fmt.Errorf("validator app is shutting down") - } -} - -// StartHandlingValidator starts a validator instance with the given Babylon public key -// Note: this should be called right after the validator is registered -func (app *ValidatorApp) StartHandlingValidator(valPk *bbntypes.BIP340PubKey, passphrase string) error { - return app.validatorManager.StartValidator(valPk, passphrase) -} - -// NOTE: this is not safe in production, so only used for testing purpose -func (app *ValidatorApp) getValPrivKey(valPk []byte) (*btcec.PrivateKey, error) { - record, err := app.eotsManager.KeyRecord(valPk, "") - if err != nil { - return nil, err - } - - return record.PrivKey, nil -} - -// Start starts only the validator daemon without any validator instances -func (app *ValidatorApp) Start() error { - var startErr error - app.startOnce.Do(func() { - app.logger.Info("Starting ValidatorApp") - - app.eventWg.Add(1) - go app.eventLoop() - - app.sentWg.Add(1) - go app.registrationLoop() - }) - - return startErr -} - -func (app *ValidatorApp) Stop() error { - var stopErr error - app.stopOnce.Do(func() { - app.logger.Info("Stopping ValidatorApp") - - // Always stop the submission loop first to not generate additional events and actions - app.logger.Debug("Stopping submission loop") - close(app.quit) - app.wg.Wait() - - app.logger.Debug("Stopping validators") - if err := app.validatorManager.Stop(); err != nil { - stopErr = err - return - } - - app.logger.Debug("Sent to Babylon loop stopped") - close(app.sentQuit) - app.sentWg.Wait() - - app.logger.Debug("Stopping main eventLoop") - close(app.eventQuit) - app.eventWg.Wait() - - // Closing db as last to avoid anybody to write do db - app.logger.Debug("Stopping data store") - if err := app.vs.Close(); err != nil { - stopErr = err - return - } - - app.logger.Debug("Stopping EOTS manager") - if err := app.eotsManager.Close(); err != nil { - stopErr = err - return - } - - app.logger.Debug("ValidatorApp successfully stopped") - - }) - return stopErr -} - -func (app *ValidatorApp) CreateValidator( - keyName, chainID, passPhrase, hdPath string, - description []byte, - commission *sdkmath.LegacyDec, -) (*CreateValidatorResult, error) { - - req := &createValidatorRequest{ - keyName: keyName, - chainID: chainID, - passPhrase: passPhrase, - hdPath: hdPath, - description: description, - commission: commission, - errResponse: make(chan error, 1), - successResponse: make(chan *createValidatorResponse, 1), - } - - app.createValidatorRequestChan <- req - - select { - case err := <-req.errResponse: - return nil, err - case successResponse := <-req.successResponse: - return &CreateValidatorResult{ - ValPk: successResponse.ValPk, - }, nil - case <-app.quit: - return nil, fmt.Errorf("validator app is shutting down") - } -} - -func (app *ValidatorApp) handleCreateValidatorRequest(req *createValidatorRequest) (*createValidatorResponse, error) { - valPkBytes, err := app.eotsManager.CreateKey(req.keyName, req.passPhrase, req.hdPath) - if err != nil { - return nil, err - } - - valPk, err := bbntypes.NewBIP340PubKey(valPkBytes) - if err != nil { - return nil, err - } - - kr, err := valkr.NewChainKeyringControllerWithKeyring(app.kr, req.keyName, app.input) - if err != nil { - return nil, err - } - - keyPair, err := kr.CreateChainKey(req.passPhrase, req.hdPath) - if err != nil { - return nil, fmt.Errorf("failed to create chain key for the validator: %w", err) - } - pk := &secp256k1.PubKey{Key: keyPair.PublicKey.SerializeCompressed()} - - valRecord, err := app.eotsManager.KeyRecord(valPk.MustMarshal(), req.passPhrase) - if err != nil { - return nil, fmt.Errorf("failed to get validator record: %w", err) - } - - pop, err := kr.CreatePop(valRecord.PrivKey, req.passPhrase) - if err != nil { - return nil, fmt.Errorf("failed to create proof-of-possession of the validator: %w", err) - } - - validator := valstore.NewStoreValidator(pk, valPk, req.keyName, req.chainID, pop, req.description, req.commission) - - if err := app.vs.SaveValidator(validator); err != nil { - return nil, fmt.Errorf("failed to save validator: %w", err) - } - - app.logger.Info("successfully created a validator", - zap.String("btc_pk", valPk.MarshalHex()), - zap.String("key_name", req.keyName), - ) - - return &createValidatorResponse{ - ValPk: valPk, - }, nil -} - -// main event loop for the validator app -func (app *ValidatorApp) eventLoop() { - defer app.eventWg.Done() - - for { - select { - case req := <-app.createValidatorRequestChan: - res, err := app.handleCreateValidatorRequest(req) - if err != nil { - req.errResponse <- err - continue - } - - req.successResponse <- &createValidatorResponse{ValPk: res.ValPk} - - case ev := <-app.validatorRegisteredEventChan: - valStored, err := app.vs.GetStoreValidator(ev.btcPubKey.MustMarshal()) - if err != nil { - // we always check if the validator is in the DB before sending the registration request - app.logger.Fatal( - "registered validator not found in DB", - zap.String("pk", ev.btcPubKey.MarshalHex()), - zap.Error(err), - ) - } - - // change the status of the validator to registered - err = app.vs.SetValidatorStatus(valStored, proto.ValidatorStatus_REGISTERED) - if err != nil { - app.logger.Fatal("failed to set validator status to REGISTERED", - zap.String("pk", ev.btcPubKey.MarshalHex()), - zap.Error(err), - ) - } - - // return to the caller - ev.successResponse <- &RegisterValidatorResponse{ - bbnPubKey: valStored.GetBabylonPK(), - btcPubKey: valStored.MustGetBIP340BTCPK(), - TxHash: ev.txHash, - } - - case <-app.eventQuit: - app.logger.Debug("exiting main event loop") - return - } - } -} - -func (app *ValidatorApp) registrationLoop() { - defer app.sentWg.Done() - for { - select { - case req := <-app.registerValidatorRequestChan: - // we won't do any retries here to not block the loop for more important messages. - // Most probably it fails due so some user error so we just return the error to the user. - // TODO: need to start passing context here to be able to cancel the request in case of app quiting - popBytes, err := req.pop.Marshal() - if err != nil { - req.errResponse <- err - continue - } - - res, err := app.cc.RegisterValidator( - req.bbnPubKey.Key, - req.btcPubKey.MustToBTCPK(), - popBytes, - req.commission, - req.description, - ) - - if err != nil { - app.logger.Error( - "failed to register validator", - zap.String("pk", req.btcPubKey.MarshalHex()), - zap.Error(err), - ) - req.errResponse <- err - continue - } - - app.logger.Info( - "successfully registered validator on babylon", - zap.String("btc_pk", req.btcPubKey.MarshalHex()), - zap.String("babylon_pk", hex.EncodeToString(req.bbnPubKey.Key)), - zap.String("txHash", res.TxHash), - ) - - app.validatorRegisteredEventChan <- &validatorRegisteredEvent{ - btcPubKey: req.btcPubKey, - bbnPubKey: req.bbnPubKey, - txHash: res.TxHash, - // pass the channel to the event so that we can send the response to the user which requested - // the registration - successResponse: req.successResponse, - } - case <-app.sentQuit: - app.logger.Debug("exiting registration loop") - return - } - } -} diff --git a/validator/service/client/rpcclient.go b/validator/service/client/rpcclient.go deleted file mode 100644 index e8793550..00000000 --- a/validator/service/client/rpcclient.go +++ /dev/null @@ -1,122 +0,0 @@ -package client - -import ( - "context" - "fmt" - - sdkmath "cosmossdk.io/math" - bbntypes "github.com/babylonchain/babylon/types" - "github.com/cosmos/cosmos-sdk/x/staking/types" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" - - "github.com/babylonchain/btc-validator/validator/proto" -) - -type ValidatorServiceGRpcClient struct { - client proto.BtcValidatorsClient -} - -func NewValidatorServiceGRpcClient(remoteAddr string) (*ValidatorServiceGRpcClient, func(), error) { - conn, err := grpc.Dial(remoteAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) - if err != nil { - return nil, nil, fmt.Errorf("failed to build gRPC connection to %s: %w", remoteAddr, err) - } - - cleanUp := func() { - conn.Close() - } - - return &ValidatorServiceGRpcClient{ - client: proto.NewBtcValidatorsClient(conn), - }, cleanUp, nil -} - -func (c *ValidatorServiceGRpcClient) GetInfo(ctx context.Context) (*proto.GetInfoResponse, error) { - req := &proto.GetInfoRequest{} - res, err := c.client.GetInfo(ctx, req) - if err != nil { - return nil, err - } - - return res, nil -} - -func (c *ValidatorServiceGRpcClient) RegisterValidator( - ctx context.Context, - valPk *bbntypes.BIP340PubKey, - passphrase string, -) (*proto.RegisterValidatorResponse, error) { - - req := &proto.RegisterValidatorRequest{BtcPk: valPk.MarshalHex(), Passphrase: passphrase} - res, err := c.client.RegisterValidator(ctx, req) - if err != nil { - return nil, err - } - - return res, nil -} - -func (c *ValidatorServiceGRpcClient) CreateValidator( - ctx context.Context, - keyName, chainID, passphrase, hdPath string, - description types.Description, - commission *sdkmath.LegacyDec, -) (*proto.CreateValidatorResponse, error) { - - descBytes, err := description.Marshal() - if err != nil { - return nil, err - } - - req := &proto.CreateValidatorRequest{ - KeyName: keyName, - ChainId: chainID, - Passphrase: passphrase, - HdPath: hdPath, - Description: descBytes, - Commission: commission.String(), - } - - res, err := c.client.CreateValidator(ctx, req) - if err != nil { - return nil, err - } - - return res, nil -} - -func (c *ValidatorServiceGRpcClient) AddFinalitySignature(ctx context.Context, valPk string, height uint64, lch []byte) (*proto.AddFinalitySignatureResponse, error) { - req := &proto.AddFinalitySignatureRequest{ - BtcPk: valPk, - Height: height, - AppHash: lch, - } - - res, err := c.client.AddFinalitySignature(ctx, req) - if err != nil { - return nil, err - } - - return res, nil -} - -func (c *ValidatorServiceGRpcClient) QueryValidatorList(ctx context.Context) (*proto.QueryValidatorListResponse, error) { - req := &proto.QueryValidatorListRequest{} - res, err := c.client.QueryValidatorList(ctx, req) - if err != nil { - return nil, err - } - - return res, nil -} - -func (c *ValidatorServiceGRpcClient) QueryValidatorInfo(ctx context.Context, valPk *bbntypes.BIP340PubKey) (*proto.QueryValidatorResponse, error) { - req := &proto.QueryValidatorRequest{BtcPk: valPk.MarshalHex()} - res, err := c.client.QueryValidator(ctx, req) - if err != nil { - return nil, err - } - - return res, nil -} diff --git a/validator/service/rpcserver.go b/validator/service/rpcserver.go deleted file mode 100644 index 9e0848d8..00000000 --- a/validator/service/rpcserver.go +++ /dev/null @@ -1,210 +0,0 @@ -package service - -import ( - "context" - "encoding/hex" - "fmt" - "sync" - "sync/atomic" - - "cosmossdk.io/math" - bbntypes "github.com/babylonchain/babylon/types" - "google.golang.org/grpc" - - "github.com/babylonchain/btc-validator/types" - "github.com/babylonchain/btc-validator/validator/proto" - "github.com/babylonchain/btc-validator/version" -) - -// rpcServer is the main RPC server for the BTC-Validator daemon that handles -// gRPC incoming requests. -type rpcServer struct { - started int32 - shutdown int32 - - proto.UnimplementedBtcValidatorsServer - - app *ValidatorApp - - quit chan struct{} - wg sync.WaitGroup -} - -// newRPCServer creates a new RPC sever from the set of input dependencies. -func newRPCServer( - v *ValidatorApp, -) *rpcServer { - - return &rpcServer{ - quit: make(chan struct{}), - app: v, - } -} - -// Start signals that the RPC server starts accepting requests. -func (r *rpcServer) Start() error { - if atomic.AddInt32(&r.started, 1) != 1 { - return nil - } - - return nil -} - -// Stop signals that the RPC server should attempt a graceful shutdown and -// cancel any outstanding requests. -func (r *rpcServer) Stop() error { - if atomic.AddInt32(&r.shutdown, 1) != 1 { - return nil - } - - close(r.quit) - - r.wg.Wait() - - return nil -} - -// RegisterWithGrpcServer registers the rpcServer with the passed root gRPC -// server. -func (r *rpcServer) RegisterWithGrpcServer(grpcServer *grpc.Server) error { - // Register the main RPC server. - proto.RegisterBtcValidatorsServer(grpcServer, r) - return nil -} - -// GetInfo returns general information relating to the active daemon -func (r *rpcServer) GetInfo(context.Context, *proto.GetInfoRequest) (*proto.GetInfoResponse, error) { - - return &proto.GetInfoResponse{ - Version: version.Version(), - }, nil -} - -// CreateValidator generates a validator object and saves it in the database -func (r *rpcServer) CreateValidator(ctx context.Context, req *proto.CreateValidatorRequest) ( - *proto.CreateValidatorResponse, error) { - - commissionRate, err := math.LegacyNewDecFromStr(req.Commission) - if err != nil { - return nil, err - } - - result, err := r.app.CreateValidator( - req.KeyName, - req.ChainId, - req.Passphrase, - req.HdPath, - req.Description, - &commissionRate, - ) - - if err != nil { - return nil, err - } - - return &proto.CreateValidatorResponse{ - BtcPk: result.ValPk.MarshalHex(), - }, nil - -} - -// RegisterValidator sends a transactions to Babylon to register a BTC validator -func (r *rpcServer) RegisterValidator(ctx context.Context, req *proto.RegisterValidatorRequest) ( - *proto.RegisterValidatorResponse, error) { - - txRes, err := r.app.RegisterValidator(req.BtcPk) - if err != nil { - return nil, fmt.Errorf("failed to register the validator to Babylon: %w", err) - } - - // the validator instance should be started right after registration - if err := r.app.StartHandlingValidator(txRes.btcPubKey, req.Passphrase); err != nil { - return nil, fmt.Errorf("failed to start the registered validator %s: %w", hex.EncodeToString(txRes.bbnPubKey.Key), err) - } - - return &proto.RegisterValidatorResponse{TxHash: txRes.TxHash}, nil -} - -// AddFinalitySignature adds a manually constructed finality signature to Babylon -// NOTE: this is only used for presentation/testing purposes -func (r *rpcServer) AddFinalitySignature(ctx context.Context, req *proto.AddFinalitySignatureRequest) ( - *proto.AddFinalitySignatureResponse, error) { - - valPk, err := bbntypes.NewBIP340PubKeyFromHex(req.BtcPk) - if err != nil { - return nil, err - } - - v, err := r.app.GetValidatorInstance(valPk) - if err != nil { - return nil, err - } - - b := &types.BlockInfo{ - Height: req.Height, - Hash: req.AppHash, - } - - txRes, privKey, err := v.TestSubmitFinalitySignatureAndExtractPrivKey(b) - if err != nil { - return nil, err - } - - res := &proto.AddFinalitySignatureResponse{TxHash: txRes.TxHash} - - // if privKey is not empty, then this BTC validator - // has voted for a fork and will be slashed - if privKey != nil { - localPrivKey, err := r.app.getValPrivKey(valPk.MustMarshal()) - res.ExtractedSkHex = privKey.Key.String() - if err != nil { - return nil, err - } - localSkHex := localPrivKey.Key.String() - localSkNegateHex := localPrivKey.Key.Negate().String() - if res.ExtractedSkHex == localSkHex { - res.LocalSkHex = localSkHex - } else if res.ExtractedSkHex == localSkNegateHex { - res.LocalSkHex = localSkNegateHex - } else { - return nil, fmt.Errorf("the validator's BTC private key is extracted but does not match the local key,"+ - "extrated: %s, local: %s, local-negated: %s", - res.ExtractedSkHex, localSkHex, localSkNegateHex) - } - } - - return res, nil -} - -// QueryValidator queries the information of the validator -func (r *rpcServer) QueryValidator(ctx context.Context, req *proto.QueryValidatorRequest) ( - *proto.QueryValidatorResponse, error) { - - valPk, err := bbntypes.NewBIP340PubKeyFromHex(req.BtcPk) - if err != nil { - return nil, err - } - val, err := r.app.GetValidatorInstance(valPk) - if err != nil { - return nil, err - } - - valInfo := proto.NewValidatorInfo(val.GetStoreValidator()) - - return &proto.QueryValidatorResponse{Validator: valInfo}, nil -} - -// QueryValidatorList queries the information of a list of validators -func (r *rpcServer) QueryValidatorList(ctx context.Context, req *proto.QueryValidatorListRequest) ( - *proto.QueryValidatorListResponse, error) { - - vals := r.app.ListValidatorInstances() - - valsInfo := make([]*proto.ValidatorInfo, len(vals)) - for i, v := range vals { - valInfo := proto.NewValidatorInfo(v.GetStoreValidator()) - valsInfo[i] = valInfo - } - - return &proto.QueryValidatorListResponse{Validators: valsInfo}, nil -} diff --git a/validator/service/types.go b/validator/service/types.go deleted file mode 100644 index 3eaff467..00000000 --- a/validator/service/types.go +++ /dev/null @@ -1,201 +0,0 @@ -package service - -import ( - "sync" - - sdkmath "cosmossdk.io/math" - bbntypes "github.com/babylonchain/babylon/types" - btcstakingtypes "github.com/babylonchain/babylon/x/btcstaking/types" - "github.com/btcsuite/btcd/btcec/v2" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - "go.uber.org/zap" - - "github.com/babylonchain/btc-validator/validator/proto" - valstore "github.com/babylonchain/btc-validator/validator/store" -) - -type createValidatorResponse struct { - ValPk *bbntypes.BIP340PubKey -} -type createValidatorRequest struct { - keyName string - passPhrase string - hdPath string - chainID string - description []byte - commission *sdkmath.LegacyDec - errResponse chan error - successResponse chan *createValidatorResponse -} - -type registerValidatorRequest struct { - bbnPubKey *secp256k1.PubKey - btcPubKey *bbntypes.BIP340PubKey - // TODO we should have our own representation of PoP - pop *btcstakingtypes.ProofOfPossession - description []byte - commission *sdkmath.LegacyDec - errResponse chan error - successResponse chan *RegisterValidatorResponse -} - -type validatorRegisteredEvent struct { - bbnPubKey *secp256k1.PubKey - btcPubKey *bbntypes.BIP340PubKey - txHash string - successResponse chan *RegisterValidatorResponse -} - -type RegisterValidatorResponse struct { - bbnPubKey *secp256k1.PubKey - btcPubKey *bbntypes.BIP340PubKey - TxHash string -} - -type CreateValidatorResult struct { - ValPk *bbntypes.BIP340PubKey -} - -type valState struct { - mu sync.Mutex - v *proto.StoreValidator - s *valstore.ValidatorStore -} - -func (vs *valState) getStoreValidator() *proto.StoreValidator { - vs.mu.Lock() - defer vs.mu.Unlock() - return vs.v -} - -func (vs *valState) setStatus(s proto.ValidatorStatus) error { - vs.mu.Lock() - vs.v.Status = s - vs.mu.Unlock() - return vs.s.UpdateValidator(vs.v) -} - -func (vs *valState) setLastProcessedHeight(height uint64) error { - vs.mu.Lock() - vs.v.LastProcessedHeight = height - vs.mu.Unlock() - return vs.s.UpdateValidator(vs.v) -} - -func (vs *valState) setLastCommittedHeight(height uint64) error { - vs.mu.Lock() - vs.v.LastCommittedHeight = height - vs.mu.Unlock() - return vs.s.UpdateValidator(vs.v) -} - -func (vs *valState) setLastProcessedAndVotedHeight(height uint64) error { - vs.mu.Lock() - vs.v.LastVotedHeight = height - vs.v.LastProcessedHeight = height - vs.mu.Unlock() - return vs.s.UpdateValidator(vs.v) -} - -func (v *ValidatorInstance) GetStoreValidator() *proto.StoreValidator { - return v.state.getStoreValidator() -} - -func (v *ValidatorInstance) GetBabylonPk() *secp256k1.PubKey { - return v.state.getStoreValidator().GetBabylonPK() -} - -func (v *ValidatorInstance) GetBabylonPkHex() string { - return v.state.getStoreValidator().GetBabylonPkHexString() -} - -func (v *ValidatorInstance) GetBtcPkBIP340() *bbntypes.BIP340PubKey { - return v.state.getStoreValidator().MustGetBIP340BTCPK() -} - -func (v *ValidatorInstance) MustGetBtcPk() *btcec.PublicKey { - return v.state.getStoreValidator().MustGetBTCPK() -} - -func (v *ValidatorInstance) GetBtcPkHex() string { - return v.GetBtcPkBIP340().MarshalHex() -} - -func (v *ValidatorInstance) GetStatus() proto.ValidatorStatus { - return v.state.getStoreValidator().Status -} - -func (v *ValidatorInstance) GetLastVotedHeight() uint64 { - return v.state.getStoreValidator().LastVotedHeight -} - -func (v *ValidatorInstance) GetLastProcessedHeight() uint64 { - return v.state.getStoreValidator().LastProcessedHeight -} - -func (v *ValidatorInstance) GetLastCommittedHeight() uint64 { - return v.state.getStoreValidator().LastCommittedHeight -} - -func (v *ValidatorInstance) GetChainID() []byte { - return []byte(v.state.getStoreValidator().ChainId) -} - -func (v *ValidatorInstance) SetStatus(s proto.ValidatorStatus) error { - return v.state.setStatus(s) -} - -func (v *ValidatorInstance) MustSetStatus(s proto.ValidatorStatus) { - if err := v.SetStatus(s); err != nil { - v.logger.Fatal("failed to set validator status", - zap.String("pk", v.GetBtcPkHex()), zap.String("status", s.String())) - } -} - -func (v *ValidatorInstance) SetLastProcessedHeight(height uint64) error { - return v.state.setLastProcessedHeight(height) -} - -func (v *ValidatorInstance) MustSetLastProcessedHeight(height uint64) { - if err := v.SetLastProcessedHeight(height); err != nil { - v.logger.Fatal("failed to set last processed height", - zap.String("pk", v.GetBtcPkHex()), zap.Uint64("last_processed_height", height)) - } -} - -func (v *ValidatorInstance) SetLastCommittedHeight(height uint64) error { - return v.state.setLastCommittedHeight(height) -} - -func (v *ValidatorInstance) MustSetLastCommittedHeight(height uint64) { - if err := v.SetLastCommittedHeight(height); err != nil { - v.logger.Fatal("failed to set last committed height", - zap.String("pk", v.GetBtcPkHex()), zap.Uint64("last_committed_height", height)) - } -} - -func (v *ValidatorInstance) updateStateAfterFinalitySigSubmission(height uint64) error { - return v.state.setLastProcessedAndVotedHeight(height) -} - -func (v *ValidatorInstance) MustUpdateStateAfterFinalitySigSubmission(height uint64) { - if err := v.updateStateAfterFinalitySigSubmission(height); err != nil { - v.logger.Fatal("failed to update state after finality signature submitted", - zap.String("pk", v.GetBtcPkHex()), zap.Uint64("height", height)) - } -} - -func (v *ValidatorInstance) getEOTSPrivKey() (*btcec.PrivateKey, error) { - // TODO ignore pass phrase for now - record, err := v.em.KeyRecord(v.btcPk.MustMarshal(), v.passphrase) - if err != nil { - return nil, err - } - - return record.PrivKey, nil -} - -// only used for testing purposes -func (v *ValidatorInstance) BtcPrivKey() (*btcec.PrivateKey, error) { - return v.getEOTSPrivKey() -} diff --git a/validator/service/validator_manager.go b/validator/service/validator_manager.go deleted file mode 100644 index 34ed331f..00000000 --- a/validator/service/validator_manager.go +++ /dev/null @@ -1,344 +0,0 @@ -package service - -import ( - "errors" - "fmt" - "sync" - "time" - - "github.com/avast/retry-go/v4" - bbntypes "github.com/babylonchain/babylon/types" - btcstakingtypes "github.com/babylonchain/babylon/x/btcstaking/types" - "go.uber.org/atomic" - "go.uber.org/zap" - - "github.com/babylonchain/btc-validator/clientcontroller" - "github.com/babylonchain/btc-validator/eotsmanager" - "github.com/babylonchain/btc-validator/types" - valcfg "github.com/babylonchain/btc-validator/validator/config" - "github.com/babylonchain/btc-validator/validator/proto" - valstore "github.com/babylonchain/btc-validator/validator/store" -) - -const instanceTerminatingMsg = "terminating the validator instance due to critical error" - -type CriticalError struct { - err error - valBtcPk *bbntypes.BIP340PubKey -} - -func (ce *CriticalError) Error() string { - return fmt.Sprintf("critical err on validator %s: %s", ce.valBtcPk.MarshalHex(), ce.err.Error()) -} - -type ValidatorManager struct { - isStarted *atomic.Bool - - mu sync.Mutex - wg sync.WaitGroup - - // running validator instances map keyed by the hex string of the BTC public key - vals map[string]*ValidatorInstance - - // needed for initiating validator instances - vs *valstore.ValidatorStore - config *valcfg.Config - cc clientcontroller.ClientController - em eotsmanager.EOTSManager - logger *zap.Logger - - criticalErrChan chan *CriticalError - - quit chan struct{} -} - -func NewValidatorManager(vs *valstore.ValidatorStore, - config *valcfg.Config, - cc clientcontroller.ClientController, - em eotsmanager.EOTSManager, - logger *zap.Logger, -) (*ValidatorManager, error) { - return &ValidatorManager{ - vals: make(map[string]*ValidatorInstance), - criticalErrChan: make(chan *CriticalError), - isStarted: atomic.NewBool(false), - vs: vs, - config: config, - cc: cc, - em: em, - logger: logger, - quit: make(chan struct{}), - }, nil -} - -// monitorCriticalErr takes actions when it receives critical errors from a validator instance -// if the validator is slashed, it will be terminated and the program keeps running in case -// new validators join -// otherwise, the program will panic -func (vm *ValidatorManager) monitorCriticalErr() { - defer vm.wg.Done() - - var criticalErr *CriticalError - for { - select { - case criticalErr = <-vm.criticalErrChan: - vi, err := vm.GetValidatorInstance(criticalErr.valBtcPk) - if err != nil { - panic(fmt.Errorf("failed to get the validator instance: %w", err)) - } - if errors.Is(criticalErr.err, btcstakingtypes.ErrBTCValAlreadySlashed) { - vm.setValidatorSlashed(vi) - vm.logger.Debug("the validator has been slashed", - zap.String("pk", criticalErr.valBtcPk.MarshalHex())) - continue - } - vi.logger.Fatal(instanceTerminatingMsg, - zap.String("pk", criticalErr.valBtcPk.MarshalHex()), zap.Error(criticalErr.err)) - case <-vm.quit: - return - } - } -} - -// monitorStatusUpdate periodically check the status of each managed validators and update -// it accordingly. We update the status by querying the latest voting power and the slashed_height. -// In particular, we perform the following status transitions (REGISTERED, ACTIVE, INACTIVE, SLASHED): -// 1. if power == 0 and slashed_height == 0, if status == ACTIVE, change to INACTIVE, otherwise remain the same -// 2. if power == 0 and slashed_height > 0, set status to SLASHED and stop and remove the validator instance -// 3. if power > 0 (slashed_height must > 0), set status to ACTIVE -// NOTE: once error occurs, we log and continue as the status update is not critical to the entire program -func (vm *ValidatorManager) monitorStatusUpdate() { - defer vm.wg.Done() - - if vm.config.StatusUpdateInterval == 0 { - vm.logger.Info("the status update is disabled") - return - } - - statusUpdateTicker := time.NewTicker(vm.config.StatusUpdateInterval) - defer statusUpdateTicker.Stop() - - for { - select { - case <-statusUpdateTicker.C: - latestBlock, err := vm.getLatestBlockWithRetry() - if err != nil { - vm.logger.Debug("failed to get the latest block", zap.Error(err)) - continue - } - vals := vm.ListValidatorInstances() - for _, v := range vals { - oldStatus := v.GetStatus() - power, err := v.GetVotingPowerWithRetry(latestBlock.Height) - if err != nil { - vm.logger.Debug( - "failed to get the voting power", - zap.String("val_btc_pk", v.GetBtcPkHex()), - zap.Uint64("height", latestBlock.Height), - zap.Error(err), - ) - continue - } - // power > 0 (slashed_height must > 0), set status to ACTIVE - if power > 0 { - if oldStatus != proto.ValidatorStatus_ACTIVE { - v.MustSetStatus(proto.ValidatorStatus_ACTIVE) - vm.logger.Debug( - "the validator status is changed to ACTIVE", - zap.String("val_btc_pk", v.GetBtcPkHex()), - zap.String("old_status", oldStatus.String()), - zap.Uint64("power", power), - ) - } - continue - } - slashed, err := v.GetValidatorSlashedWithRetry() - if err != nil { - vm.logger.Debug( - "failed to get the slashed height", - zap.String("val_btc_pk", v.GetBtcPkHex()), - zap.Error(err), - ) - continue - } - // power == 0 and slashed == true, set status to SLASHED and stop and remove the validator instance - if slashed { - vm.setValidatorSlashed(v) - vm.logger.Debug( - "the validator is slashed", - zap.String("val_btc_pk", v.GetBtcPkHex()), - zap.String("old_status", oldStatus.String()), - ) - continue - } - // power == 0 and slashed_height == 0, change to INACTIVE if the current status is ACTIVE - if oldStatus == proto.ValidatorStatus_ACTIVE { - v.MustSetStatus(proto.ValidatorStatus_INACTIVE) - vm.logger.Debug( - "the validator status is changed to INACTIVE", - zap.String("val_btc_pk", v.GetBtcPkHex()), - zap.String("old_status", oldStatus.String()), - ) - } - } - case <-vm.quit: - return - } - } -} - -func (vm *ValidatorManager) setValidatorSlashed(vi *ValidatorInstance) { - vi.MustSetStatus(proto.ValidatorStatus_SLASHED) - if err := vm.removeValidatorInstance(vi.GetBtcPkBIP340()); err != nil { - panic(fmt.Errorf("failed to terminate a slashed validator %s: %w", vi.GetBtcPkHex(), err)) - } -} - -func (vm *ValidatorManager) StartValidator(valPk *bbntypes.BIP340PubKey, passphrase string) error { - if !vm.isStarted.Load() { - vm.isStarted.Store(true) - - vm.wg.Add(1) - go vm.monitorCriticalErr() - - vm.wg.Add(1) - go vm.monitorStatusUpdate() - } - - if vm.numOfRunningValidators() >= int(vm.config.MaxNumValidators) { - return fmt.Errorf("reaching maximum number of running validators %v", vm.config.MaxNumValidators) - } - - if err := vm.addValidatorInstance(valPk, passphrase); err != nil { - return err - } - - return nil -} - -func (vm *ValidatorManager) Stop() error { - if !vm.isStarted.Swap(false) { - return fmt.Errorf("the validator manager has already stopped") - } - - var stopErr error - - for _, v := range vm.vals { - if !v.IsRunning() { - continue - } - if err := v.Stop(); err != nil { - stopErr = err - break - } - } - - close(vm.quit) - vm.wg.Wait() - - return stopErr -} - -func (vm *ValidatorManager) ListValidatorInstances() []*ValidatorInstance { - vm.mu.Lock() - defer vm.mu.Unlock() - - valsList := make([]*ValidatorInstance, 0, len(vm.vals)) - for _, v := range vm.vals { - valsList = append(valsList, v) - } - - return valsList -} - -func (vm *ValidatorManager) GetValidatorInstance(valPk *bbntypes.BIP340PubKey) (*ValidatorInstance, error) { - vm.mu.Lock() - defer vm.mu.Unlock() - - keyHex := valPk.MarshalHex() - v, exists := vm.vals[keyHex] - if !exists { - return nil, fmt.Errorf("cannot find the validator instance with PK: %s", keyHex) - } - - return v, nil -} - -func (vm *ValidatorManager) removeValidatorInstance(valPk *bbntypes.BIP340PubKey) error { - vm.mu.Lock() - defer vm.mu.Unlock() - - keyHex := valPk.MarshalHex() - v, exists := vm.vals[keyHex] - if !exists { - return fmt.Errorf("cannot find the validator instance with PK: %s", keyHex) - } - if v.IsRunning() { - if err := v.Stop(); err != nil { - return fmt.Errorf("failed to stop the validator instance %s", keyHex) - } - } - - delete(vm.vals, keyHex) - return nil -} - -func (vm *ValidatorManager) numOfRunningValidators() int { - vm.mu.Lock() - defer vm.mu.Unlock() - - return len(vm.vals) -} - -// addValidatorInstance creates a validator instance, starts it and adds it into the validator manager -func (vm *ValidatorManager) addValidatorInstance( - pk *bbntypes.BIP340PubKey, - passphrase string, -) error { - vm.mu.Lock() - defer vm.mu.Unlock() - - pkHex := pk.MarshalHex() - if _, exists := vm.vals[pkHex]; exists { - return fmt.Errorf("validator instance already exists") - } - - valIns, err := NewValidatorInstance(pk, vm.config, vm.vs, vm.cc, vm.em, passphrase, vm.criticalErrChan, vm.logger) - if err != nil { - return fmt.Errorf("failed to create validator %s instance: %w", pkHex, err) - } - - if err := valIns.Start(); err != nil { - return fmt.Errorf("failed to start validator %s instance: %w", pkHex, err) - } - - vm.vals[pkHex] = valIns - - return nil -} - -func (vm *ValidatorManager) getLatestBlockWithRetry() (*types.BlockInfo, error) { - var ( - latestBlock *types.BlockInfo - err error - ) - - if err := retry.Do(func() error { - latestBlock, err = vm.cc.QueryBestBlock() - if err != nil { - return err - } - return nil - }, RtyAtt, RtyDel, RtyErr, retry.OnRetry(func(n uint, err error) { - vm.logger.Debug( - "failed to query the consumer chain for the latest block", - zap.Uint("attempt", n+1), - zap.Uint("max_attempts", RtyAttNum), - zap.Error(err), - ) - })); err != nil { - return nil, err - } - - return latestBlock, nil -} diff --git a/validator/store/valstore.go b/validator/store/valstore.go deleted file mode 100644 index ae1ece03..00000000 --- a/validator/store/valstore.go +++ /dev/null @@ -1,210 +0,0 @@ -package store - -import ( - "fmt" - "math" - - sdkmath "cosmossdk.io/math" - "github.com/babylonchain/babylon/types" - bstypes "github.com/babylonchain/babylon/x/btcstaking/types" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - gproto "google.golang.org/protobuf/proto" - - "github.com/babylonchain/btc-validator/store" - "github.com/babylonchain/btc-validator/validator/proto" -) - -const ( - validatorPrefix = "validator" -) - -func NewStoreValidator(babylonPk *secp256k1.PubKey, btcPk *types.BIP340PubKey, keyName, chainID string, pop *bstypes.ProofOfPossession, des []byte, com *sdkmath.LegacyDec) *proto.StoreValidator { - return &proto.StoreValidator{ - KeyName: keyName, - BabylonPk: babylonPk.Bytes(), - BtcPk: btcPk.MustMarshal(), - Pop: &proto.ProofOfPossession{ - BabylonSig: pop.BabylonSig, - BtcSig: pop.BtcSig, - }, - ChainId: chainID, - Status: proto.ValidatorStatus_CREATED, - Description: des, - Commission: com.String(), - } -} - -type ValidatorStore struct { - s store.Store -} - -func NewValidatorStore(dbPath string, dbName string, dbBackend string) (*ValidatorStore, error) { - s, err := openStore(dbPath, dbName, dbBackend) - if err != nil { - return nil, err - } - - return &ValidatorStore{s: s}, nil -} - -func getValidatorKey(pk []byte) []byte { - return append([]byte(validatorPrefix), pk...) -} - -func (vs *ValidatorStore) getValidatorListKey() []byte { - return []byte(validatorPrefix) -} - -func (vs *ValidatorStore) SaveValidator(val *proto.StoreValidator) error { - k := getValidatorKey(val.BtcPk) - v, err := gproto.Marshal(val) - if err != nil { - return fmt.Errorf("failed to marshal the created validator object: %w", err) - } - - if err := vs.s.Put(k, v); err != nil { - return fmt.Errorf("failed to save the created validator object: %w", err) - } - - return nil -} - -func (vs *ValidatorStore) UpdateValidator(val *proto.StoreValidator) error { - k := getValidatorKey(val.BtcPk) - exists, err := vs.s.Exists(k) - if err != nil { - return err - } - if !exists { - return fmt.Errorf("the validator does not exist") - } - - v, err := gproto.Marshal(val) - if err != nil { - return err - } - - if err := vs.s.Put(k, v); err != nil { - return err - } - - return nil -} - -func (vs *ValidatorStore) SetValidatorStatus(val *proto.StoreValidator, status proto.ValidatorStatus) error { - val.Status = status - return vs.UpdateValidator(val) -} - -func (vs *ValidatorStore) GetStoreValidator(pk []byte) (*proto.StoreValidator, error) { - k := getValidatorKey(pk) - valsBytes, err := vs.s.Get(k) - if err != nil { - return nil, err - } - - val := new(proto.StoreValidator) - err = gproto.Unmarshal(valsBytes, val) - if err != nil { - panic(fmt.Errorf("unable to unmarshal validator object: %w", err)) - } - - return val, nil -} - -func (vs *ValidatorStore) ListValidators() ([]*proto.StoreValidator, error) { - k := vs.getValidatorListKey() - valsBytes, err := vs.s.List(k) - if err != nil { - return nil, err - } - - valsList := make([]*proto.StoreValidator, len(valsBytes)) - for i := 0; i < len(valsBytes); i++ { - val := new(proto.StoreValidator) - err := gproto.Unmarshal(valsBytes[i].Value, val) - if err != nil { - panic(fmt.Errorf("failed to unmarshal validator from the database: %w", err)) - } - valsList[i] = val - } - - return valsList, nil -} - -// ListRegisteredValidators returns a list of validators whose status is more than CREATED -// but less than SLASHED -func (vs *ValidatorStore) ListRegisteredValidators() ([]*proto.StoreValidator, error) { - k := vs.getValidatorListKey() - valsBytes, err := vs.s.List(k) - if err != nil { - return nil, err - } - - valsList := make([]*proto.StoreValidator, 0) - for i := 0; i < len(valsBytes); i++ { - val := new(proto.StoreValidator) - err := gproto.Unmarshal(valsBytes[i].Value, val) - if err != nil { - panic(fmt.Errorf("failed to unmarshal validator from the database: %w", err)) - } - if val.Status > proto.ValidatorStatus_CREATED && val.Status < proto.ValidatorStatus_SLASHED { - valsList = append(valsList, val) - } - } - - return valsList, nil -} - -func (vs *ValidatorStore) GetEarliestActiveValidatorVotedHeight() (uint64, error) { - registeredValidators, err := vs.ListRegisteredValidators() - if err != nil { - return 0, err - } - - if len(registeredValidators) == 0 { - return 0, nil - } - - earliestHeight := uint64(math.MaxUint64) - activeValsCnt := 0 - for _, val := range registeredValidators { - // Note there might be a delay between the validator being active on Babylon - // and this program capturing that. However, given that we only care - // about the `LastVotedHeight` of the validator, other parts of the program - // ensure that when this value is set, the validator is stored as ACTIVE. - // TODO: Another option would be to query here for the - // active status of each validator although this might prove inefficient. - if val.Status != proto.ValidatorStatus_ACTIVE { - continue - } - activeValsCnt += 1 - if earliestHeight > val.LastVotedHeight { - earliestHeight = val.LastVotedHeight - } - } - // If there are no active validators, return 0 - if activeValsCnt == 0 { - return 0, nil - } - return earliestHeight, nil -} - -func (vs *ValidatorStore) Close() error { - if err := vs.s.Close(); err != nil { - return err - } - - return nil -} - -// openStore returns a Store instance with the given db type, path and name -// currently, we only support bbolt -func openStore(dbPath string, dbName string, dbBackend string) (store.Store, error) { - switch dbBackend { - case "bbolt": - return store.NewBboltStore(dbPath, dbName) - default: - return nil, fmt.Errorf("unsupported database type") - } -} diff --git a/validator/store/valstore_test.go b/validator/store/valstore_test.go deleted file mode 100644 index 6cde8a53..00000000 --- a/validator/store/valstore_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package store_test - -import ( - "math/rand" - "os" - "path/filepath" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/babylonchain/btc-validator/testutil" - valstore "github.com/babylonchain/btc-validator/validator/store" -) - -// FuzzValidators tests save and list validators properly -func FuzzValidatorStore(f *testing.F) { - testutil.AddRandomSeedsToFuzzer(f, 10) - f.Fuzz(func(t *testing.T, seed int64) { - r := rand.New(rand.NewSource(seed)) - - dbPath := filepath.Join(t.TempDir(), "db") - dbcfg := testutil.GenDBConfig(r, t) - vs, err := valstore.NewValidatorStore(dbPath, dbcfg.Name, dbcfg.Backend) - require.NoError(t, err) - - defer func() { - err := os.RemoveAll(dbPath) - require.NoError(t, err) - }() - - validator := testutil.GenRandomValidator(r, t) - err = vs.SaveValidator(validator) - require.NoError(t, err) - - valList, err := vs.ListValidators() - require.NoError(t, err) - require.Equal(t, validator.BtcPk, valList[0].BtcPk) - - actualVal, err := vs.GetStoreValidator(validator.BtcPk) - require.NoError(t, err) - require.Equal(t, validator.BabylonPk, actualVal.BabylonPk) - require.Equal(t, validator.BtcPk, actualVal.BtcPk) - require.Equal(t, validator.KeyName, actualVal.KeyName) - }) -} diff --git a/version/version.go b/version/version.go index ca3888d5..17f641b9 100644 --- a/version/version.go +++ b/version/version.go @@ -52,17 +52,17 @@ const ( // defaultAgentName is the default name of the software that is added as // the first part of the user agent string. - defaultAgentName = "vald" + defaultAgentName = "fpd" ) // agentName stores the name of the software that is added as the first part of -// the user agent string. This defaults to the value "vald" when being run as -// a standalone component but can be overwritten by LiT for example when vald +// the user agent string. This defaults to the value "fpd" when being run as +// a standalone component but can be overwritten by LiT for example when fpd // is integrated into the UI. var agentName = defaultAgentName // SetAgentName overwrites the default agent name which can be used to identify -// the software vald is bundled in (for example LiT). This function panics if +// the software fpd is bundled in (for example LiT). This function panics if // the agent name contains characters outside of the allowed semantic alphabet. func SetAgentName(newAgentName string) { for _, r := range newAgentName {