From 9ffe4206545f8bf9dbee08e1ac6e6cc2b4daea06 Mon Sep 17 00:00:00 2001 From: Lazar Date: Tue, 12 Nov 2024 15:36:33 +0100 Subject: [PATCH] batch 1 of fixes --- babylonclient/babyloncontroller.go | 25 ++++----- babylonclient/interface.go | 20 +++---- babylonclient/msgsender.go | 23 ++++---- babylonclient/utils.go | 1 - cmd/stakercli/admin/admin.go | 8 +-- cmd/stakercli/daemon/daemoncommands.go | 18 +++---- cmd/stakercli/main.go | 8 +-- cmd/stakercli/transaction/transactions.go | 5 +- .../transaction/transactions_test.go | 8 +-- itest/e2e_test.go | 24 ++++----- staker/babylontypes.go | 8 ++- staker/commands.go | 4 +- staker/feeestimator.go | 1 - staker/nodebackend.go | 2 +- staker/stakerapp.go | 54 +++++++++---------- staker/stakercontroller.go | 5 +- staker/types.go | 25 ++++----- stakercfg/babylon.go | 2 +- stakercfg/bitcoind.go | 4 +- stakercfg/config.go | 32 +++++------ stakercfg/dbcfg.go | 4 +- stakercfg/utils.go | 23 ++++---- stakerdb/trackedtransactionstore_test.go | 31 ++++++----- stakerservice/client/rpcclient.go | 27 +++++----- stakerservice/service.go | 13 ++--- types/walletbackend.go | 1 - walletcontroller/client.go | 18 +++---- walletcontroller/transaction.go | 2 - 28 files changed, 183 insertions(+), 213 deletions(-) diff --git a/babylonclient/babyloncontroller.go b/babylonclient/babyloncontroller.go index c995597..83f38ae 100644 --- a/babylonclient/babyloncontroller.go +++ b/babylonclient/babyloncontroller.go @@ -16,7 +16,6 @@ import ( "github.com/avast/retry-go/v4" bbnclient "github.com/babylonlabs-io/babylon/client/client" bbntypes "github.com/babylonlabs-io/babylon/types" - bcctypes "github.com/babylonlabs-io/babylon/x/btccheckpoint/types" btclctypes "github.com/babylonlabs-io/babylon/x/btclightclient/types" btcstypes "github.com/babylonlabs-io/babylon/x/btcstaking/types" "github.com/babylonlabs-io/btc-staker/stakercfg" @@ -135,7 +134,7 @@ func (bc *BabylonController) Stop() error { func (bc *BabylonController) Params() (*StakingParams, error) { // TODO: it would probably be good to have separate methods for those - var bccParams *bcctypes.Params + var bccParams *btcctypes.Params if err := retry.Do(func() error { response, err := bc.bbnClient.BTCCheckpointParams() if err != nil { @@ -181,8 +180,8 @@ func (bc *BabylonController) Params() (*StakingParams, error) { } return &StakingParams{ - ConfirmationTimeBlocks: uint32(bccParams.BtcConfirmationDepth), - FinalizationTimeoutBlocks: uint32(bccParams.CheckpointFinalizationTimeout), + ConfirmationTimeBlocks: bccParams.BtcConfirmationDepth, + FinalizationTimeoutBlocks: bccParams.CheckpointFinalizationTimeout, SlashingPkScript: stakingTrackerParams.SlashingPkScript, CovenantPks: stakingTrackerParams.CovenantPks, MinSlashingTxFeeSat: stakingTrackerParams.MinSlashingFee, @@ -375,13 +374,13 @@ func delegationDataToMsg(dg *DelegationData) (*btcstypes.MsgCreateBTCDelegation, slashUnbondingTxSig := bbntypes.NewBIP340SignatureFromBTCSig(dg.Ud.SlashUnbondingTransactionSig) - var stakingTransactionInclusionProof *btcstypes.InclusionProof = nil + var stakingTransactionInclusionProof *btcstypes.InclusionProof if dg.StakingTransactionInclusionInfo != nil { inclusionBlockHash := bbntypes.NewBTCHeaderHashBytesFromChainhash( dg.StakingTransactionInclusionInfo.StakingTransactionInclusionBlockHash, ) - txKey := &bcctypes.TransactionKey{ + txKey := &btcctypes.TransactionKey{ Index: dg.StakingTransactionInclusionInfo.StakingTransactionIdx, Hash: &inclusionBlockHash, } @@ -670,7 +669,6 @@ func (bc *BabylonController) QueryHeaderDepth(headerHash *chainhash.Hash) (uint3 "error": err, }).Error("Failed to query babylon for the depth of the header") })); err != nil { - // translate errors to locally handable ones if strings.Contains(err.Error(), btclctypes.ErrHeaderDoesNotExist.Error()) { return 0, fmt.Errorf("%s: %w", err.Error(), ErrHeaderNotKnownToBabylon) @@ -681,10 +679,9 @@ func (bc *BabylonController) QueryHeaderDepth(headerHash *chainhash.Hash) (uint3 } return response.Depth, nil - } -// Insert BTC block header using rpc client +// InsertBtcBlockHeaders Insert BTC block header using rpc client func (bc *BabylonController) InsertBtcBlockHeaders(headers []*wire.BlockHeader) (*pv.RelayerTxResponse, error) { msg := &btclctypes.MsgInsertHeaders{ Signer: bc.getTxSigner(), @@ -748,7 +745,7 @@ func (bc *BabylonController) QueryDelegationInfo(stakingTxHash *chainhash.Hash) return err } - var udi *UndelegationInfo = nil + var udi *UndelegationInfo if resp.BtcDelegation.UndelegationResponse != nil { var coventSigInfos []CovenantSignatureInfo @@ -873,7 +870,7 @@ func (bc *BabylonController) QueryPendingBTCDelegations() ([]*btcstypes.BTCDeleg res, err := queryClient.BTCDelegations(ctx, &queryRequest) if err != nil { - return nil, fmt.Errorf("failed to query BTC delegations: %v", err) + return nil, fmt.Errorf("failed to query BTC delegations: %w", err) } return res.BtcDelegations, nil @@ -900,17 +897,16 @@ func (bc *BabylonController) InsertSpvProofs(submitter string, proofs []*btcctyp func (bc *BabylonController) QueryBtcLightClientTip() (*btclctypes.BTCHeaderInfoResponse, error) { res, err := bc.bbnClient.QueryClient.BTCHeaderChainTip() if err != nil { - return nil, fmt.Errorf("failed to query BTC tip: %v", err) + return nil, fmt.Errorf("failed to query BTC tip: %w", err) } return res.Header, nil } func (bc *BabylonController) ActivateDelegation( - ctx context.Context, + _ context.Context, stakingTxHash chainhash.Hash, proof *btcctypes.BTCSpvProof) (*pv.RelayerTxResponse, error) { - msg := &btcstypes.MsgAddBTCDelegationInclusionProof{ Signer: bc.getTxSigner(), StakingTxHash: stakingTxHash.String(), @@ -923,5 +919,4 @@ func (bc *BabylonController) ActivateDelegation( } return res, nil - } diff --git a/babylonclient/interface.go b/babylonclient/interface.go index eeee91d..588c9ec 100644 --- a/babylonclient/interface.go +++ b/babylonclient/interface.go @@ -34,25 +34,25 @@ type StakingParams struct { // The rate at which the staked funds will be slashed, expressed as a decimal. SlashingRate sdkmath.LegacyDec - // Convenant quorum threshold + // Covenant quorum threshold CovenantQuruomThreshold uint32 - // Minimum unbonding time required by bayblon + // Minimum unbonding time required by babylon MinUnbondingTime uint16 // Fee required by unbonding transaction UnbondingFee btcutil.Amount - // Minimum staking time required by bayblon + // Minimum staking time required by babylon MinStakingTime uint16 - // Maximum staking time required by bayblon + // Maximum staking time required by babylon MaxStakingTime uint16 - // Minimum staking value required by bayblon + // Minimum staking value required by babylon MinStakingValue btcutil.Amount - // Maximum staking value required by bayblon + // Maximum staking value required by babylon MaxStakingValue btcutil.Amount } @@ -124,7 +124,7 @@ func (m *MockBabylonClient) Delegate(dg *DelegationData) (*pv.RelayerTxResponse, return &pv.RelayerTxResponse{Code: 0}, nil } -func (m *MockBabylonClient) QueryFinalityProviders(limit uint64, offset uint64) (*FinalityProvidersClientResponse, error) { +func (m *MockBabylonClient) QueryFinalityProviders(_ uint64, _ uint64) (*FinalityProvidersClientResponse, error) { return &FinalityProvidersClientResponse{ FinalityProviders: []FinalityProviderInfo{*m.ActiveFinalityProvider}, Total: 1, @@ -136,12 +136,12 @@ func (m *MockBabylonClient) QueryFinalityProvider(btcPubKey *btcec.PublicKey) (* return &FinalityProviderClientResponse{ FinalityProvider: *m.ActiveFinalityProvider, }, nil - } else { - return nil, ErrFinalityProviderDoesNotExist } + + return nil, ErrFinalityProviderDoesNotExist } -func (m *MockBabylonClient) QueryHeaderDepth(headerHash *chainhash.Hash) (uint32, error) { +func (m *MockBabylonClient) QueryHeaderDepth(_ *chainhash.Hash) (uint32, error) { // return always confirmed depth return m.ClientParams.ConfirmationTimeBlocks + 1, nil } diff --git a/babylonclient/msgsender.go b/babylonclient/msgsender.go index 028de65..2660aeb 100644 --- a/babylonclient/msgsender.go +++ b/babylonclient/msgsender.go @@ -66,22 +66,22 @@ func NewBabylonMsgSender( } } -func (b *BabylonMsgSender) Start() { - b.startOnce.Do(func() { - b.wg.Add(1) - go b.handleSentToBabylon() +func (m *BabylonMsgSender) Start() { + m.startOnce.Do(func() { + m.wg.Add(1) + go m.handleSentToBabylon() }) } -func (b *BabylonMsgSender) Stop() { - b.stopOnce.Do(func() { - close(b.quit) - b.wg.Wait() +func (m *BabylonMsgSender) Stop() { + m.stopOnce.Do(func() { + close(m.quit) + m.wg.Wait() }) } // isBabylonBtcLcReady checks if Babylon BTC light client is ready to receive delegation -func (b *BabylonMsgSender) isBabylonBtcLcReady( +func (m *BabylonMsgSender) isBabylonBtcLcReady( requiredInclusionBlockDepth uint32, req *DelegationData, ) error { @@ -90,7 +90,7 @@ func (b *BabylonMsgSender) isBabylonBtcLcReady( return nil } - depth, err := b.cl.QueryHeaderDepth(req.StakingTransactionInclusionInfo.StakingTransactionInclusionBlockHash) + depth, err := m.cl.QueryHeaderDepth(req.StakingTransactionInclusionInfo.StakingTransactionInclusionBlockHash) if err != nil { // If header is not known to babylon, or it is on LCFork, then most probably @@ -103,7 +103,7 @@ func (b *BabylonMsgSender) isBabylonBtcLcReady( return fmt.Errorf("error while getting delegation data: %w", err) } - if uint32(depth) < requiredInclusionBlockDepth { + if depth < requiredInclusionBlockDepth { return fmt.Errorf("btc lc not ready, required depth: %d, current depth: %d: %w", requiredInclusionBlockDepth, depth, ErrBabylonBtcLightClientNotReady) } @@ -183,5 +183,4 @@ func (m *BabylonMsgSender) SendDelegation( m.sendDelegationRequestChan, m.quit, ) - } diff --git a/babylonclient/utils.go b/babylonclient/utils.go index 6a979c1..e0c993d 100644 --- a/babylonclient/utils.go +++ b/babylonclient/utils.go @@ -8,7 +8,6 @@ import ( ) func GenerateProof(block *wire.MsgBlock, txIdx uint32) ([]byte, error) { - headerBytes := babylontypes.NewBTCHeaderBytesFromBlockHeader(&block.Header) var txsBytes [][]byte diff --git a/cmd/stakercli/admin/admin.go b/cmd/stakercli/admin/admin.go index 641fa8a..4311332 100644 --- a/cmd/stakercli/admin/admin.go +++ b/cmd/stakercli/admin/admin.go @@ -86,7 +86,7 @@ const ( mnemonicEntropySize = 256 secp256k1Type = "secp256k1" - chainIdFlag = "chain-id" + chainIDFlag = "chain-id" keyringBackendFlag = "keyring-backend" keyNameFlag = "key-name" keyringDir = "keyring-dir" @@ -135,13 +135,13 @@ func createKeyRing(c *cli.Context) error { app := babylonApp.NewTmpBabylonApp() - chainId := c.String(chainIdFlag) + chainID := c.String(chainIDFlag) backend := c.String(keyringBackendFlag) keyName := c.String(keyNameFlag) keyDir := c.String(keyringDir) kb, err := keyring.New( - chainId, + chainID, backend, keyDir, nil, @@ -189,7 +189,7 @@ var createCosmosKeyringCommand = cli.Command{ Value: defaultBackend, }, cli.StringFlag{ - Name: chainIdFlag, + Name: chainIDFlag, Usage: "Chain ID for which account is created", Value: defaultChainID, }, diff --git a/cmd/stakercli/daemon/daemoncommands.go b/cmd/stakercli/daemon/daemoncommands.go index fe13558..997ca0c 100644 --- a/cmd/stakercli/daemon/daemoncommands.go +++ b/cmd/stakercli/daemon/daemoncommands.go @@ -240,7 +240,7 @@ var withdrawableTransactionsCmd = cli.Command{ func checkHealth(ctx *cli.Context) error { daemonAddress := ctx.String(stakingDaemonAddressFlag) - client, err := dc.NewStakerServiceJsonRpcClient(daemonAddress) + client, err := dc.NewStakerServiceJsonRPCClient(daemonAddress) if err != nil { return err } @@ -260,7 +260,7 @@ func checkHealth(ctx *cli.Context) error { func listOutputs(ctx *cli.Context) error { daemonAddress := ctx.String(stakingDaemonAddressFlag) - client, err := dc.NewStakerServiceJsonRpcClient(daemonAddress) + client, err := dc.NewStakerServiceJsonRPCClient(daemonAddress) if err != nil { return err } @@ -280,7 +280,7 @@ func listOutputs(ctx *cli.Context) error { func babylonFinalityProviders(ctx *cli.Context) error { daemonAddress := ctx.String(stakingDaemonAddressFlag) - client, err := dc.NewStakerServiceJsonRpcClient(daemonAddress) + client, err := dc.NewStakerServiceJsonRPCClient(daemonAddress) if err != nil { return err } @@ -312,7 +312,7 @@ func babylonFinalityProviders(ctx *cli.Context) error { func stake(ctx *cli.Context) error { daemonAddress := ctx.String(stakingDaemonAddressFlag) - client, err := dc.NewStakerServiceJsonRpcClient(daemonAddress) + client, err := dc.NewStakerServiceJsonRPCClient(daemonAddress) if err != nil { return err } @@ -337,7 +337,7 @@ func stake(ctx *cli.Context) error { func unstake(ctx *cli.Context) error { daemonAddress := ctx.String(stakingDaemonAddressFlag) - client, err := dc.NewStakerServiceJsonRpcClient(daemonAddress) + client, err := dc.NewStakerServiceJsonRPCClient(daemonAddress) if err != nil { return err } @@ -358,7 +358,7 @@ func unstake(ctx *cli.Context) error { func unbond(ctx *cli.Context) error { daemonAddress := ctx.String(stakingDaemonAddressFlag) - client, err := dc.NewStakerServiceJsonRpcClient(daemonAddress) + client, err := dc.NewStakerServiceJsonRPCClient(daemonAddress) if err != nil { return err } @@ -379,7 +379,7 @@ func unbond(ctx *cli.Context) error { func stakingDetails(ctx *cli.Context) error { daemonAddress := ctx.String(stakingDaemonAddressFlag) - client, err := dc.NewStakerServiceJsonRpcClient(daemonAddress) + client, err := dc.NewStakerServiceJsonRPCClient(daemonAddress) if err != nil { return err } @@ -400,7 +400,7 @@ func stakingDetails(ctx *cli.Context) error { func listStakingTransactions(ctx *cli.Context) error { daemonAddress := ctx.String(stakingDaemonAddressFlag) - client, err := dc.NewStakerServiceJsonRpcClient(daemonAddress) + client, err := dc.NewStakerServiceJsonRPCClient(daemonAddress) if err != nil { return err } @@ -432,7 +432,7 @@ func listStakingTransactions(ctx *cli.Context) error { func withdrawableTransactions(ctx *cli.Context) error { daemonAddress := ctx.String(stakingDaemonAddressFlag) - client, err := dc.NewStakerServiceJsonRpcClient(daemonAddress) + client, err := dc.NewStakerServiceJsonRPCClient(daemonAddress) if err != nil { return err } diff --git a/cmd/stakercli/main.go b/cmd/stakercli/main.go index 4a27eb4..fbb4358 100644 --- a/cmd/stakercli/main.go +++ b/cmd/stakercli/main.go @@ -18,8 +18,8 @@ func fatal(err error) { const ( btcNetworkFlag = "btc-network" btcWalletHostFlag = "btc-wallet-host" - btcWalletRpcUserFlag = "btc-wallet-rpc-user" - btcWalletRpcPassFlag = "btc-wallet-rpc-pass" + btcWalletRPCUserFlag = "btc-wallet-rpc-user" + btcWalletRPCPassFlag = "btc-wallet-rpc-pass" btcWalletPassphraseFlag = "btc-wallet-passphrase" btcWalletBackendFlag = "btc-wallet-backend" ) @@ -40,12 +40,12 @@ func main() { Value: "127.0.0.1:18554", }, cli.StringFlag{ - Name: btcWalletRpcUserFlag, + Name: btcWalletRPCUserFlag, Usage: "Bitcoin wallet rpc user", Value: "user", }, cli.StringFlag{ - Name: btcWalletRpcPassFlag, + Name: btcWalletRPCPassFlag, Usage: "Bitcoin wallet rpc password", Value: "pass", }, diff --git a/cmd/stakercli/transaction/transactions.go b/cmd/stakercli/transaction/transactions.go index da16aad..b3ef85f 100644 --- a/cmd/stakercli/transaction/transactions.go +++ b/cmd/stakercli/transaction/transactions.go @@ -99,7 +99,6 @@ func validateTxAgainstParams( tx *wire.MsgTx, globalParams *parser.ParsedGlobalParams, net *chaincfg.Params) *CheckPhase1StakingTxResponse { - var info []*ValidityInfo for i := len(globalParams.Versions) - 1; i >= 0; i-- { @@ -330,7 +329,7 @@ var checkPhase1StakingTransactionCmd = cli.Command{ Name: "check-phase1-staking-transaction", ShortName: "cpst", Usage: "Checks whether provided staking transactions is valid staking transaction (tx must be funded/have inputs)", - Description: "Checks staking transaction agains custom set of parameters. Use for custom transactions" + + Description: "Checks staking transaction against custom set of parameters. Use for custom transactions" + "that may not obey the global parameters. For most cases use `check-phase1-staking-transaction-params`", Flags: []cli.Flag{ cli.StringFlag{ @@ -527,7 +526,6 @@ func createPhase1StakingTransactionWithParams(ctx *cli.Context) error { if err != nil { return fmt.Errorf("error parsing file %s: %w", inputFilePath, err) - } currentNetwork, err := utils.GetBtcNetworkParams(ctx.String(networkNameFlag)) @@ -891,7 +889,6 @@ func createWithdrawalInfo( parsedStakingTransaction *btcstaking.ParsedV0StakingTx, paramsForHeight *parser.ParsedVersionedGlobalParams, net *chaincfg.Params) (*withdrawalInfo, error) { - if len(unbondingTxHex) > 0 { // withdrawal from unbonding output unbondingTx, _, err := bbn.NewBTCTxFromHex(unbondingTxHex) diff --git a/cmd/stakercli/transaction/transactions_test.go b/cmd/stakercli/transaction/transactions_test.go index bcde69c..b9839a6 100644 --- a/cmd/stakercli/transaction/transactions_test.go +++ b/cmd/stakercli/transaction/transactions_test.go @@ -71,6 +71,7 @@ var ( Versions: []*parser.VersionedGlobalParams{&defaultParam}, } + //nolint:errchkjson paramsMarshalled, _ = json.Marshal(globalParams) parsedGlobalParams, _ = parser.ParseGlobalParams(&globalParams) @@ -78,6 +79,7 @@ var ( ) func TestVerifyUnspendableKeyPath(t *testing.T) { + t.Parallel() bz, err := hex.DecodeString(unspendableKeyPath) require.NoError(t, err) @@ -221,7 +223,7 @@ func appRunCreatePhase1WithdrawalTx(r *rand.Rand, t *testing.T, app *cli.App, ar return data } -func randRange(r *rand.Rand, min, max int) int { +func randRange(_ *rand.Rand, min, max int) int { return rand.Intn(max+1-min) + min } @@ -277,6 +279,7 @@ func createCustomValidStakeParams( } func TestCheckPhase1StakingTransactionCmd(t *testing.T) { + t.Parallel() app := testApp() stakerCliCheckP1StkTx := []string{ "stakercli", "transaction", "check-phase1-staking-transaction", @@ -593,7 +596,6 @@ func FuzzCreateWithdrawalStaking(f *testing.F) { require.Equal(t, ctrlBlockBytes, decoded.Inputs[0].TaprootLeafScript[0].ControlBlock) require.Equal(t, tli.RevealedLeaf.Script, decoded.Inputs[0].TaprootLeafScript[0].Script) require.Equal(t, tli.RevealedLeaf.LeafVersion, decoded.Inputs[0].TaprootLeafScript[0].LeafVersion) - }) } @@ -684,7 +686,7 @@ func FuzzCreateWithdrawalUnbonding(f *testing.F) { addrPkScript, err := txscript.PayToAddrScript(addr) require.NoError(t, err) require.Equal(t, addrPkScript, wtx.TxOut[0].PkScript) - require.Equal(t, int64(unbondingInfo.UnbondingOutput.Value)-fee, wtx.TxOut[0].Value) + require.Equal(t, unbondingInfo.UnbondingOutput.Value-fee, wtx.TxOut[0].Value) decodedBytes, err := base64.StdEncoding.DecodeString(wr.WithdrawalPsbtPacketBase64) require.NoError(t, err) diff --git a/itest/e2e_test.go b/itest/e2e_test.go index 0412590..c60344c 100644 --- a/itest/e2e_test.go +++ b/itest/e2e_test.go @@ -95,10 +95,10 @@ func defaultStakerConfig(t *testing.T, walletName, passphrase, bitcoindHost stri bitcoindPass := "pass" // Wallet configuration - defaultConfig.WalletRpcConfig.Host = bitcoindHost - defaultConfig.WalletRpcConfig.User = bitcoindUser - defaultConfig.WalletRpcConfig.Pass = bitcoindPass - defaultConfig.WalletRpcConfig.DisableTls = true + defaultConfig.WalletRPCConfig.Host = bitcoindHost + defaultConfig.WalletRPCConfig.User = bitcoindUser + defaultConfig.WalletRPCConfig.Pass = bitcoindPass + defaultConfig.WalletRPCConfig.DisableTLS = true defaultConfig.WalletConfig.WalletPass = passphrase defaultConfig.WalletConfig.WalletName = walletName @@ -147,7 +147,7 @@ type TestManager struct { MinerAddr btcutil.Address wg *sync.WaitGroup serviceAddress string - StakerClient *dc.StakerServiceJsonRpcClient + StakerClient *dc.StakerServiceJsonRPCClient CovenantPrivKeys []*btcec.PrivateKey BitcoindHandler *BitcoindTestHandler TestRpcClient *rpcclient.Client @@ -272,7 +272,7 @@ func StartManager( rpcHost := fmt.Sprintf("127.0.0.1:%s", bitcoind.GetPort("18443/tcp")) cfg, c := defaultStakerConfig(t, walletName, passphrase, rpcHost) cfg.BtcNodeBackendConfig.Bitcoind.RPCHost = rpcHost - cfg.WalletRpcConfig.Host = fmt.Sprintf("127.0.0.1:%s", bitcoind.GetPort("18443/tcp")) + cfg.WalletRPCConfig.Host = fmt.Sprintf("127.0.0.1:%s", bitcoind.GetPort("18443/tcp")) // update port with the dynamically allocated one from docker cfg.BabylonConfig.RPCAddr = fmt.Sprintf("http://localhost:%s", babylond.GetPort("26657/tcp")) @@ -325,7 +325,7 @@ func StartManager( addressString := fmt.Sprintf("127.0.0.1:%d", testutil.AllocateUniquePort(t)) addrPort := netip.MustParseAddrPort(addressString) address := net.TCPAddrFromAddrPort(addrPort) - cfg.RpcListeners = append(cfg.RpcListeners, address) // todo(lazar): check with konrad who uses this + cfg.RPCListeners = append(cfg.RPCListeners, address) // todo(lazar): check with konrad who uses this stakerService := service.NewStakerService( cfg, @@ -346,7 +346,7 @@ func StartManager( // Wait for the server to start time.Sleep(3 * time.Second) - stakerClient, err := dc.NewStakerServiceJsonRpcClient("tcp://" + addressString) + stakerClient, err := dc.NewStakerServiceJsonRPCClient("tcp://" + addressString) require.NoError(t, err) return &TestManager{ @@ -426,7 +426,7 @@ func (tm *TestManager) RestartAppWithAction(t *testing.T, ctx context.Context, c tm.wg = &wg tm.Db = dbbackend tm.Sa = stakerApp - stakerClient, err := dc.NewStakerServiceJsonRpcClient("tcp://" + tm.serviceAddress) + stakerClient, err := dc.NewStakerServiceJsonRPCClient("tcp://" + tm.serviceAddress) require.NoError(t, err) tm.StakerClient = stakerClient } @@ -1747,9 +1747,9 @@ func TestBitcoindWalletRpcApi(t *testing.T) { // hardcoded config scfg := stakercfg.DefaultConfig() - scfg.WalletRpcConfig.Host = fmt.Sprintf("127.0.0.1:%s", bitcoind.GetPort("18443/tcp")) - scfg.WalletRpcConfig.User = "user" - scfg.WalletRpcConfig.Pass = "pass" + scfg.WalletRPCConfig.Host = fmt.Sprintf("127.0.0.1:%s", bitcoind.GetPort("18443/tcp")) + scfg.WalletRPCConfig.User = "user" + scfg.WalletRPCConfig.Pass = "pass" scfg.ActiveNetParams.Name = "regtest" scfg.WalletConfig.WalletPass = passphrase scfg.WalletConfig.WalletName = walletName diff --git a/staker/babylontypes.go b/staker/babylontypes.go index f2ad7ae..aebe160 100644 --- a/staker/babylontypes.go +++ b/staker/babylontypes.go @@ -71,7 +71,7 @@ func (app *StakerApp) buildOwnedDelegation( externalData.babylonParams.SlashingPkScript, externalData.babylonParams.UnbondingFee, // TODO: Possiblity to customize finalization time - uint16(externalData.babylonParams.MinUnbondingTime)+1, + externalData.babylonParams.MinUnbondingTime+1, app.getSlashingFee(externalData.babylonParams.MinSlashingTxFeeSat), externalData.babylonParams.SlashingRate, app.network, @@ -137,7 +137,6 @@ func (app *StakerApp) buildDelegation( req *sendDelegationRequest, stakerAddress btcutil.Address, storedTx *stakerdb.StoredTransaction) (*cl.DelegationData, error) { - if storedTx.Watched { watchedData, err := app.txTracker.GetWatchedTransactionData(&req.txHash) @@ -178,7 +177,7 @@ func (app *StakerApp) buildDelegation( } } -// TODO for now we launch this handler indefinitly. At some point we may introduce +// TODO for now we launch this handler indefinitely. At some point we may introduce // timeout, and if signatures are not find in this timeout, then we may submit // evidence that covenant members are censoring our staking transactions func (app *StakerApp) checkForUnbondingTxSignaturesOnBabylon(stakingTxHash *chainhash.Hash) { @@ -477,9 +476,8 @@ func (app *StakerApp) activateVerifiedDelegation( "stakingTxHash": stakingTxHash, }).Error("failed to send staking transaction to btc chain to activate verified delegation") } - // at this point we send signed staking transaciton to BTC chain, we will + // at this point we send signed staking transaction to BTC chain, we will // still wait for its activation - case <-app.quit: return } diff --git a/staker/commands.go b/staker/commands.go index 3f61ceb..aee8b0a 100644 --- a/staker/commands.go +++ b/staker/commands.go @@ -123,11 +123,11 @@ func newWatchedStakingCmd( } } -func (event *stakingRequestCmd) EventId() chainhash.Hash { +func (req *stakingRequestCmd) EventId() chainhash.Hash { // we do not have has for this event return chainhash.Hash{} } -func (event *stakingRequestCmd) EventDesc() string { +func (req *stakingRequestCmd) EventDesc() string { return "STAKING_REQUESTED_CMD" } diff --git a/staker/feeestimator.go b/staker/feeestimator.go index f1fb367..a44ad2c 100644 --- a/staker/feeestimator.go +++ b/staker/feeestimator.go @@ -36,7 +36,6 @@ func NewDynamicBtcFeeEstimator( cfg *scfg.BtcNodeBackendConfig, _ *chaincfg.Params, logger *logrus.Logger) (*DynamicBtcFeeEstimator, error) { - minFeeRate := chainfee.SatPerKVByte(cfg.MinFeeRate * 1000) maxFeeRate := chainfee.SatPerKVByte(cfg.MaxFeeRate * 1000) diff --git a/staker/nodebackend.go b/staker/nodebackend.go index fbdb9aa..ade74c2 100644 --- a/staker/nodebackend.go +++ b/staker/nodebackend.go @@ -26,7 +26,7 @@ type NodeBackend struct { // According to chain.BitcoindConfig docs it should also support tor if node backend // works over tor. func BuildDialer(rpcHost string) func(string) (net.Conn, error) { - return func(addr string) (net.Conn, error) { + return func(_ string) (net.Conn, error) { return net.Dial("tcp", rpcHost) } } diff --git a/staker/stakerapp.go b/staker/stakerapp.go index 0266b69..841f8a2 100644 --- a/staker/stakerapp.go +++ b/staker/stakerapp.go @@ -46,7 +46,7 @@ type externalDelegationData struct { babylonParams *cl.StakingParams } -type stakingDbInfo struct { +type stakingDBInfo struct { stakingTxHash *chainhash.Hash stakingTxState proto.TransactionState } @@ -169,7 +169,7 @@ func NewStakerAppFromConfig( ) if err != nil { - return nil, fmt.Errorf("unable to create height hint cache: %v", err) + return nil, fmt.Errorf("unable to create height hint cache: %w", err) } nodeNotifier, err := NewNodeBackend(config.BtcNodeBackendConfig, &config.ActiveNetParams, hintCache) @@ -247,7 +247,7 @@ func NewStakerAppFromDeps( // channel which receives confirmation that unbonding transaction was confirmed on BTC unbondingTxConfirmedOnBtcEvChan: make(chan *unbondingTxConfirmedOnBtcEvent), // channel which receives critical errors, critical errors are errors which we do not know - // how to handle, so we just log them. It is up to user to investigate, what had happend + // how to handle, so we just log them. It is up to user to investigate what had happened // and report the situation criticalErrorEvChan: make(chan *criticalErrorEvent), }, nil @@ -416,7 +416,6 @@ func (app *StakerApp) handleBtcTxInfo( currentBestBlockHeight uint32, txStatus walletcontroller.TxStatus, btcTxInfo *notifier.TxConfirmation) error { - switch txStatus { case walletcontroller.TxNotFound: // Most probable reason this happened is transaction was included in btc chain (removed from mempool) @@ -448,9 +447,9 @@ func (app *StakerApp) handleBtcTxInfo( }).Debug("Transaction found in chain") if currentBestBlockHeight < btcTxInfo.BlockHeight { - // This is wierd case, we retrieved transaction from btc wallet, even though wallet best height + // This is a wierd case; we retrieved transaction from btc wallet, even though wallet the best height // is lower than block height of transaction. - // Log it as error so that user can investigate. + // Log it as an error so that user can investigate. app.logger.WithFields(logrus.Fields{ "btcTxHash": stakingTxHash, "btcTxBlockHeight": btcTxInfo.BlockHeight, @@ -485,7 +484,6 @@ func (app *StakerApp) handleBtcTxInfo( ev, app.quit, ) - } else { app.logger.WithFields(logrus.Fields{ "btcTxHash": stakingTxHash, @@ -525,17 +523,17 @@ func (app *StakerApp) checkTransactionsStatus() error { return err } - // Keep track of all staking transactions which need checking. chainhash.Hash objects are not relativly small + // Keep track of all staking transactions which need checking. chainhash.Hash objects are not relatively small // so it should not OOM even for larage database var transactionsSentToBtc []*chainhash.Hash var transactionConfirmedOnBtc []*chainhash.Hash - var transactionsOnBabylon []*stakingDbInfo + var transactionsOnBabylon []*stakingDBInfo var transactionsVerifiedOnBabylon []*chainhash.Hash reset := func() { transactionsSentToBtc = make([]*chainhash.Hash, 0) transactionConfirmedOnBtc = make([]*chainhash.Hash, 0) - transactionsOnBabylon = make([]*stakingDbInfo, 0) + transactionsOnBabylon = make([]*stakingDBInfo, 0) transactionsVerifiedOnBabylon = make([]*chainhash.Hash, 0) } @@ -544,7 +542,7 @@ func (app *StakerApp) checkTransactionsStatus() error { // to use to update transaction state. err = app.txTracker.ScanTrackedTransactions(func(tx *stakerdb.StoredTransaction) error { // TODO : We need to have another stare like UnstakeTransaction sent and store - // info about transaction sent (hash) to check wheter it was confirmed after staker + // info about transaction sent (hash) to check whether it was confirmed after staker // restarts stakingTxHash := tx.StakingTx.TxHash() switch tx.State { @@ -558,9 +556,9 @@ func (app *StakerApp) checkTransactionsStatus() error { // that we sent undelegation msg, but restart happened before we could update // database case proto.TransactionState_SENT_TO_BABYLON: - // TODO: If we will have automatic unstaking, we should check wheter tx is expired + // TODO: If we will have automatic unstaking, we should check whether tx is expired // and proceed with sending unstake transaction - transactionsOnBabylon = append(transactionsOnBabylon, &stakingDbInfo{ + transactionsOnBabylon = append(transactionsOnBabylon, &stakingDBInfo{ stakingTxHash: &stakingTxHash, stakingTxState: tx.State, }) @@ -569,13 +567,13 @@ func (app *StakerApp) checkTransactionsStatus() error { transactionsVerifiedOnBabylon = append(transactionsVerifiedOnBabylon, &stakingTxHash) return nil case proto.TransactionState_DELEGATION_ACTIVE: - transactionsOnBabylon = append(transactionsOnBabylon, &stakingDbInfo{ + transactionsOnBabylon = append(transactionsOnBabylon, &stakingDBInfo{ stakingTxHash: &stakingTxHash, stakingTxState: tx.State, }) return nil case proto.TransactionState_UNBONDING_CONFIRMED_ON_BTC: - transactionsOnBabylon = append(transactionsOnBabylon, &stakingDbInfo{ + transactionsOnBabylon = append(transactionsOnBabylon, &stakingDBInfo{ stakingTxHash: &stakingTxHash, stakingTxState: tx.State, }) @@ -700,7 +698,7 @@ func (app *StakerApp) checkTransactionsStatus() error { // we only can have one local states here if localInfo.stakingTxState == proto.TransactionState_SENT_TO_BABYLON { stakingTxHash := localInfo.stakingTxHash - // we crashed after succesful send to babaylon, restart checking for unbonding signatures + // we crashed after successful send to babylon, restart checking for unbonding signatures app.wg.Add(1) go app.checkForUnbondingTxSignaturesOnBabylon(stakingTxHash) } else if localInfo.stakingTxState == proto.TransactionState_DELEGATION_ACTIVE { @@ -947,7 +945,6 @@ func (app *StakerApp) sendUnbondingTxToBtcWithWitness( storedTx *stakerdb.StoredTransaction, unbondingData *stakerdb.UnbondingStoreData, ) error { - stakerPubKey, err := app.wc.AddressPublicKey(stakerAddress) if err != nil { @@ -1038,14 +1035,13 @@ func (app *StakerApp) sendUnbondingTxToBtcWithWitness( // sendUnbondingTxToBtc sends unbonding tx to btc and registers for inclusion notification. // It retries until it successfully sends unbonding tx to btc and registers for notification.or until program finishes -// TODO: Investigate wheter some of the errors should be treated as fatal and abort whole process +// TODO: Investigate whether some of the errors should be treated as fatal and abort whole process func (app *StakerApp) sendUnbondingTxToBtc( ctx context.Context, stakingTxHash *chainhash.Hash, stakerAddress btcutil.Address, storedTx *stakerdb.StoredTransaction, unbondingData *stakerdb.UnbondingStoreData) (*notifier.ConfirmationEvent, error) { - err := retry.Do(func() error { return app.sendUnbondingTxToBtcWithWitness( stakingTxHash, @@ -1272,7 +1268,7 @@ func (app *StakerApp) handlePreApprovalCmd( stakingOutputIdx, cmd.stakingTime, cmd.fpBtcPks, - babylonPopToDbPop(cmd.pop), + babylonPopToDBPop(cmd.pop), cmd.stakerAddress, ) @@ -1303,7 +1299,7 @@ func (app *StakerApp) handlePreApprovalCmd( stakingOutputIdx, cmd.stakingTime, cmd.fpBtcPks, - babylonPopToDbPop(cmd.pop), + babylonPopToDBPop(cmd.pop), cmd.stakerAddress, delegationData.Ud.UnbondingTransaction, delegationData.Ud.UnbondingTxUnbondingTime, @@ -1356,7 +1352,7 @@ func (app *StakerApp) handlePostApprovalCmd( &stakingTxHash, stakingOutputPkScript, cmd.requiredDepthOnBtcChain, - uint32(bestBlockHeight), + bestBlockHeight, ); err != nil { return nil, err } @@ -1366,7 +1362,7 @@ func (app *StakerApp) handlePostApprovalCmd( stakingOutputIdx, cmd.stakingTime, cmd.fpBtcPks, - babylonPopToDbPop(cmd.pop), + babylonPopToDBPop(cmd.pop), cmd.stakerAddress, ); err != nil { return nil, err @@ -1411,7 +1407,7 @@ func (app *StakerApp) handleStakingCommands() { cmd.watchTxData.stakingOutputIdx, cmd.stakingTime, cmd.fpBtcPks, - babylonPopToDbPop(cmd.pop), + babylonPopToDBPop(cmd.pop), cmd.stakerAddress, cmd.watchTxData.slashingTx, cmd.watchTxData.slashingTxSig, @@ -1433,7 +1429,7 @@ func (app *StakerApp) handleStakingCommands() { &cmd.watchTxData.stakingTxHash, cmd.watchTxData.stakingTx.TxOut[cmd.watchTxData.stakingOutputIdx].PkScript, cmd.requiredDepthOnBtcChain, - uint32(bestBlockHeight), + bestBlockHeight, ); err != nil { cmd.errChan <- err continue @@ -1532,7 +1528,7 @@ func (app *StakerApp) handleStakingEvents() { if err := app.txTracker.SetTxUnbondingSignaturesReceived( &ev.stakingTxHash, - babylonCovSigsToDbSigSigs(ev.covenantUnbondingSignatures), + babylonCovSigsToDBSigSigs(ev.covenantUnbondingSignatures), ); err != nil { // TODO: handle this error somehow, it means we possilbly make invalid state transition app.logger.Fatalf("Error setting state for tx %s: %s", &ev.stakingTxHash, err) @@ -1762,7 +1758,6 @@ func (app *StakerApp) StakeFunds( stakingTimeBlocks uint16, sendToBabylonFirst bool, ) (*chainhash.Hash, error) { - // check we are not shutting down select { case <-app.quit: @@ -1815,7 +1810,7 @@ func (app *StakerApp) StakeFunds( return nil, err } - // build proof of possesion, no point moving forward if staker do not have all + // build proof of possession, no point moving forward if staker do not have all // the necessary keys stakerPubKey, err := app.wc.AddressPublicKey(stakerAddress) @@ -1980,7 +1975,6 @@ func (app *StakerApp) signTaprootScriptSpendUsingWallet( leaf *txscript.TapLeaf, controlBlock *txscript.ControlBlock, ) (*walletcontroller.TaprootSigningResult, error) { - if err := app.wc.UnlockWallet(defaultWalletUnlockTimeout); err != nil { return nil, fmt.Errorf("failed to unlock wallet before signing: %w", err) } @@ -2185,7 +2179,7 @@ func (app *StakerApp) UnbondStaking( stakerAddress, err := btcutil.DecodeAddress(tx.StakerAddress, app.network) if err != nil { - return nil, fmt.Errorf("error decoding staker address: %s. Err: %v", tx.StakerAddress, err) + return nil, fmt.Errorf("error decoding staker address: %s. Err: %w", tx.StakerAddress, err) } // TODO: Move this to event handler to avoid somebody starting multiple unbonding routines diff --git a/staker/stakercontroller.go b/staker/stakercontroller.go index 7b08cec..0e0d0c1 100644 --- a/staker/stakercontroller.go +++ b/staker/stakercontroller.go @@ -16,9 +16,8 @@ type StakerController struct { func NewStakerControllerFromClients( wc walletcontroller.WalletController, - BabylonClient cl.BabylonClient, + babylonClient cl.BabylonClient, ) (*StakerController, error) { - networkName := wc.NetworkName() params, err := ut.GetBtcNetworkParams(networkName) @@ -30,6 +29,6 @@ func NewStakerControllerFromClients( return &StakerController{ Wc: wc, network: params, - BabylonClient: BabylonClient, + BabylonClient: babylonClient, }, err } diff --git a/staker/types.go b/staker/types.go index d0e22b4..e47888e 100644 --- a/staker/types.go +++ b/staker/types.go @@ -7,7 +7,6 @@ import ( "sort" sdkmath "cosmossdk.io/math" - "github.com/babylonlabs-io/babylon/btcstaking" staking "github.com/babylonlabs-io/babylon/btcstaking" bbn "github.com/babylonlabs-io/babylon/types" @@ -33,23 +32,23 @@ type spendStakeTxInfo struct { calculatedFee btcutil.Amount } -// babylonPopToDbPop receives already validated pop from external sources and converts it to database representation -func babylonPopToDbPop(pop *cl.BabylonPop) *stakerdb.ProofOfPossession { +// babylonPopToDBPop receives already validated pop from external sources and converts it to database representation +func babylonPopToDBPop(pop *cl.BabylonPop) *stakerdb.ProofOfPossession { return &stakerdb.ProofOfPossession{ BtcSigType: pop.PopTypeNum(), BtcSigOverBabylonAddr: pop.BtcSig, } } -func babylonCovSigToDbCovSig(covSig cl.CovenantSignatureInfo) stakerdb.PubKeySigPair { +func babylonCovSigToDBCovSig(covSig cl.CovenantSignatureInfo) stakerdb.PubKeySigPair { return stakerdb.NewCovenantMemberSignature(covSig.Signature, covSig.PubKey) } -func babylonCovSigsToDbSigSigs(covSigs []cl.CovenantSignatureInfo) []stakerdb.PubKeySigPair { +func babylonCovSigsToDBSigSigs(covSigs []cl.CovenantSignatureInfo) []stakerdb.PubKeySigPair { sigSigs := make([]stakerdb.PubKeySigPair, len(covSigs)) for i := range covSigs { - sigSigs[i] = babylonCovSigToDbCovSig(covSigs[i]) + sigSigs[i] = babylonCovSigToDBCovSig(covSigs[i]) } return sigSigs @@ -78,7 +77,6 @@ func createWitnessSignaturesForPubKeys( covenantQuorum uint32, receivedSignaturePairs []stakerdb.PubKeySigPair, ) ([]*schnorr.Signature, error) { - if len(receivedSignaturePairs) < int(covenantQuorum) { return nil, fmt.Errorf("not enough signatures to create witness. Required: %d, received: %d", covenantQuorum, len(receivedSignaturePairs)) } @@ -131,7 +129,7 @@ func slashingTxForStakingTx( ) if err != nil { - return nil, nil, fmt.Errorf("buidling slashing transaction failed: %w", err) + return nil, nil, fmt.Errorf("building slashing transaction failed: %w", err) } stakingInfo, err := staking.BuildStakingInfo( @@ -166,8 +164,7 @@ func createDelegationData( babylonStakerAddr sdk.AccAddress, undelegationData *cl.UndelegationData, ) *cl.DelegationData { - - var incInfo *cl.StakingTransactionInclusionInfo = nil + var incInfo *cl.StakingTransactionInclusionInfo if inclusionInfo != nil { inclusionBlockHash := inclusionInfo.inclusionBlock.BlockHash() @@ -220,7 +217,7 @@ func createSpendStakeTx( fee := txrules.FeeForSerializeSize(btcutil.Amount(feeRate), txSize) - spendTx.TxOut[0].Value = spendTx.TxOut[0].Value - int64(fee) + spendTx.TxOut[0].Value -= int64(fee) if spendTx.TxOut[0].Value <= 0 { return nil, nil, fmt.Errorf("too big fee rate for spend stake tx. calculated fee: %d. funding output value: %d", fee, fundingOutput.Value) @@ -516,7 +513,7 @@ func parseWatchStakingRequest( return nil, fmt.Errorf("failed to watch staking tx. Unbonding time must be greater than min unbonding time. Unbonding time: %d, min unbonding time: %d", unbondingTime, currentParams.MinUnbondingTime) } - // 2. Check wheter slashing tx match staking tx + // 2. Check whether slashing tx match staking tx err = staking.CheckSlashingTxMatchFundingTx( slashingTx, stakingTx, @@ -557,7 +554,7 @@ func parseWatchStakingRequest( } // 6. Validate unbonding related data - if err := btcstaking.IsSimpleTransfer(unbondingTx); err != nil { + if err := staking.IsSimpleTransfer(unbondingTx); err != nil { return nil, fmt.Errorf("failed to watch staking tx. Invalid unbonding tx: %w", err) } @@ -637,7 +634,7 @@ func parseWatchStakingRequest( req := newWatchedStakingCmd( stakerAddress, stakingTx, - uint32(stakingOutputIdx), + stakingOutputIdx, stakingTx.TxOut[stakingOutputIdx].PkScript, stakingTime, stakingValue, diff --git a/stakercfg/babylon.go b/stakercfg/babylon.go index e845097..1f8983a 100644 --- a/stakercfg/babylon.go +++ b/stakercfg/babylon.go @@ -25,7 +25,7 @@ type BBNConfig struct { func DefaultBBNConfig() BBNConfig { dc := bbncfg.DefaultBabylonConfig() - //fill up the config from dc config + // fill up the config from dc config return BBNConfig{ Key: dc.Key, ChainID: dc.ChainID, diff --git a/stakercfg/bitcoind.go b/stakercfg/bitcoind.go index 8d78177..ab16d03 100644 --- a/stakercfg/bitcoind.go +++ b/stakercfg/bitcoind.go @@ -10,7 +10,7 @@ const ( DefaultTxPollingJitter = 0.5 DefaultEstimateMode = "CONSERVATIVE" - defaultBitcoindRpcHost = "127.0.0.1:8334" + defaultBitcoindRPCHost = "127.0.0.1:8334" defaultBitcoindRPCUser = "user" defaultBitcoindRPCPass = "pass" defaultBitcoindBlockCacheSize = 20 * 1024 * 1024 // 20 MB @@ -41,7 +41,7 @@ type Bitcoind struct { func DefaultBitcoindConfig() Bitcoind { return Bitcoind{ - RPCHost: defaultBitcoindRpcHost, + RPCHost: defaultBitcoindRPCHost, RPCUser: defaultBitcoindRPCUser, RPCPass: defaultBitcoindRPCPass, RPCPolling: true, diff --git a/stakercfg/config.go b/stakercfg/config.go index 1437907..9db71e8 100644 --- a/stakercfg/config.go +++ b/stakercfg/config.go @@ -73,18 +73,18 @@ func DefaultWalletConfig() WalletConfig { } } -type WalletRpcConfig struct { +type WalletRPCConfig struct { Host string `long:"wallethost" description:"location of the wallet rpc server"` User string `long:"walletuser" description:"user auth for the wallet rpc server"` Pass string `long:"walletpassword" description:"password auth for the wallet rpc server"` - DisableTls bool `long:"noclienttls" description:"disables tls for the wallet rpc client"` + DisableTLS bool `long:"noclienttls" description:"disables tls for the wallet rpc client"` RPCWalletCert string `long:"rpcwalletcert" description:"File containing the wallet daemon's certificate file"` RawRPCWalletCert string `long:"rawrpcwalletcert" description:"The raw bytes of the wallet daemon's PEM-encoded certificate chain which will be used to authenticate the RPC connection."` } -func DefaultWalletRpcConfig() WalletRpcConfig { - return WalletRpcConfig{ - DisableTls: true, +func DefaultWalletRPCConfig() WalletRPCConfig { + return WalletRPCConfig{ + DisableTLS: true, Host: "localhost:18556", User: "rpcuser", Pass: "rpcpass", @@ -125,7 +125,7 @@ func DefaultBtcNodeBackendConfig() BtcNodeBackendConfig { type StakerConfig struct { BabylonStallingInterval time.Duration `long:"babylonstallinginterval" description:"The interval for Babylon node BTC light client to catch up with the real chain before re-sending delegation request"` UnbondingTxCheckInterval time.Duration `long:"unbondingtxcheckinterval" description:"The interval for staker whether delegation received all covenant signatures"` - CheckActiveInterval time.Duration `long:"checkactiveinterval" description:"The interval for staker to check wheter delegation is active on Babylon node"` + CheckActiveInterval time.Duration `long:"checkactiveinterval" description:"The interval for staker to check whether delegation is active on Babylon node"` MaxConcurrentTransactions uint32 `long:"maxconcurrenttransactions" description:"Maximum concurrent transactions in flight to babylon node"` ExitOnCriticalError bool `long:"exitoncriticalerror" description:"Exit stakerd on critical error"` } @@ -152,7 +152,7 @@ type Config struct { WalletConfig *WalletConfig `group:"walletconfig" namespace:"walletconfig"` - WalletRpcConfig *WalletRpcConfig `group:"walletrpcconfig" namespace:"walletrpcconfig"` + WalletRPCConfig *WalletRPCConfig `group:"walletrpcconfig" namespace:"walletrpcconfig"` ChainConfig *ChainConfig `group:"chain" namespace:"chain"` @@ -166,15 +166,15 @@ type Config struct { MetricsConfig *MetricsConfig `group:"metricsconfig" namespace:"metricsconfig"` - JsonRpcServerConfig *JsonRpcServerConfig + JsonRPCServerConfig *JsonRpcServerConfig ActiveNetParams chaincfg.Params - RpcListeners []net.Addr + RPCListeners []net.Addr } func DefaultConfig() Config { - rpcConf := DefaultWalletRpcConfig() + rpcConf := DefaultWalletRPCConfig() walletConf := DefaultWalletConfig() chainCfg := DefaultChainConfig() nodeBackendCfg := DefaultBtcNodeBackendConfig() @@ -189,7 +189,7 @@ func DefaultConfig() Config { DebugLevel: defaultLogLevel, LogDir: defaultLogDir, WalletConfig: &walletConf, - WalletRpcConfig: &rpcConf, + WalletRPCConfig: &rpcConf, ChainConfig: &chainCfg, BtcNodeBackendConfig: &nodeBackendCfg, BabylonConfig: &bbnConfig, @@ -491,10 +491,10 @@ func ValidateConfig(cfg Config) (*Config, error) { // At least one RPCListener is required. So listen on localhost per // default. - if len(cfg.JsonRpcServerConfig.RawRPCListeners) == 0 { + if len(cfg.JsonRPCServerConfig.RawRPCListeners) == 0 { addr := fmt.Sprintf("localhost:%d", DefaultRPCPort) - cfg.JsonRpcServerConfig.RawRPCListeners = append( - cfg.JsonRpcServerConfig.RawRPCListeners, addr, + cfg.JsonRPCServerConfig.RawRPCListeners = append( + cfg.JsonRPCServerConfig.RawRPCListeners, addr, ) } @@ -506,8 +506,8 @@ func ValidateConfig(cfg Config) (*Config, error) { // Add default port to all RPC listener addresses if needed and remove // duplicate addresses. - cfg.RpcListeners, err = lncfg.NormalizeAddresses( - cfg.JsonRpcServerConfig.RawRPCListeners, strconv.Itoa(DefaultRPCPort), + cfg.RPCListeners, err = lncfg.NormalizeAddresses( + cfg.JsonRPCServerConfig.RawRPCListeners, strconv.Itoa(DefaultRPCPort), net.ResolveTCPAddr, ) diff --git a/stakercfg/dbcfg.go b/stakercfg/dbcfg.go index 232d1f3..57d75b4 100644 --- a/stakercfg/dbcfg.go +++ b/stakercfg/dbcfg.go @@ -7,7 +7,7 @@ import ( ) const ( - defaultDbName = "staker.db" + defaultDBName = "staker.db" ) type DBConfig struct { @@ -43,7 +43,7 @@ type DBConfig struct { func DefaultDBConfig() DBConfig { return DBConfig{ DBPath: defaultDataDir, - DBFileName: defaultDbName, + DBFileName: defaultDBName, NoFreelistSync: true, AutoCompact: false, AutoCompactMinAge: kvdb.DefaultBoltAutoCompactMinAge, diff --git a/stakercfg/utils.go b/stakercfg/utils.go index 0bc84de..223fd09 100644 --- a/stakercfg/utils.go +++ b/stakercfg/utils.go @@ -14,18 +14,17 @@ func ReadCertFile(rawCert string, certFilePath string) ([]byte, error) { } return rpcCert, nil - } else { - certFile, err := os.Open(certFilePath) - if err != nil { - return nil, err - } - defer certFile.Close() - - rpcCert, err := io.ReadAll(certFile) - if err != nil { - return nil, err - } + } + certFile, err := os.Open(certFilePath) + if err != nil { + return nil, err + } + defer certFile.Close() - return rpcCert, nil + rpcCert, err := io.ReadAll(certFile) + if err != nil { + return nil, err } + + return rpcCert, nil } diff --git a/stakerdb/trackedtransactionstore_test.go b/stakerdb/trackedtransactionstore_test.go index 2d2be75..f872d0d 100644 --- a/stakerdb/trackedtransactionstore_test.go +++ b/stakerdb/trackedtransactionstore_test.go @@ -100,6 +100,7 @@ func genNStoredTransactions(t *testing.T, r *rand.Rand, n int, maxStakingTime ui } func TestEmptyStore(t *testing.T) { + t.Parallel() r := rand.New(rand.NewSource(time.Now().UnixNano())) s := MakeTestStore(t) hash := datagen.GenRandomBtcdHash(r) @@ -176,6 +177,7 @@ func FuzzStoringTxs(f *testing.F) { } func TestStateTransitions(t *testing.T) { + t.Parallel() r := rand.New(rand.NewSource(time.Now().UnixNano())) s := MakeTestStore(t) tx := genStoredTransaction(t, r, 200) @@ -192,7 +194,7 @@ func TestStateTransitions(t *testing.T) { ) require.NoError(t, err) - // Inital state + // Initial state storedTx, err := s.GetTransaction(&txHash) require.NoError(t, err) require.Equal(t, proto.TransactionState_SENT_TO_BTC, storedTx.State) @@ -229,6 +231,7 @@ func TestStateTransitions(t *testing.T) { } func TestPaginator(t *testing.T) { + t.Parallel() r := rand.New(rand.NewSource(time.Now().UnixNano())) s := MakeTestStore(t) numTx := 45 @@ -276,19 +279,19 @@ func TestPaginator(t *testing.T) { require.Equal(t, 5, len(storedResult3.Transactions)) require.Equal(t, numTx, int(storedResult3.Total)) - var allTransactionsFromDb []stakerdb.StoredTransaction - allTransactionsFromDb = append(allTransactionsFromDb, storedResult1.Transactions...) - allTransactionsFromDb = append(allTransactionsFromDb, storedResult2.Transactions...) - allTransactionsFromDb = append(allTransactionsFromDb, storedResult3.Transactions...) + var allTransactionsFromDB []stakerdb.StoredTransaction + allTransactionsFromDB = append(allTransactionsFromDB, storedResult1.Transactions...) + allTransactionsFromDB = append(allTransactionsFromDB, storedResult2.Transactions...) + allTransactionsFromDB = append(allTransactionsFromDB, storedResult3.Transactions...) - require.Equal(t, len(generatedStoredTxs), len(allTransactionsFromDb)) + require.Equal(t, len(generatedStoredTxs), len(allTransactionsFromDB)) for i, storedTx := range generatedStoredTxs { - require.Equal(t, storedTx.StakingTx, allTransactionsFromDb[i].StakingTx) - require.Equal(t, storedTx.StakingOutputIndex, allTransactionsFromDb[i].StakingOutputIndex) - require.Equal(t, storedTx.StakingTime, allTransactionsFromDb[i].StakingTime) - require.True(t, pubKeysSliceEqual(storedTx.FinalityProvidersBtcPks, allTransactionsFromDb[i].FinalityProvidersBtcPks)) - require.Equal(t, storedTx.Pop, allTransactionsFromDb[i].Pop) - require.Equal(t, storedTx.StakerAddress, allTransactionsFromDb[i].StakerAddress) + require.Equal(t, storedTx.StakingTx, allTransactionsFromDB[i].StakingTx) + require.Equal(t, storedTx.StakingOutputIndex, allTransactionsFromDB[i].StakingOutputIndex) + require.Equal(t, storedTx.StakingTime, allTransactionsFromDB[i].StakingTime) + require.True(t, pubKeysSliceEqual(storedTx.FinalityProvidersBtcPks, allTransactionsFromDB[i].FinalityProvidersBtcPks)) + require.Equal(t, storedTx.Pop, allTransactionsFromDB[i].Pop) + require.Equal(t, storedTx.StakerAddress, allTransactionsFromDB[i].StakerAddress) } } @@ -299,7 +302,7 @@ func FuzzQuerySpendableTx(f *testing.F) { f.Fuzz(func(t *testing.T, seed int64) { r := rand.New(rand.NewSource(seed)) s := MakeTestStore(t) - // ganerate random transactions between 20 and 50 + // generate random transactions between 20 and 50 maxCreatedTx := int(r.Int31n(31) + 20) // random staking time between 150 and 250 blocks maxStakingTime := r.Int31n(101) + 150 @@ -322,7 +325,7 @@ func FuzzQuerySpendableTx(f *testing.F) { query := stakerdb.DefaultStoredTransactionQuery() // random confirmation block confirmationBlock := uint32(r.Int31n(1000) + 1) - halfOfMaxStaking := int32(maxStakingTime / 2) + halfOfMaxStaking := maxStakingTime / 2 currentBestBlock := confirmationBlock + uint32(r.Int31n(halfOfMaxStaking)+1) filteredQuery := query.WithdrawableTransactionsFilter(currentBestBlock) diff --git a/stakerservice/client/rpcclient.go b/stakerservice/client/rpcclient.go index 4dbbe26..c158f01 100644 --- a/stakerservice/client/rpcclient.go +++ b/stakerservice/client/rpcclient.go @@ -7,23 +7,23 @@ import ( jsonrpcclient "github.com/cometbft/cometbft/rpc/jsonrpc/client" ) -type StakerServiceJsonRpcClient struct { +type StakerServiceJsonRPCClient struct { client *jsonrpcclient.Client } // TODO Add some kind of timeout config -func NewStakerServiceJsonRpcClient(remoteAddress string) (*StakerServiceJsonRpcClient, error) { +func NewStakerServiceJsonRPCClient(remoteAddress string) (*StakerServiceJsonRPCClient, error) { client, err := jsonrpcclient.New(remoteAddress) if err != nil { return nil, err } - return &StakerServiceJsonRpcClient{ + return &StakerServiceJsonRPCClient{ client: client, }, nil } -func (c *StakerServiceJsonRpcClient) Health(ctx context.Context) (*service.ResultHealth, error) { +func (c *StakerServiceJsonRPCClient) Health(ctx context.Context) (*service.ResultHealth, error) { result := new(service.ResultHealth) _, err := c.client.Call(ctx, "health", map[string]interface{}{}, result) if err != nil { @@ -32,7 +32,7 @@ func (c *StakerServiceJsonRpcClient) Health(ctx context.Context) (*service.Resul return result, nil } -func (c *StakerServiceJsonRpcClient) ListOutputs(ctx context.Context) (*service.OutputsResponse, error) { +func (c *StakerServiceJsonRPCClient) ListOutputs(ctx context.Context) (*service.OutputsResponse, error) { result := new(service.OutputsResponse) _, err := c.client.Call(ctx, "list_outputs", map[string]interface{}{}, result) if err != nil { @@ -41,7 +41,7 @@ func (c *StakerServiceJsonRpcClient) ListOutputs(ctx context.Context) (*service. return result, nil } -func (c *StakerServiceJsonRpcClient) BabylonFinalityProviders(ctx context.Context, offset *int, limit *int) (*service.FinalityProvidersResponse, error) { +func (c *StakerServiceJsonRPCClient) BabylonFinalityProviders(ctx context.Context, offset *int, limit *int) (*service.FinalityProvidersResponse, error) { result := new(service.FinalityProvidersResponse) params := make(map[string]interface{}) @@ -61,7 +61,7 @@ func (c *StakerServiceJsonRpcClient) BabylonFinalityProviders(ctx context.Contex return result, nil } -func (c *StakerServiceJsonRpcClient) Stake( +func (c *StakerServiceJsonRPCClient) Stake( ctx context.Context, stakerAddress string, stakingAmount int64, @@ -85,7 +85,7 @@ func (c *StakerServiceJsonRpcClient) Stake( return result, nil } -func (c *StakerServiceJsonRpcClient) ListStakingTransactions(ctx context.Context, offset *int, limit *int) (*service.ListStakingTransactionsResponse, error) { +func (c *StakerServiceJsonRPCClient) ListStakingTransactions(ctx context.Context, offset *int, limit *int) (*service.ListStakingTransactionsResponse, error) { result := new(service.ListStakingTransactionsResponse) params := make(map[string]interface{}) @@ -105,7 +105,7 @@ func (c *StakerServiceJsonRpcClient) ListStakingTransactions(ctx context.Context return result, nil } -func (c *StakerServiceJsonRpcClient) WithdrawableTransactions(ctx context.Context, offset *int, limit *int) (*service.WithdrawableTransactionsResponse, error) { +func (c *StakerServiceJsonRPCClient) WithdrawableTransactions(ctx context.Context, offset *int, limit *int) (*service.WithdrawableTransactionsResponse, error) { result := new(service.WithdrawableTransactionsResponse) params := make(map[string]interface{}) @@ -125,7 +125,7 @@ func (c *StakerServiceJsonRpcClient) WithdrawableTransactions(ctx context.Contex return result, nil } -func (c *StakerServiceJsonRpcClient) StakingDetails(ctx context.Context, txHash string) (*service.StakingDetails, error) { +func (c *StakerServiceJsonRPCClient) StakingDetails(ctx context.Context, txHash string) (*service.StakingDetails, error) { result := new(service.StakingDetails) params := make(map[string]interface{}) @@ -138,7 +138,7 @@ func (c *StakerServiceJsonRpcClient) StakingDetails(ctx context.Context, txHash return result, nil } -func (c *StakerServiceJsonRpcClient) SpendStakingTransaction(ctx context.Context, txHash string) (*service.SpendTxDetails, error) { +func (c *StakerServiceJsonRPCClient) SpendStakingTransaction(ctx context.Context, txHash string) (*service.SpendTxDetails, error) { result := new(service.SpendTxDetails) params := make(map[string]interface{}) @@ -151,7 +151,7 @@ func (c *StakerServiceJsonRpcClient) SpendStakingTransaction(ctx context.Context return result, nil } -func (c *StakerServiceJsonRpcClient) WatchStaking( +func (c *StakerServiceJsonRPCClient) WatchStaking( ctx context.Context, stakingTx string, stakingTime int, @@ -169,7 +169,6 @@ func (c *StakerServiceJsonRpcClient) WatchStaking( unbondingTime int, popType int, ) (*service.ResultStake, error) { - result := new(service.ResultStake) params := make(map[string]interface{}) params["stakingTx"] = stakingTx @@ -195,7 +194,7 @@ func (c *StakerServiceJsonRpcClient) WatchStaking( return result, nil } -func (c *StakerServiceJsonRpcClient) UnbondStaking(ctx context.Context, txHash string) (*service.UnbondingResponse, error) { +func (c *StakerServiceJsonRPCClient) UnbondStaking(ctx context.Context, txHash string) (*service.UnbondingResponse, error) { result := new(service.UnbondingResponse) params := make(map[string]interface{}) diff --git a/stakerservice/service.go b/stakerservice/service.go index 45f5274..fca3c87 100644 --- a/stakerservice/service.go +++ b/stakerservice/service.go @@ -82,7 +82,6 @@ func (s *StakerService) stake(_ *rpctypes.Context, stakingTimeBlocks int64, sendToBabylonFirst bool, ) (*ResultStake, error) { - if stakingAmount <= 0 { return nil, fmt.Errorf("staking amount must be positive") } @@ -94,7 +93,7 @@ func (s *StakerService) stake(_ *rpctypes.Context, return nil, err } - var fpPubKeys []*btcec.PublicKey = make([]*btcec.PublicKey, 0) + fpPubKeys := make([]*btcec.PublicKey, 0) for _, fpPk := range fpBtcPks { fpPkBytes, err := hex.DecodeString(fpPk) @@ -166,7 +165,6 @@ func (s *StakerService) spendStake(_ *rpctypes.Context, } func (s *StakerService) listOutputs(_ *rpctypes.Context) (*OutputsResponse, error) { - outputs, err := s.staker.ListUnspentOutputs() if err != nil { @@ -224,7 +222,6 @@ func getPageParams(offsetPtr *int, limitPtr *int) (*PageParams, error) { } func (s *StakerService) providers(_ *rpctypes.Context, offset, limit *int) (*FinalityProvidersResponse, error) { - pageParams, err := getPageParams(offset, limit) if err != nil { return nil, err @@ -300,7 +297,7 @@ func (s *StakerService) withdrawableTransactions(_ *rpctypes.Context, offset, li stakingDetails = append(stakingDetails, storedTxToStakingDetails(&tx)) } - var lastIdx string = "0" + lastIdx := "0" if len(stakingDetails) > 0 { // this should ease up pagination i.e in case when whe have 1000 transactions, and we limit query to 50 // due to filetring we can retrun response with 50 transactions when last one have index 400, @@ -405,7 +402,7 @@ func (s *StakerService) watchStaking( return nil, err } - var fpPubKeys []*btcec.PublicKey = make([]*btcec.PublicKey, 0) + fpPubKeys := make([]*btcec.PublicKey, 0) for _, fpPk := range fpBtcPks { fpPkBytes, err := hex.DecodeString(fpPk) @@ -609,8 +606,8 @@ func (s *StakerService) RunUntilShutdown(ctx context.Context) error { // TODO: investigate if we can use logrus directly to pass it to rpcserver rpcLogger := log.NewTMLogger(s.logger.Writer()) - listeners := make([]net.Listener, len(s.config.RpcListeners)) - for i, listenAddr := range s.config.RpcListeners { + listeners := make([]net.Listener, len(s.config.RPCListeners)) + for i, listenAddr := range s.config.RPCListeners { listenAddressStr := listenAddr.Network() + "://" + listenAddr.String() mux := http.NewServeMux() rpc.RegisterRPCFuncs(mux, routes, rpcLogger) diff --git a/types/walletbackend.go b/types/walletbackend.go index a05936f..ab7908e 100644 --- a/types/walletbackend.go +++ b/types/walletbackend.go @@ -18,5 +18,4 @@ func NewWalletBackend(backend string) (SupportedWalletBackend, error) { default: return BtcwalletWalletBackend, fmt.Errorf("invalid wallet type: %s", backend) } - } diff --git a/walletcontroller/client.go b/walletcontroller/client.go index ce48e1a..ca149dd 100644 --- a/walletcontroller/client.go +++ b/walletcontroller/client.go @@ -9,7 +9,6 @@ import ( "github.com/babylonlabs-io/babylon/crypto/bip322" "github.com/babylonlabs-io/btc-staker/stakercfg" - scfg "github.com/babylonlabs-io/btc-staker/stakercfg" "github.com/babylonlabs-io/btc-staker/types" "github.com/btcsuite/btcd/btcec/v2" "github.com/btcsuite/btcd/btcec/v2/schnorr" @@ -40,17 +39,17 @@ const ( func NewRpcWalletController(scfg *stakercfg.Config) (*RpcWalletController, error) { return NewRpcWalletControllerFromArgs( - scfg.WalletRpcConfig.Host, - scfg.WalletRpcConfig.User, - scfg.WalletRpcConfig.Pass, + scfg.WalletRPCConfig.Host, + scfg.WalletRPCConfig.User, + scfg.WalletRPCConfig.Pass, scfg.ActiveNetParams.Name, scfg.WalletConfig.WalletName, scfg.WalletConfig.WalletPass, scfg.BtcNodeBackendConfig.ActiveWalletBackend, &scfg.ActiveNetParams, - scfg.WalletRpcConfig.DisableTls, - scfg.WalletRpcConfig.RawRPCWalletCert, - scfg.WalletRpcConfig.RPCWalletCert, + scfg.WalletRPCConfig.DisableTLS, + scfg.WalletRPCConfig.RawRPCWalletCert, + scfg.WalletRPCConfig.RPCWalletCert, ) } @@ -66,7 +65,6 @@ func NewRpcWalletControllerFromArgs( disableTls bool, rawWalletCert string, walletCertFilePath string, ) (*RpcWalletController, error) { - connCfg := &rpcclient.ConnConfig{ Host: rpcHostURL(host, walletName), User: user, @@ -80,7 +78,7 @@ func NewRpcWalletControllerFromArgs( } if !connCfg.DisableTLS { - cert, err := scfg.ReadCertFile(rawWalletCert, walletCertFilePath) + cert, err := stakercfg.ReadCertFile(rawWalletCert, walletCertFilePath) if err != nil { return nil, err } @@ -143,7 +141,6 @@ func (w *RpcWalletController) CreateTransaction( changeAddres btcutil.Address, useUtxoFn UseUtxoFn, ) (*wire.MsgTx, error) { - utxoResults, err := w.ListUnspent() if err != nil { @@ -457,5 +454,4 @@ func (w *RpcWalletController) SignOneInputTaprootSpendingTransaction(request *Ta // neither witness, nor signature is filled. return nil, fmt.Errorf("no signature found in PSBT packet. Wallet can't sign given tx") - } diff --git a/walletcontroller/transaction.go b/walletcontroller/transaction.go index 248e7e1..6abefa7 100644 --- a/walletcontroller/transaction.go +++ b/walletcontroller/transaction.go @@ -79,7 +79,6 @@ func makeInputSource(utxos []Utxo) txauthor.InputSource { return func(target btcutil.Amount) (btcutil.Amount, []*wire.TxIn, []btcutil.Amount, [][]byte, error) { - for currentTotal < target && len(utxos) != 0 { nextCredit := &utxos[0] utxos = utxos[1:] @@ -98,7 +97,6 @@ func buildTxFromOutputs( outputs []*wire.TxOut, feeRatePerKb btcutil.Amount, changeScript []byte) (*wire.MsgTx, error) { - if len(utxos) == 0 { return nil, fmt.Errorf("there must be at least 1 usable UTXO to build transaction") }