From 19c01615e418700fe29fa8e91098d9478f8f0425 Mon Sep 17 00:00:00 2001 From: bap2pecs Date: Mon, 1 Jul 2024 11:48:26 -0400 Subject: [PATCH] fix long lines --- clientcontroller/api/interface.go | 24 +++- clientcontroller/babylon/babylon.go | 82 ++++++++--- clientcontroller/babylon/consumer.go | 57 ++++++-- clientcontroller/cosmwasm/consumer.go | 129 ++++++++++++++---- clientcontroller/factory.go | 17 ++- clientcontroller/opstackl2/consumer.go | 51 +++++-- cosmwasmclient/client/client.go | 7 +- cosmwasmclient/client/keys.go | 5 +- cosmwasmclient/client/tx.go | 14 +- cosmwasmclient/query/tendermint.go | 20 ++- cosmwasmclient/query/wasm.go | 18 ++- eotsmanager/client/rpcclient.go | 23 +++- eotsmanager/cmd/eotsd/daemon/init.go | 3 +- eotsmanager/cmd/eotsd/daemon/keys.go | 4 +- eotsmanager/cmd/eotsd/daemon/sign.go | 6 +- eotsmanager/cmd/eotsd/daemon/sign_test.go | 75 ++++++++-- eotsmanager/cmd/eotsd/daemon/start.go | 15 +- eotsmanager/cmd/eotsd/main.go | 8 +- eotsmanager/config/config.go | 6 +- eotsmanager/eotsmanager.go | 16 ++- eotsmanager/localmanager.go | 76 +++++++++-- eotsmanager/localmanager_test.go | 30 +++- eotsmanager/randgenerator/randgenerator.go | 6 +- eotsmanager/service/rpcserver.go | 13 +- eotsmanager/service/server.go | 8 +- .../cmd/fpcli/daemon/daemoncmd.go | 20 ++- finality-provider/cmd/fpd/daemon/init.go | 3 +- finality-provider/cmd/fpd/daemon/keys.go | 7 +- finality-provider/cmd/fpd/daemon/start.go | 8 +- finality-provider/config/babylon.go | 26 ++-- finality-provider/config/config.go | 30 ++-- finality-provider/config/cosmwasm.go | 28 ++-- finality-provider/config/opstackl2.go | 30 ++-- finality-provider/config/poller.go | 6 +- finality-provider/service/app.go | 71 ++++++++-- finality-provider/service/app_test.go | 34 ++++- finality-provider/service/chain_poller.go | 11 +- .../service/chain_poller_test.go | 26 +++- finality-provider/service/client/rpcclient.go | 29 +++- .../service/eots_manager_adapter.go | 29 +++- finality-provider/service/fastsync.go | 4 +- finality-provider/service/fastsync_test.go | 108 +++++++++++---- finality-provider/service/fp_instance.go | 128 +++++++++++++---- finality-provider/service/fp_instance_test.go | 94 ++++++++++--- finality-provider/service/fp_manager.go | 62 +++++++-- finality-provider/service/fp_manager_test.go | 61 +++++++-- finality-provider/service/rpcserver.go | 41 ++++-- finality-provider/service/server.go | 8 +- finality-provider/store/fpstore.go | 19 ++- itest/babylon/babylon_e2e_test.go | 33 ++++- itest/babylon/babylon_test_manager.go | 35 ++++- itest/babylon_node_handler.go | 6 +- itest/cosmwasm/bcd/bcd_consumer_e2e_test.go | 66 +++++++-- itest/cosmwasm/bcd/bcd_handler.go | 44 +++++- itest/cosmwasm/bcd/bcd_test_manager.go | 34 ++++- itest/cosmwasm/wasmd/wasmd_e2e_test.go | 52 +++++-- itest/cosmwasm/wasmd/wasmd_handler.go | 102 ++++++++++++-- itest/cosmwasm/wasmd/wasmd_test_manager.go | 58 +++++++- itest/eotsmanager_handler.go | 15 +- itest/opstackl2/op_e2e_test.go | 14 +- itest/opstackl2/op_test_manager.go | 75 ++++++++-- itest/test-manager/base_test_manager.go | 54 ++++++-- itest/test_helpers.go | 48 +++++-- itest/utils.go | 9 +- keyring/keyring.go | 7 +- keyring/keyringcontroller.go | 24 +++- keyring/keyringcontroller_test.go | 7 +- metrics/config.go | 4 +- metrics/fp_collectors.go | 10 +- testutil/datagen.go | 26 +++- testutil/utils.go | 6 +- 71 files changed, 1886 insertions(+), 439 deletions(-) diff --git a/clientcontroller/api/interface.go b/clientcontroller/api/interface.go index 2e6c11ba..4798a9c6 100644 --- a/clientcontroller/api/interface.go +++ b/clientcontroller/api/interface.go @@ -34,13 +34,31 @@ type ClientController interface { type ConsumerController interface { // CommitPubRandList commits a list of EOTS public randomness the consumer chain // it returns tx hash and error - CommitPubRandList(fpPk *btcec.PublicKey, startHeight uint64, numPubRand uint64, commitment []byte, sig *schnorr.Signature) (*types.TxResponse, error) + CommitPubRandList( + fpPk *btcec.PublicKey, + startHeight uint64, + numPubRand uint64, + commitment []byte, + sig *schnorr.Signature, + ) (*types.TxResponse, error) // SubmitFinalitySig submits the finality signature to the consumer chain - SubmitFinalitySig(fpPk *btcec.PublicKey, block *types.BlockInfo, pubRand *btcec.FieldVal, proof []byte, sig *btcec.ModNScalar) (*types.TxResponse, error) + SubmitFinalitySig( + fpPk *btcec.PublicKey, + block *types.BlockInfo, + pubRand *btcec.FieldVal, + proof []byte, + sig *btcec.ModNScalar, + ) (*types.TxResponse, error) // SubmitBatchFinalitySigs submits a batch of finality signatures to the consumer chain - SubmitBatchFinalitySigs(fpPk *btcec.PublicKey, blocks []*types.BlockInfo, pubRandList []*btcec.FieldVal, proofList [][]byte, sigs []*btcec.ModNScalar) (*types.TxResponse, error) + SubmitBatchFinalitySigs( + fpPk *btcec.PublicKey, + blocks []*types.BlockInfo, + pubRandList []*btcec.FieldVal, + proofList [][]byte, + sigs []*btcec.ModNScalar, + ) (*types.TxResponse, error) // Note: the following queries are only for PoC diff --git a/clientcontroller/babylon/babylon.go b/clientcontroller/babylon/babylon.go index 1514f5cd..1ce7de5f 100644 --- a/clientcontroller/babylon/babylon.go +++ b/clientcontroller/babylon/babylon.go @@ -95,11 +95,19 @@ func (bc *BabylonController) GetKeyAddress() sdk.AccAddress { return addr } -func (bc *BabylonController) reliablySendMsg(msg sdk.Msg, expectedErrs []*sdkErr.Error, unrecoverableErrs []*sdkErr.Error) (*provider.RelayerTxResponse, error) { +func (bc *BabylonController) reliablySendMsg( + msg sdk.Msg, + expectedErrs []*sdkErr.Error, + unrecoverableErrs []*sdkErr.Error, +) (*provider.RelayerTxResponse, error) { return bc.reliablySendMsgs([]sdk.Msg{msg}, expectedErrs, unrecoverableErrs) } -func (bc *BabylonController) reliablySendMsgs(msgs []sdk.Msg, expectedErrs []*sdkErr.Error, unrecoverableErrs []*sdkErr.Error) (*provider.RelayerTxResponse, error) { +func (bc *BabylonController) reliablySendMsgs( + msgs []sdk.Msg, + expectedErrs []*sdkErr.Error, + unrecoverableErrs []*sdkErr.Error, +) (*provider.RelayerTxResponse, error) { return bc.bbnClient.ReliablySendMsgs( context.Background(), msgs, @@ -150,7 +158,11 @@ func (bc *BabylonController) QueryFinalityProviderSlashed(fpPk *btcec.PublicKey) fpPubKey := bbntypes.NewBIP340PubKeyFromBTCPK(fpPk) res, err := bc.bbnClient.QueryClient.FinalityProvider(fpPubKey.MarshalHex()) if err != nil { - return false, fmt.Errorf("failed to query the finality provider %s: %v", fpPubKey.MarshalHex(), err) + return false, fmt.Errorf( + "failed to query the finality provider %s: %v", + fpPubKey.MarshalHex(), + err, + ) } slashed := res.FinalityProvider.SlashedBtcHeight > 0 @@ -159,7 +171,10 @@ func (bc *BabylonController) QueryFinalityProviderSlashed(fpPk *btcec.PublicKey) } // QueryFinalityProviderVotingPower queries the voting power of the finality provider at a given height -func (bc *BabylonController) QueryFinalityProviderVotingPower(fpPk *btcec.PublicKey, blockHeight uint64) (uint64, error) { +func (bc *BabylonController) QueryFinalityProviderVotingPower( + fpPk *btcec.PublicKey, + blockHeight uint64, +) (uint64, error) { res, err := bc.bbnClient.QueryClient.FinalityProviderPowerAtHeight( bbntypes.NewBIP340PubKeyFromBTCPK(fpPk).MarshalHex(), blockHeight, @@ -175,18 +190,34 @@ func (bc *BabylonController) QueryLatestFinalizedBlocks(count uint64) ([]*types. return bc.queryLatestBlocks(nil, count, finalitytypes.QueriedBlockStatus_FINALIZED, true) } -func (bc *BabylonController) QueryBlocks(startHeight, endHeight, limit uint64) ([]*types.BlockInfo, error) { +func (bc *BabylonController) QueryBlocks( + startHeight, endHeight, limit uint64, +) ([]*types.BlockInfo, error) { if endHeight < startHeight { - return nil, fmt.Errorf("the startHeight %v should not be higher than the endHeight %v", startHeight, endHeight) + return nil, fmt.Errorf( + "the startHeight %v should not be higher than the endHeight %v", + startHeight, + endHeight, + ) } count := endHeight - startHeight + 1 if count > limit { count = limit } - return bc.queryLatestBlocks(sdk.Uint64ToBigEndian(startHeight), count, finalitytypes.QueriedBlockStatus_ANY, false) + return bc.queryLatestBlocks( + sdk.Uint64ToBigEndian(startHeight), + count, + finalitytypes.QueriedBlockStatus_ANY, + false, + ) } -func (bc *BabylonController) queryLatestBlocks(startKey []byte, count uint64, status finalitytypes.QueriedBlockStatus, reverse bool) ([]*types.BlockInfo, error) { +func (bc *BabylonController) queryLatestBlocks( + startKey []byte, + count uint64, + status finalitytypes.QueriedBlockStatus, + reverse bool, +) ([]*types.BlockInfo, error) { var blocks []*types.BlockInfo pagination := &sdkquery.PageRequest{ Limit: count, @@ -268,7 +299,9 @@ func (bc *BabylonController) CreateBTCDelegation( return &types.TxResponse{TxHash: res.TxHash}, nil } -func (bc *BabylonController) InsertBtcBlockHeaders(headers []bbntypes.BTCHeaderBytes) (*provider.RelayerTxResponse, error) { +func (bc *BabylonController) InsertBtcBlockHeaders( + headers []bbntypes.BTCHeaderBytes, +) (*provider.RelayerTxResponse, error) { msg := &btclctypes.MsgInsertHeaders{ Signer: bc.MustGetTxSigner(), Headers: headers, @@ -307,7 +340,9 @@ func (bc *BabylonController) QueryFinalityProviders() ([]*btcstakingtypes.Finali return fps, nil } -func (bc *BabylonController) QueryConsumerFinalityProviders(consumerId string) ([]*bsctypes.FinalityProviderResponse, error) { +func (bc *BabylonController) QueryConsumerFinalityProviders( + consumerId string, +) ([]*bsctypes.FinalityProviderResponse, error) { var fps []*bsctypes.FinalityProviderResponse pagination := &sdkquery.PageRequest{ Limit: 100, @@ -348,18 +383,25 @@ func (bc *BabylonController) QueryVotesAtHeight(height uint64) ([]bbntypes.BIP34 return res.BtcPks, nil } -func (bc *BabylonController) QueryPendingDelegations(limit uint64) ([]*btcstakingtypes.BTCDelegationResponse, error) { +func (bc *BabylonController) QueryPendingDelegations( + limit uint64, +) ([]*btcstakingtypes.BTCDelegationResponse, error) { return bc.queryDelegationsWithStatus(btcstakingtypes.BTCDelegationStatus_PENDING, limit) } -func (bc *BabylonController) QueryActiveDelegations(limit uint64) ([]*btcstakingtypes.BTCDelegationResponse, error) { +func (bc *BabylonController) QueryActiveDelegations( + limit uint64, +) ([]*btcstakingtypes.BTCDelegationResponse, error) { return bc.queryDelegationsWithStatus(btcstakingtypes.BTCDelegationStatus_ACTIVE, limit) } // queryDelegationsWithStatus queries BTC delegations // with the given status (either pending or unbonding) // it is only used when the program is running in Covenant mode -func (bc *BabylonController) queryDelegationsWithStatus(status btcstakingtypes.BTCDelegationStatus, limit uint64) ([]*btcstakingtypes.BTCDelegationResponse, error) { +func (bc *BabylonController) queryDelegationsWithStatus( + status btcstakingtypes.BTCDelegationStatus, + limit uint64, +) ([]*btcstakingtypes.BTCDelegationResponse, error) { pagination := &sdkquery.PageRequest{ Limit: limit, } @@ -393,7 +435,10 @@ func (bc *BabylonController) QueryStakingParams() (*types.StakingParams, error) } covenantPks = append(covenantPks, covPk) } - slashingAddress, err := btcutil.DecodeAddress(stakingParamRes.Params.SlashingAddress, bc.btcParams) + slashingAddress, err := btcutil.DecodeAddress( + stakingParamRes.Params.SlashingAddress, + bc.btcParams, + ) if err != nil { return nil, err } @@ -436,7 +481,10 @@ func (bc *BabylonController) SubmitCovenantSigs( return &types.TxResponse{TxHash: res.TxHash}, nil } -func (bc *BabylonController) InsertSpvProofs(submitter string, proofs []*btcctypes.BTCSpvProof) (*provider.RelayerTxResponse, error) { +func (bc *BabylonController) InsertSpvProofs( + submitter string, + proofs []*btcctypes.BTCSpvProof, +) (*provider.RelayerTxResponse, error) { msg := &btcctypes.MsgInsertBTCSpvProof{ Submitter: submitter, Proofs: proofs, @@ -451,7 +499,9 @@ func (bc *BabylonController) InsertSpvProofs(submitter string, proofs []*btcctyp } // RegisterConsumerChain registers a consumer chain via a MsgRegisterChain to Babylon -func (bc *BabylonController) RegisterConsumerChain(id, name, description string) (*types.TxResponse, error) { +func (bc *BabylonController) RegisterConsumerChain( + id, name, description string, +) (*types.TxResponse, error) { msg := &bsctypes.MsgRegisterConsumer{ Signer: bc.MustGetTxSigner(), ConsumerId: id, diff --git a/clientcontroller/babylon/consumer.go b/clientcontroller/babylon/consumer.go index ec564301..fa503386 100644 --- a/clientcontroller/babylon/consumer.go +++ b/clientcontroller/babylon/consumer.go @@ -87,11 +87,19 @@ func (bc *BabylonConsumerController) GetKeyAddress() sdk.AccAddress { return addr } -func (bc *BabylonConsumerController) reliablySendMsg(msg sdk.Msg, expectedErrs []*sdkErr.Error, unrecoverableErrs []*sdkErr.Error) (*provider.RelayerTxResponse, error) { +func (bc *BabylonConsumerController) reliablySendMsg( + msg sdk.Msg, + expectedErrs []*sdkErr.Error, + unrecoverableErrs []*sdkErr.Error, +) (*provider.RelayerTxResponse, error) { return bc.reliablySendMsgs([]sdk.Msg{msg}, expectedErrs, unrecoverableErrs) } -func (bc *BabylonConsumerController) reliablySendMsgs(msgs []sdk.Msg, expectedErrs []*sdkErr.Error, unrecoverableErrs []*sdkErr.Error) (*provider.RelayerTxResponse, error) { +func (bc *BabylonConsumerController) reliablySendMsgs( + msgs []sdk.Msg, + expectedErrs []*sdkErr.Error, + unrecoverableErrs []*sdkErr.Error, +) (*provider.RelayerTxResponse, error) { return bc.bbnClient.ReliablySendMsgs( context.Background(), msgs, @@ -179,7 +187,11 @@ func (bc *BabylonConsumerController) SubmitBatchFinalitySigs( 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)) + return nil, fmt.Errorf( + "the number of blocks %v should match the number of finality signatures %v", + len(blocks), + len(sigs), + ) } msgs := make([]sdk.Msg, 0, len(blocks)) @@ -216,13 +228,20 @@ func (bc *BabylonConsumerController) SubmitBatchFinalitySigs( } // QueryFinalityProviderVotingPower queries the voting power of the finality provider at a given height -func (bc *BabylonConsumerController) QueryFinalityProviderVotingPower(fpPk *btcec.PublicKey, blockHeight uint64) (uint64, error) { +func (bc *BabylonConsumerController) QueryFinalityProviderVotingPower( + fpPk *btcec.PublicKey, + blockHeight uint64, +) (uint64, error) { res, err := bc.bbnClient.QueryClient.FinalityProviderPowerAtHeight( bbntypes.NewBIP340PubKeyFromBTCPK(fpPk).MarshalHex(), blockHeight, ) if err != nil { - return 0, fmt.Errorf("failed to query the finality provider's voting power at height %d: %w", blockHeight, err) + return 0, fmt.Errorf( + "failed to query the finality provider's voting power at height %d: %w", + blockHeight, + err, + ) } return res.VotingPower, nil @@ -236,18 +255,34 @@ func (bc *BabylonConsumerController) QueryLatestFinalizedBlock() (*types.BlockIn return blocks[0], err } -func (bc *BabylonConsumerController) QueryBlocks(startHeight, endHeight, limit uint64) ([]*types.BlockInfo, error) { +func (bc *BabylonConsumerController) QueryBlocks( + startHeight, endHeight, limit uint64, +) ([]*types.BlockInfo, error) { if endHeight < startHeight { - return nil, fmt.Errorf("the startHeight %v should not be higher than the endHeight %v", startHeight, endHeight) + return nil, fmt.Errorf( + "the startHeight %v should not be higher than the endHeight %v", + startHeight, + endHeight, + ) } count := endHeight - startHeight + 1 if count > limit { count = limit } - return bc.queryLatestBlocks(sdk.Uint64ToBigEndian(startHeight), count, finalitytypes.QueriedBlockStatus_ANY, false) + return bc.queryLatestBlocks( + sdk.Uint64ToBigEndian(startHeight), + count, + finalitytypes.QueriedBlockStatus_ANY, + false, + ) } -func (bc *BabylonConsumerController) queryLatestBlocks(startKey []byte, count uint64, status finalitytypes.QueriedBlockStatus, reverse bool) ([]*types.BlockInfo, error) { +func (bc *BabylonConsumerController) queryLatestBlocks( + startKey []byte, + count uint64, + status finalitytypes.QueriedBlockStatus, + reverse bool, +) ([]*types.BlockInfo, error) { var blocks []*types.BlockInfo pagination := &sdkquery.PageRequest{ Limit: count, @@ -284,7 +319,9 @@ func (bc *BabylonConsumerController) QueryBlock(height uint64) (*types.BlockInfo } // QueryLastPublicRandCommit returns the last public randomness commitments -func (bc *BabylonConsumerController) QueryLastPublicRandCommit(fpPk *btcec.PublicKey) (*types.PubRandCommit, error) { +func (bc *BabylonConsumerController) QueryLastPublicRandCommit( + fpPk *btcec.PublicKey, +) (*types.PubRandCommit, error) { fpBtcPk := bbntypes.NewBIP340PubKeyFromBTCPK(fpPk) pagination := &sdkquery.PageRequest{ diff --git a/clientcontroller/cosmwasm/consumer.go b/clientcontroller/cosmwasm/consumer.go index ac6104fb..b9c389bc 100644 --- a/clientcontroller/cosmwasm/consumer.go +++ b/clientcontroller/cosmwasm/consumer.go @@ -65,11 +65,19 @@ func NewCosmwasmConsumerController( }, nil } -func (wc *CosmwasmConsumerController) reliablySendMsg(msg sdk.Msg, expectedErrs []*sdkErr.Error, unrecoverableErrs []*sdkErr.Error) (*provider.RelayerTxResponse, error) { +func (wc *CosmwasmConsumerController) reliablySendMsg( + msg sdk.Msg, + expectedErrs []*sdkErr.Error, + unrecoverableErrs []*sdkErr.Error, +) (*provider.RelayerTxResponse, error) { return wc.reliablySendMsgs([]sdk.Msg{msg}, expectedErrs, unrecoverableErrs) } -func (wc *CosmwasmConsumerController) reliablySendMsgs(msgs []sdk.Msg, expectedErrs []*sdkErr.Error, unrecoverableErrs []*sdkErr.Error) (*provider.RelayerTxResponse, error) { +func (wc *CosmwasmConsumerController) reliablySendMsgs( + msgs []sdk.Msg, + expectedErrs []*sdkErr.Error, + unrecoverableErrs []*sdkErr.Error, +) (*provider.RelayerTxResponse, error) { return wc.cwClient.ReliablySendMsgs( context.Background(), msgs, @@ -131,10 +139,14 @@ func (wc *CosmwasmConsumerController) SubmitFinalitySig( SubmitFinalitySignature: &SubmitFinalitySignature{ FpPubkeyHex: bbntypes.NewBIP340PubKeyFromBTCPK(fpPk).MarshalHex(), Height: block.Height, - PubRand: base64.StdEncoding.EncodeToString(bbntypes.NewSchnorrPubRandFromFieldVal(pubRand).MustMarshal()), - Proof: ConvertProof(cmtProof), - BlockHash: base64.StdEncoding.EncodeToString(block.Hash), - Signature: base64.StdEncoding.EncodeToString(bbntypes.NewSchnorrEOTSSigFromModNScalar(sig).MustMarshal()), + PubRand: base64.StdEncoding.EncodeToString( + bbntypes.NewSchnorrPubRandFromFieldVal(pubRand).MustMarshal(), + ), + Proof: ConvertProof(cmtProof), + BlockHash: base64.StdEncoding.EncodeToString(block.Hash), + Signature: base64.StdEncoding.EncodeToString( + bbntypes.NewSchnorrEOTSSigFromModNScalar(sig).MustMarshal(), + ), }, } @@ -170,10 +182,14 @@ func (wc *CosmwasmConsumerController) SubmitBatchFinalitySigs( SubmitFinalitySignature: &SubmitFinalitySignature{ FpPubkeyHex: bbntypes.NewBIP340PubKeyFromBTCPK(fpPk).MarshalHex(), Height: b.Height, - PubRand: base64.StdEncoding.EncodeToString(bbntypes.NewSchnorrPubRandFromFieldVal(pubRandList[i]).MustMarshal()), - Proof: ConvertProof(cmtProof), - BlockHash: base64.StdEncoding.EncodeToString(b.Hash), - Signature: base64.StdEncoding.EncodeToString(bbntypes.NewSchnorrEOTSSigFromModNScalar(sigs[i]).MustMarshal()), + PubRand: base64.StdEncoding.EncodeToString( + bbntypes.NewSchnorrPubRandFromFieldVal(pubRandList[i]).MustMarshal(), + ), + Proof: ConvertProof(cmtProof), + BlockHash: base64.StdEncoding.EncodeToString(b.Hash), + Signature: base64.StdEncoding.EncodeToString( + bbntypes.NewSchnorrEOTSSigFromModNScalar(sigs[i]).MustMarshal(), + ), }, } @@ -199,7 +215,10 @@ func (wc *CosmwasmConsumerController) SubmitBatchFinalitySigs( } // QueryFinalityProviderVotingPower queries the voting power of the finality provider at a given height -func (wc *CosmwasmConsumerController) QueryFinalityProviderVotingPower(fpPk *btcec.PublicKey, blockHeight uint64) (uint64, error) { +func (wc *CosmwasmConsumerController) QueryFinalityProviderVotingPower( + fpPk *btcec.PublicKey, + blockHeight uint64, +) (uint64, error) { fpBtcPkHex := bbntypes.NewBIP340PubKeyFromBTCPK(fpPk).MarshalHex() queryMsgStruct := QueryMsgFinalityProviderInfo{ @@ -212,7 +231,10 @@ func (wc *CosmwasmConsumerController) QueryFinalityProviderVotingPower(fpPk *btc if err != nil { return 0, fmt.Errorf("failed to marshal query message: %v", err) } - dataFromContract, err := wc.QuerySmartContractState(wc.cfg.BtcStakingContractAddress, string(queryMsgBytes)) + dataFromContract, err := wc.QuerySmartContractState( + wc.cfg.BtcStakingContractAddress, + string(queryMsgBytes), + ) if err != nil { return 0, err } @@ -236,7 +258,10 @@ func (wc *CosmwasmConsumerController) QueryFinalityProvidersByPower() (*Consumer return nil, fmt.Errorf("failed to marshal query message: %v", err) } - dataFromContract, err := wc.QuerySmartContractState(wc.cfg.BtcStakingContractAddress, string(queryMsgBytes)) + dataFromContract, err := wc.QuerySmartContractState( + wc.cfg.BtcStakingContractAddress, + string(queryMsgBytes), + ) if err != nil { return nil, err } @@ -279,7 +304,9 @@ func (wc *CosmwasmConsumerController) QueryLatestFinalizedBlock() (*fptypes.Bloc return block, nil } -func (wc *CosmwasmConsumerController) QueryBlocks(startHeight, endHeight, limit uint64) ([]*fptypes.BlockInfo, error) { +func (wc *CosmwasmConsumerController) QueryBlocks( + startHeight, endHeight, limit uint64, +) ([]*fptypes.BlockInfo, error) { //if endHeight < startHeight { // return nil, fmt.Errorf("the startHeight %v should not be higher than the endHeight %v", startHeight, endHeight) //} @@ -294,8 +321,12 @@ func (wc *CosmwasmConsumerController) QueryBlocks(startHeight, endHeight, limit return wc.queryCometBlocksInRange(startHeight, endHeight) } +// //nolint:unused -func (wc *CosmwasmConsumerController) queryLatestBlocks(startAfter, limit *uint64, finalized, reverse *bool) ([]*fptypes.BlockInfo, error) { +func (wc *CosmwasmConsumerController) queryLatestBlocks( + startAfter, limit *uint64, + finalized, reverse *bool, +) ([]*fptypes.BlockInfo, error) { // Construct the query message queryMsg := QueryMsgBlocks{ Blocks: BlocksQuery{ @@ -313,7 +344,10 @@ func (wc *CosmwasmConsumerController) queryLatestBlocks(startAfter, limit *uint6 } // Query the smart contract state - dataFromContract, err := wc.QuerySmartContractState(wc.cfg.BtcStakingContractAddress, string(queryMsgBytes)) + dataFromContract, err := wc.QuerySmartContractState( + wc.cfg.BtcStakingContractAddress, + string(queryMsgBytes), + ) if err != nil { return nil, fmt.Errorf("failed to query smart contract state: %w", err) } @@ -352,7 +386,10 @@ func (wc *CosmwasmConsumerController) queryIndexedBlock(height uint64) (*Indexed } // Query the smart contract state - dataFromContract, err := wc.QuerySmartContractState(wc.cfg.BtcStakingContractAddress, string(queryMsgBytes)) + dataFromContract, err := wc.QuerySmartContractState( + wc.cfg.BtcStakingContractAddress, + string(queryMsgBytes), + ) if err != nil { return nil, fmt.Errorf("failed to query smart contract state: %w", err) } @@ -391,7 +428,9 @@ func (wc *CosmwasmConsumerController) QueryBlock(height uint64) (*fptypes.BlockI } // QueryLastPublicRandCommit returns the last public randomness commitments -func (wc *CosmwasmConsumerController) QueryLastPublicRandCommit(fpPk *btcec.PublicKey) (*fptypes.PubRandCommit, error) { +func (wc *CosmwasmConsumerController) QueryLastPublicRandCommit( + fpPk *btcec.PublicKey, +) (*fptypes.PubRandCommit, error) { fpBtcPk := bbntypes.NewBIP340PubKeyFromBTCPK(fpPk) // Construct the query message @@ -409,7 +448,10 @@ func (wc *CosmwasmConsumerController) QueryLastPublicRandCommit(fpPk *btcec.Publ } // Query the smart contract state - dataFromContract, err := wc.QuerySmartContractState(wc.cfg.BtcStakingContractAddress, string(queryMsgBytes)) + dataFromContract, err := wc.QuerySmartContractState( + wc.cfg.BtcStakingContractAddress, + string(queryMsgBytes), + ) if err != nil { return nil, fmt.Errorf("failed to query smart contract state: %w", err) } @@ -481,7 +523,10 @@ func (wc *CosmwasmConsumerController) QueryActivatedHeight() (uint64, error) { } // Query the smart contract state - dataFromContract, err := wc.QuerySmartContractState(wc.cfg.BtcStakingContractAddress, string(queryMsgBytes)) + dataFromContract, err := wc.QuerySmartContractState( + wc.cfg.BtcStakingContractAddress, + string(queryMsgBytes), + ) if err != nil { return 0, fmt.Errorf("failed to query smart contract state: %w", err) } @@ -521,7 +566,10 @@ func (wc *CosmwasmConsumerController) QueryLatestBlockHeight() (uint64, error) { return block.Height, err } -func (wc *CosmwasmConsumerController) QueryFinalitySignature(fpBtcPkHex string, height uint64) (*FinalitySignatureResponse, error) { +func (wc *CosmwasmConsumerController) QueryFinalitySignature( + fpBtcPkHex string, + height uint64, +) (*FinalitySignatureResponse, error) { queryMsgStruct := QueryMsgFinalitySignature{ FinalitySignature: FinalitySignatureQuery{ BtcPkHex: fpBtcPkHex, @@ -533,7 +581,10 @@ func (wc *CosmwasmConsumerController) QueryFinalitySignature(fpBtcPkHex string, return nil, fmt.Errorf("failed to marshal query message: %v", err) } - dataFromContract, err := wc.QuerySmartContractState(wc.cfg.BtcStakingContractAddress, string(queryMsgBytes)) + dataFromContract, err := wc.QuerySmartContractState( + wc.cfg.BtcStakingContractAddress, + string(queryMsgBytes), + ) if err != nil { return nil, err } @@ -557,7 +608,10 @@ func (wc *CosmwasmConsumerController) QueryFinalityProviders() (*ConsumerFpsResp return nil, fmt.Errorf("failed to marshal query message: %v", err) } - dataFromContract, err := wc.QuerySmartContractState(wc.cfg.BtcStakingContractAddress, string(queryMsgBytes)) + dataFromContract, err := wc.QuerySmartContractState( + wc.cfg.BtcStakingContractAddress, + string(queryMsgBytes), + ) if err != nil { return nil, err } @@ -581,7 +635,10 @@ func (wc *CosmwasmConsumerController) QueryDelegations() (*ConsumerDelegationsRe return nil, fmt.Errorf("failed to marshal query message: %v", err) } - dataFromContract, err := wc.QuerySmartContractState(wc.cfg.BtcStakingContractAddress, string(queryMsgBytes)) + dataFromContract, err := wc.QuerySmartContractState( + wc.cfg.BtcStakingContractAddress, + string(queryMsgBytes), + ) if err != nil { return nil, err } @@ -613,12 +670,18 @@ func (wc *CosmwasmConsumerController) queryCometBestBlock() (*fptypes.BlockInfo, }, nil } -func (wc *CosmwasmConsumerController) queryCometBlocksInRange(startHeight, endHeight uint64) ([]*fptypes.BlockInfo, error) { +func (wc *CosmwasmConsumerController) queryCometBlocksInRange( + startHeight, endHeight uint64, +) ([]*fptypes.BlockInfo, error) { ctx, cancel := context.WithTimeout(context.Background(), wc.cfg.Timeout) defer cancel() // this will return 20 items at max in the descending order (highest first) - chainInfo, err := wc.cwClient.RPCClient.BlockchainInfo(ctx, int64(startHeight), int64(endHeight)) + chainInfo, err := wc.cwClient.RPCClient.BlockchainInfo( + ctx, + int64(startHeight), + int64(endHeight), + ) if err != nil { return nil, err } @@ -654,7 +717,9 @@ func (wc *CosmwasmConsumerController) Close() error { return wc.cwClient.Stop() } -func (wc *CosmwasmConsumerController) ExecuteContract(msgBytes []byte) (*provider.RelayerTxResponse, error) { +func (wc *CosmwasmConsumerController) ExecuteContract( + msgBytes []byte, +) (*provider.RelayerTxResponse, error) { execMsg := &wasmdtypes.MsgExecuteContract{ Sender: wc.cwClient.MustGetAddr(), Contract: wc.cfg.BtcStakingContractAddress, @@ -671,7 +736,10 @@ func (wc *CosmwasmConsumerController) ExecuteContract(msgBytes []byte) (*provide // QuerySmartContractState queries the smart contract state // NOTE: this function is only meant to be used in tests. -func (wc *CosmwasmConsumerController) QuerySmartContractState(contractAddress string, queryData string) (*wasmdtypes.QuerySmartContractStateResponse, error) { +func (wc *CosmwasmConsumerController) QuerySmartContractState( + contractAddress string, + queryData string, +) (*wasmdtypes.QuerySmartContractStateResponse, error) { return wc.cwClient.QuerySmartContractState(contractAddress, queryData) } @@ -749,7 +817,10 @@ func (wc *CosmwasmConsumerController) GetLatestCodeId() (uint64, error) { // ListContractsByCode lists all contracts by wasm code id // NOTE: this function is only meant to be used in tests. -func (wc *CosmwasmConsumerController) ListContractsByCode(codeID uint64, pagination *sdkquerytypes.PageRequest) (*wasmdtypes.QueryContractsByCodeResponse, error) { +func (wc *CosmwasmConsumerController) ListContractsByCode( + codeID uint64, + pagination *sdkquerytypes.PageRequest, +) (*wasmdtypes.QueryContractsByCodeResponse, error) { return wc.cwClient.ListContractsByCode(codeID, pagination) } diff --git a/clientcontroller/factory.go b/clientcontroller/factory.go index 53d622c8..abbf8202 100644 --- a/clientcontroller/factory.go +++ b/clientcontroller/factory.go @@ -28,7 +28,10 @@ func NewClientController(config *fpcfg.Config, logger *zap.Logger) (api.ClientCo return cc, err } -func NewConsumerController(config *fpcfg.Config, logger *zap.Logger) (api.ConsumerController, error) { +func NewConsumerController( + config *fpcfg.Config, + logger *zap.Logger, +) (api.ConsumerController, error) { var ( ccc api.ConsumerController err error @@ -36,7 +39,11 @@ func NewConsumerController(config *fpcfg.Config, logger *zap.Logger) (api.Consum switch config.ChainName { case BabylonConsumerChainName: - ccc, err = babylon.NewBabylonConsumerController(config.BabylonConfig, &config.BTCNetParams, logger) + ccc, err = babylon.NewBabylonConsumerController( + config.BabylonConfig, + &config.BTCNetParams, + logger, + ) if err != nil { return nil, fmt.Errorf("failed to create Babylon rpc client: %w", err) } @@ -47,7 +54,11 @@ func NewConsumerController(config *fpcfg.Config, logger *zap.Logger) (api.Consum } case WasmConsumerChainName: wasmEncodingCfg := cosmwasmcfg.GetWasmdEncodingConfig() - ccc, err = cosmwasm.NewCosmwasmConsumerController(config.CosmwasmConfig, wasmEncodingCfg, logger) + ccc, err = cosmwasm.NewCosmwasmConsumerController( + config.CosmwasmConfig, + wasmEncodingCfg, + logger, + ) if err != nil { return nil, fmt.Errorf("failed to create Wasm rpc client: %w", err) } diff --git a/clientcontroller/opstackl2/consumer.go b/clientcontroller/opstackl2/consumer.go index ccb9c835..845088d8 100644 --- a/clientcontroller/opstackl2/consumer.go +++ b/clientcontroller/opstackl2/consumer.go @@ -88,11 +88,19 @@ func NewOPStackL2ConsumerController( }, nil } -func (cc *OPStackL2ConsumerController) ReliablySendMsg(msg sdk.Msg, expectedErrs []*sdkErr.Error, unrecoverableErrs []*sdkErr.Error) (*provider.RelayerTxResponse, error) { +func (cc *OPStackL2ConsumerController) ReliablySendMsg( + msg sdk.Msg, + expectedErrs []*sdkErr.Error, + unrecoverableErrs []*sdkErr.Error, +) (*provider.RelayerTxResponse, error) { return cc.reliablySendMsgs([]sdk.Msg{msg}, expectedErrs, unrecoverableErrs) } -func (cc *OPStackL2ConsumerController) reliablySendMsgs(msgs []sdk.Msg, expectedErrs []*sdkErr.Error, unrecoverableErrs []*sdkErr.Error) (*provider.RelayerTxResponse, error) { +func (cc *OPStackL2ConsumerController) reliablySendMsgs( + msgs []sdk.Msg, + expectedErrs []*sdkErr.Error, + unrecoverableErrs []*sdkErr.Error, +) (*provider.RelayerTxResponse, error) { return cc.CwClient.ReliablySendMsgs( context.Background(), msgs, @@ -186,7 +194,11 @@ func (cc *OPStackL2ConsumerController) SubmitBatchFinalitySigs( 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)) + return nil, fmt.Errorf( + "the number of blocks %v should match the number of finality signatures %v", + len(blocks), + len(sigs), + ) } msgs := make([]sdk.Msg, 0, len(blocks)) for i, block := range blocks { @@ -229,7 +241,10 @@ func (cc *OPStackL2ConsumerController) SubmitBatchFinalitySigs( // This interface function only used for checking if the FP is eligible for submitting sigs. // Now we can simply hardcode the voting power to a positive value. // TODO: see this issue https://github.com/babylonchain/finality-provider/issues/390 for more details -func (cc *OPStackL2ConsumerController) QueryFinalityProviderVotingPower(fpPk *btcec.PublicKey, blockHeight uint64) (uint64, error) { +func (cc *OPStackL2ConsumerController) QueryFinalityProviderVotingPower( + fpPk *btcec.PublicKey, + blockHeight uint64, +) (uint64, error) { return 1, nil } @@ -240,7 +255,10 @@ func (cc *OPStackL2ConsumerController) QueryLatestFinalizedBlock() (*types.Block ctx, cancel := context.WithTimeout(context.Background(), cc.Cfg.Timeout) defer cancel() - l2Block, err := cc.opl2Client.HeaderByNumber(ctx, big.NewInt(ethrpc.FinalizedBlockNumber.Int64())) + l2Block, err := cc.opl2Client.HeaderByNumber( + ctx, + big.NewInt(ethrpc.FinalizedBlockNumber.Int64()), + ) if err != nil { return nil, err } @@ -250,7 +268,9 @@ func (cc *OPStackL2ConsumerController) QueryLatestFinalizedBlock() (*types.Block }, nil } -func (cc *OPStackL2ConsumerController) QueryBlocks(startHeight, endHeight, limit uint64) ([]*types.BlockInfo, error) { +func (cc *OPStackL2ConsumerController) QueryBlocks( + startHeight, endHeight, limit uint64, +) ([]*types.BlockInfo, error) { var blocks []*types.BlockInfo var count uint64 = 0 @@ -301,7 +321,10 @@ func (cc *OPStackL2ConsumerController) QueryActivatedHeight() (uint64, error) { if err != nil { return 0, fmt.Errorf("failed marshaling to JSON: %w", err) } - stateResp, err := cc.CwClient.QuerySmartContractState(cc.Cfg.OPFinalityGadgetAddress, string(jsonData)) + stateResp, err := cc.CwClient.QuerySmartContractState( + cc.Cfg.OPFinalityGadgetAddress, + string(jsonData), + ) if err != nil { return 0, fmt.Errorf("failed to query smart contract state: %w", err) } @@ -320,7 +343,10 @@ func (cc *OPStackL2ConsumerController) QueryLatestBlockHeight() (uint64, error) ctx, cancel := context.WithTimeout(context.Background(), cc.Cfg.Timeout) defer cancel() - l2LatestBlock, err := cc.opl2Client.HeaderByNumber(ctx, big.NewInt(ethrpc.LatestBlockNumber.Int64())) + l2LatestBlock, err := cc.opl2Client.HeaderByNumber( + ctx, + big.NewInt(ethrpc.LatestBlockNumber.Int64()), + ) if err != nil { return 0, err } @@ -330,7 +356,9 @@ func (cc *OPStackL2ConsumerController) QueryLatestBlockHeight() (uint64, error) // QueryLastPublicRandCommit returns the last public randomness commitments // It is fetched from the state of a CosmWasm contract OP finality gadget. -func (cc *OPStackL2ConsumerController) QueryLastPublicRandCommit(fpPk *btcec.PublicKey) (*types.PubRandCommit, error) { +func (cc *OPStackL2ConsumerController) QueryLastPublicRandCommit( + fpPk *btcec.PublicKey, +) (*types.PubRandCommit, error) { fpPubKey := bbntypes.NewBIP340PubKeyFromBTCPK(fpPk) queryMsg := &QueryMsg{ LastPubRandCommit: &LastPubRandCommit{ @@ -343,7 +371,10 @@ func (cc *OPStackL2ConsumerController) QueryLastPublicRandCommit(fpPk *btcec.Pub return nil, fmt.Errorf("failed marshaling to JSON: %w", err) } - stateResp, err := cc.CwClient.QuerySmartContractState(cc.Cfg.OPFinalityGadgetAddress, string(jsonData)) + stateResp, err := cc.CwClient.QuerySmartContractState( + cc.Cfg.OPFinalityGadgetAddress, + string(jsonData), + ) if err != nil { return nil, fmt.Errorf("failed to query smart contract state: %w", err) } diff --git a/cosmwasmclient/client/client.go b/cosmwasmclient/client/client.go index ac72d981..37bc3a12 100644 --- a/cosmwasmclient/client/client.go +++ b/cosmwasmclient/client/client.go @@ -21,7 +21,12 @@ type Client struct { cfg *config.CosmwasmConfig } -func New(cfg *config.CosmwasmConfig, chainName string, encodingCfg wasmdparams.EncodingConfig, logger *zap.Logger) (*Client, error) { +func New( + cfg *config.CosmwasmConfig, + chainName string, + encodingCfg wasmdparams.EncodingConfig, + logger *zap.Logger, +) (*Client, error) { var ( zapLogger *zap.Logger err error diff --git a/cosmwasmclient/client/keys.go b/cosmwasmclient/client/keys.go index baf6b7ba..d76f5ee1 100644 --- a/cosmwasmclient/client/keys.go +++ b/cosmwasmclient/client/keys.go @@ -42,7 +42,10 @@ func (c *Client) accessKeyWithLock(accessFunc func()) error { // unlock and release access if err := lock.Unlock(); err != nil { - return fmt.Errorf("error unlocking file system lock (%s), please manually delete", lockFilePath) + return fmt.Errorf( + "error unlocking file system lock (%s), please manually delete", + lockFilePath, + ) } return nil diff --git a/cosmwasmclient/client/tx.go b/cosmwasmclient/client/tx.go index 5801fa76..708a7f6f 100644 --- a/cosmwasmclient/client/tx.go +++ b/cosmwasmclient/client/tx.go @@ -54,14 +54,24 @@ func (c *Client) SendMsgsToMempool(ctx context.Context, msgs []sdk.Msg) error { // ReliablySendMsg reliable sends a message to the chain. // It utilizes a file lock as well as a keyring lock to ensure atomic access. // TODO: needs tests -func (c *Client) ReliablySendMsg(ctx context.Context, msg sdk.Msg, expectedErrors []*errors.Error, unrecoverableErrors []*errors.Error) (*pv.RelayerTxResponse, error) { +func (c *Client) ReliablySendMsg( + ctx context.Context, + msg sdk.Msg, + expectedErrors []*errors.Error, + unrecoverableErrors []*errors.Error, +) (*pv.RelayerTxResponse, error) { return c.ReliablySendMsgs(ctx, []sdk.Msg{msg}, expectedErrors, unrecoverableErrors) } // ReliablySendMsgs reliably sends a list of messages to the chain. // It utilizes a file lock as well as a keyring lock to ensure atomic access. // TODO: needs tests -func (c *Client) ReliablySendMsgs(ctx context.Context, msgs []sdk.Msg, expectedErrors []*errors.Error, unrecoverableErrors []*errors.Error) (*pv.RelayerTxResponse, error) { +func (c *Client) ReliablySendMsgs( + ctx context.Context, + msgs []sdk.Msg, + expectedErrors []*errors.Error, + unrecoverableErrors []*errors.Error, +) (*pv.RelayerTxResponse, error) { var ( rlyResp *pv.RelayerTxResponse callbackErr error diff --git a/cosmwasmclient/query/tendermint.go b/cosmwasmclient/query/tendermint.go index cf00304d..4049d847 100644 --- a/cosmwasmclient/query/tendermint.go +++ b/cosmwasmclient/query/tendermint.go @@ -24,7 +24,12 @@ func (c *QueryClient) GetBlock(height int64) (*coretypes.ResultBlock, error) { } // BlockSearch searches for blocks satisfying the events specified on the events list -func (c *QueryClient) BlockSearch(events []string, page *int, perPage *int, orderBy string) (*coretypes.ResultBlockSearch, error) { +func (c *QueryClient) BlockSearch( + events []string, + page *int, + perPage *int, + orderBy string, +) (*coretypes.ResultBlockSearch, error) { ctx, cancel := c.getQueryContext() defer cancel() @@ -32,7 +37,13 @@ func (c *QueryClient) BlockSearch(events []string, page *int, perPage *int, orde } // TxSearch searches for transactions satisfying the events specified on the events list -func (c *QueryClient) TxSearch(events []string, prove bool, page *int, perPage *int, orderBy string) (*coretypes.ResultTxSearch, error) { +func (c *QueryClient) TxSearch( + events []string, + prove bool, + page *int, + perPage *int, + orderBy string, +) (*coretypes.ResultTxSearch, error) { ctx, cancel := c.getQueryContext() defer cancel() @@ -47,7 +58,10 @@ func (c *QueryClient) GetTx(hash []byte) (*coretypes.ResultTx, error) { return c.RPCClient.Tx(ctx, hash, false) } -func (c *QueryClient) Subscribe(subscriber, query string, outCapacity ...int) (out <-chan coretypes.ResultEvent, err error) { +func (c *QueryClient) Subscribe( + subscriber, query string, + outCapacity ...int, +) (out <-chan coretypes.ResultEvent, err error) { return c.RPCClient.Subscribe(context.Background(), subscriber, query, outCapacity...) } diff --git a/cosmwasmclient/query/wasm.go b/cosmwasmclient/query/wasm.go index 59d45afb..3febc150 100644 --- a/cosmwasmclient/query/wasm.go +++ b/cosmwasmclient/query/wasm.go @@ -8,7 +8,9 @@ import ( sdkquerytypes "github.com/cosmos/cosmos-sdk/types/query" ) -func (c *QueryClient) QueryWasm(f func(ctx context.Context, queryClient wasmtypes.QueryClient) error) error { +func (c *QueryClient) QueryWasm( + f func(ctx context.Context, queryClient wasmtypes.QueryClient) error, +) error { ctx, cancel := c.getQueryContext() defer cancel() @@ -18,7 +20,9 @@ func (c *QueryClient) QueryWasm(f func(ctx context.Context, queryClient wasmtype return f(ctx, queryClient) } -func (c *QueryClient) ListCodes(pagination *sdkquerytypes.PageRequest) (*wasmtypes.QueryCodesResponse, error) { +func (c *QueryClient) ListCodes( + pagination *sdkquerytypes.PageRequest, +) (*wasmtypes.QueryCodesResponse, error) { var resp *wasmtypes.QueryCodesResponse err := c.QueryWasm(func(ctx context.Context, queryClient wasmtypes.QueryClient) error { var err error @@ -32,7 +36,10 @@ func (c *QueryClient) ListCodes(pagination *sdkquerytypes.PageRequest) (*wasmtyp return resp, err } -func (c *QueryClient) ListContractsByCode(codeID uint64, pagination *sdkquerytypes.PageRequest) (*wasmtypes.QueryContractsByCodeResponse, error) { +func (c *QueryClient) ListContractsByCode( + codeID uint64, + pagination *sdkquerytypes.PageRequest, +) (*wasmtypes.QueryContractsByCodeResponse, error) { var resp *wasmtypes.QueryContractsByCodeResponse err := c.QueryWasm(func(ctx context.Context, queryClient wasmtypes.QueryClient) error { var err error @@ -47,7 +54,10 @@ func (c *QueryClient) ListContractsByCode(codeID uint64, pagination *sdkquerytyp return resp, err } -func (c *QueryClient) QuerySmartContractState(contractAddress string, queryData string) (*wasmtypes.QuerySmartContractStateResponse, error) { +func (c *QueryClient) QuerySmartContractState( + contractAddress string, + queryData string, +) (*wasmtypes.QuerySmartContractStateResponse, error) { var resp *wasmtypes.QuerySmartContractStateResponse err := c.QueryWasm(func(ctx context.Context, queryClient wasmtypes.QueryClient) error { var err error diff --git a/eotsmanager/client/rpcclient.go b/eotsmanager/client/rpcclient.go index 53356cc8..a805ca92 100644 --- a/eotsmanager/client/rpcclient.go +++ b/eotsmanager/client/rpcclient.go @@ -22,7 +22,10 @@ type EOTSManagerGRpcClient struct { } func NewEOTSManagerGRpcClient(remoteAddr string) (*EOTSManagerGRpcClient, error) { - conn, err := grpc.NewClient(remoteAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + conn, err := grpc.NewClient( + remoteAddr, + grpc.WithTransportCredentials(insecure.NewCredentials()), + ) if err != nil { return nil, fmt.Errorf("failed to build gRPC connection to %s: %w", remoteAddr, err) } @@ -60,7 +63,12 @@ func (c *EOTSManagerGRpcClient) CreateKey(name, passphrase, hdPath string) ([]by return res.Pk, nil } -func (c *EOTSManagerGRpcClient) CreateRandomnessPairList(uid, chainID []byte, startHeight uint64, num uint32, passphrase string) ([]*btcec.FieldVal, error) { +func (c *EOTSManagerGRpcClient) CreateRandomnessPairList( + uid, chainID []byte, + startHeight uint64, + num uint32, + passphrase string, +) ([]*btcec.FieldVal, error) { req := &proto.CreateRandomnessPairListRequest{ Uid: uid, ChainId: chainID, @@ -99,7 +107,11 @@ func (c *EOTSManagerGRpcClient) KeyRecord(uid []byte, passphrase string) (*types }, nil } -func (c *EOTSManagerGRpcClient) SignEOTS(uid, chaiID, msg []byte, height uint64, passphrase string) (*btcec.ModNScalar, error) { +func (c *EOTSManagerGRpcClient) SignEOTS( + uid, chaiID, msg []byte, + height uint64, + passphrase string, +) (*btcec.ModNScalar, error) { req := &proto.SignEOTSRequest{ Uid: uid, ChainId: chaiID, @@ -118,7 +130,10 @@ func (c *EOTSManagerGRpcClient) SignEOTS(uid, chaiID, msg []byte, height uint64, return &s, nil } -func (c *EOTSManagerGRpcClient) SignSchnorrSig(uid, msg []byte, passphrase string) (*schnorr.Signature, error) { +func (c *EOTSManagerGRpcClient) SignSchnorrSig( + uid, msg []byte, + passphrase string, +) (*schnorr.Signature, error) { req := &proto.SignSchnorrSigRequest{Uid: uid, Msg: msg, Passphrase: passphrase} res, err := c.client.SignSchnorrSig(context.Background(), req) if err != nil { diff --git a/eotsmanager/cmd/eotsd/daemon/init.go b/eotsmanager/cmd/eotsd/daemon/init.go index 9855ab31..2b0fd215 100644 --- a/eotsmanager/cmd/eotsd/daemon/init.go +++ b/eotsmanager/cmd/eotsd/daemon/init.go @@ -60,5 +60,6 @@ func initHome(c *cli.Context) error { defaultConfig.DatabaseConfig.DBPath = dataDir fileParser := flags.NewParser(defaultConfig, flags.Default) - return flags.NewIniParser(fileParser).WriteFile(eotscfg.ConfigFile(homePath), flags.IniIncludeComments|flags.IniIncludeDefaults) + return flags.NewIniParser(fileParser). + WriteFile(eotscfg.ConfigFile(homePath), flags.IniIncludeComments|flags.IniIncludeDefaults) } diff --git a/eotsmanager/cmd/eotsd/daemon/keys.go b/eotsmanager/cmd/eotsd/daemon/keys.go index f6efa4ca..89be65a7 100644 --- a/eotsmanager/cmd/eotsd/daemon/keys.go +++ b/eotsmanager/cmd/eotsd/daemon/keys.go @@ -18,8 +18,8 @@ import ( ) type KeyOutput struct { - Name string `json:"name" yaml:"name"` - PubKeyHex string `json:"pub_key_hex" yaml:"pub_key_hex"` + Name string `json:"name" yaml:"name"` + PubKeyHex string `json:"pub_key_hex" yaml:"pub_key_hex"` Mnemonic string `json:"mnemonic,omitempty" yaml:"mnemonic"` } diff --git a/eotsmanager/cmd/eotsd/daemon/sign.go b/eotsmanager/cmd/eotsd/daemon/sign.go index abfa14d1..fe51bc1c 100644 --- a/eotsmanager/cmd/eotsd/daemon/sign.go +++ b/eotsmanager/cmd/eotsd/daemon/sign.go @@ -134,7 +134,11 @@ func SignSchnorr(ctx *cli.Context) error { } if len(fpPkStr) == 0 && len(keyName) == 0 { - return fmt.Errorf("at least one of the flags: %s, %s needs to be informed", keyNameFlag, fpPkFlag) + return fmt.Errorf( + "at least one of the flags: %s, %s needs to be informed", + keyNameFlag, + fpPkFlag, + ) } homePath, err := getHomeFlag(ctx) diff --git a/eotsmanager/cmd/eotsd/daemon/sign_test.go b/eotsmanager/cmd/eotsd/daemon/sign_test.go index f0632c7f..99ba7a43 100644 --- a/eotsmanager/cmd/eotsd/daemon/sign_test.go +++ b/eotsmanager/cmd/eotsd/daemon/sign_test.go @@ -42,7 +42,12 @@ func FuzzSignAndVerifySchnorrSig(f *testing.F) { keyName := testutil.GenRandomHexStr(r, 10) keyNameFlag := fmt.Sprintf("--key-name=%s", keyName) - outputKeysAdd := appRunWithOutput(r, t, app, []string{"eotsd", "keys", "add", hFlag, keyNameFlag}) + outputKeysAdd := appRunWithOutput( + r, + t, + app, + []string{"eotsd", "keys", "add", hFlag, keyNameFlag}, + ) keyOutJson := searchInTxt(outputKeysAdd, "for recovery):") var keyOut dcli.KeyOutput @@ -54,11 +59,27 @@ func FuzzSignAndVerifySchnorrSig(f *testing.F) { btcPkFlag := fmt.Sprintf("--btc-pk=%s", keyOut.PubKeyHex) dataSignedBtcPk := appRunSignSchnorr(r, t, app, []string{fpInfoPath, hFlag, btcPkFlag}) - err = app.Run([]string{"eotsd", "verify-schnorr-sig", fpInfoPath, btcPkFlag, fmt.Sprintf("--signature=%s", dataSignedBtcPk.SchnorrSignatureHex)}) + err = app.Run( + []string{ + "eotsd", + "verify-schnorr-sig", + fpInfoPath, + btcPkFlag, + fmt.Sprintf("--signature=%s", dataSignedBtcPk.SchnorrSignatureHex), + }, + ) require.NoError(t, err) dataSignedKeyName := appRunSignSchnorr(r, t, app, []string{fpInfoPath, hFlag, keyNameFlag}) - err = app.Run([]string{"eotsd", "verify-schnorr-sig", fpInfoPath, btcPkFlag, fmt.Sprintf("--signature=%s", dataSignedKeyName.SchnorrSignatureHex)}) + err = app.Run( + []string{ + "eotsd", + "verify-schnorr-sig", + fpInfoPath, + btcPkFlag, + fmt.Sprintf("--signature=%s", dataSignedKeyName.SchnorrSignatureHex), + }, + ) require.NoError(t, err) // check if both generated signatures match @@ -67,20 +88,43 @@ func FuzzSignAndVerifySchnorrSig(f *testing.F) { require.Equal(t, dataSignedBtcPk.SignedDataHashHex, dataSignedKeyName.SignedDataHashHex) // sign with both keys and btc-pk, should give btc-pk preference - dataSignedBoth := appRunSignSchnorr(r, t, app, []string{fpInfoPath, hFlag, btcPkFlag, keyNameFlag}) + dataSignedBoth := appRunSignSchnorr( + r, + t, + app, + []string{fpInfoPath, hFlag, btcPkFlag, keyNameFlag}, + ) require.Equal(t, dataSignedBoth, dataSignedKeyName) // the keyname can even be from a invalid keyname, since it gives btc-pk preference badKeyname := "badKeyName" - dataSignedBothBadKeyName := appRunSignSchnorr(r, t, app, []string{fpInfoPath, hFlag, btcPkFlag, fmt.Sprintf("--key-name=%s", badKeyname)}) + dataSignedBothBadKeyName := appRunSignSchnorr( + r, + t, + app, + []string{fpInfoPath, hFlag, btcPkFlag, fmt.Sprintf("--key-name=%s", badKeyname)}, + ) require.Equal(t, badKeyname, dataSignedBothBadKeyName.KeyName) require.Equal(t, dataSignedBtcPk.PubKeyHex, dataSignedBothBadKeyName.PubKeyHex) - require.Equal(t, dataSignedBtcPk.SchnorrSignatureHex, dataSignedBothBadKeyName.SchnorrSignatureHex) - require.Equal(t, dataSignedBtcPk.SignedDataHashHex, dataSignedBothBadKeyName.SignedDataHashHex) + require.Equal( + t, + dataSignedBtcPk.SchnorrSignatureHex, + dataSignedBothBadKeyName.SchnorrSignatureHex, + ) + require.Equal( + t, + dataSignedBtcPk.SignedDataHashHex, + dataSignedBothBadKeyName.SignedDataHashHex, + ) }) } -func appRunSignSchnorr(r *rand.Rand, t *testing.T, app *cli.App, arguments []string) dcli.DataSigned { +func appRunSignSchnorr( + r *rand.Rand, + t *testing.T, + app *cli.App, + arguments []string, +) dcli.DataSigned { args := []string{"eotsd", "sign-schnorr"} args = append(args, arguments...) outputSign := appRunWithOutput(r, t, app, args) @@ -93,7 +137,12 @@ func appRunSignSchnorr(r *rand.Rand, t *testing.T, app *cli.App, arguments []str return dataSigned } -func appRunWithOutput(r *rand.Rand, t *testing.T, app *cli.App, arguments []string) (output string) { +func appRunWithOutput( + r *rand.Rand, + t *testing.T, + app *cli.App, + arguments []string, +) (output string) { outPut := filepath.Join(t.TempDir(), fmt.Sprintf("%s-out.txt", testutil.GenRandomHexStr(r, 10))) outPutFile, err := os.Create(outPut) require.NoError(t, err) @@ -149,7 +198,13 @@ func writeFpInfoToFile(r *rand.Rand, t *testing.T, fpInfoPath, btcPk string) { func testApp() *cli.App { app := cli.NewApp() app.Name = "eotsd" - app.Commands = append(app.Commands, dcli.StartCommand, dcli.InitCommand, dcli.SignSchnorrSig, dcli.VerifySchnorrSig) + app.Commands = append( + app.Commands, + dcli.StartCommand, + dcli.InitCommand, + dcli.SignSchnorrSig, + dcli.VerifySchnorrSig, + ) app.Commands = append(app.Commands, dcli.KeysCommands...) return app } diff --git a/eotsmanager/cmd/eotsd/daemon/start.go b/eotsmanager/cmd/eotsd/daemon/start.go index 8350d16b..4845ca2d 100644 --- a/eotsmanager/cmd/eotsd/daemon/start.go +++ b/eotsmanager/cmd/eotsd/daemon/start.go @@ -63,7 +63,12 @@ func startFn(ctx *cli.Context) error { return fmt.Errorf("failed to create db backend: %w", err) } - eotsManager, err := eotsmanager.NewLocalEOTSManager(homePath, cfg.KeyringBackend, dbBackend, logger) + eotsManager, err := eotsmanager.NewLocalEOTSManager( + homePath, + cfg.KeyringBackend, + dbBackend, + logger, + ) if err != nil { return fmt.Errorf("failed to create EOTS manager: %w", err) } @@ -74,7 +79,13 @@ func startFn(ctx *cli.Context) error { return err } - eotsServer := eotsservice.NewEOTSManagerServer(cfg, logger, eotsManager, dbBackend, shutdownInterceptor) + eotsServer := eotsservice.NewEOTSManagerServer( + cfg, + logger, + eotsManager, + dbBackend, + shutdownInterceptor, + ) return eotsServer.RunUntilShutdown() } diff --git a/eotsmanager/cmd/eotsd/main.go b/eotsmanager/cmd/eotsd/main.go index 1b63d197..9f878f55 100644 --- a/eotsmanager/cmd/eotsd/main.go +++ b/eotsmanager/cmd/eotsd/main.go @@ -18,7 +18,13 @@ func main() { app := cli.NewApp() app.Name = "eotsd" app.Usage = "Extractable One Time Signature Daemon (eotsd)." - app.Commands = append(app.Commands, dcli.StartCommand, dcli.InitCommand, dcli.SignSchnorrSig, dcli.VerifySchnorrSig) + app.Commands = append( + app.Commands, + dcli.StartCommand, + dcli.InitCommand, + dcli.SignSchnorrSig, + dcli.VerifySchnorrSig, + ) app.Commands = append(app.Commands, dcli.KeysCommands...) if err := app.Run(os.Args); err != nil { diff --git a/eotsmanager/config/config.go b/eotsmanager/config/config.go index 0f664925..a7aa3a68 100644 --- a/eotsmanager/config/config.go +++ b/eotsmanager/config/config.go @@ -35,10 +35,10 @@ var ( ) 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"` + LogLevel string `long:"loglevel" description:"Logging level for all subsystems" choice:"trace"` KeyringBackend string `long:"keyring-type" description:"Type of keyring to use"` - RpcListener string `long:"rpclistener" description:"the listener for RPC connections, e.g., 127.0.0.1:1234"` - Metrics *metrics.Config `group:"metrics" namespace:"metrics"` + RpcListener string `long:"rpclistener" description:"the listener for RPC connections, e.g., 127.0.0.1:1234"` + Metrics *metrics.Config ` group:"metrics" namespace:"metrics"` DatabaseConfig *DBConfig `group:"dbconfig" namespace:"dbconfig"` } diff --git a/eotsmanager/eotsmanager.go b/eotsmanager/eotsmanager.go index 2e8e1619..c9ff80e9 100644 --- a/eotsmanager/eotsmanager.go +++ b/eotsmanager/eotsmanager.go @@ -19,7 +19,13 @@ type EOTSManager interface { // 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) + CreateRandomnessPairList( + uid []byte, + chainID []byte, + startHeight uint64, + num uint32, + passphrase string, + ) ([]*btcec.FieldVal, error) // KeyRecord returns the finality provider record // It fails if the finality provider does not exist or passPhrase is incorrect @@ -29,7 +35,13 @@ type EOTSManager interface { // secret randomness of the give chain at 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) + 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 finality provider // It fails if the finality provider does not exist or the message size is not 32 bytes diff --git a/eotsmanager/localmanager.go b/eotsmanager/localmanager.go index 8e7aa2ee..f331e265 100644 --- a/eotsmanager/localmanager.go +++ b/eotsmanager/localmanager.go @@ -39,7 +39,11 @@ type LocalEOTSManager struct { metrics *metrics.EotsMetrics } -func NewLocalEOTSManager(homeDir, keyringBackend string, dbbackend kvdb.Backend, logger *zap.Logger) (*LocalEOTSManager, error) { +func NewLocalEOTSManager( + homeDir, keyringBackend string, + dbbackend kvdb.Backend, + logger *zap.Logger, +) (*LocalEOTSManager, error) { inputReader := strings.NewReader("") es, err := store.NewEOTSStore(dbbackend) @@ -63,7 +67,10 @@ func NewLocalEOTSManager(homeDir, keyringBackend string, dbbackend kvdb.Backend, }, nil } -func initKeyring(homeDir, keyringBackend string, inputReader *strings.Reader) (keyring.Keyring, error) { +func initKeyring( + homeDir, keyringBackend string, + inputReader *strings.Reader, +) (keyring.Keyring, error) { return keyring.New( "eots-manager", keyringBackend, @@ -102,7 +109,9 @@ func NewMnemonic() (string, error) { return mnemonic, nil } -func (lm *LocalEOTSManager) CreateKeyWithMnemonic(name, passphrase, hdPath, mnemonic string) (*bbntypes.BIP340PubKey, error) { +func (lm *LocalEOTSManager) CreateKeyWithMnemonic( + name, passphrase, hdPath, mnemonic string, +) (*bbntypes.BIP340PubKey, error) { if lm.keyExists(name) { return nil, eotstypes.ErrFinalityProviderAlreadyExisted } @@ -165,7 +174,13 @@ func loadBIP340PubKeyFromKeyringRecord(record *keyring.Record) (*bbntypes.BIP340 // // 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(fpPk []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++ { @@ -178,12 +193,21 @@ func (lm *LocalEOTSManager) CreateRandomnessPairList(fpPk []byte, chainID []byte prList = append(prList, pubRand) } lm.metrics.IncrementEotsFpTotalGeneratedRandomnessCounter(hex.EncodeToString(fpPk)) - lm.metrics.SetEotsFpLastGeneratedRandomnessHeight(hex.EncodeToString(fpPk), float64(startHeight)) + lm.metrics.SetEotsFpLastGeneratedRandomnessHeight( + hex.EncodeToString(fpPk), + float64(startHeight), + ) return prList, nil } -func (lm *LocalEOTSManager) SignEOTS(fpPk []byte, chainID []byte, msg []byte, height uint64, passphrase string) (*btcec.ModNScalar, error) { +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) @@ -201,7 +225,11 @@ func (lm *LocalEOTSManager) SignEOTS(fpPk []byte, chainID []byte, msg []byte, he return eots.Sign(privKey, privRand, msg) } -func (lm *LocalEOTSManager) SignSchnorrSig(fpPk []byte, msg []byte, passphrase string) (*schnorr.Signature, error) { +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) @@ -211,13 +239,20 @@ func (lm *LocalEOTSManager) SignSchnorrSig(fpPk []byte, msg []byte, passphrase s } // signSchnorrSigFromPrivKey signs a Schnorr signature using the private key and updates metrics by the fpPk -func (lm *LocalEOTSManager) signSchnorrSigFromPrivKey(privKey *btcec.PrivateKey, fpPk []byte, msg []byte) (*schnorr.Signature, error) { +func (lm *LocalEOTSManager) signSchnorrSigFromPrivKey( + privKey *btcec.PrivateKey, + fpPk []byte, + msg []byte, +) (*schnorr.Signature, error) { // Update metrics lm.metrics.IncrementEotsFpTotalSchnorrSignCounter(hex.EncodeToString(fpPk)) return schnorr.Sign(privKey, msg) } -func (lm *LocalEOTSManager) SignSchnorrSigFromKeyname(keyName, passphrase string, msg []byte) (*schnorr.Signature, *bbntypes.BIP340PubKey, error) { +func (lm *LocalEOTSManager) SignSchnorrSigFromKeyname( + keyName, passphrase string, + msg []byte, +) (*schnorr.Signature, *bbntypes.BIP340PubKey, error) { lm.input.Reset(passphrase) k, err := lm.kr.Key(keyName) if err != nil { @@ -246,17 +281,29 @@ func (lm *LocalEOTSManager) Close() error { } // 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) { +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 } - privRand, pubRand := randgenerator.GenerateRandomness(record.PrivKey.Serialize(), chainID, height) + privRand, pubRand := randgenerator.GenerateRandomness( + record.PrivKey.Serialize(), + chainID, + height, + ) return privRand, pubRand, nil } // TODO: we ignore passPhrase in local implementation for now -func (lm *LocalEOTSManager) KeyRecord(fpPk []byte, passphrase string) (*eotstypes.KeyRecord, error) { +func (lm *LocalEOTSManager) KeyRecord( + fpPk []byte, + passphrase string, +) (*eotstypes.KeyRecord, error) { name, err := lm.es.GetEOTSKeyName(fpPk) if err != nil { return nil, err @@ -272,7 +319,10 @@ func (lm *LocalEOTSManager) KeyRecord(fpPk []byte, passphrase string) (*eotstype }, nil } -func (lm *LocalEOTSManager) getEOTSPrivKey(fpPk []byte, passphrase string) (*btcec.PrivateKey, error) { +func (lm *LocalEOTSManager) getEOTSPrivKey( + fpPk []byte, + passphrase string, +) (*btcec.PrivateKey, error) { keyName, err := lm.es.GetEOTSKeyName(fpPk) if err != nil { return nil, err diff --git a/eotsmanager/localmanager_test.go b/eotsmanager/localmanager_test.go index adea480c..a43f67d0 100644 --- a/eotsmanager/localmanager_test.go +++ b/eotsmanager/localmanager_test.go @@ -38,7 +38,12 @@ func FuzzCreateKey(f *testing.F) { require.NoError(t, err) }() - lm, err := eotsmanager.NewLocalEOTSManager(homeDir, eotsCfg.KeyringBackend, dbBackend, zap.NewNop()) + lm, err := eotsmanager.NewLocalEOTSManager( + homeDir, + eotsCfg.KeyringBackend, + dbBackend, + zap.NewNop(), + ) require.NoError(t, err) fpPk, err := lm.CreateKey(fpName, passphrase, hdPath) @@ -72,7 +77,12 @@ func FuzzCreateRandomnessPairList(f *testing.F) { require.NoError(t, err) }() require.NoError(t, err) - lm, err := eotsmanager.NewLocalEOTSManager(homeDir, eotsCfg.KeyringBackend, dbBackend, zap.NewNop()) + lm, err := eotsmanager.NewLocalEOTSManager( + homeDir, + eotsCfg.KeyringBackend, + dbBackend, + zap.NewNop(), + ) require.NoError(t, err) fpPk, err := lm.CreateKey(fpName, passphrase, hdPath) @@ -81,12 +91,24 @@ func FuzzCreateRandomnessPairList(f *testing.F) { chainID := datagen.GenRandomByteArray(r, 10) startHeight := datagen.RandomInt(r, 100) num := r.Intn(10) + 1 - pubRandList, err := lm.CreateRandomnessPairList(fpPk, 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(fpPk, 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/randgenerator/randgenerator.go b/eotsmanager/randgenerator/randgenerator.go index 570031f0..4aa68009 100644 --- a/eotsmanager/randgenerator/randgenerator.go +++ b/eotsmanager/randgenerator/randgenerator.go @@ -12,7 +12,11 @@ import ( // GenerateRandomness generates a random scalar with the given key and src // the result is deterministic with each given input -func GenerateRandomness(key []byte, chainID []byte, height uint64) (*eots.PrivateRand, *eots.PublicRand) { +func GenerateRandomness( + key []byte, + chainID []byte, + height uint64, +) (*eots.PrivateRand, *eots.PublicRand) { // calculate the randomn hash of the key concatenated with chainID and height digest := hmac.New(sha256.New, key) digest.Write(append(sdk.Uint64ToBigEndian(height), chainID...)) diff --git a/eotsmanager/service/rpcserver.go b/eotsmanager/service/rpcserver.go index b8cc4990..854d76b6 100644 --- a/eotsmanager/service/rpcserver.go +++ b/eotsmanager/service/rpcserver.go @@ -53,10 +53,19 @@ func (r *rpcServer) CreateKey(ctx context.Context, req *proto.CreateKeyRequest) } // CreateRandomnessPairList returns a list of Schnorr randomness pairs -func (r *rpcServer) CreateRandomnessPairList(ctx context.Context, req *proto.CreateRandomnessPairListRequest) ( +func (r *rpcServer) CreateRandomnessPairList( + ctx context.Context, + req *proto.CreateRandomnessPairListRequest, +) ( *proto.CreateRandomnessPairListResponse, error) { - pubRandList, err := r.em.CreateRandomnessPairList(req.Uid, req.ChainId, req.StartHeight, req.Num, req.Passphrase) + pubRandList, err := r.em.CreateRandomnessPairList( + req.Uid, + req.ChainId, + req.StartHeight, + req.Num, + req.Passphrase, + ) if err != nil { return nil, err diff --git a/eotsmanager/service/server.go b/eotsmanager/service/server.go index d9e2f310..2b101b59 100644 --- a/eotsmanager/service/server.go +++ b/eotsmanager/service/server.go @@ -35,7 +35,13 @@ type Server struct { } // NewEOTSManagerServer creates a new server with the given config. -func NewEOTSManagerServer(cfg *config.Config, l *zap.Logger, em eotsmanager.EOTSManager, db kvdb.Backend, sig signal.Interceptor) *Server { +func NewEOTSManagerServer( + cfg *config.Config, + l *zap.Logger, + em eotsmanager.EOTSManager, + db kvdb.Backend, + sig signal.Interceptor, +) *Server { return &Server{ cfg: cfg, logger: l, diff --git a/finality-provider/cmd/fpcli/daemon/daemoncmd.go b/finality-provider/cmd/fpcli/daemon/daemoncmd.go index 7d662094..49abe4ee 100644 --- a/finality-provider/cmd/fpcli/daemon/daemoncmd.go +++ b/finality-provider/cmd/fpcli/daemon/daemoncmd.go @@ -173,7 +173,13 @@ func getDescriptionFromContext(ctx *cli.Context) (stakingtypes.Description, erro securityContactStr := ctx.String(securityContactFlag) detailsStr := ctx.String(detailsFlag) - description := stakingtypes.NewDescription(monikerStr, identityStr, websiteStr, securityContactStr, detailsStr) + description := stakingtypes.NewDescription( + monikerStr, + identityStr, + websiteStr, + securityContactStr, + detailsStr, + ) return description.EnsureLength() } @@ -291,7 +297,11 @@ func registerFp(ctx *cli.Context) error { } defer cleanUp() - res, err := rpcClient.RegisterFinalityProvider(context.Background(), fpPk, ctx.String(passphraseFlag)) + res, err := rpcClient.RegisterFinalityProvider( + context.Background(), + fpPk, + ctx.String(passphraseFlag), + ) if err != nil { return err } @@ -383,7 +393,11 @@ func loadKeyName(ctx *cli.Context) (string, error) { // beforehand cfg, err := fpcfg.LoadConfig(ctx.String(homeFlag)) if err != nil { - return "", fmt.Errorf("failed to load config from %s: %w", fpcfg.ConfigFile(ctx.String(homeFlag)), err) + return "", fmt.Errorf( + "failed to load config from %s: %w", + fpcfg.ConfigFile(ctx.String(homeFlag)), + err, + ) } keyName = cfg.BabylonConfig.Key diff --git a/finality-provider/cmd/fpd/daemon/init.go b/finality-provider/cmd/fpd/daemon/init.go index 5c95330b..a421798a 100644 --- a/finality-provider/cmd/fpd/daemon/init.go +++ b/finality-provider/cmd/fpd/daemon/init.go @@ -54,5 +54,6 @@ func initHome(c *cli.Context) error { defaultConfig := fpcfg.DefaultConfigWithHome(homePath) fileParser := flags.NewParser(&defaultConfig, flags.Default) - return flags.NewIniParser(fileParser).WriteFile(fpcfg.ConfigFile(homePath), flags.IniIncludeComments|flags.IniIncludeDefaults) + return flags.NewIniParser(fileParser). + WriteFile(fpcfg.ConfigFile(homePath), flags.IniIncludeComments|flags.IniIncludeDefaults) } diff --git a/finality-provider/cmd/fpd/daemon/keys.go b/finality-provider/cmd/fpd/daemon/keys.go index 3deb0850..e3b06dae 100644 --- a/finality-provider/cmd/fpd/daemon/keys.go +++ b/finality-provider/cmd/fpd/daemon/keys.go @@ -17,8 +17,8 @@ import ( ) type KeyOutput struct { - Name string `json:"name" yaml:"name"` - Address string `json:"address" yaml:"address"` + Name string `json:"name" yaml:"name"` + Address string `json:"address" yaml:"address"` Mnemonic string `json:"mnemonic,omitempty" yaml:"mnemonic"` } @@ -131,7 +131,8 @@ func addKey(ctx *cli.Context) error { cfg.BabylonConfig.KeyringBackend = keyBackend fileParser := flags.NewParser(cfg, flags.Default) - return flags.NewIniParser(fileParser).WriteFile(fpcfg.ConfigFile(homePath), flags.IniIncludeComments|flags.IniIncludeDefaults) + return flags.NewIniParser(fileParser). + WriteFile(fpcfg.ConfigFile(homePath), flags.IniIncludeComments|flags.IniIncludeDefaults) } func printRespJSON(resp interface{}) { diff --git a/finality-provider/cmd/fpd/daemon/start.go b/finality-provider/cmd/fpd/daemon/start.go index a2820571..d3220050 100644 --- a/finality-provider/cmd/fpd/daemon/start.go +++ b/finality-provider/cmd/fpd/daemon/start.go @@ -90,7 +90,13 @@ func start(ctx *cli.Context) error { return err } - fpServer := service.NewFinalityProviderServer(cfg, logger, fpApp, dbBackend, shutdownInterceptor) + fpServer := service.NewFinalityProviderServer( + cfg, + logger, + fpApp, + dbBackend, + shutdownInterceptor, + ) return fpServer.RunUntilShutdown() } diff --git a/finality-provider/config/babylon.go b/finality-provider/config/babylon.go index c6eeb69f..ab3e5cd6 100644 --- a/finality-provider/config/babylon.go +++ b/finality-provider/config/babylon.go @@ -7,20 +7,20 @@ import ( ) type BBNConfig struct { - Key string `long:"key" description:"name of the key to sign transactions with"` - ChainID string `long:"chain-id" description:"chain id of the chain to connect to"` - RPCAddr string `long:"rpc-address" description:"address of the rpc server to connect to"` - GRPCAddr string `long:"grpc-address" description:"address of the grpc server to connect to"` - AccountPrefix string `long:"acc-prefix" description:"account prefix to use for addresses"` - KeyringBackend string `long:"keyring-type" description:"type of keyring to use"` + Key string `long:"key" description:"name of the key to sign transactions with"` + ChainID string `long:"chain-id" description:"chain id of the chain to connect to"` + RPCAddr string `long:"rpc-address" description:"address of the rpc server to connect to"` + GRPCAddr string `long:"grpc-address" description:"address of the grpc server to connect to"` + AccountPrefix string `long:"acc-prefix" description:"account prefix to use for addresses"` + KeyringBackend string `long:"keyring-type" description:"type of keyring to use"` GasAdjustment float64 `long:"gas-adjustment" description:"adjustment factor when using gas estimation"` - GasPrices string `long:"gas-prices" description:"comma separated minimum gas prices to accept for transactions"` - KeyDirectory string `long:"key-dir" description:"directory to store keys in"` - Debug bool `long:"debug" description:"flag to print debug output"` - Timeout time.Duration `long:"timeout" description:"client timeout when doing queries"` - BlockTimeout time.Duration `long:"block-timeout" description:"block timeout when waiting for block events"` - OutputFormat string `long:"output-format" description:"default output when printint responses"` - SignModeStr string `long:"sign-mode" description:"sign mode to use"` + GasPrices string `long:"gas-prices" description:"comma separated minimum gas prices to accept for transactions"` + KeyDirectory string `long:"key-dir" description:"directory to store keys in"` + Debug bool `long:"debug" description:"flag to print debug output"` + Timeout time.Duration `long:"timeout" description:"client timeout when doing queries"` + BlockTimeout time.Duration `long:"block-timeout" description:"block timeout when waiting for block events"` + OutputFormat string `long:"output-format" description:"default output when printint responses"` + SignModeStr string `long:"sign-mode" description:"sign mode to use"` } func DefaultBBNConfig() BBNConfig { diff --git a/finality-provider/config/config.go b/finality-provider/config/config.go index 3f10466f..77c23e51 100644 --- a/finality-provider/config/config.go +++ b/finality-provider/config/config.go @@ -53,22 +53,22 @@ var ( // 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 string `long:"chainname" description:"the name of the consumer chain"` - 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 finality-provider status"` + LogLevel string `long:"loglevel" description:"Logging level for all subsystems" choice:"trace"` + ChainName string `long:"chainname" description:"the name of the consumer chain"` + 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 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"` - MaxSubmissionRetries uint64 `long:"maxsubmissionretries" description:"The maximum number of retries to submit finality signature or public randomness"` - FastSyncInterval time.Duration `long:"fastsyncinterval" description:"The interval between each try of fast sync, which is disabled if the value is 0"` - 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"` - 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"` + SubmissionRetryInterval time.Duration `long:"submissionretryinterval" description:"The interval between each attempt to submit finality signature or public randomness after a failure"` + MaxSubmissionRetries uint64 `long:"maxsubmissionretries" description:"The maximum number of retries to submit finality signature or public randomness"` + FastSyncInterval time.Duration `long:"fastsyncinterval" description:"The interval between each try of fast sync, which is disabled if the value is 0"` + 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"` + 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"` BTCNetParams chaincfg.Params diff --git a/finality-provider/config/cosmwasm.go b/finality-provider/config/cosmwasm.go index b2ec725c..79ea4c9b 100644 --- a/finality-provider/config/cosmwasm.go +++ b/finality-provider/config/cosmwasm.go @@ -10,20 +10,20 @@ import ( ) type CosmwasmConfig struct { - Key string `long:"key" description:"name of the key to sign transactions with"` - ChainID string `long:"chain-id" description:"chain id of the chain to connect to"` - RPCAddr string `long:"rpc-address" description:"address of the rpc server to connect to"` - GRPCAddr string `long:"grpc-address" description:"address of the grpc server to connect to"` - AccountPrefix string `long:"acc-prefix" description:"account prefix to use for addresses"` - KeyringBackend string `long:"keyring-type" description:"type of keyring to use"` - GasAdjustment float64 `long:"gas-adjustment" description:"adjustment factor when using gas estimation"` - GasPrices string `long:"gas-prices" description:"comma separated minimum gas prices to accept for transactions"` - KeyDirectory string `long:"key-dir" description:"directory to store keys in"` - Debug bool `long:"debug" description:"flag to print debug output"` - Timeout time.Duration `long:"timeout" description:"client timeout when doing queries"` - BlockTimeout time.Duration `long:"block-timeout" description:"block timeout when waiting for block events"` - OutputFormat string `long:"output-format" description:"default output when printint responses"` - SignModeStr string `long:"sign-mode" description:"sign mode to use"` + Key string `long:"key" description:"name of the key to sign transactions with"` + ChainID string `long:"chain-id" description:"chain id of the chain to connect to"` + RPCAddr string `long:"rpc-address" description:"address of the rpc server to connect to"` + GRPCAddr string `long:"grpc-address" description:"address of the grpc server to connect to"` + AccountPrefix string `long:"acc-prefix" description:"account prefix to use for addresses"` + KeyringBackend string `long:"keyring-type" description:"type of keyring to use"` + GasAdjustment float64 `long:"gas-adjustment" description:"adjustment factor when using gas estimation"` + GasPrices string `long:"gas-prices" description:"comma separated minimum gas prices to accept for transactions"` + KeyDirectory string `long:"key-dir" description:"directory to store keys in"` + Debug bool `long:"debug" description:"flag to print debug output"` + Timeout time.Duration `long:"timeout" description:"client timeout when doing queries"` + BlockTimeout time.Duration `long:"block-timeout" description:"block timeout when waiting for block events"` + OutputFormat string `long:"output-format" description:"default output when printint responses"` + SignModeStr string `long:"sign-mode" description:"sign mode to use"` BtcStakingContractAddress string `long:"btc-staking-contract-address" description:"address of the BTC staking contract"` } diff --git a/finality-provider/config/opstackl2.go b/finality-provider/config/opstackl2.go index 7c6d474a..97e82b60 100644 --- a/finality-provider/config/opstackl2.go +++ b/finality-provider/config/opstackl2.go @@ -11,22 +11,22 @@ import ( type OPStackL2Config struct { OPStackL2RPCAddress string `long:"opstackl2-rpc-address" description:"the rpc address of the op-stack-l2 node to connect to"` - OPFinalityGadgetAddress string `long:"op-finality-gadget" description:"the contract address of the op-finality-gadget"` + OPFinalityGadgetAddress string `long:"op-finality-gadget" description:"the contract address of the op-finality-gadget"` // Below configurations are needed for the Babylon client - Key string `long:"key" description:"name of the key to sign transactions with"` - ChainID string `long:"chain-id" description:"chain id of the chain to connect to"` - RPCAddr string `long:"rpc-address" description:"address of the rpc server to connect to"` - GRPCAddr string `long:"grpc-address" description:"address of the grpc server to connect to"` - AccountPrefix string `long:"acc-prefix" description:"account prefix to use for addresses"` - KeyringBackend string `long:"keyring-type" description:"type of keyring to use"` - GasAdjustment float64 `long:"gas-adjustment" description:"adjustment factor when using gas estimation"` - GasPrices string `long:"gas-prices" description:"comma separated minimum gas prices to accept for transactions"` - KeyDirectory string `long:"key-dir" description:"directory to store keys in"` - Debug bool `long:"debug" description:"flag to print debug output"` - Timeout time.Duration `long:"timeout" description:"client timeout when doing queries"` - BlockTimeout time.Duration `long:"block-timeout" description:"block timeout when waiting for block events"` - OutputFormat string `long:"output-format" description:"default output when printint responses"` - SignModeStr string `long:"sign-mode" description:"sign mode to use"` + Key string `long:"key" description:"name of the key to sign transactions with"` + ChainID string `long:"chain-id" description:"chain id of the chain to connect to"` + RPCAddr string `long:"rpc-address" description:"address of the rpc server to connect to"` + GRPCAddr string `long:"grpc-address" description:"address of the grpc server to connect to"` + AccountPrefix string `long:"acc-prefix" description:"account prefix to use for addresses"` + KeyringBackend string `long:"keyring-type" description:"type of keyring to use"` + GasAdjustment float64 `long:"gas-adjustment" description:"adjustment factor when using gas estimation"` + GasPrices string `long:"gas-prices" description:"comma separated minimum gas prices to accept for transactions"` + KeyDirectory string `long:"key-dir" description:"directory to store keys in"` + Debug bool `long:"debug" description:"flag to print debug output"` + Timeout time.Duration `long:"timeout" description:"client timeout when doing queries"` + BlockTimeout time.Duration `long:"block-timeout" description:"block timeout when waiting for block events"` + OutputFormat string `long:"output-format" description:"default output when printint responses"` + SignModeStr string `long:"sign-mode" description:"sign mode to use"` } func (cfg *OPStackL2Config) Validate() error { diff --git a/finality-provider/config/poller.go b/finality-provider/config/poller.go index 71bdeb15..5f1b1af6 100644 --- a/finality-provider/config/poller.go +++ b/finality-provider/config/poller.go @@ -9,10 +9,10 @@ var ( ) type ChainPollerConfig struct { - BufferSize uint32 `long:"buffersize" description:"The maximum number of Babylon blocks that can be stored in the buffer"` - PollInterval time.Duration `long:"pollinterval" description:"The interval between each polling of Babylon blocks"` + BufferSize uint32 `long:"buffersize" description:"The maximum number of Babylon blocks that can be stored in the buffer"` + PollInterval time.Duration `long:"pollinterval" description:"The interval between each polling of Babylon blocks"` StaticChainScanningStartHeight uint64 `long:"staticchainscanningstartheight" description:"The static height from which we start polling the chain"` - AutoChainScanningMode bool `long:"autochainscanningmode" description:"Automatically discover the height from which to start polling the chain"` + AutoChainScanningMode bool `long:"autochainscanningmode" description:"Automatically discover the height from which to start polling the chain"` } func DefaultChainPollerConfig() ChainPollerConfig { diff --git a/finality-provider/service/app.go b/finality-provider/service/app.go index e3ee8eb1..af38886c 100644 --- a/finality-provider/service/app.go +++ b/finality-provider/service/app.go @@ -66,7 +66,11 @@ func NewFinalityProviderAppFromConfig( } consumerCon, err := fpcc.NewConsumerController(cfg, logger) if err != nil { - return nil, fmt.Errorf("failed to create rpc client for the consumer chain %s: %v", cfg.ChainName, err) + return nil, fmt.Errorf( + "failed to create rpc client for the consumer chain %s: %v", + cfg.ChainName, + err, + ) } // if the EOTSManagerAddress is empty, run a local EOTS manager; // otherwise connect a remote one with a gRPC client @@ -75,7 +79,10 @@ func NewFinalityProviderAppFromConfig( return nil, fmt.Errorf("failed to create EOTS manager client: %w", err) } - logger.Info("successfully connected to a remote EOTS manager", zap.String("address", cfg.EOTSManagerAddress)) + logger.Info( + "successfully connected to a remote EOTS manager", + zap.String("address", cfg.EOTSManagerAddress), + ) return NewFinalityProviderApp(cfg, cc, consumerCon, em, db, logger) } @@ -110,7 +117,16 @@ func NewFinalityProviderApp( fpMetrics := metrics.NewFpMetrics() - fpm, err := NewFinalityProviderManager(fpStore, pubRandStore, config, cc, consumerCon, em, fpMetrics, logger) + fpm, err := NewFinalityProviderManager( + fpStore, + pubRandStore, + config, + cc, + consumerCon, + em, + fpMetrics, + logger, + ) if err != nil { return nil, fmt.Errorf("failed to create finality-provider manager: %w", err) } @@ -158,7 +174,9 @@ func (app *FinalityProviderApp) ListFinalityProviderInstances() []*FinalityProvi return app.fpManager.ListFinalityProviderInstances() } -func (app *FinalityProviderApp) ListFinalityProviderInstancesForChain(chainID string) []*FinalityProviderInstance { +func (app *FinalityProviderApp) ListFinalityProviderInstancesForChain( + chainID string, +) []*FinalityProviderInstance { return app.fpManager.ListFinalityProviderInstancesForChain(chainID) } @@ -166,16 +184,22 @@ func (app *FinalityProviderApp) ListAllFinalityProvidersInfo() ([]*proto.Finalit return app.fpManager.AllFinalityProviders() } -func (app *FinalityProviderApp) GetFinalityProviderInfo(fpPk *bbntypes.BIP340PubKey) (*proto.FinalityProviderInfo, error) { +func (app *FinalityProviderApp) GetFinalityProviderInfo( + fpPk *bbntypes.BIP340PubKey, +) (*proto.FinalityProviderInfo, error) { return app.fpManager.FinalityProviderInfo(fpPk) } // GetFinalityProviderInstance returns the finality-provider instance with the given Babylon public key -func (app *FinalityProviderApp) GetFinalityProviderInstance(fpPk *bbntypes.BIP340PubKey) (*FinalityProviderInstance, error) { +func (app *FinalityProviderApp) GetFinalityProviderInstance( + fpPk *bbntypes.BIP340PubKey, +) (*FinalityProviderInstance, error) { return app.fpManager.GetFinalityProviderInstance(fpPk) } -func (app *FinalityProviderApp) RegisterFinalityProvider(fpPkStr string) (*RegisterFinalityProviderResponse, error) { +func (app *FinalityProviderApp) RegisterFinalityProvider( + fpPkStr string, +) (*RegisterFinalityProviderResponse, error) { fpPk, err := bbntypes.NewBIP340PubKeyFromHex(fpPkStr) if err != nil { return nil, err @@ -226,7 +250,10 @@ func (app *FinalityProviderApp) RegisterFinalityProvider(fpPkStr string) (*Regis // 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 { +func (app *FinalityProviderApp) StartHandlingFinalityProvider( + fpPk *bbntypes.BIP340PubKey, + passphrase string, +) error { return app.fpManager.StartFinalityProvider(fpPk, passphrase) } @@ -365,7 +392,9 @@ func (app *FinalityProviderApp) CreateFinalityProvider( } } -func (app *FinalityProviderApp) handleCreateFinalityProviderRequest(req *createFinalityProviderRequest) (*createFinalityProviderResponse, error) { +func (app *FinalityProviderApp) handleCreateFinalityProviderRequest( + req *createFinalityProviderRequest, +) (*createFinalityProviderResponse, error) { // 1. check if the chain key exists kr, err := fpkr.NewChainKeyringControllerWithKeyring(app.kr, req.keyName, app.input) if err != nil { @@ -399,7 +428,10 @@ func (app *FinalityProviderApp) handleCreateFinalityProviderRequest(req *createF // 3. create proof-of-possession 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) + return nil, fmt.Errorf( + "failed to create proof-of-possession of the finality-provider: %w", + err, + ) } if err := app.fps.CreateFinalityProvider(chainPk, fpPk.MustToBTCPK(), req.description, req.commission, req.keyName, req.chainID, pop.BabylonSig, pop.BtcSig); err != nil { @@ -487,7 +519,10 @@ func (app *FinalityProviderApp) StoreFinalityProvider( // 3. create proof-of-possession pop, err := kr.CreatePop(fpRecord.PrivKey, passPhrase) if err != nil { - return nil, fmt.Errorf("failed to create proof-of-possession of the finality provider: %w", err) + return nil, fmt.Errorf( + "failed to create proof-of-possession of the finality provider: %w", + err, + ) } if err := app.fps.CreateFinalityProvider(chainPk, fpPk.MustToBTCPK(), description, commission, keyName, chainID, pop.BabylonSig, pop.BtcSig); err != nil { @@ -509,7 +544,9 @@ func (app *FinalityProviderApp) StoreFinalityProvider( return storedFp, nil } -func CreateChainKey(keyringDir, chainID, keyName, backend, passphrase, hdPath, mnemonic string) (*types.ChainKeyInfo, error) { +func CreateChainKey( + keyringDir, chainID, keyName, backend, passphrase, hdPath, mnemonic string, +) (*types.ChainKeyInfo, error) { sdkCtx, err := fpkr.CreateClientCtx( keyringDir, chainID, ) @@ -546,14 +583,20 @@ func (app *FinalityProviderApp) eventLoop() { case ev := <-app.finalityProviderRegisteredEventChan: // change the status of the finality-provider to registered - err := app.fps.SetFpStatus(ev.btcPubKey.MustToBTCPK(), proto.FinalityProviderStatus_REGISTERED) + err := app.fps.SetFpStatus( + ev.btcPubKey.MustToBTCPK(), + 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), ) } - app.fpManager.metrics.RecordFpStatus(ev.btcPubKey.MarshalHex(), proto.FinalityProviderStatus_REGISTERED) + app.fpManager.metrics.RecordFpStatus( + ev.btcPubKey.MarshalHex(), + proto.FinalityProviderStatus_REGISTERED, + ) // return to the caller ev.successResponse <- &RegisterFinalityProviderResponse{ diff --git a/finality-provider/service/app_test.go b/finality-provider/service/app_test.go index d88432f6..d677428a 100644 --- a/finality-provider/service/app_test.go +++ b/finality-provider/service/app_test.go @@ -37,7 +37,12 @@ func FuzzRegisterFinalityProvider(f *testing.F) { eotsCfg := eotscfg.DefaultConfigWithHomePath(eotsHomeDir) dbBackend, err := eotsCfg.DatabaseConfig.GetDbBackend() require.NoError(t, err) - em, err := eotsmanager.NewLocalEOTSManager(eotsHomeDir, eotsCfg.KeyringBackend, dbBackend, logger) + em, err := eotsmanager.NewLocalEOTSManager( + eotsHomeDir, + eotsCfg.KeyringBackend, + dbBackend, + logger, + ) require.NoError(t, err) defer func() { dbBackend.Close() @@ -48,7 +53,12 @@ func FuzzRegisterFinalityProvider(f *testing.F) { // Create mocked babylon client randomStartingHeight := uint64(r.Int63n(100) + 1) currentHeight := randomStartingHeight + uint64(r.Int63n(10)+2) - mockConsumerController := testutil.PrepareMockedConsumerController(t, r, randomStartingHeight, currentHeight) + mockConsumerController := testutil.PrepareMockedConsumerController( + t, + r, + randomStartingHeight, + currentHeight, + ) mockConsumerController.EXPECT().QueryLatestFinalizedBlock().Return(nil, nil).AnyTimes() mockConsumerController.EXPECT().QueryFinalityProviderVotingPower(gomock.Any(), gomock.Any()).Return(uint64(0), nil).AnyTimes() @@ -61,7 +71,14 @@ func FuzzRegisterFinalityProvider(f *testing.F) { fpCfg.PollerConfig.StaticChainScanningStartHeight = randomStartingHeight fpdb, err := fpCfg.DatabaseConfig.GetDbBackend() require.NoError(t, err) - app, err := service.NewFinalityProviderApp(&fpCfg, mockBabylonController, mockConsumerController, em, fpdb, logger) + app, err := service.NewFinalityProviderApp( + &fpCfg, + mockBabylonController, + mockConsumerController, + em, + fpdb, + logger, + ) require.NoError(t, err) defer func() { err = fpdb.Close() @@ -112,13 +129,20 @@ func FuzzRegisterFinalityProvider(f *testing.F) { require.NoError(t, err) require.Equal(t, txHash, res.TxHash) - mockConsumerController.EXPECT().QueryLastPublicRandCommit(gomock.Any()).Return(nil, nil).AnyTimes() + mockConsumerController.EXPECT(). + QueryLastPublicRandCommit(gomock.Any()). + Return(nil, nil). + AnyTimes() err = app.StartHandlingFinalityProvider(fp.GetBIP340BTCPK(), passphrase) require.NoError(t, err) fpAfterReg, err := app.GetFinalityProviderInstance(fp.GetBIP340BTCPK()) require.NoError(t, err) - require.Equal(t, proto.FinalityProviderStatus_REGISTERED, fpAfterReg.GetStoreFinalityProvider().Status) + require.Equal( + t, + proto.FinalityProviderStatus_REGISTERED, + fpAfterReg.GetStoreFinalityProvider().Status, + ) fpInfo, err = app.GetFinalityProviderInfo(fp.GetBIP340BTCPK()) require.NoError(t, err) diff --git a/finality-provider/service/chain_poller.go b/finality-provider/service/chain_poller.go index 6ec4b32c..91039fa7 100644 --- a/finality-provider/service/chain_poller.go +++ b/finality-provider/service/chain_poller.go @@ -198,7 +198,11 @@ func (cp *ChainPoller) validateStartHeight(startHeight uint64) error { // Allow the start height to be the next chain height if startHeight > currentBestChainHeight+1 { - return fmt.Errorf("start height %d is more than the next chain tip height %d", startHeight, currentBestChainHeight+1) + return fmt.Errorf( + "start height %d is more than the next chain tip height %d", + startHeight, + currentBestChainHeight+1, + ) } return nil @@ -210,7 +214,10 @@ func (cp *ChainPoller) waitForActivation() { for { activatedHeight, err := cp.consumerCon.QueryActivatedHeight() if err != nil { - cp.logger.Debug("failed to query the consumer chain for the activated height", zap.Error(err)) + cp.logger.Debug( + "failed to query the consumer chain for the activated height", + zap.Error(err), + ) } else { if cp.nextHeight < activatedHeight { cp.nextHeight = activatedHeight diff --git a/finality-provider/service/chain_poller_test.go b/finality-provider/service/chain_poller_test.go index 6d777f2d..edb1f2e0 100644 --- a/finality-provider/service/chain_poller_test.go +++ b/finality-provider/service/chain_poller_test.go @@ -35,7 +35,10 @@ func FuzzChainPoller_Start(f *testing.F) { mockConsumerController := mocks.NewMockConsumerController(ctl) mockConsumerController.EXPECT().QueryActivatedHeight().Return(uint64(1), nil).AnyTimes() - mockConsumerController.EXPECT().QueryLatestBlockHeight().Return(currentHeight, nil).AnyTimes() + mockConsumerController.EXPECT(). + QueryLatestBlockHeight(). + Return(currentHeight, nil). + AnyTimes() for i := startHeight; i <= endHeight; i++ { resBlock := &types.BlockInfo{ @@ -48,7 +51,13 @@ func FuzzChainPoller_Start(f *testing.F) { m := metrics.NewFpMetrics() pollerCfg := fpcfg.DefaultChainPollerConfig() pollerCfg.PollInterval = 10 * time.Millisecond - poller := service.NewChainPoller(zap.NewNop(), &pollerCfg, mockBabylonController, mockConsumerController, m) + poller := service.NewChainPoller( + zap.NewNop(), + &pollerCfg, + mockBabylonController, + mockConsumerController, + m, + ) err := poller.Start(startHeight) require.NoError(t, err) defer func() { @@ -83,7 +92,10 @@ func FuzzChainPoller_SkipHeight(f *testing.F) { mockConsumerController := mocks.NewMockConsumerController(ctl) mockBabylonController.EXPECT().Close().Return(nil).AnyTimes() mockConsumerController.EXPECT().QueryActivatedHeight().Return(uint64(1), nil).AnyTimes() - mockConsumerController.EXPECT().QueryLatestBlockHeight().Return(currentHeight, nil).AnyTimes() + mockConsumerController.EXPECT(). + QueryLatestBlockHeight(). + Return(currentHeight, nil). + AnyTimes() for i := startHeight; i <= skipHeight; i++ { resBlock := &types.BlockInfo{ @@ -96,7 +108,13 @@ func FuzzChainPoller_SkipHeight(f *testing.F) { m := metrics.NewFpMetrics() pollerCfg := fpcfg.DefaultChainPollerConfig() pollerCfg.PollInterval = 1 * time.Second - poller := service.NewChainPoller(zap.NewNop(), &pollerCfg, mockBabylonController, mockConsumerController, m) + poller := service.NewChainPoller( + zap.NewNop(), + &pollerCfg, + mockBabylonController, + mockConsumerController, + m, + ) // should expect error if the poller is not started err := poller.SkipToHeight(skipHeight) require.Error(t, err) diff --git a/finality-provider/service/client/rpcclient.go b/finality-provider/service/client/rpcclient.go index 402c3160..2e3bb986 100644 --- a/finality-provider/service/client/rpcclient.go +++ b/finality-provider/service/client/rpcclient.go @@ -17,8 +17,13 @@ type FinalityProviderServiceGRpcClient struct { client proto.FinalityProvidersClient } -func NewFinalityProviderServiceGRpcClient(remoteAddr string) (*FinalityProviderServiceGRpcClient, func(), error) { - conn, err := grpc.NewClient(remoteAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) +func NewFinalityProviderServiceGRpcClient( + remoteAddr string, +) (*FinalityProviderServiceGRpcClient, func(), error) { + conn, err := grpc.NewClient( + remoteAddr, + grpc.WithTransportCredentials(insecure.NewCredentials()), + ) if err != nil { return nil, nil, fmt.Errorf("failed to build gRPC connection to %s: %w", remoteAddr, err) } @@ -32,7 +37,9 @@ func NewFinalityProviderServiceGRpcClient(remoteAddr string) (*FinalityProviderS }, cleanUp, nil } -func (c *FinalityProviderServiceGRpcClient) GetInfo(ctx context.Context) (*proto.GetInfoResponse, error) { +func (c *FinalityProviderServiceGRpcClient) GetInfo( + ctx context.Context, +) (*proto.GetInfoResponse, error) { req := &proto.GetInfoRequest{} res, err := c.client.GetInfo(ctx, req) if err != nil { @@ -86,7 +93,12 @@ func (c *FinalityProviderServiceGRpcClient) CreateFinalityProvider( return res, nil } -func (c *FinalityProviderServiceGRpcClient) AddFinalitySignature(ctx context.Context, fpPk string, height uint64, appHash []byte) (*proto.AddFinalitySignatureResponse, error) { +func (c *FinalityProviderServiceGRpcClient) AddFinalitySignature( + ctx context.Context, + fpPk string, + height uint64, + appHash []byte, +) (*proto.AddFinalitySignatureResponse, error) { req := &proto.AddFinalitySignatureRequest{ BtcPk: fpPk, Height: height, @@ -101,7 +113,9 @@ func (c *FinalityProviderServiceGRpcClient) AddFinalitySignature(ctx context.Con return res, nil } -func (c *FinalityProviderServiceGRpcClient) QueryFinalityProviderList(ctx context.Context) (*proto.QueryFinalityProviderListResponse, error) { +func (c *FinalityProviderServiceGRpcClient) QueryFinalityProviderList( + ctx context.Context, +) (*proto.QueryFinalityProviderListResponse, error) { req := &proto.QueryFinalityProviderListRequest{} res, err := c.client.QueryFinalityProviderList(ctx, req) if err != nil { @@ -111,7 +125,10 @@ func (c *FinalityProviderServiceGRpcClient) QueryFinalityProviderList(ctx contex return res, nil } -func (c *FinalityProviderServiceGRpcClient) QueryFinalityProviderInfo(ctx context.Context, fpPk *bbntypes.BIP340PubKey) (*proto.QueryFinalityProviderResponse, error) { +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 { diff --git a/finality-provider/service/eots_manager_adapter.go b/finality-provider/service/eots_manager_adapter.go index 765f7e1d..7ed47c16 100644 --- a/finality-provider/service/eots_manager_adapter.go +++ b/finality-provider/service/eots_manager_adapter.go @@ -11,7 +11,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -func (fp *FinalityProviderInstance) GetPubRandList(startHeight uint64, numPubRand uint64) ([]*btcec.FieldVal, error) { +func (fp *FinalityProviderInstance) GetPubRandList( + startHeight uint64, + numPubRand uint64, +) ([]*btcec.FieldVal, error) { pubRandList, err := fp.em.CreateRandomnessPairList( fp.btcPk.MustMarshal(), fp.GetChainID(), @@ -27,7 +30,11 @@ func (fp *FinalityProviderInstance) GetPubRandList(startHeight uint64, numPubRan } // TODO: have this function in Babylon side -func getHashToSignForCommitPubRand(startHeight uint64, numPubRand uint64, commitment []byte) ([]byte, error) { +func getHashToSignForCommitPubRand( + startHeight uint64, + numPubRand uint64, + commitment []byte, +) ([]byte, error) { hasher := tmhash.New() if _, err := hasher.Write(sdk.Uint64ToBigEndian(startHeight)); err != nil { return nil, err @@ -41,7 +48,11 @@ func getHashToSignForCommitPubRand(startHeight uint64, numPubRand uint64, commit return hasher.Sum(nil), nil } -func (fp *FinalityProviderInstance) SignPubRandCommit(startHeight uint64, numPubRand uint64, commitment []byte) (*schnorr.Signature, error) { +func (fp *FinalityProviderInstance) SignPubRandCommit( + startHeight uint64, + numPubRand uint64, + commitment []byte, +) (*schnorr.Signature, error) { hash, err := getHashToSignForCommitPubRand(startHeight, numPubRand, commitment) if err != nil { return nil, fmt.Errorf("failed to sign the commit public randomness message: %w", err) @@ -56,10 +67,18 @@ func getMsgToSignForVote(blockHeight uint64, blockHash []byte) []byte { return append(sdk.Uint64ToBigEndian(blockHeight), blockHash...) } -func (fp *FinalityProviderInstance) SignFinalitySig(b *types.BlockInfo) (*bbntypes.SchnorrEOTSSig, error) { +func (fp *FinalityProviderInstance) SignFinalitySig( + b *types.BlockInfo, +) (*bbntypes.SchnorrEOTSSig, error) { // build proper finality signature request msgToSign := getMsgToSignForVote(b.Height, b.Hash) - sig, err := fp.em.SignEOTS(fp.btcPk.MustMarshal(), fp.GetChainID(), msgToSign, b.Height, fp.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) } diff --git a/finality-provider/service/fastsync.go b/finality-provider/service/fastsync.go index 0e1c6a52..9ce4825f 100644 --- a/finality-provider/service/fastsync.go +++ b/finality-provider/service/fastsync.go @@ -17,7 +17,9 @@ 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 (fp *FinalityProviderInstance) FastSync(startHeight, endHeight uint64) (*FastSyncResult, error) { +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") } diff --git a/finality-provider/service/fastsync_test.go b/finality-provider/service/fastsync_test.go index 99ac2941..35ff0238 100644 --- a/finality-provider/service/fastsync_test.go +++ b/finality-provider/service/fastsync_test.go @@ -24,20 +24,39 @@ func FuzzFastSync_SufficientRandomness(f *testing.F) { randomStartingHeight := uint64(r.Int63n(100) + 1) finalizedHeight := randomStartingHeight + uint64(r.Int63n(10)+2) currentHeight := finalizedHeight + uint64(r.Int63n(10)+1) - mockConsumerController := testutil.PrepareMockedConsumerController(t, r, randomStartingHeight, currentHeight) + mockConsumerController := testutil.PrepareMockedConsumerController( + t, + r, + randomStartingHeight, + currentHeight, + ) mockBabylonController := testutil.PrepareMockedBabylonController(t) mockConsumerController.EXPECT().QueryLatestFinalizedBlock().Return(nil, nil).AnyTimes() - _, fpIns, cleanUp := startFinalityProviderAppWithRegisteredFp(t, r, mockBabylonController, mockConsumerController, randomStartingHeight) + _, fpIns, cleanUp := startFinalityProviderAppWithRegisteredFp( + t, + r, + mockBabylonController, + mockConsumerController, + randomStartingHeight, + ) defer cleanUp() // commit pub rand - mockConsumerController.EXPECT().QueryLastPublicRandCommit(gomock.Any()).Return(nil, nil).Times(1) - mockConsumerController.EXPECT().CommitPubRandList(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).Times(1) + mockConsumerController.EXPECT(). + QueryLastPublicRandCommit(gomock.Any()). + Return(nil, nil). + Times(1) + mockConsumerController.EXPECT(). + CommitPubRandList(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, nil). + Times(1) _, err := fpIns.CommitPubRand(randomStartingHeight) require.NoError(t, err) - mockConsumerController.EXPECT().QueryFinalityProviderVotingPower(fpIns.GetBtcPk(), gomock.Any()). - Return(uint64(1), nil).AnyTimes() + mockConsumerController.EXPECT(). + QueryFinalityProviderVotingPower(fpIns.GetBtcPk(), gomock.Any()). + Return(uint64(1), nil). + AnyTimes() // the last committed height is higher than the current height // to make sure the randomness is sufficient lastCommittedHeight := randomStartingHeight + testutil.TestPubRandNum @@ -46,16 +65,27 @@ func FuzzFastSync_SufficientRandomness(f *testing.F) { NumPubRand: 1000, Commitment: datagen.GenRandomByteArray(r, 32), } - mockConsumerController.EXPECT().QueryLastPublicRandCommit(gomock.Any()).Return(lastCommittedPubRand, nil).AnyTimes() + mockConsumerController.EXPECT(). + QueryLastPublicRandCommit(gomock.Any()). + Return(lastCommittedPubRand, nil). + AnyTimes() catchUpBlocks := testutil.GenBlocks(r, finalizedHeight+1, currentHeight) expectedTxHash := testutil.GenRandomHexStr(r, 32) - finalizedBlock := &types.BlockInfo{Height: finalizedHeight, Hash: testutil.GenRandomByteArray(r, 32)} - mockConsumerController.EXPECT().QueryLatestFinalizedBlock().Return(finalizedBlock, nil).AnyTimes() + finalizedBlock := &types.BlockInfo{ + Height: finalizedHeight, + Hash: testutil.GenRandomByteArray(r, 32), + } + mockConsumerController.EXPECT(). + QueryLatestFinalizedBlock(). + Return(finalizedBlock, nil). + AnyTimes() mockConsumerController.EXPECT().QueryBlocks(finalizedHeight+1, currentHeight, uint64(10)). Return(catchUpBlocks, nil) - mockConsumerController.EXPECT().SubmitBatchFinalitySigs(fpIns.GetBtcPk(), catchUpBlocks, gomock.Any(), gomock.Any(), gomock.Any()). - Return(&types.TxResponse{TxHash: expectedTxHash}, nil).AnyTimes() + mockConsumerController.EXPECT(). + SubmitBatchFinalitySigs(fpIns.GetBtcPk(), catchUpBlocks, gomock.Any(), gomock.Any(), gomock.Any()). + Return(&types.TxResponse{TxHash: expectedTxHash}, nil). + AnyTimes() result, err := fpIns.FastSync(finalizedHeight+1, currentHeight) require.NoError(t, err) require.NotNil(t, result) @@ -77,37 +107,69 @@ func FuzzFastSync_NoRandomness(f *testing.F) { randomStartingHeight := uint64(r.Int63n(100) + 100) finalizedHeight := randomStartingHeight + uint64(r.Int63n(10)+2) currentHeight := finalizedHeight + uint64(r.Int63n(10)+1) - mockConsumerController := testutil.PrepareMockedConsumerController(t, r, randomStartingHeight, currentHeight) + mockConsumerController := testutil.PrepareMockedConsumerController( + t, + r, + randomStartingHeight, + currentHeight, + ) mockBabylonController := testutil.PrepareMockedBabylonController(t) mockConsumerController.EXPECT().QueryLatestFinalizedBlock().Return(nil, nil).AnyTimes() - _, fpIns, cleanUp := startFinalityProviderAppWithRegisteredFp(t, r, mockBabylonController, mockConsumerController, randomStartingHeight) + _, fpIns, cleanUp := startFinalityProviderAppWithRegisteredFp( + t, + r, + mockBabylonController, + mockConsumerController, + randomStartingHeight, + ) defer cleanUp() // commit pub rand - mockConsumerController.EXPECT().QueryLastPublicRandCommit(gomock.Any()).Return(nil, nil).Times(1) - mockConsumerController.EXPECT().CommitPubRandList(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).Times(1) + mockConsumerController.EXPECT(). + QueryLastPublicRandCommit(gomock.Any()). + Return(nil, nil). + Times(1) + mockConsumerController.EXPECT(). + CommitPubRandList(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, nil). + Times(1) _, err := fpIns.CommitPubRand(randomStartingHeight) require.NoError(t, err) - mockConsumerController.EXPECT().QueryFinalityProviderVotingPower(fpIns.GetBtcPk(), gomock.Any()). - Return(uint64(1), nil).AnyTimes() + mockConsumerController.EXPECT(). + QueryFinalityProviderVotingPower(fpIns.GetBtcPk(), gomock.Any()). + Return(uint64(1), nil). + AnyTimes() // the last height with pub rand is a random value inside [finalizedHeight+1, currentHeight] - lastHeightWithPubRand := uint64(rand.Intn(int(currentHeight)-int(finalizedHeight))) + finalizedHeight + 1 + lastHeightWithPubRand := uint64( + rand.Intn(int(currentHeight)-int(finalizedHeight)), + ) + finalizedHeight + 1 lastCommittedPubRand := &types.PubRandCommit{ StartHeight: lastHeightWithPubRand - 10, NumPubRand: 10 + 1, Commitment: datagen.GenRandomByteArray(r, 32), } - mockConsumerController.EXPECT().QueryLastPublicRandCommit(gomock.Any()).Return(lastCommittedPubRand, nil).AnyTimes() + mockConsumerController.EXPECT(). + QueryLastPublicRandCommit(gomock.Any()). + Return(lastCommittedPubRand, nil). + AnyTimes() catchUpBlocks := testutil.GenBlocks(r, finalizedHeight+1, currentHeight) expectedTxHash := testutil.GenRandomHexStr(r, 32) - finalizedBlock := &types.BlockInfo{Height: finalizedHeight, Hash: testutil.GenRandomByteArray(r, 32)} - mockConsumerController.EXPECT().QueryLatestFinalizedBlock().Return(finalizedBlock, nil).AnyTimes() + finalizedBlock := &types.BlockInfo{ + Height: finalizedHeight, + Hash: testutil.GenRandomByteArray(r, 32), + } + mockConsumerController.EXPECT(). + QueryLatestFinalizedBlock(). + Return(finalizedBlock, nil). + AnyTimes() mockConsumerController.EXPECT().QueryBlocks(finalizedHeight+1, currentHeight, uint64(10)). Return(catchUpBlocks, nil) - mockConsumerController.EXPECT().SubmitBatchFinalitySigs(fpIns.GetBtcPk(), catchUpBlocks[:lastHeightWithPubRand-finalizedHeight], gomock.Any(), gomock.Any(), gomock.Any()). - Return(&types.TxResponse{TxHash: expectedTxHash}, nil).AnyTimes() + mockConsumerController.EXPECT(). + SubmitBatchFinalitySigs(fpIns.GetBtcPk(), catchUpBlocks[:lastHeightWithPubRand-finalizedHeight], gomock.Any(), gomock.Any(), gomock.Any()). + Return(&types.TxResponse{TxHash: expectedTxHash}, nil). + AnyTimes() result, err := fpIns.FastSync(finalizedHeight+1, currentHeight) require.NoError(t, err) require.NotNil(t, result) diff --git a/finality-provider/service/fp_instance.go b/finality-provider/service/fp_instance.go index 13603f42..71d3564b 100644 --- a/finality-provider/service/fp_instance.go +++ b/finality-provider/service/fp_instance.go @@ -75,7 +75,11 @@ func NewFinalityProviderInstance( ) (*FinalityProviderInstance, error) { sfp, err := s.GetFinalityProvider(fpPk.MustToBTCPK()) if err != nil { - return nil, fmt.Errorf("failed to retrive the finality-provider %s from DB: %w", fpPk.MarshalHex(), err) + return nil, fmt.Errorf( + "failed to retrive the finality-provider %s from DB: %w", + fpPk.MarshalHex(), + err, + ) } // ensure the finality-provider has been registered @@ -174,7 +178,10 @@ func (fp *FinalityProviderInstance) Stop() error { close(fp.quit) fp.wg.Wait() - fp.logger.Info("the finality-provider instance %s is successfully stopped", zap.String("pk", fp.GetBtcPkHex())) + fp.logger.Info( + "the finality-provider instance %s is successfully stopped", + zap.String("pk", fp.GetBtcPkHex()), + ) return nil } @@ -392,7 +399,11 @@ func (fp *FinalityProviderInstance) tryFastSync(targetBlockHeight uint64) (*Fast } if startHeight > targetBlockHeight { - return nil, fmt.Errorf("the start height %v should not be higher than the current block %v", startHeight, targetBlockHeight) + return nil, fmt.Errorf( + "the start height %v should not be higher than the current block %v", + startHeight, + targetBlockHeight, + ) } fp.logger.Debug("the finality-provider is entering fast sync") @@ -468,7 +479,9 @@ func (fp *FinalityProviderInstance) checkLagging(currentBlockHeight uint64) bool // finalized // error will be returned if maximum retries have been reached or the query to // the consumer chain fails -func (fp *FinalityProviderInstance) retryCheckRandomnessUntilBlockFinalized(targetBlock *types.BlockInfo) error { +func (fp *FinalityProviderInstance) retryCheckRandomnessUntilBlockFinalized( + targetBlock *types.BlockInfo, +) error { var failedCycles uint32 // we break the for loop if the block is finalized or the randomness is successfully committed @@ -502,7 +515,11 @@ func (fp *FinalityProviderInstance) retryCheckRandomnessUntilBlockFinalized(targ // periodically query the index block to be later checked whether it is Finalized finalized, err := fp.consumerCon.QueryIsBlockFinalized(targetBlock.Height) if err != nil { - return fmt.Errorf("failed to query block finalization at height %v: %w", targetBlock.Height, err) + return fmt.Errorf( + "failed to query block finalization at height %v: %w", + targetBlock.Height, + err, + ) } if finalized { fp.logger.Debug( @@ -516,7 +533,10 @@ func (fp *FinalityProviderInstance) retryCheckRandomnessUntilBlockFinalized(targ } case <-fp.quit: - fp.logger.Debug("the finality-provider instance is closing", zap.String("pk", fp.GetBtcPkHex())) + fp.logger.Debug( + "the finality-provider instance is closing", + zap.String("pk", fp.GetBtcPkHex()), + ) return nil } } @@ -524,7 +544,9 @@ func (fp *FinalityProviderInstance) retryCheckRandomnessUntilBlockFinalized(targ // 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 (fp *FinalityProviderInstance) 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 @@ -563,7 +585,11 @@ func (fp *FinalityProviderInstance) retrySubmitFinalitySignatureUntilBlockFinali // periodically query the index block to be later checked whether it is Finalized finalized, err := fp.consumerCon.QueryIsBlockFinalized(targetBlock.Height) if err != nil { - return nil, fmt.Errorf("failed to query block finalization at height %v: %w", targetBlock.Height, err) + return nil, fmt.Errorf( + "failed to query block finalization at height %v: %w", + targetBlock.Height, + err, + ) } if finalized { fp.logger.Debug( @@ -577,7 +603,10 @@ func (fp *FinalityProviderInstance) retrySubmitFinalitySignatureUntilBlockFinali } case <-fp.quit: - fp.logger.Debug("the finality-provider instance is closing", zap.String("pk", fp.GetBtcPkHex())) + fp.logger.Debug( + "the finality-provider instance is closing", + zap.String("pk", fp.GetBtcPkHex()), + ) return nil, nil } } @@ -585,7 +614,9 @@ func (fp *FinalityProviderInstance) retrySubmitFinalitySignatureUntilBlockFinali // 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 (fp *FinalityProviderInstance) retryCommitPubRandUntilBlockFinalized(targetBlockHeight uint64) (*types.TxResponse, error) { +func (fp *FinalityProviderInstance) retryCommitPubRandUntilBlockFinalized( + targetBlockHeight uint64, +) (*types.TxResponse, error) { var failedCycles uint32 // we break the for loop if the block is finalized or the public rand is successfully committed @@ -624,7 +655,11 @@ func (fp *FinalityProviderInstance) retryCommitPubRandUntilBlockFinalized(target // periodically query the index block to be later checked whether it is Finalized finalized, err := fp.consumerCon.QueryIsBlockFinalized(targetBlockHeight) if err != nil { - return nil, fmt.Errorf("failed to query block finalization at height %v: %w", targetBlockHeight, err) + return nil, fmt.Errorf( + "failed to query block finalization at height %v: %w", + targetBlockHeight, + err, + ) } if finalized { fp.logger.Debug( @@ -638,7 +673,10 @@ func (fp *FinalityProviderInstance) retryCommitPubRandUntilBlockFinalized(target } case <-fp.quit: - fp.logger.Debug("the finality-provider instance is closing", zap.String("pk", fp.GetBtcPkHex())) + fp.logger.Debug( + "the finality-provider instance is closing", + zap.String("pk", fp.GetBtcPkHex()), + ) return nil, nil } } @@ -695,7 +733,13 @@ func (fp *FinalityProviderInstance) CommitPubRand(tipHeight uint64) (*types.TxRe return nil, fmt.Errorf("failed to sign the Schnorr signature: %w", err) } - res, err := fp.consumerCon.CommitPubRandList(fp.GetBtcPk(), startHeight, numPubRand, commitment, schnorrSig) + res, err := fp.consumerCon.CommitPubRandList( + fp.GetBtcPk(), + startHeight, + numPubRand, + commitment, + schnorrSig, + ) if err != nil { return nil, fmt.Errorf("failed to commit public randomness to the consumer chain: %w", err) } @@ -709,7 +753,9 @@ func (fp *FinalityProviderInstance) CommitPubRand(tipHeight uint64) (*types.TxRe } // SubmitFinalitySignature builds and sends a finality signature over the given block to the consumer chain -func (fp *FinalityProviderInstance) SubmitFinalitySignature(b *types.BlockInfo) (*types.TxResponse, error) { +func (fp *FinalityProviderInstance) SubmitFinalitySignature( + b *types.BlockInfo, +) (*types.TxResponse, error) { sig, err := fp.SignFinalitySig(b) if err != nil { return nil, err @@ -729,7 +775,13 @@ func (fp *FinalityProviderInstance) SubmitFinalitySignature(b *types.BlockInfo) } // send finality signature to the consumer chain - res, err := fp.consumerCon.SubmitFinalitySig(fp.GetBtcPk(), b, pubRand, proofBytes, sig.ToModNScalar()) + res, err := fp.consumerCon.SubmitFinalitySig( + fp.GetBtcPk(), + b, + pubRand, + proofBytes, + sig.ToModNScalar(), + ) if err != nil { return nil, fmt.Errorf("failed to send finality signature to the consumer chain: %w", err) } @@ -746,7 +798,9 @@ func (fp *FinalityProviderInstance) SubmitFinalitySignature(b *types.BlockInfo) // 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 (fp *FinalityProviderInstance) 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") } @@ -774,9 +828,18 @@ func (fp *FinalityProviderInstance) SubmitBatchFinalitySignatures(blocks []*type } // send finality signature to the consumer chain - res, err := fp.consumerCon.SubmitBatchFinalitySigs(fp.GetBtcPk(), blocks, prList, proofBytesList, sigList) + res, err := fp.consumerCon.SubmitBatchFinalitySigs( + fp.GetBtcPk(), + blocks, + prList, + proofBytesList, + sigList, + ) if err != nil { - return nil, fmt.Errorf("failed to send a batch of finality signatures to the consumer chain: %w", err) + return nil, fmt.Errorf( + "failed to send a batch of finality signatures to the consumer chain: %w", + err, + ) } // update DB @@ -789,15 +852,20 @@ func (fp *FinalityProviderInstance) SubmitBatchFinalitySignatures(blocks []*type // 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 (fp *FinalityProviderInstance) 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 lastCommittedHeight, err := fp.GetLastCommittedHeight() if err != nil { return nil, nil, err } if lastCommittedHeight < b.Height { - return nil, nil, fmt.Errorf("the finality-provider's last committed height %v is lower than the current block height %v", - lastCommittedHeight, b.Height) + return nil, nil, fmt.Errorf( + "the finality-provider's last committed height %v is lower than the current block height %v", + lastCommittedHeight, + b.Height, + ) } // get public randomness @@ -820,9 +888,18 @@ func (fp *FinalityProviderInstance) TestSubmitFinalitySignatureAndExtractPrivKey } // send finality signature to the consumer chain - res, err := fp.consumerCon.SubmitFinalitySig(fp.GetBtcPk(), b, pubRand, proofBytes, eotsSig.ToModNScalar()) + res, err := fp.consumerCon.SubmitFinalitySig( + fp.GetBtcPk(), + b, + pubRand, + proofBytes, + eotsSig.ToModNScalar(), + ) if err != nil { - return nil, nil, fmt.Errorf("failed to send finality signature to the consumer chain: %w", err) + return nil, nil, fmt.Errorf( + "failed to send finality signature to the consumer chain: %w", + err, + ) } // try to extract the private key @@ -837,7 +914,10 @@ func (fp *FinalityProviderInstance) TestSubmitFinalitySignatureAndExtractPrivKey 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()) + return nil, nil, fmt.Errorf( + "failed to decode evidence bytes to evidence: %s", + err.Error(), + ) } privKey, err = evidence.ExtractBTCSK() if err != nil { diff --git a/finality-provider/service/fp_instance_test.go b/finality-provider/service/fp_instance_test.go index d45eed91..8071e734 100644 --- a/finality-provider/service/fp_instance_test.go +++ b/finality-provider/service/fp_instance_test.go @@ -29,19 +29,38 @@ func FuzzCommitPubRandList(f *testing.F) { randomStartingHeight := uint64(r.Int63n(100) + 1) currentHeight := randomStartingHeight + uint64(r.Int63n(10)+2) - startingBlock := &types.BlockInfo{Height: randomStartingHeight, Hash: testutil.GenRandomByteArray(r, 32)} + startingBlock := &types.BlockInfo{ + Height: randomStartingHeight, + Hash: testutil.GenRandomByteArray(r, 32), + } mockBabylonController := testutil.PrepareMockedBabylonController(t) - mockConsumerController := testutil.PrepareMockedConsumerController(t, r, randomStartingHeight, currentHeight) - mockConsumerController.EXPECT().QueryFinalityProviderVotingPower(gomock.Any(), gomock.Any()). - Return(uint64(0), nil).AnyTimes() - _, fpIns, cleanUp := startFinalityProviderAppWithRegisteredFp(t, r, mockBabylonController, mockConsumerController, randomStartingHeight) + mockConsumerController := testutil.PrepareMockedConsumerController( + t, + r, + randomStartingHeight, + currentHeight, + ) + mockConsumerController.EXPECT(). + QueryFinalityProviderVotingPower(gomock.Any(), gomock.Any()). + Return(uint64(0), nil). + AnyTimes() + _, fpIns, cleanUp := startFinalityProviderAppWithRegisteredFp( + t, + r, + mockBabylonController, + mockConsumerController, + randomStartingHeight, + ) defer cleanUp() expectedTxHash := testutil.GenRandomHexStr(r, 32) mockConsumerController.EXPECT(). CommitPubRandList(fpIns.GetBtcPk(), startingBlock.Height+1, gomock.Any(), gomock.Any(), gomock.Any()). Return(&types.TxResponse{TxHash: expectedTxHash}, nil).AnyTimes() - mockConsumerController.EXPECT().QueryLastPublicRandCommit(gomock.Any()).Return(nil, nil).AnyTimes() + mockConsumerController.EXPECT(). + QueryLastPublicRandCommit(gomock.Any()). + Return(nil, nil). + AnyTimes() res, err := fpIns.CommitPubRand(startingBlock.Height) require.NoError(t, err) require.Equal(t, expectedTxHash, res.TxHash) @@ -55,17 +74,37 @@ func FuzzSubmitFinalitySig(f *testing.F) { randomStartingHeight := uint64(r.Int63n(100) + 1) currentHeight := randomStartingHeight + uint64(r.Int63n(10)+1) - startingBlock := &types.BlockInfo{Height: randomStartingHeight, Hash: testutil.GenRandomByteArray(r, 32)} - mockConsumerController := testutil.PrepareMockedConsumerController(t, r, randomStartingHeight, currentHeight) + startingBlock := &types.BlockInfo{ + Height: randomStartingHeight, + Hash: testutil.GenRandomByteArray(r, 32), + } + mockConsumerController := testutil.PrepareMockedConsumerController( + t, + r, + randomStartingHeight, + currentHeight, + ) mockBabylonController := testutil.PrepareMockedBabylonController(t) mockConsumerController.EXPECT().QueryLatestFinalizedBlock().Return(nil, nil).AnyTimes() - _, fpIns, cleanUp := startFinalityProviderAppWithRegisteredFp(t, r, mockBabylonController, mockConsumerController, randomStartingHeight) + _, fpIns, cleanUp := startFinalityProviderAppWithRegisteredFp( + t, + r, + mockBabylonController, + mockConsumerController, + randomStartingHeight, + ) defer cleanUp() // commit pub rand - mockConsumerController.EXPECT().QueryLastPublicRandCommit(gomock.Any()).Return(nil, nil).Times(1) - mockConsumerController.EXPECT().CommitPubRandList(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).Times(1) + mockConsumerController.EXPECT(). + QueryLastPublicRandCommit(gomock.Any()). + Return(nil, nil). + Times(1) + mockConsumerController.EXPECT(). + CommitPubRandList(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(nil, nil). + Times(1) _, err := fpIns.CommitPubRand(startingBlock.Height) require.NoError(t, err) @@ -76,10 +115,15 @@ func FuzzSubmitFinalitySig(f *testing.F) { NumPubRand: 1000, Commitment: datagen.GenRandomByteArray(r, 32), } - mockConsumerController.EXPECT().QueryLastPublicRandCommit(gomock.Any()).Return(lastCommittedPubRand, nil).AnyTimes() + mockConsumerController.EXPECT(). + QueryLastPublicRandCommit(gomock.Any()). + Return(lastCommittedPubRand, nil). + AnyTimes() // mock voting power and commit pub rand - mockConsumerController.EXPECT().QueryFinalityProviderVotingPower(fpIns.GetBtcPk(), gomock.Any()). - Return(uint64(1), nil).AnyTimes() + mockConsumerController.EXPECT(). + QueryFinalityProviderVotingPower(fpIns.GetBtcPk(), gomock.Any()). + Return(uint64(1), nil). + AnyTimes() // submit finality sig nextBlock := &types.BlockInfo{ @@ -100,7 +144,13 @@ func FuzzSubmitFinalitySig(f *testing.F) { }) } -func startFinalityProviderAppWithRegisteredFp(t *testing.T, r *rand.Rand, cc ccapi.ClientController, consumerCon ccapi.ConsumerController, startingHeight uint64) (*service.FinalityProviderApp, *service.FinalityProviderInstance, func()) { +func startFinalityProviderAppWithRegisteredFp( + t *testing.T, + r *rand.Rand, + cc ccapi.ClientController, + consumerCon ccapi.ConsumerController, + startingHeight uint64, +) (*service.FinalityProviderApp, *service.FinalityProviderInstance, func()) { logger := zap.NewNop() // create an EOTS manager eotsHomeDir := filepath.Join(t.TempDir(), "eots-home") @@ -133,7 +183,19 @@ func startFinalityProviderAppWithRegisteredFp(t *testing.T, r *rand.Rand, cc cca require.NoError(t, err) // TODO: use mock metrics m := metrics.NewFpMetrics() - fpIns, err := service.NewFinalityProviderInstance(fp.GetBIP340BTCPK(), &fpCfg, app.GetFinalityProviderStore(), pubRandProofStore, cc, consumerCon, em, m, passphrase, make(chan *service.CriticalError), logger) + fpIns, err := service.NewFinalityProviderInstance( + fp.GetBIP340BTCPK(), + &fpCfg, + app.GetFinalityProviderStore(), + pubRandProofStore, + cc, + consumerCon, + em, + m, + passphrase, + make(chan *service.CriticalError), + logger, + ) require.NoError(t, err) cleanUp := func() { diff --git a/finality-provider/service/fp_manager.go b/finality-provider/service/fp_manager.go index 6e339070..3ff656ee 100644 --- a/finality-provider/service/fp_manager.go +++ b/finality-provider/service/fp_manager.go @@ -28,7 +28,11 @@ type CriticalError struct { } func (ce *CriticalError) Error() string { - return fmt.Sprintf("critical err on finality-provider %s: %s", ce.fpBtcPk.MarshalHex(), ce.err.Error()) + return fmt.Sprintf( + "critical err on finality-provider %s: %s", + ce.fpBtcPk.MarshalHex(), + ce.err.Error(), + ) } type FinalityProviderManager struct { @@ -101,7 +105,10 @@ func (fpm *FinalityProviderManager) monitorCriticalErr() { } // cannot use error.Is because the unwrapped error // is not the expected error type - if strings.Contains(criticalErr.err.Error(), btcstakingtypes.ErrFpAlreadySlashed.Error()) { + if strings.Contains( + criticalErr.err.Error(), + btcstakingtypes.ErrFpAlreadySlashed.Error(), + ) { fpm.setFinalityProviderSlashed(fpi) fpm.logger.Debug("the finality-provider has been slashed", zap.String("pk", criticalErr.fpBtcPk.MarshalHex())) @@ -205,11 +212,20 @@ func (fpm *FinalityProviderManager) monitorStatusUpdate() { 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)) + 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 { +func (fpm *FinalityProviderManager) StartFinalityProvider( + fpPk *bbntypes.BIP340PubKey, + passphrase string, +) error { if !fpm.isStarted.Load() { fpm.isStarted.Store(true) @@ -221,7 +237,10 @@ func (fpm *FinalityProviderManager) StartFinalityProvider(fpPk *bbntypes.BIP340P } if fpm.numOfRunningFinalityProviders() >= int(fpm.config.MaxNumFinalityProviders) { - return fmt.Errorf("reaching maximum number of running finality providers %v", 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 { @@ -248,7 +267,8 @@ func (fpm *FinalityProviderManager) StartAll() error { } for _, fp := range storedFps { - if fp.Status == proto.FinalityProviderStatus_CREATED || fp.Status == proto.FinalityProviderStatus_SLASHED { + if fp.Status == proto.FinalityProviderStatus_CREATED || + fp.Status == proto.FinalityProviderStatus_SLASHED { fpm.logger.Info("the finality provider cannot be started with status", zap.String("btc-pk", fp.GetBIP340BTCPK().MarshalHex()), zap.String("status", fp.Status.String())) @@ -298,7 +318,9 @@ func (fpm *FinalityProviderManager) ListFinalityProviderInstances() []*FinalityP return fpisList } -func (fpm *FinalityProviderManager) ListFinalityProviderInstancesForChain(chainID string) []*FinalityProviderInstance { +func (fpm *FinalityProviderManager) ListFinalityProviderInstancesForChain( + chainID string, +) []*FinalityProviderInstance { fpm.mu.Lock() defer fpm.mu.Unlock() @@ -332,7 +354,9 @@ func (fpm *FinalityProviderManager) AllFinalityProviders() ([]*proto.FinalityPro return fpsInfo, nil } -func (fpm *FinalityProviderManager) FinalityProviderInfo(fpPk *bbntypes.BIP340PubKey) (*proto.FinalityProviderInfo, error) { +func (fpm *FinalityProviderManager) FinalityProviderInfo( + fpPk *bbntypes.BIP340PubKey, +) (*proto.FinalityProviderInfo, error) { storedFp, err := fpm.fps.GetFinalityProvider(fpPk.MustToBTCPK()) if err != nil { return nil, err @@ -355,7 +379,9 @@ func (fpm *FinalityProviderManager) IsFinalityProviderRunning(fpPk *bbntypes.BIP return exists } -func (fpm *FinalityProviderManager) GetFinalityProviderInstance(fpPk *bbntypes.BIP340PubKey) (*FinalityProviderInstance, error) { +func (fpm *FinalityProviderManager) GetFinalityProviderInstance( + fpPk *bbntypes.BIP340PubKey, +) (*FinalityProviderInstance, error) { fpm.mu.Lock() defer fpm.mu.Unlock() @@ -368,7 +394,9 @@ func (fpm *FinalityProviderManager) GetFinalityProviderInstance(fpPk *bbntypes.B return v, nil } -func (fpm *FinalityProviderManager) removeFinalityProviderInstance(fpPk *bbntypes.BIP340PubKey) error { +func (fpm *FinalityProviderManager) removeFinalityProviderInstance( + fpPk *bbntypes.BIP340PubKey, +) error { fpm.mu.Lock() defer fpm.mu.Unlock() @@ -408,7 +436,19 @@ func (fpm *FinalityProviderManager) addFinalityProviderInstance( return fmt.Errorf("finality-provider instance already exists") } - fpIns, err := NewFinalityProviderInstance(pk, fpm.config, fpm.fps, fpm.pubRandStore, fpm.cc, fpm.consumerCon, fpm.em, fpm.metrics, passphrase, fpm.criticalErrChan, fpm.logger) + fpIns, err := NewFinalityProviderInstance( + pk, + fpm.config, + fpm.fps, + fpm.pubRandStore, + fpm.cc, + fpm.consumerCon, + fpm.em, + fpm.metrics, + passphrase, + fpm.criticalErrChan, + fpm.logger, + ) if err != nil { return fmt.Errorf("failed to create finality-provider %s instance: %w", pkHex, err) } diff --git a/finality-provider/service/fp_manager_test.go b/finality-provider/service/fp_manager_test.go index a3015811..42f5d930 100644 --- a/finality-provider/service/fp_manager_test.go +++ b/finality-provider/service/fp_manager_test.go @@ -43,7 +43,12 @@ func FuzzStatusUpdate(f *testing.F) { ctl := gomock.NewController(t) mockClientController := testutil.PrepareMockedBabylonController(t) mockConsumerController := mocks.NewMockConsumerController(ctl) - vm, fpPk, cleanUp := newFinalityProviderManagerWithRegisteredFp(t, r, mockClientController, mockConsumerController) + vm, fpPk, cleanUp := newFinalityProviderManagerWithRegisteredFp( + t, + r, + mockClientController, + mockConsumerController, + ) defer cleanUp() // setup mocks @@ -54,17 +59,35 @@ func FuzzStatusUpdate(f *testing.F) { } mockConsumerController.EXPECT().Close().Return(nil).AnyTimes() mockConsumerController.EXPECT().QueryLatestFinalizedBlock().Return(nil, nil).AnyTimes() - mockConsumerController.EXPECT().QueryLatestBlockHeight().Return(currentHeight, nil).AnyTimes() + mockConsumerController.EXPECT(). + QueryLatestBlockHeight(). + Return(currentHeight, nil). + AnyTimes() mockConsumerController.EXPECT().QueryActivatedHeight().Return(uint64(1), nil).AnyTimes() - mockConsumerController.EXPECT().QueryBlock(gomock.Any()).Return(currentBlockRes, nil).AnyTimes() - mockConsumerController.EXPECT().QueryLastPublicRandCommit(gomock.Any()).Return(nil, nil).AnyTimes() + mockConsumerController.EXPECT(). + QueryBlock(gomock.Any()). + Return(currentBlockRes, nil). + AnyTimes() + mockConsumerController.EXPECT(). + QueryLastPublicRandCommit(gomock.Any()). + Return(nil, nil). + AnyTimes() votingPower := uint64(r.Intn(2)) - mockConsumerController.EXPECT().QueryFinalityProviderVotingPower(gomock.Any(), currentHeight).Return(votingPower, nil).AnyTimes() - mockConsumerController.EXPECT().SubmitFinalitySig(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&types.TxResponse{TxHash: ""}, nil).AnyTimes() + mockConsumerController.EXPECT(). + QueryFinalityProviderVotingPower(gomock.Any(), currentHeight). + Return(votingPower, nil). + AnyTimes() + mockConsumerController.EXPECT(). + SubmitFinalitySig(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + Return(&types.TxResponse{TxHash: ""}, nil). + AnyTimes() var slashedHeight uint64 if votingPower == 0 { - mockClientController.EXPECT().QueryFinalityProviderSlashed(gomock.Any()).Return(true, nil).AnyTimes() + mockClientController.EXPECT(). + QueryFinalityProviderSlashed(gomock.Any()). + Return(true, nil). + AnyTimes() } err := vm.StartFinalityProvider(fpPk, passphrase) @@ -86,14 +109,23 @@ func FuzzStatusUpdate(f *testing.F) { }) } -func waitForStatus(t *testing.T, fpIns *service.FinalityProviderInstance, s proto.FinalityProviderStatus) { +func waitForStatus( + t *testing.T, + fpIns *service.FinalityProviderInstance, + s proto.FinalityProviderStatus, +) { require.Eventually(t, func() bool { return fpIns.GetStatus() == s }, EventuallyWaitTimeOut, EventuallyPollTime) } -func newFinalityProviderManagerWithRegisteredFp(t *testing.T, r *rand.Rand, cc ccapi.ClientController, consumerCon ccapi.ConsumerController) (*service.FinalityProviderManager, *bbntypes.BIP340PubKey, func()) { +func newFinalityProviderManagerWithRegisteredFp( + t *testing.T, + r *rand.Rand, + cc ccapi.ClientController, + consumerCon ccapi.ConsumerController, +) (*service.FinalityProviderManager, *bbntypes.BIP340PubKey, func()) { logger := zap.NewNop() // create an EOTS manager eotsHomeDir := filepath.Join(t.TempDir(), "eots-home") @@ -125,7 +157,16 @@ func newFinalityProviderManagerWithRegisteredFp(t *testing.T, r *rand.Rand, cc c require.NoError(t, err) metricsCollectors := metrics.NewFpMetrics() - vm, err := service.NewFinalityProviderManager(fpStore, pubRandStore, &fpCfg, cc, consumerCon, em, metricsCollectors, logger) + vm, err := service.NewFinalityProviderManager( + fpStore, + pubRandStore, + &fpCfg, + cc, + consumerCon, + em, + metricsCollectors, + logger, + ) require.NoError(t, err) // create registered finality-provider diff --git a/finality-provider/service/rpcserver.go b/finality-provider/service/rpcserver.go index 877a9dd2..f7910b54 100644 --- a/finality-provider/service/rpcserver.go +++ b/finality-provider/service/rpcserver.go @@ -74,7 +74,10 @@ func (r *rpcServer) RegisterWithGrpcServer(grpcServer *grpc.Server) error { } // GetInfo returns general information relating to the active daemon -func (r *rpcServer) GetInfo(context.Context, *proto.GetInfoRequest) (*proto.GetInfoResponse, error) { +func (r *rpcServer) GetInfo( + context.Context, + *proto.GetInfoRequest, +) (*proto.GetInfoResponse, error) { return &proto.GetInfoResponse{ Version: version.Version(), @@ -82,7 +85,10 @@ func (r *rpcServer) GetInfo(context.Context, *proto.GetInfoRequest) (*proto.GetI } // CreateFinalityProvider generates a finality-provider object and saves it in the database -func (r *rpcServer) CreateFinalityProvider(ctx context.Context, req *proto.CreateFinalityProviderRequest) ( +func (r *rpcServer) CreateFinalityProvider( + ctx context.Context, + req *proto.CreateFinalityProviderRequest, +) ( *proto.CreateFinalityProviderResponse, error) { commissionRate, err := math.LegacyNewDecFromStr(req.Commission) @@ -115,7 +121,10 @@ func (r *rpcServer) CreateFinalityProvider(ctx context.Context, req *proto.Creat } // RegisterFinalityProvider sends a transactions to Babylon to register a BTC finality-provider -func (r *rpcServer) RegisterFinalityProvider(ctx context.Context, req *proto.RegisterFinalityProviderRequest) ( +func (r *rpcServer) RegisterFinalityProvider( + ctx context.Context, + req *proto.RegisterFinalityProviderRequest, +) ( *proto.RegisterFinalityProviderResponse, error) { txRes, err := r.app.RegisterFinalityProvider(req.BtcPk) @@ -125,7 +134,11 @@ func (r *rpcServer) RegisterFinalityProvider(ctx context.Context, req *proto.Reg // 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 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 @@ -133,7 +146,10 @@ func (r *rpcServer) RegisterFinalityProvider(ctx context.Context, req *proto.Reg // 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) ( +func (r *rpcServer) AddFinalitySignature( + ctx context.Context, + req *proto.AddFinalitySignatureRequest, +) ( *proto.AddFinalitySignatureResponse, error) { fpPk, err := bbntypes.NewBIP340PubKeyFromHex(req.BtcPk) @@ -183,7 +199,10 @@ func (r *rpcServer) AddFinalitySignature(ctx context.Context, req *proto.AddFina } // QueryFinalityProvider queries the information of the finality-provider -func (r *rpcServer) QueryFinalityProvider(ctx context.Context, req *proto.QueryFinalityProviderRequest) ( +func (r *rpcServer) QueryFinalityProvider( + ctx context.Context, + req *proto.QueryFinalityProviderRequest, +) ( *proto.QueryFinalityProviderResponse, error) { fpPk, err := bbntypes.NewBIP340PubKeyFromHex(req.BtcPk) @@ -199,7 +218,10 @@ func (r *rpcServer) QueryFinalityProvider(ctx context.Context, req *proto.QueryF } // QueryFinalityProviderList queries the information of a list of finality providers -func (r *rpcServer) QueryFinalityProviderList(ctx context.Context, req *proto.QueryFinalityProviderListRequest) ( +func (r *rpcServer) QueryFinalityProviderList( + ctx context.Context, + req *proto.QueryFinalityProviderListRequest, +) ( *proto.QueryFinalityProviderListResponse, error) { fps, err := r.app.ListAllFinalityProvidersInfo() @@ -211,7 +233,10 @@ func (r *rpcServer) QueryFinalityProviderList(ctx context.Context, req *proto.Qu } // SignMessageFromChainKey signs a message from the chain keyring. -func (r *rpcServer) SignMessageFromChainKey(ctx context.Context, req *proto.SignMessageFromChainKeyRequest) ( +func (r *rpcServer) SignMessageFromChainKey( + ctx context.Context, + req *proto.SignMessageFromChainKeyRequest, +) ( *proto.SignMessageFromChainKeyResponse, error) { signature, err := r.app.SignRawMsg(req.KeyName, req.Passphrase, req.HdPath, req.MsgToSign) if err != nil { diff --git a/finality-provider/service/server.go b/finality-provider/service/server.go index 94050b81..4579a503 100644 --- a/finality-provider/service/server.go +++ b/finality-provider/service/server.go @@ -33,7 +33,13 @@ type Server struct { } // NewFinalityproviderServer creates a new server with the given config. -func NewFinalityProviderServer(cfg *fpcfg.Config, l *zap.Logger, fpa *FinalityProviderApp, db kvdb.Backend, sig signal.Interceptor) *Server { +func NewFinalityProviderServer( + cfg *fpcfg.Config, + l *zap.Logger, + fpa *FinalityProviderApp, + db kvdb.Backend, + sig signal.Interceptor, +) *Server { return &Server{ cfg: cfg, logger: l, diff --git a/finality-provider/store/fpstore.go b/finality-provider/store/fpstore.go index ea0d7cca..7b4367fd 100644 --- a/finality-provider/store/fpstore.go +++ b/finality-provider/store/fpstore.go @@ -104,7 +104,10 @@ func saveFinalityProvider( return fpBucket.Put(fp.BtcPk, marshalled) } -func (s *FinalityProviderStore) SetFpStatus(btcPk *btcec.PublicKey, status proto.FinalityProviderStatus) error { +func (s *FinalityProviderStore) SetFpStatus( + btcPk *btcec.PublicKey, + status proto.FinalityProviderStatus, +) error { setFpStatus := func(fp *proto.FinalityProvider) error { fp.Status = status return nil @@ -115,7 +118,10 @@ func (s *FinalityProviderStore) SetFpStatus(btcPk *btcec.PublicKey, status proto // SetFpLastVotedHeight sets the last voted height to the stored last voted height and last processed height // only if it is larger than the stored one. This is to ensure the stored state to increase monotonically -func (s *FinalityProviderStore) SetFpLastVotedHeight(btcPk *btcec.PublicKey, lastVotedHeight uint64) error { +func (s *FinalityProviderStore) SetFpLastVotedHeight( + btcPk *btcec.PublicKey, + lastVotedHeight uint64, +) error { setFpLastVotedHeight := func(fp *proto.FinalityProvider) error { if fp.LastVotedHeight < lastVotedHeight { fp.LastVotedHeight = lastVotedHeight @@ -132,7 +138,10 @@ func (s *FinalityProviderStore) SetFpLastVotedHeight(btcPk *btcec.PublicKey, las // SetFpLastProcessedHeight sets the last processed height to the stored last processed height // only if it is larger than the stored one. This is to ensure the stored state to increase monotonically -func (s *FinalityProviderStore) SetFpLastProcessedHeight(btcPk *btcec.PublicKey, lastProcessedHeight uint64) error { +func (s *FinalityProviderStore) SetFpLastProcessedHeight( + btcPk *btcec.PublicKey, + lastProcessedHeight uint64, +) error { setFpLastProcessedHeight := func(fp *proto.FinalityProvider) error { if fp.LastProcessedHeight < lastProcessedHeight { fp.LastProcessedHeight = lastProcessedHeight @@ -173,7 +182,9 @@ func (s *FinalityProviderStore) setFinalityProviderState( }) } -func (s *FinalityProviderStore) GetFinalityProvider(btcPk *btcec.PublicKey) (*StoredFinalityProvider, error) { +func (s *FinalityProviderStore) GetFinalityProvider( + btcPk *btcec.PublicKey, +) (*StoredFinalityProvider, error) { var storedFp *StoredFinalityProvider pkBytes := schnorr.SerializePubKey(btcPk) diff --git a/itest/babylon/babylon_e2e_test.go b/itest/babylon/babylon_e2e_test.go index 4a6a39fa..54c1f107 100644 --- a/itest/babylon/babylon_e2e_test.go +++ b/itest/babylon/babylon_e2e_test.go @@ -31,7 +31,12 @@ func TestFinalityProviderLifeCycle(t *testing.T) { e2eutils.WaitForFpPubRandCommitted(t, fpIns, 1) // send a BTC delegation - _ = tm.InsertBTCDelegation(t, []*btcec.PublicKey{fpIns.GetBtcPk()}, e2eutils.StakingTime, e2eutils.StakingAmount) + _ = tm.InsertBTCDelegation( + t, + []*btcec.PublicKey{fpIns.GetBtcPk()}, + e2eutils.StakingTime, + e2eutils.StakingAmount, + ) // check the BTC delegation is pending delsResp := tm.WaitForNPendingDels(t, 1) @@ -63,7 +68,12 @@ func TestDoubleSigning(t *testing.T) { e2eutils.WaitForFpPubRandCommitted(t, fpIns, 1) // send a BTC delegation - _ = tm.InsertBTCDelegation(t, []*btcec.PublicKey{fpIns.GetBtcPk()}, e2eutils.StakingTime, e2eutils.StakingAmount) + _ = tm.InsertBTCDelegation( + t, + []*btcec.PublicKey{fpIns.GetBtcPk()}, + e2eutils.StakingTime, + e2eutils.StakingAmount, + ) // check the BTC delegation is pending delsResp := tm.WaitForNPendingDels(t, 1) @@ -94,7 +104,10 @@ func TestDoubleSigning(t *testing.T) { require.NoError(t, err) require.NotNil(t, extractedKey) localKey := tm.GetFpPrivKey(t, fpIns.GetBtcPkBIP340().MustMarshal()) - require.True(t, localKey.Key.Equals(&extractedKey.Key) || localKey.Key.Negate().Equals(&extractedKey.Key)) + require.True( + t, + localKey.Key.Equals(&extractedKey.Key) || localKey.Key.Negate().Equals(&extractedKey.Key), + ) t.Logf("the equivocation attack is successful") @@ -121,7 +134,12 @@ func TestMultipleFinalityProviders(t *testing.T) { // check the public randomness is committed e2eutils.WaitForFpPubRandCommitted(t, fpi, 1) // send a BTC delegation - _ = tm.InsertBTCDelegation(t, []*btcec.PublicKey{fpi.GetBtcPk()}, e2eutils.StakingTime, e2eutils.StakingAmount) + _ = tm.InsertBTCDelegation( + t, + []*btcec.PublicKey{fpi.GetBtcPk()}, + e2eutils.StakingTime, + e2eutils.StakingAmount, + ) } // check the BTC delegations are pending @@ -154,7 +172,12 @@ func TestFastSync(t *testing.T) { e2eutils.WaitForFpPubRandCommitted(t, fpIns, 1) // send a BTC delegation - _ = tm.InsertBTCDelegation(t, []*btcec.PublicKey{fpIns.GetBtcPk()}, e2eutils.StakingTime, e2eutils.StakingAmount) + _ = tm.InsertBTCDelegation( + t, + []*btcec.PublicKey{fpIns.GetBtcPk()}, + e2eutils.StakingTime, + e2eutils.StakingAmount, + ) // check the BTC delegation is pending delsResp := tm.WaitForNPendingDels(t, 1) diff --git a/itest/babylon/babylon_test_manager.go b/itest/babylon/babylon_test_manager.go index 62561037..e08649b5 100644 --- a/itest/babylon/babylon_test_manager.go +++ b/itest/babylon/babylon_test_manager.go @@ -113,7 +113,10 @@ func (tm *TestManager) WaitForServicesStart(t *testing.T) { t.Logf("Babylon node is started") } -func StartManagerWithFinalityProvider(t *testing.T, n int) (*TestManager, []*service.FinalityProviderInstance) { +func StartManagerWithFinalityProvider( + t *testing.T, + n int, +) (*TestManager, []*service.FinalityProviderInstance) { tm := StartManager(t) app := tm.Fpa @@ -123,9 +126,24 @@ func StartManagerWithFinalityProvider(t *testing.T, n int) (*TestManager, []*ser commission := sdkmath.LegacyZeroDec() desc := e2eutils.NewDescription(moniker) cfg := app.GetConfig() - _, err := service.CreateChainKey(cfg.BabylonConfig.KeyDirectory, cfg.BabylonConfig.ChainID, fpName, keyring.BackendTest, e2eutils.Passphrase, e2eutils.HdPath, "") + _, err := service.CreateChainKey( + cfg.BabylonConfig.KeyDirectory, + cfg.BabylonConfig.ChainID, + fpName, + keyring.BackendTest, + e2eutils.Passphrase, + e2eutils.HdPath, + "", + ) require.NoError(t, err) - res, err := app.CreateFinalityProvider(fpName, e2eutils.ChainID, e2eutils.Passphrase, e2eutils.HdPath, desc, &commission) + res, err := app.CreateFinalityProvider( + fpName, + e2eutils.ChainID, + e2eutils.Passphrase, + e2eutils.HdPath, + desc, + &commission, + ) require.NoError(t, err) fpPk, err := bbntypes.NewBIP340PubKeyFromHex(res.FpInfo.BtcPkHex) require.NoError(t, err) @@ -215,7 +233,10 @@ func (tm *TestManager) CheckBlockFinalization(t *testing.T, height uint64, num i }, e2eutils.EventuallyWaitTimeOut, e2eutils.EventuallyPollTime) } -func (tm *TestManager) WaitForFpVoteCast(t *testing.T, fpIns *service.FinalityProviderInstance) uint64 { +func (tm *TestManager) WaitForFpVoteCast( + t *testing.T, + fpIns *service.FinalityProviderInstance, +) uint64 { var lastVotedHeight uint64 require.Eventually(t, func() bool { if fpIns.GetLastVotedHeight() > 0 { @@ -265,7 +286,11 @@ func (tm *TestManager) WaitForFpShutDown(t *testing.T, pk *bbntypes.BIP340PubKey t.Logf("the finality-provider instance %s is shutdown", pk.MarshalHex()) } -func (tm *TestManager) StopAndRestartFpAfterNBlocks(t *testing.T, n uint, fpIns *service.FinalityProviderInstance) { +func (tm *TestManager) StopAndRestartFpAfterNBlocks( + t *testing.T, + n uint, + fpIns *service.FinalityProviderInstance, +) { blockBeforeStopHeight, err := tm.BBNConsumerClient.QueryLatestBlockHeight() require.NoError(t, err) err = fpIns.Stop() diff --git a/itest/babylon_node_handler.go b/itest/babylon_node_handler.go index 76e520d3..a6d3a80c 100644 --- a/itest/babylon_node_handler.go +++ b/itest/babylon_node_handler.go @@ -102,7 +102,11 @@ type BabylonNodeHandler struct { babylonNode *babylonNode } -func NewBabylonNodeHandler(t *testing.T, covenantQuorum int, covenantPks []*types.BIP340PubKey) *BabylonNodeHandler { +func NewBabylonNodeHandler( + t *testing.T, + covenantQuorum int, + covenantPks []*types.BIP340PubKey, +) *BabylonNodeHandler { testDir, err := BaseDir("zBabylonTest") require.NoError(t, err) defer func() { diff --git a/itest/cosmwasm/bcd/bcd_consumer_e2e_test.go b/itest/cosmwasm/bcd/bcd_consumer_e2e_test.go index 295fcc44..a7d0734d 100644 --- a/itest/cosmwasm/bcd/bcd_consumer_e2e_test.go +++ b/itest/cosmwasm/bcd/bcd_consumer_e2e_test.go @@ -69,7 +69,10 @@ func TestConsumerFpLifecycle(t *testing.T) { require.NoError(t, err) // get btc staking contract address - resp, err := ctm.BcdConsumerClient.ListContractsByCode(btcStakingContractWasmId, &sdkquerytypes.PageRequest{}) + resp, err := ctm.BcdConsumerClient.ListContractsByCode( + btcStakingContractWasmId, + &sdkquerytypes.PageRequest{}, + ) require.NoError(t, err) require.Len(t, resp.Contracts, 1) btcStakingContractAddr := sdk.MustAccAddressFromBech32(resp.Contracts[0]) @@ -77,7 +80,11 @@ func TestConsumerFpLifecycle(t *testing.T) { ctm.BcdConsumerClient.SetBtcStakingContractAddress(btcStakingContractAddr.String()) // register consumer to babylon - _, err = ctm.BBNClient.RegisterConsumerChain(bcdChainID, "Consumer chain 1 (test)", "Test Consumer Chain 1") + _, err = ctm.BBNClient.RegisterConsumerChain( + bcdChainID, + "Consumer chain 1 (test)", + "Test Consumer Chain 1", + ) require.NoError(t, err) // register consumer fps to babylon @@ -87,9 +94,24 @@ func TestConsumerFpLifecycle(t *testing.T) { moniker := e2eutils.MonikerPrefix + bcdChainID commission := sdkmath.LegacyZeroDec() desc := e2eutils.NewDescription(moniker) - _, err = service.CreateChainKey(cfg.BabylonConfig.KeyDirectory, bcdChainID, fpName, keyring.BackendTest, e2eutils.Passphrase, e2eutils.HdPath, "") - require.NoError(t, err) - res, err := app.CreateFinalityProvider(fpName, bcdChainID, e2eutils.Passphrase, e2eutils.HdPath, desc, &commission) + _, err = service.CreateChainKey( + cfg.BabylonConfig.KeyDirectory, + bcdChainID, + fpName, + keyring.BackendTest, + e2eutils.Passphrase, + e2eutils.HdPath, + "", + ) + require.NoError(t, err) + res, err := app.CreateFinalityProvider( + fpName, + bcdChainID, + e2eutils.Passphrase, + e2eutils.HdPath, + desc, + &commission, + ) require.NoError(t, err) fpPk, err := bbntypes.NewBIP340PubKeyFromHex(res.FpInfo.BtcPkHex) require.NoError(t, err) @@ -116,13 +138,32 @@ func TestConsumerFpLifecycle(t *testing.T) { require.NoError(t, err) require.NotNil(t, consumerDelsResp) require.Len(t, consumerDelsResp.Delegations, 1) - require.Empty(t, consumerDelsResp.Delegations[0].UndelegationInfo.DelegatorUnbondingSig) // assert there is no delegator unbonding sig + require.Empty( + t, + consumerDelsResp.Delegations[0].UndelegationInfo.DelegatorUnbondingSig, + ) // assert there is no delegator unbonding sig require.Equal(t, msg.BtcStaking.ActiveDel[0].BTCPkHex, consumerDelsResp.Delegations[0].BtcPkHex) - require.Equal(t, msg.BtcStaking.ActiveDel[0].StartHeight, consumerDelsResp.Delegations[0].StartHeight) - require.Equal(t, msg.BtcStaking.ActiveDel[0].EndHeight, consumerDelsResp.Delegations[0].EndHeight) + require.Equal( + t, + msg.BtcStaking.ActiveDel[0].StartHeight, + consumerDelsResp.Delegations[0].StartHeight, + ) + require.Equal( + t, + msg.BtcStaking.ActiveDel[0].EndHeight, + consumerDelsResp.Delegations[0].EndHeight, + ) require.Equal(t, msg.BtcStaking.ActiveDel[0].TotalSat, consumerDelsResp.Delegations[0].TotalSat) - require.Equal(t, msg.BtcStaking.ActiveDel[0].StakingTx, base64.StdEncoding.EncodeToString(consumerDelsResp.Delegations[0].StakingTx)) // make sure to compare b64 encoded strings - require.Equal(t, msg.BtcStaking.ActiveDel[0].SlashingTx, base64.StdEncoding.EncodeToString(consumerDelsResp.Delegations[0].SlashingTx)) // make sure to compare b64 encoded strings + require.Equal( + t, + msg.BtcStaking.ActiveDel[0].StakingTx, + base64.StdEncoding.EncodeToString(consumerDelsResp.Delegations[0].StakingTx), + ) // make sure to compare b64 encoded strings + require.Equal( + t, + msg.BtcStaking.ActiveDel[0].SlashingTx, + base64.StdEncoding.EncodeToString(consumerDelsResp.Delegations[0].SlashingTx), + ) // make sure to compare b64 encoded strings // ensure fp has voting power in smart contract consumerFpsByPowerResp, err := ctm.BcdConsumerClient.QueryFinalityProvidersByPower() @@ -182,7 +223,10 @@ func TestConsumerFpLifecycle(t *testing.T) { // ensure finality signature is submitted to smart contract require.Eventually(t, func() bool { - fpSigsResponse, err := ctm.BcdConsumerClient.QueryFinalitySignature(fpPk.MarshalHex(), uint64(lookupHeight)) + fpSigsResponse, err := ctm.BcdConsumerClient.QueryFinalitySignature( + fpPk.MarshalHex(), + uint64(lookupHeight), + ) if err != nil { t.Logf("failed to query finality signature: %s", err.Error()) return false diff --git a/itest/cosmwasm/bcd/bcd_handler.go b/itest/cosmwasm/bcd/bcd_handler.go index 3a99af0e..6a20d681 100644 --- a/itest/cosmwasm/bcd/bcd_handler.go +++ b/itest/cosmwasm/bcd/bcd_handler.go @@ -132,7 +132,15 @@ func (w *BcdNodeHandler) cleanup() error { } func bcdInit(homeDir string) error { - _, err := common.RunCommand("bcd", "init", "--home", homeDir, "--chain-id", bcdChainID, common.WasmMoniker) + _, err := common.RunCommand( + "bcd", + "init", + "--home", + homeDir, + "--chain-id", + bcdChainID, + common.WasmMoniker, + ) return err } @@ -144,17 +152,45 @@ func bcdUpdateGenesisFile(homeDir string) error { } func bcdKeysAdd(homeDir string) error { - _, err := common.RunCommand("bcd", "keys", "add", "validator", "--home", homeDir, "--keyring-backend=test") + _, err := common.RunCommand( + "bcd", + "keys", + "add", + "validator", + "--home", + homeDir, + "--keyring-backend=test", + ) return err } func bcdAddValidatorGenesisAccount(homeDir string) error { - _, err := common.RunCommand("bcd", "genesis", "add-genesis-account", "validator", fmt.Sprintf("1000000000000%s,1000000000000%s", common.WasmStake, common.WasmFee), "--home", homeDir, "--keyring-backend=test") + _, err := common.RunCommand( + "bcd", + "genesis", + "add-genesis-account", + "validator", + fmt.Sprintf("1000000000000%s,1000000000000%s", common.WasmStake, common.WasmFee), + "--home", + homeDir, + "--keyring-backend=test", + ) return err } func bcdGentxValidator(homeDir string) error { - _, err := common.RunCommand("bcd", "genesis", "gentx", "validator", fmt.Sprintf("250000000%s", common.WasmStake), "--chain-id="+bcdChainID, "--amount="+fmt.Sprintf("250000000%s", common.WasmStake), "--home", homeDir, "--keyring-backend=test") + _, err := common.RunCommand( + "bcd", + "genesis", + "gentx", + "validator", + fmt.Sprintf("250000000%s", common.WasmStake), + "--chain-id="+bcdChainID, + "--amount="+fmt.Sprintf("250000000%s", common.WasmStake), + "--home", + homeDir, + "--keyring-backend=test", + ) return err } diff --git a/itest/cosmwasm/bcd/bcd_test_manager.go b/itest/cosmwasm/bcd/bcd_test_manager.go index 1fd9aa1e..0f10ac7c 100644 --- a/itest/cosmwasm/bcd/bcd_test_manager.go +++ b/itest/cosmwasm/bcd/bcd_test_manager.go @@ -83,7 +83,14 @@ func StartBcdTestManager(t *testing.T) *BcdTestManager { cfg.CosmwasmConfig.ChainID = bcdChainID cfg.CosmwasmConfig.RPCAddr = fmt.Sprintf("http://localhost:%d", bcdRpcPort) // tempApp := bcdapp.NewTmpApp() // TODO: investigate why wasmapp works and bcdapp doesn't - tempApp := wasmapp.NewWasmApp(sdklogs.NewNopLogger(), dbm.NewMemDB(), nil, false, simtestutil.NewAppOptionsWithFlagHome(t.TempDir()), []wasmkeeper.Option{}) + tempApp := wasmapp.NewWasmApp( + sdklogs.NewNopLogger(), + dbm.NewMemDB(), + nil, + false, + simtestutil.NewAppOptionsWithFlagHome(t.TempDir()), + []wasmkeeper.Option{}, + ) encodingCfg := wasmparams.EncodingConfig{ InterfaceRegistry: tempApp.InterfaceRegistry(), Codec: tempApp.AppCodec(), @@ -163,7 +170,11 @@ func (ctm *BcdTestManager) Stop(t *testing.T) { require.NoError(t, err) } -func (ctm *BcdTestManager) CreateConsumerFinalityProviders(t *testing.T, consumerId string, n int) []*service.FinalityProviderInstance { +func (ctm *BcdTestManager) CreateConsumerFinalityProviders( + t *testing.T, + consumerId string, + n int, +) []*service.FinalityProviderInstance { app := ctm.Fpa cfg := app.GetConfig() @@ -174,9 +185,24 @@ func (ctm *BcdTestManager) CreateConsumerFinalityProviders(t *testing.T, consume moniker := e2eutils.MonikerPrefix + consumerId + "-" + strconv.Itoa(i) commission := sdkmath.LegacyZeroDec() desc := e2eutils.NewDescription(moniker) - _, err := service.CreateChainKey(cfg.BabylonConfig.KeyDirectory, consumerId, fpName, keyring.BackendTest, e2eutils.Passphrase, e2eutils.HdPath, "") + _, err := service.CreateChainKey( + cfg.BabylonConfig.KeyDirectory, + consumerId, + fpName, + keyring.BackendTest, + e2eutils.Passphrase, + e2eutils.HdPath, + "", + ) require.NoError(t, err) - res, err := app.CreateFinalityProvider(fpName, consumerId, e2eutils.Passphrase, e2eutils.HdPath, desc, &commission) + res, err := app.CreateFinalityProvider( + fpName, + consumerId, + e2eutils.Passphrase, + e2eutils.HdPath, + desc, + &commission, + ) require.NoError(t, err) fpPk, err := bbntypes.NewBIP340PubKeyFromHex(res.FpInfo.BtcPkHex) require.NoError(t, err) diff --git a/itest/cosmwasm/wasmd/wasmd_e2e_test.go b/itest/cosmwasm/wasmd/wasmd_e2e_test.go index 969be430..812e93e5 100644 --- a/itest/cosmwasm/wasmd/wasmd_e2e_test.go +++ b/itest/cosmwasm/wasmd/wasmd_e2e_test.go @@ -67,7 +67,10 @@ func TestConsumerFpDataInjection(t *testing.T) { require.NoError(t, err) // get btc staking contract address - resp, err := ctm.WasmdConsumerClient.ListContractsByCode(btcStakingContractWasmId, &sdkquerytypes.PageRequest{}) + resp, err := ctm.WasmdConsumerClient.ListContractsByCode( + btcStakingContractWasmId, + &sdkquerytypes.PageRequest{}, + ) require.NoError(t, err) require.Len(t, resp.Contracts, 1) btcStakingContractAddr := sdk.MustAccAddressFromBech32(resp.Contracts[0]) @@ -100,13 +103,32 @@ func TestConsumerFpDataInjection(t *testing.T) { require.NoError(t, err) require.NotNil(t, consumerDelsResp) require.Len(t, consumerDelsResp.Delegations, 1) - require.Empty(t, consumerDelsResp.Delegations[0].UndelegationInfo.DelegatorUnbondingSig) // assert there is no delegator unbonding sig + require.Empty( + t, + consumerDelsResp.Delegations[0].UndelegationInfo.DelegatorUnbondingSig, + ) // assert there is no delegator unbonding sig require.Equal(t, msg.BtcStaking.ActiveDel[0].BTCPkHex, consumerDelsResp.Delegations[0].BtcPkHex) - require.Equal(t, msg.BtcStaking.ActiveDel[0].StartHeight, consumerDelsResp.Delegations[0].StartHeight) - require.Equal(t, msg.BtcStaking.ActiveDel[0].EndHeight, consumerDelsResp.Delegations[0].EndHeight) + require.Equal( + t, + msg.BtcStaking.ActiveDel[0].StartHeight, + consumerDelsResp.Delegations[0].StartHeight, + ) + require.Equal( + t, + msg.BtcStaking.ActiveDel[0].EndHeight, + consumerDelsResp.Delegations[0].EndHeight, + ) require.Equal(t, msg.BtcStaking.ActiveDel[0].TotalSat, consumerDelsResp.Delegations[0].TotalSat) - require.Equal(t, msg.BtcStaking.ActiveDel[0].StakingTx, base64.StdEncoding.EncodeToString(consumerDelsResp.Delegations[0].StakingTx)) // make sure to compare b64 encoded strings - require.Equal(t, msg.BtcStaking.ActiveDel[0].SlashingTx, base64.StdEncoding.EncodeToString(consumerDelsResp.Delegations[0].SlashingTx)) // make sure to compare b64 encoded strings + require.Equal( + t, + msg.BtcStaking.ActiveDel[0].StakingTx, + base64.StdEncoding.EncodeToString(consumerDelsResp.Delegations[0].StakingTx), + ) // make sure to compare b64 encoded strings + require.Equal( + t, + msg.BtcStaking.ActiveDel[0].SlashingTx, + base64.StdEncoding.EncodeToString(consumerDelsResp.Delegations[0].SlashingTx), + ) // make sure to compare b64 encoded strings // ensure fp has voting power in smart contract consumerFpsByPowerResp, err := ctm.WasmdConsumerClient.QueryFinalityProvidersByPower() @@ -133,14 +155,26 @@ func TestConsumerFpDataInjection(t *testing.T) { wasmdNodeStatus, err := ctm.WasmdConsumerClient.GetCometNodeStatus() require.NoError(t, err) cometLatestHeight := wasmdNodeStatus.SyncInfo.LatestBlockHeight - finalitySigMsg := common.GenFinalitySigExecMsg(uint64(1), uint64(cometLatestHeight), randList, fpSk) + finalitySigMsg := common.GenFinalitySigExecMsg( + uint64(1), + uint64(cometLatestHeight), + randList, + fpSk, + ) finalitySigMsgBytes, err := json.Marshal(finalitySigMsg) require.NoError(t, err) _, err = ctm.WasmdConsumerClient.ExecuteContract(finalitySigMsgBytes) require.NoError(t, err) - fpSigsResponse, err := ctm.WasmdConsumerClient.QueryFinalitySignature(msgPub.FpBtcPk.MarshalHex(), uint64(cometLatestHeight)) + fpSigsResponse, err := ctm.WasmdConsumerClient.QueryFinalitySignature( + msgPub.FpBtcPk.MarshalHex(), + uint64(cometLatestHeight), + ) require.NoError(t, err) require.NotNil(t, fpSigsResponse) require.NotNil(t, fpSigsResponse.Signature) - require.Equal(t, finalitySigMsg.SubmitFinalitySignature.Signature, base64.StdEncoding.EncodeToString(fpSigsResponse.Signature)) + require.Equal( + t, + finalitySigMsg.SubmitFinalitySignature.Signature, + base64.StdEncoding.EncodeToString(fpSigsResponse.Signature), + ) } diff --git a/itest/cosmwasm/wasmd/wasmd_handler.go b/itest/cosmwasm/wasmd/wasmd_handler.go index ee9f17e8..edb69714 100644 --- a/itest/cosmwasm/wasmd/wasmd_handler.go +++ b/itest/cosmwasm/wasmd/wasmd_handler.go @@ -136,7 +136,15 @@ func (w *WasmdNodeHandler) cleanup() error { } func wasmdInit(homeDir string) error { - _, err := common.RunCommand("wasmd", "init", "--home", homeDir, "--chain-id", wasmdChainID, common.WasmMoniker) + _, err := common.RunCommand( + "wasmd", + "init", + "--home", + homeDir, + "--chain-id", + wasmdChainID, + common.WasmMoniker, + ) return err } @@ -148,17 +156,45 @@ func updateGenesisFile(homeDir string) error { } func wasmdKeysAdd(homeDir string) error { - _, err := common.RunCommand("wasmd", "keys", "add", "validator", "--home", homeDir, "--keyring-backend=test") + _, err := common.RunCommand( + "wasmd", + "keys", + "add", + "validator", + "--home", + homeDir, + "--keyring-backend=test", + ) return err } func addValidatorGenesisAccount(homeDir string) error { - _, err := common.RunCommand("wasmd", "genesis", "add-genesis-account", "validator", fmt.Sprintf("1000000000000%s,1000000000000%s", common.WasmStake, common.WasmFee), "--home", homeDir, "--keyring-backend=test") + _, err := common.RunCommand( + "wasmd", + "genesis", + "add-genesis-account", + "validator", + fmt.Sprintf("1000000000000%s,1000000000000%s", common.WasmStake, common.WasmFee), + "--home", + homeDir, + "--keyring-backend=test", + ) return err } func gentxValidator(homeDir string) error { - _, err := common.RunCommand("wasmd", "genesis", "gentx", "validator", fmt.Sprintf("250000000%s", common.WasmStake), "--chain-id="+wasmdChainID, "--amount="+fmt.Sprintf("250000000%s", common.WasmStake), "--home", homeDir, "--keyring-backend=test") + _, err := common.RunCommand( + "wasmd", + "genesis", + "gentx", + "validator", + fmt.Sprintf("250000000%s", common.WasmStake), + "--chain-id="+wasmdChainID, + "--amount="+fmt.Sprintf("250000000%s", common.WasmStake), + "--home", + homeDir, + "--keyring-backend=test", + ) return err } @@ -219,9 +255,30 @@ type TxResponse struct { } func (w *WasmdNodeHandler) StoreWasmCode(wasmFile string) (string, string, error) { - cmd := exec.Command("wasmd", "tx", "wasm", "store", wasmFile, - "--from", "validator", "--gas=auto", "--gas-prices=1ustake", "--gas-adjustment=1.3", "-y", "--chain-id", wasmdChainID, - "--node", w.GetRpcUrl(), "--home", w.GetHomeDir(), "-b", "sync", "-o", "json", "--keyring-backend=test") + cmd := exec.Command( + "wasmd", + "tx", + "wasm", + "store", + wasmFile, + "--from", + "validator", + "--gas=auto", + "--gas-prices=1ustake", + "--gas-adjustment=1.3", + "-y", + "--chain-id", + wasmdChainID, + "--node", + w.GetRpcUrl(), + "--home", + w.GetHomeDir(), + "-b", + "sync", + "-o", + "json", + "--keyring-backend=test", + ) var out bytes.Buffer cmd.Stdout = &out @@ -241,7 +298,16 @@ func (w *WasmdNodeHandler) StoreWasmCode(wasmFile string) (string, string, error } time.Sleep(3 * time.Second) - queryOutput, err := common.RunCommand("wasmd", "--node", w.GetRpcUrl(), "q", "tx", txResp.TxHash, "-o", "json") + queryOutput, err := common.RunCommand( + "wasmd", + "--node", + w.GetRpcUrl(), + "q", + "tx", + txResp.TxHash, + "-o", + "json", + ) if err != nil { return "", "", fmt.Errorf("error querying transaction: %v", err) } @@ -279,7 +345,14 @@ type StatusResponse struct { } func (w *WasmdNodeHandler) GetLatestBlockHeight() (int64, error) { - out, err := common.RunCommand("wasmd", "status", "--node", w.GetRpcUrl(), "--home", w.GetHomeDir()) + out, err := common.RunCommand( + "wasmd", + "status", + "--node", + w.GetRpcUrl(), + "--home", + w.GetHomeDir(), + ) if err != nil { return 0, fmt.Errorf("error running wasmd status command: %v", err) } @@ -308,7 +381,16 @@ type CodeInfo struct { } func (w *WasmdNodeHandler) GetLatestCodeID() (string, error) { - output, err := common.RunCommand("wasmd", "--node", w.GetRpcUrl(), "q", "wasm", "list-code", "-o", "json") + output, err := common.RunCommand( + "wasmd", + "--node", + w.GetRpcUrl(), + "q", + "wasm", + "list-code", + "-o", + "json", + ) if err != nil { return "", fmt.Errorf("error running wasmd list-code command: %v", err) } diff --git a/itest/cosmwasm/wasmd/wasmd_test_manager.go b/itest/cosmwasm/wasmd/wasmd_test_manager.go index a32234ed..150e3d3b 100644 --- a/itest/cosmwasm/wasmd/wasmd_test_manager.go +++ b/itest/cosmwasm/wasmd/wasmd_test_manager.go @@ -80,7 +80,14 @@ func StartWasmdTestManager(t *testing.T) *WasmdTestManager { cfg.ChainName = fpcc.WasmConsumerChainName cfg.CosmwasmConfig.AccountPrefix = "wasm" cfg.CosmwasmConfig.ChainID = wasmdChainID - tempApp := wasmapp.NewWasmApp(sdklogs.NewNopLogger(), dbm.NewMemDB(), nil, false, simtestutil.NewAppOptionsWithFlagHome(t.TempDir()), []wasmkeeper.Option{}) + tempApp := wasmapp.NewWasmApp( + sdklogs.NewNopLogger(), + dbm.NewMemDB(), + nil, + false, + simtestutil.NewAppOptionsWithFlagHome(t.TempDir()), + []wasmkeeper.Option{}, + ) encodingCfg := wasmparams.EncodingConfig{ InterfaceRegistry: tempApp.InterfaceRegistry(), Codec: tempApp.AppCodec(), @@ -160,7 +167,10 @@ func (ctm *WasmdTestManager) Stop(t *testing.T) { require.NoError(t, err) } -func StartConsumerManagerWithFps(t *testing.T, n int) (*WasmdTestManager, []*service.FinalityProviderInstance) { +func StartConsumerManagerWithFps( + t *testing.T, + n int, +) (*WasmdTestManager, []*service.FinalityProviderInstance) { ctm := StartWasmdTestManager(t) app := ctm.Fpa @@ -170,9 +180,24 @@ func StartConsumerManagerWithFps(t *testing.T, n int) (*WasmdTestManager, []*ser commission := sdkmath.LegacyZeroDec() desc := e2eutils.NewDescription(moniker) cfg := app.GetConfig() - _, err := service.CreateChainKey(cfg.BabylonConfig.KeyDirectory, cfg.BabylonConfig.ChainID, fpName, keyring.BackendTest, e2eutils.Passphrase, e2eutils.HdPath, "") + _, err := service.CreateChainKey( + cfg.BabylonConfig.KeyDirectory, + cfg.BabylonConfig.ChainID, + fpName, + keyring.BackendTest, + e2eutils.Passphrase, + e2eutils.HdPath, + "", + ) require.NoError(t, err) - res, err := app.CreateFinalityProvider(fpName, e2eutils.ChainID, e2eutils.Passphrase, e2eutils.HdPath, desc, &commission) + res, err := app.CreateFinalityProvider( + fpName, + e2eutils.ChainID, + e2eutils.Passphrase, + e2eutils.HdPath, + desc, + &commission, + ) require.NoError(t, err) fpPk, err := bbntypes.NewBIP340PubKeyFromHex(res.FpInfo.BtcPkHex) require.NoError(t, err) @@ -218,7 +243,11 @@ func StartConsumerManagerWithFps(t *testing.T, n int) (*WasmdTestManager, []*ser return ctm, fpInsList } -func (ctm *WasmdTestManager) CreateFinalityProvidersForChain(t *testing.T, chainID string, n int) []*service.FinalityProviderInstance { +func (ctm *WasmdTestManager) CreateFinalityProvidersForChain( + t *testing.T, + chainID string, + n int, +) []*service.FinalityProviderInstance { app := ctm.Fpa cfg := app.GetConfig() @@ -229,9 +258,24 @@ func (ctm *WasmdTestManager) CreateFinalityProvidersForChain(t *testing.T, chain moniker := e2eutils.MonikerPrefix + chainID + "-" + strconv.Itoa(i) commission := sdkmath.LegacyZeroDec() desc := e2eutils.NewDescription(moniker) - _, err := service.CreateChainKey(cfg.BabylonConfig.KeyDirectory, chainID, fpName, keyring.BackendTest, e2eutils.Passphrase, e2eutils.HdPath, "") + _, err := service.CreateChainKey( + cfg.BabylonConfig.KeyDirectory, + chainID, + fpName, + keyring.BackendTest, + e2eutils.Passphrase, + e2eutils.HdPath, + "", + ) require.NoError(t, err) - res, err := app.CreateFinalityProvider(fpName, chainID, e2eutils.Passphrase, e2eutils.HdPath, desc, &commission) + res, err := app.CreateFinalityProvider( + fpName, + chainID, + e2eutils.Passphrase, + e2eutils.HdPath, + desc, + &commission, + ) require.NoError(t, err) fpPk, err := bbntypes.NewBIP340PubKeyFromHex(res.FpInfo.BtcPkHex) require.NoError(t, err) diff --git a/itest/eotsmanager_handler.go b/itest/eotsmanager_handler.go index 8f94ba81..c00d8729 100644 --- a/itest/eotsmanager_handler.go +++ b/itest/eotsmanager_handler.go @@ -25,10 +25,21 @@ func NewEOTSServerHandler(t *testing.T, cfg *config.Config, eotsHomeDir string) dbBackend, err := cfg.DatabaseConfig.GetDbBackend() require.NoError(t, err) logger := zap.NewNop() - eotsManager, err := eotsmanager.NewLocalEOTSManager(eotsHomeDir, cfg.KeyringBackend, dbBackend, logger) + eotsManager, err := eotsmanager.NewLocalEOTSManager( + eotsHomeDir, + cfg.KeyringBackend, + dbBackend, + logger, + ) require.NoError(t, err) - eotsServer := service.NewEOTSManagerServer(cfg, logger, eotsManager, dbBackend, shutdownInterceptor) + eotsServer := service.NewEOTSManagerServer( + cfg, + logger, + eotsManager, + dbBackend, + shutdownInterceptor, + ) return &EOTSServerHandler{ t: t, diff --git a/itest/opstackl2/op_e2e_test.go b/itest/opstackl2/op_e2e_test.go index 1d414a6e..7d40c7e0 100644 --- a/itest/opstackl2/op_e2e_test.go +++ b/itest/opstackl2/op_e2e_test.go @@ -124,8 +124,18 @@ func TestBlockBabylonFinalized(t *testing.T) { // send a BTC delegation to consumer and Babylon finality providers // for the first FP, we give it more power b/c it will be used later - ctm.InsertBTCDelegation(t, []*btcec.PublicKey{bbnFpList[0].GetBtcPk(), fpList[0].GetBtcPk()}, e2eutils.StakingTime, 3*e2eutils.StakingAmount) - ctm.InsertBTCDelegation(t, []*btcec.PublicKey{bbnFpList[0].GetBtcPk(), fpList[1].GetBtcPk()}, e2eutils.StakingTime, e2eutils.StakingAmount) + ctm.InsertBTCDelegation( + t, + []*btcec.PublicKey{bbnFpList[0].GetBtcPk(), fpList[0].GetBtcPk()}, + e2eutils.StakingTime, + 3*e2eutils.StakingAmount, + ) + ctm.InsertBTCDelegation( + t, + []*btcec.PublicKey{bbnFpList[0].GetBtcPk(), fpList[1].GetBtcPk()}, + e2eutils.StakingTime, + e2eutils.StakingAmount, + ) // check the BTC delegations are pending delsResp := ctm.WaitForNPendingDels(t, n) diff --git a/itest/opstackl2/op_test_manager.go b/itest/opstackl2/op_test_manager.go index 49318eee..b43f19c4 100644 --- a/itest/opstackl2/op_test_manager.go +++ b/itest/opstackl2/op_test_manager.go @@ -90,7 +90,10 @@ func StartOpL2ConsumerManager(t *testing.T) *OpL2ConsumerTestManager { t.Logf("Register consumer %s to Babylon", opConsumerId) // 4. new op consumer controller - opcc, err := opstackl2.NewOPStackL2ConsumerController(mockOpL2ConsumerCtrlConfig(bh.GetNodeDataDir()), logger) + opcc, err := opstackl2.NewOPStackL2ConsumerController( + mockOpL2ConsumerCtrlConfig(bh.GetNodeDataDir()), + logger, + ) require.NoError(t, err) // 5. store op-finality-gadget contract @@ -99,7 +102,12 @@ func StartOpL2ConsumerManager(t *testing.T) *OpL2ConsumerTestManager { opFinalityGadgetContractWasmId, err := getLatestCodeId(opcc) require.NoError(t, err) - require.Equal(t, uint64(1), opFinalityGadgetContractWasmId, "first deployed contract code_id should be 1") + require.Equal( + t, + uint64(1), + opFinalityGadgetContractWasmId, + "first deployed contract code_id should be 1", + ) // 6. instantiate op contract opFinalityGadgetInitMsg := map[string]interface{}{ @@ -110,11 +118,18 @@ func StartOpL2ConsumerManager(t *testing.T) *OpL2ConsumerTestManager { } opFinalityGadgetInitMsgBytes, err := json.Marshal(opFinalityGadgetInitMsg) require.NoError(t, err) - err = instantiateWasmContract(opcc, opFinalityGadgetContractWasmId, opFinalityGadgetInitMsgBytes) + err = instantiateWasmContract( + opcc, + opFinalityGadgetContractWasmId, + opFinalityGadgetInitMsgBytes, + ) require.NoError(t, err) // get op contract address - resp, err := opcc.CwClient.ListContractsByCode(opFinalityGadgetContractWasmId, &sdkquerytypes.PageRequest{}) + resp, err := opcc.CwClient.ListContractsByCode( + opFinalityGadgetContractWasmId, + &sdkquerytypes.PageRequest{}, + ) require.NoError(t, err) require.Len(t, resp.Contracts, 1) @@ -203,12 +218,20 @@ func (ctm *OpL2ConsumerTestManager) WaitForServicesStart(t *testing.T) { t.Logf("Babylon node has started") } -func (ctm *OpL2ConsumerTestManager) WaitForTargetBlockPubRand(t *testing.T, fpList []*service.FinalityProviderInstance, requiredBlockOverlapLen uint64) []*uint64 { +func (ctm *OpL2ConsumerTestManager) WaitForTargetBlockPubRand( + t *testing.T, + fpList []*service.FinalityProviderInstance, + requiredBlockOverlapLen uint64, +) []*uint64 { require.Equal(t, 2, len(fpList), "The below algorithm only supports two FPs") fpStartHeightList := make([]*uint64, 2) require.Eventually(t, func() bool { - firstFpCommittedPubRand, _ := ctm.OpL2ConsumerCtrl.QueryLastPublicRandCommit(fpList[0].GetBtcPk()) - secondFpCommittedPubRand, _ := ctm.OpL2ConsumerCtrl.QueryLastPublicRandCommit(fpList[1].GetBtcPk()) + firstFpCommittedPubRand, _ := ctm.OpL2ConsumerCtrl.QueryLastPublicRandCommit( + fpList[0].GetBtcPk(), + ) + secondFpCommittedPubRand, _ := ctm.OpL2ConsumerCtrl.QueryLastPublicRandCommit( + fpList[1].GetBtcPk(), + ) if fpStartHeightList[0] == nil { fpStartHeightList[0] = new(uint64) @@ -251,7 +274,12 @@ func (ctm *OpL2ConsumerTestManager) WaitForTargetBlockPubRand(t *testing.T, fpLi // - fp sign // - pub rand proof // - submit finality signature to smart contract -func (ctm *OpL2ConsumerTestManager) fpSubmitFinalitySignature(t *testing.T, fp *service.FinalityProviderInstance, fpStartHeight *uint64, testBlock *types.BlockInfo) { +func (ctm *OpL2ConsumerTestManager) fpSubmitFinalitySignature( + t *testing.T, + fp *service.FinalityProviderInstance, + fpStartHeight *uint64, + testBlock *types.BlockInfo, +) { pubRandList, err := fp.GetPubRandList(*fpStartHeight, ctm.FpConfig.NumPubRand) require.NoError(t, err) @@ -276,7 +304,11 @@ func (ctm *OpL2ConsumerTestManager) fpSubmitFinalitySignature(t *testing.T, fp * t.Logf("Submit finality signature to op finality contract %+v\n", testBlock) } -func (ctm *OpL2ConsumerTestManager) StartFinalityProvider(t *testing.T, isBabylonFp bool, n int) []*service.FinalityProviderInstance { +func (ctm *OpL2ConsumerTestManager) StartFinalityProvider( + t *testing.T, + isBabylonFp bool, + n int, +) []*service.FinalityProviderInstance { app := ctm.FpApp chainId := opConsumerId @@ -291,9 +323,24 @@ func (ctm *OpL2ConsumerTestManager) StartFinalityProvider(t *testing.T, isBabylo commission := sdkmath.LegacyZeroDec() desc := e2eutils.NewDescription(moniker) cfg := app.GetConfig() - _, err := service.CreateChainKey(cfg.BabylonConfig.KeyDirectory, cfg.BabylonConfig.ChainID, fpName, keyring.BackendTest, e2eutils.Passphrase, e2eutils.HdPath, "") + _, err := service.CreateChainKey( + cfg.BabylonConfig.KeyDirectory, + cfg.BabylonConfig.ChainID, + fpName, + keyring.BackendTest, + e2eutils.Passphrase, + e2eutils.HdPath, + "", + ) require.NoError(t, err) - res, err := app.CreateFinalityProvider(fpName, chainId, e2eutils.Passphrase, e2eutils.HdPath, desc, &commission) + res, err := app.CreateFinalityProvider( + fpName, + chainId, + e2eutils.Passphrase, + e2eutils.HdPath, + desc, + &commission, + ) require.NoError(t, err) fpPk, err := bbntypes.NewBIP340PubKeyFromHex(res.FpInfo.BtcPkHex) require.NoError(t, err) @@ -386,7 +433,11 @@ func storeWasmCode(opcc *opstackl2.OPStackL2ConsumerController, wasmFile string) return nil } -func instantiateWasmContract(opcc *opstackl2.OPStackL2ConsumerController, codeID uint64, initMsg []byte) error { +func instantiateWasmContract( + opcc *opstackl2.OPStackL2ConsumerController, + codeID uint64, + initMsg []byte, +) error { instantiateMsg := &wasmdtypes.MsgInstantiateContract{ Sender: opcc.CwClient.MustGetAddr(), Admin: opcc.CwClient.MustGetAddr(), diff --git a/itest/test-manager/base_test_manager.go b/itest/test-manager/base_test_manager.go index efbeaf1d..a69ccfb2 100644 --- a/itest/test-manager/base_test_manager.go +++ b/itest/test-manager/base_test_manager.go @@ -46,7 +46,12 @@ type TestDelegationData struct { StakingAmount int64 } -func (tm *BaseTestManager) InsertBTCDelegation(t *testing.T, fpPks []*btcec.PublicKey, stakingTime uint16, stakingAmount int64) *TestDelegationData { +func (tm *BaseTestManager) InsertBTCDelegation( + t *testing.T, + fpPks []*btcec.PublicKey, + stakingTime uint16, + stakingAmount int64, +) *TestDelegationData { params := tm.StakingParams r := rand.New(rand.NewSource(time.Now().UnixNano())) @@ -83,7 +88,11 @@ func (tm *BaseTestManager) InsertBTCDelegation(t *testing.T, fpPks []*btcec.Publ require.NoError(t, err) tipHeader, err := bbntypes.NewBTCHeaderBytesFromHex(btcTipHeaderResp.HeaderHex) require.NoError(t, err) - blockWithStakingTx := datagen.CreateBlockWithTransaction(r, tipHeader.ToBlockHeader(), testStakingInfo.StakingTx) + blockWithStakingTx := datagen.CreateBlockWithTransaction( + r, + tipHeader.ToBlockHeader(), + testStakingInfo.StakingTx, + ) accumulatedWork := btclctypes.CalcWork(&blockWithStakingTx.HeaderBytes) accumulatedWork = btclctypes.CumulativeWork(accumulatedWork, btcTipHeaderResp.Work) parentBlockHeaderInfo := &btclctypes.BTCHeaderInfo{ @@ -104,7 +113,11 @@ func (tm *BaseTestManager) InsertBTCDelegation(t *testing.T, fpPks []*btcec.Publ btcHeader := blockWithStakingTx.HeaderBytes serializedStakingTx, err := bbntypes.SerializeBTCTx(testStakingInfo.StakingTx) require.NoError(t, err) - txInfo := btcctypes.NewTransactionInfo(&btcctypes.TransactionKey{Index: 1, Hash: btcHeader.Hash()}, serializedStakingTx, blockWithStakingTx.SpvProof.MerkleNodes) + txInfo := btcctypes.NewTransactionInfo( + &btcctypes.TransactionKey{Index: 1, Hash: btcHeader.Hash()}, + serializedStakingTx, + blockWithStakingTx.SpvProof.MerkleNodes, + ) slashignSpendInfo, err := testStakingInfo.StakingInfo.SlashingPathSpendInfo() require.NoError(t, err) @@ -189,7 +202,10 @@ func (tm *BaseTestManager) InsertBTCDelegation(t *testing.T, fpPks []*btcec.Publ } } -func (tm *BaseTestManager) WaitForNPendingDels(t *testing.T, n int) []*bstypes.BTCDelegationResponse { +func (tm *BaseTestManager) WaitForNPendingDels( + t *testing.T, + n int, +) []*bstypes.BTCDelegationResponse { var ( dels []*bstypes.BTCDelegationResponse err error @@ -209,7 +225,10 @@ func (tm *BaseTestManager) WaitForNPendingDels(t *testing.T, n int) []*bstypes.B return dels } -func (tm *BaseTestManager) WaitForNActiveDels(t *testing.T, n int) []*bstypes.BTCDelegationResponse { +func (tm *BaseTestManager) WaitForNActiveDels( + t *testing.T, + n int, +) []*bstypes.BTCDelegationResponse { var ( dels []*bstypes.BTCDelegationResponse err error @@ -229,7 +248,10 @@ func (tm *BaseTestManager) WaitForNActiveDels(t *testing.T, n int) []*bstypes.BT return dels } -func (tm *BaseTestManager) InsertCovenantSigForDelegation(t *testing.T, btcDel *bstypes.BTCDelegation) { +func (tm *BaseTestManager) InsertCovenantSigForDelegation( + t *testing.T, + btcDel *bstypes.BTCDelegation, +) { slashingTx := btcDel.SlashingTx stakingTx := btcDel.StakingTx stakingMsgTx, err := bbntypes.NewBTCTxFromBytes(stakingTx) @@ -294,7 +316,10 @@ func (tm *BaseTestManager) InsertCovenantSigForDelegation(t *testing.T, btcDel * v, ) require.NoError(t, err) - covenantAdaptorStakingSlashing1List = append(covenantAdaptorStakingSlashing1List, covenantAdaptorStakingSlashing1.MustMarshal()) + covenantAdaptorStakingSlashing1List = append( + covenantAdaptorStakingSlashing1List, + covenantAdaptorStakingSlashing1.MustMarshal(), + ) } covenantUnbondingSig1, err := btcstaking.SignTxWithOneScriptSpendInputFromTapLeaf( @@ -318,7 +343,10 @@ func (tm *BaseTestManager) InsertCovenantSigForDelegation(t *testing.T, btcDel * v, ) require.NoError(t, err) - covenantAdaptorUnbondingSlashing1List = append(covenantAdaptorUnbondingSlashing1List, covenantAdaptorUnbondingSlashing1.MustMarshal()) + covenantAdaptorUnbondingSlashing1List = append( + covenantAdaptorUnbondingSlashing1List, + covenantAdaptorUnbondingSlashing1.MustMarshal(), + ) } _, err = tm.BBNClient.SubmitCovenantSigs( @@ -341,7 +369,10 @@ func (tm *BaseTestManager) InsertCovenantSigForDelegation(t *testing.T, btcDel * v, ) require.NoError(t, err) - covenantAdaptorStakingSlashing2List = append(covenantAdaptorStakingSlashing2List, covenantAdaptorStakingSlashing2.MustMarshal()) + covenantAdaptorStakingSlashing2List = append( + covenantAdaptorStakingSlashing2List, + covenantAdaptorStakingSlashing2.MustMarshal(), + ) } covenantUnbondingSig2, err := btcstaking.SignTxWithOneScriptSpendInputFromTapLeaf( @@ -365,7 +396,10 @@ func (tm *BaseTestManager) InsertCovenantSigForDelegation(t *testing.T, btcDel * v, ) require.NoError(t, err) - covenantAdaptorUnbondingSlashing2List = append(covenantAdaptorUnbondingSlashing2List, covenantAdaptorUnbondingSlashing2.MustMarshal()) + covenantAdaptorUnbondingSlashing2List = append( + covenantAdaptorUnbondingSlashing2List, + covenantAdaptorUnbondingSlashing2.MustMarshal(), + ) } _, err = tm.BBNClient.SubmitCovenantSigs( diff --git a/itest/test_helpers.go b/itest/test_helpers.go index 9e105f3e..2e562140 100644 --- a/itest/test_helpers.go +++ b/itest/test_helpers.go @@ -43,7 +43,10 @@ func GenBtcStakingExecMsg(fpHex string) cosmwasm.ExecMsg { return executeMessage } -func GenPubRandomnessExecMsg(fpHex, commitment, sig string, startHeight, numPubRand uint64) cosmwasm.ExecMsg { +func GenPubRandomnessExecMsg( + fpHex, commitment, sig string, + startHeight, numPubRand uint64, +) cosmwasm.ExecMsg { // create the ExecMsg instance with CommitPublicRandomness set executeMessage := cosmwasm.ExecMsg{ CommitPublicRandomness: &cosmwasm.CommitPublicRandomness{ @@ -58,7 +61,11 @@ func GenPubRandomnessExecMsg(fpHex, commitment, sig string, startHeight, numPubR return executeMessage } -func GenFinalitySigExecMsg(startHeight, blockHeight uint64, randListInfo *datagen.RandListInfo, sk *btcec.PrivateKey) cosmwasm.ExecMsg { +func GenFinalitySigExecMsg( + startHeight, blockHeight uint64, + randListInfo *datagen.RandListInfo, + sk *btcec.PrivateKey, +) cosmwasm.ExecMsg { fmsg := genAddFinalitySig(startHeight, blockHeight, randListInfo, sk) msg := cosmwasm.ExecMsg{ SubmitFinalitySignature: &cosmwasm.SubmitFinalitySignature{ @@ -157,7 +164,9 @@ func genRandomBtcDelegation() (*bstypes.Params, cosmwasm.ActiveBtcDelegation) { return bsParams, activeDel } -func convertBTCDelegationToActiveBtcDelegation(mockDel *bstypes.BTCDelegation) cosmwasm.ActiveBtcDelegation { +func convertBTCDelegationToActiveBtcDelegation( + mockDel *bstypes.BTCDelegation, +) cosmwasm.ActiveBtcDelegation { var fpBtcPkList []string for _, pk := range mockDel.FpBtcPkList { fpBtcPkList = append(fpBtcPkList, pk.MarshalHex()) @@ -196,9 +205,15 @@ func convertBTCDelegationToActiveBtcDelegation(mockDel *bstypes.BTCDelegation) c } undelegationInfo := cosmwasm.BtcUndelegationInfo{ - UnbondingTx: base64.StdEncoding.EncodeToString(mockDel.BtcUndelegation.UnbondingTx), - SlashingTx: base64.StdEncoding.EncodeToString(mockDel.BtcUndelegation.SlashingTx.MustMarshal()), - DelegatorSlashingSig: base64.StdEncoding.EncodeToString(mockDel.BtcUndelegation.DelegatorSlashingSig.MustMarshal()), + UnbondingTx: base64.StdEncoding.EncodeToString( + mockDel.BtcUndelegation.UnbondingTx, + ), + SlashingTx: base64.StdEncoding.EncodeToString( + mockDel.BtcUndelegation.SlashingTx.MustMarshal(), + ), + DelegatorSlashingSig: base64.StdEncoding.EncodeToString( + mockDel.BtcUndelegation.DelegatorSlashingSig.MustMarshal(), + ), CovenantUnbondingSigs: covenantUnbondingSigs, CovenantSlashingSigs: covenantSlashingSigs, } @@ -220,7 +235,12 @@ func convertBTCDelegationToActiveBtcDelegation(mockDel *bstypes.BTCDelegation) c } } -func GenCommitPubRandListMsg(r *rand.Rand, fpSk *btcec.PrivateKey, startHeight uint64, numPubRand uint64) (*datagen.RandListInfo, *ftypes.MsgCommitPubRandList, error) { +func GenCommitPubRandListMsg( + r *rand.Rand, + fpSk *btcec.PrivateKey, + startHeight uint64, + numPubRand uint64, +) (*datagen.RandListInfo, *ftypes.MsgCommitPubRandList, error) { randListInfo, err := genRandomPubRandList(r, numPubRand) if err != nil { return nil, nil, err @@ -267,10 +287,20 @@ func genRandomPubRandList(r *rand.Rand, numPubRand uint64) (*datagen.RandListInf // generate the commitment to these public randomness commitment, proofList := merkle.ProofsFromByteSlices(prByteList) - return &datagen.RandListInfo{SRList: srList, PRList: prList, Commitment: commitment, ProofList: proofList}, nil + return &datagen.RandListInfo{ + SRList: srList, + PRList: prList, + Commitment: commitment, + ProofList: proofList, + }, nil } -func genAddFinalitySig(startHeight uint64, blockHeight uint64, randListInfo *datagen.RandListInfo, sk *btcec.PrivateKey) *ftypes.MsgAddFinalitySig { +func genAddFinalitySig( + startHeight uint64, + blockHeight uint64, + randListInfo *datagen.RandListInfo, + sk *btcec.PrivateKey, +) *ftypes.MsgAddFinalitySig { r := rand.New(rand.NewSource(time.Now().UnixNano())) blockHash := datagen.GenRandomByteArray(r, 32) diff --git a/itest/utils.go b/itest/utils.go index 318492d1..7ecbf1c0 100644 --- a/itest/utils.go +++ b/itest/utils.go @@ -67,7 +67,10 @@ func RunCommand(name string, args ...string) ([]byte, error) { return output, nil } -func GenerateCovenantCommittee(numCovenants int, t *testing.T) ([]*btcec.PrivateKey, []*bbntypes.BIP340PubKey) { +func GenerateCovenantCommittee( + numCovenants int, + t *testing.T, +) ([]*btcec.PrivateKey, []*bbntypes.BIP340PubKey) { var ( covenantPrivKeys []*btcec.PrivateKey covenantPubKeys []*bbntypes.BIP340PubKey @@ -123,7 +126,9 @@ func DefaultFpConfig(keyringDir, homeDir string) *config.Config { // ParseRespBTCDelToBTCDel parses an BTC delegation response to BTC Delegation // adapted from // https://github.com/babylonchain/babylon/blob/1a3c50da64885452c8d669fcea2a2fad78c8a028/test/e2e/btc_staking_e2e_test.go#L548 -func ParseRespBTCDelToBTCDel(resp *bstypes.BTCDelegationResponse) (btcDel *bstypes.BTCDelegation, err error) { +func ParseRespBTCDelToBTCDel( + resp *bstypes.BTCDelegationResponse, +) (btcDel *bstypes.BTCDelegation, err error) { stakingTx, err := hex.DecodeString(resp.StakingTxHex) if err != nil { return nil, err diff --git a/keyring/keyring.go b/keyring/keyring.go index 36b526b3..d5bccbea 100644 --- a/keyring/keyring.go +++ b/keyring/keyring.go @@ -12,7 +12,12 @@ import ( "github.com/babylonchain/finality-provider/codec" ) -func CreateKeyring(keyringDir string, chainId string, backend string, input *strings.Reader) (keyring.Keyring, error) { +func CreateKeyring( + keyringDir string, + chainId string, + backend string, + input *strings.Reader, +) (keyring.Keyring, error) { ctx, err := CreateClientCtx(keyringDir, chainId) if err != nil { return nil, err diff --git a/keyring/keyringcontroller.go b/keyring/keyringcontroller.go index c04224de..5409f6c2 100644 --- a/keyring/keyringcontroller.go +++ b/keyring/keyringcontroller.go @@ -26,7 +26,10 @@ type ChainKeyringController struct { input *strings.Reader } -func NewChainKeyringController(ctx client.Context, name, keyringBackend string) (*ChainKeyringController, error) { +func NewChainKeyringController( + ctx client.Context, + name, keyringBackend string, +) (*ChainKeyringController, error) { if name == "" { return nil, fmt.Errorf("the key name should not be empty") } @@ -54,7 +57,11 @@ func NewChainKeyringController(ctx client.Context, name, keyringBackend string) }, nil } -func NewChainKeyringControllerWithKeyring(kr keyring.Keyring, name string, input *strings.Reader) (*ChainKeyringController, error) { +func NewChainKeyringControllerWithKeyring( + kr keyring.Keyring, + name string, + input *strings.Reader, +) (*ChainKeyringController, error) { if name == "" { return nil, fmt.Errorf("the key name should not be empty") } @@ -70,7 +77,9 @@ func (kc *ChainKeyringController) GetKeyring() keyring.Keyring { return kc.kr } -func (kc *ChainKeyringController) CreateChainKey(passphrase, hdPath, mnemonic string) (*types.ChainKeyInfo, error) { +func (kc *ChainKeyringController) CreateChainKey( + passphrase, hdPath, mnemonic string, +) (*types.ChainKeyInfo, error) { keyringAlgos, _ := kc.kr.SupportedAlgorithms() algo, err := keyring.NewSigningAlgoFromString(secp256k1Type, keyringAlgos) if err != nil { @@ -121,7 +130,10 @@ func (kc *ChainKeyringController) CreateChainKey(passphrase, hdPath, mnemonic st // CreatePop creates proof-of-possession of Babylon and BTC public keys // the input is the bytes of BTC public key used to sign // this requires both keys created beforehand -func (kc *ChainKeyringController) CreatePop(btcPrivKey *btcec.PrivateKey, passphrase string) (*bstypes.ProofOfPossession, error) { +func (kc *ChainKeyringController) CreatePop( + btcPrivKey *btcec.PrivateKey, + passphrase string, +) (*bstypes.ProofOfPossession, error) { bbnPrivKey, err := kc.GetChainPrivKey(passphrase) if err != nil { return nil, err @@ -130,7 +142,9 @@ func (kc *ChainKeyringController) CreatePop(btcPrivKey *btcec.PrivateKey, passph return bstypes.NewPoP(bbnPrivKey, btcPrivKey) } -func (kc *ChainKeyringController) GetChainPrivKey(passphrase string) (*sdksecp256k1.PrivKey, error) { +func (kc *ChainKeyringController) GetChainPrivKey( + passphrase string, +) (*sdksecp256k1.PrivKey, error) { kc.input.Reset(passphrase) k, err := kc.kr.Key(kc.fpName) if err != nil { diff --git a/keyring/keyringcontroller_test.go b/keyring/keyringcontroller_test.go index 4f654d57..c2903db1 100644 --- a/keyring/keyringcontroller_test.go +++ b/keyring/keyringcontroller_test.go @@ -43,7 +43,12 @@ func FuzzCreatePoP(f *testing.F) { eotsCfg := eotscfg.DefaultConfigWithHomePath(eotsHome) dbBackend, err := eotsCfg.DatabaseConfig.GetDbBackend() require.NoError(t, err) - em, err := eotsmanager.NewLocalEOTSManager(eotsHome, eotsCfg.KeyringBackend, dbBackend, zap.NewNop()) + em, err := eotsmanager.NewLocalEOTSManager( + eotsHome, + eotsCfg.KeyringBackend, + dbBackend, + zap.NewNop(), + ) defer func() { dbBackend.Close() err := os.RemoveAll(eotsHome) diff --git a/metrics/config.go b/metrics/config.go index 17bde531..d5141488 100644 --- a/metrics/config.go +++ b/metrics/config.go @@ -14,8 +14,8 @@ const ( ) type Config struct { - Host string `long:"host" description:"IP of the Prometheus server"` - Port int `long:"port" description:"Port of the Prometheus server"` + Host string `long:"host" description:"IP of the Prometheus server"` + Port int `long:"port" description:"Port of the Prometheus server"` UpdateInterval time.Duration `long:"updateinterval" description:"The interval of Prometheus metrics updated"` } diff --git a/metrics/fp_collectors.go b/metrics/fp_collectors.go index 82c6e0fc..23d4a384 100644 --- a/metrics/fp_collectors.go +++ b/metrics/fp_collectors.go @@ -277,11 +277,17 @@ func (fm *FpMetrics) UpdateFpMetrics(fps []*store.StoredFinalityProvider) { fm.RecordFpStatus(fp.GetBIP340BTCPK().MarshalHex(), fp.Status) if lastVoteTime, ok := fm.previousVoteByFp[fp.GetBIP340BTCPK().MarshalHex()]; ok { - fm.RecordFpSecondsSinceLastVote(fp.GetBIP340BTCPK().MarshalHex(), time.Since(*lastVoteTime).Seconds()) + fm.RecordFpSecondsSinceLastVote( + fp.GetBIP340BTCPK().MarshalHex(), + time.Since(*lastVoteTime).Seconds(), + ) } if lastRandomnessTime, ok := fm.previousRandomnessByFp[fp.GetBIP340BTCPK().MarshalHex()]; ok { - fm.RecordFpSecondsSinceLastRandomness(fp.GetBIP340BTCPK().MarshalHex(), time.Since(*lastRandomnessTime).Seconds()) + fm.RecordFpSecondsSinceLastRandomness( + fp.GetBIP340BTCPK().MarshalHex(), + time.Since(*lastRandomnessTime).Seconds(), + ) } } } diff --git a/testutil/datagen.go b/testutil/datagen.go index 6c3982c6..7d955737 100644 --- a/testutil/datagen.go +++ b/testutil/datagen.go @@ -106,16 +106,36 @@ func GenBlocks(r *rand.Rand, startHeight, endHeight uint64) []*types.BlockInfo { } // 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) *store.StoredFinalityProvider { +func GenStoredFinalityProvider( + r *rand.Rand, + t *testing.T, + app *service.FinalityProviderApp, + passphrase, hdPath string, +) *store.StoredFinalityProvider { // generate keyring keyName := GenRandomHexStr(r, 4) chainID := GenRandomHexStr(r, 4) cfg := app.GetConfig() - _, err := service.CreateChainKey(cfg.BabylonConfig.KeyDirectory, cfg.BabylonConfig.ChainID, keyName, keyring.BackendTest, passphrase, hdPath, "") + _, err := service.CreateChainKey( + cfg.BabylonConfig.KeyDirectory, + cfg.BabylonConfig.ChainID, + keyName, + keyring.BackendTest, + passphrase, + hdPath, + "", + ) require.NoError(t, err) - res, err := app.CreateFinalityProvider(keyName, chainID, passphrase, hdPath, RandomDescription(r), ZeroCommissionRate()) + res, err := app.CreateFinalityProvider( + keyName, + chainID, + passphrase, + hdPath, + RandomDescription(r), + ZeroCommissionRate(), + ) require.NoError(t, err) btcPk, err := bbn.NewBIP340PubKeyFromHex(res.FpInfo.BtcPkHex) diff --git a/testutil/utils.go b/testutil/utils.go index 402aa408..4b453d9a 100644 --- a/testutil/utils.go +++ b/testutil/utils.go @@ -18,7 +18,11 @@ func ZeroCommissionRate() *sdkmath.LegacyDec { return &zeroCom } -func PrepareMockedConsumerController(t *testing.T, r *rand.Rand, startHeight, currentHeight uint64) *mocks.MockConsumerController { +func PrepareMockedConsumerController( + t *testing.T, + r *rand.Rand, + startHeight, currentHeight uint64, +) *mocks.MockConsumerController { ctl := gomock.NewController(t) mockConsumerController := mocks.NewMockConsumerController(ctl)