From a66341b04a41bc35b37eb8f48fc860631493ae6b Mon Sep 17 00:00:00 2001 From: Lazar Date: Tue, 12 Nov 2024 15:54:55 +0100 Subject: [PATCH] batch 2 of fixes --- .golangci.yml | 1 + cmd/stakercli/daemon/daemoncommands.go | 18 ++-- .../transaction/transactions_test.go | 2 +- cmd/stakerd/main.go | 2 +- itest/e2e_test.go | 14 +-- staker/stakerapp.go | 2 +- stakercfg/config.go | 14 +-- stakercfg/dbcfg.go | 2 +- stakercfg/utils.go | 1 - stakerdb/errors.go | 4 +- stakerdb/paginator.go | 1 - stakerdb/trackedtranactionstore.go | 94 +++++++++---------- stakerdb/trackedtransactionstore_test.go | 2 +- stakerservice/client/rpcclient.go | 26 ++--- stakerservice/service.go | 1 - walletcontroller/client.go | 44 ++++----- 16 files changed, 111 insertions(+), 117 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index e1c1656..717f7ad 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -74,6 +74,7 @@ issues: - errcheck - dupl - gosec + - gocritic - path-except: _test\.go linters: - forbidigo \ No newline at end of file diff --git a/cmd/stakercli/daemon/daemoncommands.go b/cmd/stakercli/daemon/daemoncommands.go index 997ca0c..f62a38a 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/transaction/transactions_test.go b/cmd/stakercli/transaction/transactions_test.go index b9839a6..8208724 100644 --- a/cmd/stakercli/transaction/transactions_test.go +++ b/cmd/stakercli/transaction/transactions_test.go @@ -164,7 +164,7 @@ func genSchnorPubKeyHex(t *testing.T) string { return hex.EncodeToString(schnorr.SerializePubKey(btcPub)) } -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) string { outPut := filepath.Join(t.TempDir(), fmt.Sprintf("%s-out.txt", datagen.GenRandomHexStr(r, 10))) outPutFile, err := os.Create(outPut) require.NoError(t, err) diff --git a/cmd/stakerd/main.go b/cmd/stakerd/main.go index c8d93d9..1f5dbc8 100644 --- a/cmd/stakerd/main.go +++ b/cmd/stakerd/main.go @@ -60,7 +60,7 @@ func main() { defer pprof.StopCPUProfile() } - dbBackend, err := scfg.GetDbBackend(cfg.DBConfig) + dbBackend, err := scfg.GetDBBackend(cfg.DBConfig) if err != nil { err = fmt.Errorf("failed to load db backend: %w", err) diff --git a/itest/e2e_test.go b/itest/e2e_test.go index c60344c..01438ea 100644 --- a/itest/e2e_test.go +++ b/itest/e2e_test.go @@ -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 @@ -298,7 +298,7 @@ func StartManager( require.NoError(t, err) cfg.DBConfig.DBPath = dbTempDir - dbbackend, err := stakercfg.GetDbBackend(cfg.DBConfig) + dbbackend, err := stakercfg.GetDBBackend(cfg.DBConfig) require.NoError(t, err) m := metrics.NewStakerMetrics() @@ -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{ @@ -398,7 +398,7 @@ func (tm *TestManager) RestartAppWithAction(t *testing.T, ctx context.Context, c logger.SetLevel(logrus.DebugLevel) logger.Out = os.Stdout - dbbackend, err := stakercfg.GetDbBackend(tm.Config.DBConfig) + dbbackend, err := stakercfg.GetDBBackend(tm.Config.DBConfig) require.NoError(t, err) m := metrics.NewStakerMetrics() stakerApp, err := staker.NewStakerAppFromConfig(tm.Config, logger, zapLogger, dbbackend, m) @@ -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 } @@ -1757,7 +1757,7 @@ func TestBitcoindWalletRpcApi(t *testing.T) { scfg.ActiveNetParams = chaincfg.RegressionNetParams // Create wallet controller the same way as in staker program - wc, err := walletcontroller.NewRpcWalletController(&scfg) + wc, err := walletcontroller.NewRPCWalletController(&scfg) require.NoError(t, err) outputs, err := wc.ListOutputs(true) @@ -1825,7 +1825,7 @@ func TestBitcoindWalletBip322Signing(t *testing.T) { segwitAddress, err := c.GetNewAddress("") require.NoError(t, err) - controller, err := walletcontroller.NewRpcWalletController(cfg) + controller, err := walletcontroller.NewRPCWalletController(cfg) require.NoError(t, err) err = controller.UnlockWallet(30) diff --git a/staker/stakerapp.go b/staker/stakerapp.go index 841f8a2..09339df 100644 --- a/staker/stakerapp.go +++ b/staker/stakerapp.go @@ -144,7 +144,7 @@ func NewStakerAppFromConfig( ) (*StakerApp, error) { // TODO: If we want to support multiple wallet types, this is most probably the place to decide // on concrete implementation - walletClient, err := walletcontroller.NewRpcWalletController(config) + walletClient, err := walletcontroller.NewRPCWalletController(config) if err != nil { return nil, err } diff --git a/stakercfg/config.go b/stakercfg/config.go index 9db71e8..c8a4ef4 100644 --- a/stakercfg/config.go +++ b/stakercfg/config.go @@ -91,7 +91,7 @@ func DefaultWalletRPCConfig() WalletRPCConfig { } } -type JsonRpcServerConfig struct { +type JSONRPCServerConfig struct { RawRPCListeners []string `long:"rpclisten" description:"Add an interface/port/socket to listen for RPC connections"` } @@ -166,7 +166,7 @@ type Config struct { MetricsConfig *MetricsConfig `group:"metricsconfig" namespace:"metricsconfig"` - JsonRPCServerConfig *JsonRpcServerConfig + JSONRPCServerConfig *JSONRPCServerConfig ActiveNetParams chaincfg.Params @@ -337,6 +337,8 @@ func LoadConfig() (*Config, *logrus.Logger, *zap.Logger, error) { // ValidateConfig check the given configuration to be sane. This makes sure no // illegal values or combination of values are set. All file system paths are // normalized. The cleaned up config is returned on success. +// +//nolint:gocyclo func ValidateConfig(cfg Config) (*Config, error) { // If the provided stakerd directory is not the default, we'll modify the // path to all of the files and directories that will live within it. @@ -491,10 +493,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, ) } @@ -507,7 +509,7 @@ 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.JSONRPCServerConfig.RawRPCListeners, strconv.Itoa(DefaultRPCPort), net.ResolveTCPAddr, ) diff --git a/stakercfg/dbcfg.go b/stakercfg/dbcfg.go index 57d75b4..365a393 100644 --- a/stakercfg/dbcfg.go +++ b/stakercfg/dbcfg.go @@ -62,7 +62,7 @@ func DBConfigToBoltBackenCondfig(db *DBConfig) kvdb.BoltBackendConfig { } } -func GetDbBackend(cfg *DBConfig) (kvdb.Backend, error) { +func GetDBBackend(cfg *DBConfig) (kvdb.Backend, error) { boltConfig := DBConfigToBoltBackenCondfig(cfg) return kvdb.GetBoltBackend(&boltConfig) } diff --git a/stakercfg/utils.go b/stakercfg/utils.go index 223fd09..30e1afb 100644 --- a/stakercfg/utils.go +++ b/stakercfg/utils.go @@ -13,7 +13,6 @@ func ReadCertFile(rawCert string, certFilePath string) ([]byte, error) { return nil, err } return rpcCert, nil - } certFile, err := os.Open(certFilePath) if err != nil { diff --git a/stakerdb/errors.go b/stakerdb/errors.go index ca0c0b1..c36f458 100644 --- a/stakerdb/errors.go +++ b/stakerdb/errors.go @@ -3,8 +3,8 @@ package stakerdb import "errors" var ( - // ErrCorruptedTransactionsDb For some reason, db on disk representation have changed - ErrCorruptedTransactionsDb = errors.New("transactions db is corrupted") + // ErrCorruptedTransactionsDB For some reason, db on disk representation have changed + ErrCorruptedTransactionsDB = errors.New("transactions db is corrupted") // ErrTransactionNotFound The transaction we try update is not found in db ErrTransactionNotFound = errors.New("transaction not found") diff --git a/stakerdb/paginator.go b/stakerdb/paginator.go index 297960c..79786c6 100644 --- a/stakerdb/paginator.go +++ b/stakerdb/paginator.go @@ -25,7 +25,6 @@ type paginator struct { // in pages. func newPaginator(c kvdb.RCursor, reversed bool, indexOffset, totalItems uint64) paginator { - return paginator{ cursor: c, reversed: reversed, diff --git a/stakerdb/trackedtranactionstore.go b/stakerdb/trackedtranactionstore.go index b091eff..7848c0b 100644 --- a/stakerdb/trackedtranactionstore.go +++ b/stakerdb/trackedtranactionstore.go @@ -226,7 +226,6 @@ type StoredTransactionQueryResult struct { // NewTrackedTransactionStore returns a new store backed by db func NewTrackedTransactionStore(db kvdb.Backend) (*TrackedTransactionStore, error) { - store := &TrackedTransactionStore{db} if err := store.initBuckets(); err != nil { return nil, err @@ -277,7 +276,6 @@ func protoBtcConfirmationInfoToBtcConfirmationInfo(ci *proto.BTCConfirmationInfo Height: ci.BlockHeight, BlockHash: *hash, }, nil - } func protoUnbondingDataToUnbondingStoreData(ud *proto.UnbondingTxData) (*UnbondingStoreData, error) { @@ -327,7 +325,7 @@ func protoTxToStoredTransaction(ttx *proto.TrackedTransaction) (*StoredTransacti return nil, err } - var utd *UnbondingStoreData = nil + var utd *UnbondingStoreData if ttx.UnbondingTxData != nil { unbondingData, err := protoUnbondingDataToUnbondingStoreData(ttx.UnbondingTxData) @@ -349,8 +347,7 @@ func protoTxToStoredTransaction(ttx *proto.TrackedTransaction) (*StoredTransacti return nil, fmt.Errorf("staking time is too large. Max value is %d", math.MaxUint16) } - var fpPubkeys []*btcec.PublicKey = make([]*btcec.PublicKey, len(ttx.FinalityProvidersBtcPks)) - + fpPubkeys := make([]*btcec.PublicKey, len(ttx.FinalityProvidersBtcPks)) for i, pk := range ttx.FinalityProvidersBtcPks { fpPubkeys[i], err = schnorr.ParsePubKey(pk) @@ -474,7 +471,7 @@ func getTxByHash( if maybeTx == nil { // if we have index, but do not have transaction, it means something weird happened // and we have corrupted db - return nil, nil, ErrCorruptedTransactionsDb + return nil, nil, ErrCorruptedTransactionsDB } return maybeTx, txKey, nil @@ -490,7 +487,7 @@ func saveTrackedTransaction( id *inputData, ) error { if tx == nil { - return fmt.Errorf("cannot save nil tracked transaciton") + return fmt.Errorf("cannot save nil tracked transactions") } nextTxKey := nextTxKey(txIdxBucket) @@ -519,7 +516,7 @@ func saveTrackedTransaction( if watchedTxData != nil { watchedTxBucket := rwTx.ReadWriteBucket(watchedTxDataBucketName) if watchedTxBucket == nil { - return ErrCorruptedTransactionsDb + return ErrCorruptedTransactionsDB } marshalled, err := pm.Marshal(watchedTxData) @@ -538,7 +535,7 @@ func saveTrackedTransaction( if id != nil { inputDataBucket := rwTx.ReadWriteBucket(inputsDataBucketName) if inputDataBucket == nil { - return ErrCorruptedTransactionsDb + return ErrCorruptedTransactionsDB } for _, input := range id.inputs { @@ -565,7 +562,7 @@ func (c *TrackedTransactionStore) addTransactionInternal( transactionsBucketIdxBucket := tx.ReadWriteBucket(transactionIndexName) if transactionsBucketIdxBucket == nil { - return ErrCorruptedTransactionsDb + return ErrCorruptedTransactionsDB } // check index first to avoid duplicates @@ -576,7 +573,7 @@ func (c *TrackedTransactionStore) addTransactionInternal( transactionsBucket := tx.ReadWriteBucket(transactionBucketName) if transactionsBucket == nil { - return ErrCorruptedTransactionsDb + return ErrCorruptedTransactionsDB } return saveTrackedTransaction(tx, transactionsBucketIdxBucket, transactionsBucket, txHashBytes, tt, wd, id) @@ -730,7 +727,7 @@ func (c *TrackedTransactionStore) AddTransactionSentToBabylon( } return c.addTransactionInternal( - txHashBytes[:], &msg, nil, inputData, + txHashBytes, &msg, nil, inputData, ) } @@ -781,7 +778,7 @@ func (c *TrackedTransactionStore) AddTransactionSentToBTC( } return c.addTransactionInternal( - txHashBytes[:], &msg, nil, nil, + txHashBytes, &msg, nil, nil, ) } @@ -813,8 +810,7 @@ func (c *TrackedTransactionStore) AddWatchedTransaction( return fmt.Errorf("cannot add transaction without finality providers public keys") } - var fpPubKeysBytes [][]byte = make([][]byte, len(fpPubKeys)) - + fpPubKeysBytes := make([][]byte, len(fpPubKeys)) for i, pk := range fpPubKeys { fpPubKeysBytes[i] = schnorr.SerializePubKey(pk) } @@ -881,12 +877,12 @@ func (c *TrackedTransactionStore) setTxState( transactionIdxBucket := tx.ReadWriteBucket(transactionIndexName) if transactionIdxBucket == nil { - return ErrCorruptedTransactionsDb + return ErrCorruptedTransactionsDB } transactionsBucket := tx.ReadWriteBucket(transactionBucketName) if transactionsBucket == nil { - return ErrCorruptedTransactionsDb + return ErrCorruptedTransactionsDB } maybeTx, txKey, err := getTxByHash(txHashBytes, transactionIdxBucket, transactionsBucket) @@ -898,7 +894,7 @@ func (c *TrackedTransactionStore) setTxState( var storedTx proto.TrackedTransaction err = pm.Unmarshal(maybeTx, &storedTx) if err != nil { - return ErrCorruptedTransactionsDb + return ErrCorruptedTransactionsDB } if err := stateTransitionFn(&storedTx); err != nil { @@ -923,7 +919,7 @@ func (c *TrackedTransactionStore) setTxState( if storedTx.State == proto.TransactionState_DELEGATION_ACTIVE { inputDataBucket := tx.ReadWriteBucket(inputsDataBucketName) if inputDataBucket == nil { - return ErrCorruptedTransactionsDb + return ErrCorruptedTransactionsDB } var stakingTx wire.MsgTx @@ -947,9 +943,7 @@ func (c *TrackedTransactionStore) setTxState( return err } } - } - return nil }) } @@ -1088,12 +1082,12 @@ func (c *TrackedTransactionStore) GetTransaction(txHash *chainhash.Hash) (*Store transactionIdxBucket := tx.ReadBucket(transactionIndexName) if transactionIdxBucket == nil { - return ErrCorruptedTransactionsDb + return ErrCorruptedTransactionsDB } transactionsBucket := tx.ReadBucket(transactionBucketName) if transactionsBucket == nil { - return ErrCorruptedTransactionsDb + return ErrCorruptedTransactionsDB } maybeTx, _, err := getTxByHash(txHashBytes, transactionIdxBucket, transactionsBucket) @@ -1105,16 +1099,16 @@ func (c *TrackedTransactionStore) GetTransaction(txHash *chainhash.Hash) (*Store var storedTxProto proto.TrackedTransaction err = pm.Unmarshal(maybeTx, &storedTxProto) if err != nil { - return ErrCorruptedTransactionsDb + return ErrCorruptedTransactionsDB } - txFromDb, err := protoTxToStoredTransaction(&storedTxProto) + txFromDB, err := protoTxToStoredTransaction(&storedTxProto) if err != nil { return err } - storedTx = txFromDb + storedTx = txFromDB return nil }, func() {}) @@ -1133,7 +1127,7 @@ func (c *TrackedTransactionStore) GetWatchedTransactionData(txHash *chainhash.Ha watchedTxDataBucket := tx.ReadBucket(watchedTxDataBucketName) if watchedTxDataBucket == nil { - return ErrCorruptedTransactionsDb + return ErrCorruptedTransactionsDB } maybeWatchedData := watchedTxDataBucket.Get(txHashBytes) @@ -1146,16 +1140,16 @@ func (c *TrackedTransactionStore) GetWatchedTransactionData(txHash *chainhash.Ha err := pm.Unmarshal(maybeWatchedData, &watchedDataProto) if err != nil { - return ErrCorruptedTransactionsDb + return ErrCorruptedTransactionsDB } - watchedDataFromDb, err := protoWatchedDataToWatchedTransactionData(&watchedDataProto) + watchedDataFromDB, err := protoWatchedDataToWatchedTransactionData(&watchedDataProto) if err != nil { return err } - watchedData = watchedDataFromDb + watchedData = watchedDataFromDB return nil }, func() {}) @@ -1193,13 +1187,13 @@ func (c *TrackedTransactionStore) QueryStoredTransactions(q StoredTransactionQue err := c.db.View(func(tx kvdb.RTx) error { transactionsBucket := tx.ReadBucket(transactionBucketName) if transactionsBucket == nil { - return ErrCorruptedTransactionsDb + return ErrCorruptedTransactionsDB } transactionIdxBucket := tx.ReadBucket(transactionIndexName) if transactionIdxBucket == nil { - return ErrCorruptedTransactionsDb + return ErrCorruptedTransactionsDB } numTransactions := getNumTx(transactionIdxBucket) @@ -1215,7 +1209,7 @@ func (c *TrackedTransactionStore) QueryStoredTransactions(q StoredTransactionQue q.NumMaxTransactions, ) - accumulateTransactions := func(key, transaction []byte) (bool, error) { + accumulateTransactions := func(_, transaction []byte) (bool, error) { protoTx := proto.TrackedTransaction{} err := pm.Unmarshal(transaction, &protoTx) @@ -1223,7 +1217,7 @@ func (c *TrackedTransactionStore) QueryStoredTransactions(q StoredTransactionQue return false, err } - txFromDb, err := protoTxToStoredTransaction(&protoTx) + txFromDB, err := protoTxToStoredTransaction(&protoTx) if err != nil { return false, err @@ -1235,18 +1229,18 @@ func (c *TrackedTransactionStore) QueryStoredTransactions(q StoredTransactionQue var confirmationHeight uint32 var scriptTimeLock uint16 - if txFromDb.Watched { + if txFromDB.Watched { // cannot withdraw watched transaction directly through staker program // at least for now. return false, nil } - if txFromDb.StakingTxConfirmedOnBtc() && !txFromDb.UnbondingTxConfirmedOnBtc() { - scriptTimeLock = txFromDb.StakingTime - confirmationHeight = txFromDb.StakingTxConfirmationInfo.Height - } else if txFromDb.StakingTxConfirmedOnBtc() && txFromDb.UnbondingTxConfirmedOnBtc() { - scriptTimeLock = txFromDb.UnbondingTxData.UnbondingTime - confirmationHeight = txFromDb.UnbondingTxData.UnbondingTxConfirmationInfo.Height + if txFromDB.StakingTxConfirmedOnBtc() && !txFromDB.UnbondingTxConfirmedOnBtc() { + scriptTimeLock = txFromDB.StakingTime + confirmationHeight = txFromDB.StakingTxConfirmationInfo.Height + } else if txFromDB.StakingTxConfirmedOnBtc() && txFromDB.UnbondingTxConfirmedOnBtc() { + scriptTimeLock = txFromDB.UnbondingTxData.UnbondingTime + confirmationHeight = txFromDB.UnbondingTxData.UnbondingTxConfirmationInfo.Height } else { return false, nil } @@ -1258,13 +1252,13 @@ func (c *TrackedTransactionStore) QueryStoredTransactions(q StoredTransactionQue ) if timeLockExpired { - resp.Transactions = append(resp.Transactions, *txFromDb) + resp.Transactions = append(resp.Transactions, *txFromDB) return true, nil } else { return false, nil } } else { - resp.Transactions = append(resp.Transactions, *txFromDb) + resp.Transactions = append(resp.Transactions, *txFromDB) return true, nil } } @@ -1299,36 +1293,36 @@ func (c *TrackedTransactionStore) ScanTrackedTransactions(scanFunc StoredTransac transactionsBucket := tx.ReadBucket(transactionBucketName) if transactionsBucket == nil { - return ErrCorruptedTransactionsDb + return ErrCorruptedTransactionsDB } - return transactionsBucket.ForEach(func(k, v []byte) error { + return transactionsBucket.ForEach(func(_, v []byte) error { var storedTxProto proto.TrackedTransaction err := pm.Unmarshal(v, &storedTxProto) if err != nil { - return ErrCorruptedTransactionsDb + return ErrCorruptedTransactionsDB } - txFromDb, err := protoTxToStoredTransaction(&storedTxProto) + txFromDB, err := protoTxToStoredTransaction(&storedTxProto) if err != nil { return err } - return scanFunc(txFromDb) + return scanFunc(txFromDB) }) }, reset) } func (c *TrackedTransactionStore) OutpointUsed(op *wire.OutPoint) (bool, error) { - var used bool = false + used := false err := c.db.View(func(tx kvdb.RTx) error { inputsBucket := tx.ReadBucket(inputsDataBucketName) if inputsBucket == nil { - return ErrCorruptedTransactionsDb + return ErrCorruptedTransactionsDB } opBytes, err := outpointBytes(op) diff --git a/stakerdb/trackedtransactionstore_test.go b/stakerdb/trackedtransactionstore_test.go index f872d0d..1d546f0 100644 --- a/stakerdb/trackedtransactionstore_test.go +++ b/stakerdb/trackedtransactionstore_test.go @@ -28,7 +28,7 @@ func MakeTestStore(t *testing.T) *stakerdb.TrackedTransactionStore { cfg.DBPath = tempDirName - backend, err := stakercfg.GetDbBackend(&cfg) + backend, err := stakercfg.GetDBBackend(&cfg) require.NoError(t, err) t.Cleanup(func() { diff --git a/stakerservice/client/rpcclient.go b/stakerservice/client/rpcclient.go index c158f01..48070cc 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, @@ -194,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 fca3c87..6f56168 100644 --- a/stakerservice/service.go +++ b/stakerservice/service.go @@ -127,7 +127,6 @@ func (s *StakerService) stake(_ *rpctypes.Context, func (s *StakerService) stakingDetails(_ *rpctypes.Context, stakingTxHash string) (*StakingDetails, error) { - txHash, err := chainhash.NewHashFromStr(stakingTxHash) if err != nil { return nil, err diff --git a/walletcontroller/client.go b/walletcontroller/client.go index ca149dd..174c9cf 100644 --- a/walletcontroller/client.go +++ b/walletcontroller/client.go @@ -23,22 +23,22 @@ import ( notifier "github.com/lightningnetwork/lnd/chainntnfs" ) -type RpcWalletController struct { +type RPCWalletController struct { *rpcclient.Client walletPassphrase string network string backend types.SupportedWalletBackend } -var _ WalletController = (*RpcWalletController)(nil) +var _ WalletController = (*RPCWalletController)(nil) const ( txNotFoundErrMsgBtcd = "No information available about transaction" txNotFoundErrMsgBitcoind = "No such mempool or blockchain transaction" ) -func NewRpcWalletController(scfg *stakercfg.Config) (*RpcWalletController, error) { - return NewRpcWalletControllerFromArgs( +func NewRPCWalletController(scfg *stakercfg.Config) (*RPCWalletController, error) { + return NewRPCWalletControllerFromArgs( scfg.WalletRPCConfig.Host, scfg.WalletRPCConfig.User, scfg.WalletRPCConfig.Pass, @@ -53,7 +53,7 @@ func NewRpcWalletController(scfg *stakercfg.Config) (*RpcWalletController, error ) } -func NewRpcWalletControllerFromArgs( +func NewRPCWalletControllerFromArgs( host string, user string, pass string, @@ -62,14 +62,14 @@ func NewRpcWalletControllerFromArgs( walletPassphrase string, nodeBackend types.SupportedWalletBackend, params *chaincfg.Params, - disableTls bool, + disableTLS bool, rawWalletCert string, walletCertFilePath string, -) (*RpcWalletController, error) { +) (*RPCWalletController, error) { connCfg := &rpcclient.ConnConfig{ Host: rpcHostURL(host, walletName), User: user, Pass: pass, - DisableTLS: disableTls, + DisableTLS: disableTLS, DisableConnectOnNew: true, DisableAutoReconnect: false, // we use post mode as it sure it works with either bitcoind or btcwallet @@ -90,7 +90,7 @@ func NewRpcWalletControllerFromArgs( return nil, err } - return &RpcWalletController{ + return &RPCWalletController{ Client: rpcclient, walletPassphrase: walletPassphrase, network: params.Name, @@ -105,11 +105,11 @@ func rpcHostURL(host, walletName string) string { return host } -func (w *RpcWalletController) UnlockWallet(timoutSec int64) error { +func (w *RPCWalletController) UnlockWallet(timoutSec int64) error { return w.WalletPassphrase(w.walletPassphrase, timoutSec) } -func (w *RpcWalletController) AddressPublicKey(address btcutil.Address) (*btcec.PublicKey, error) { +func (w *RPCWalletController) AddressPublicKey(address btcutil.Address) (*btcec.PublicKey, error) { encoded := address.EncodeAddress() info, err := w.GetAddressInfo(encoded) @@ -131,11 +131,11 @@ func (w *RpcWalletController) AddressPublicKey(address btcutil.Address) (*btcec. return btcec.ParsePubKey(decodedHex) } -func (w *RpcWalletController) NetworkName() string { +func (w *RPCWalletController) NetworkName() string { return w.network } -func (w *RpcWalletController) CreateTransaction( +func (w *RPCWalletController) CreateTransaction( outputs []*wire.TxOut, feeRatePerKb btcutil.Amount, changeAddres btcutil.Address, @@ -183,7 +183,7 @@ func (w *RpcWalletController) CreateTransaction( return tx, err } -func (w *RpcWalletController) CreateAndSignTx( +func (w *RPCWalletController) CreateAndSignTx( outputs []*wire.TxOut, feeRatePerKb btcutil.Amount, changeAddress btcutil.Address, @@ -210,7 +210,7 @@ func (w *RpcWalletController) CreateAndSignTx( return fundedTx, nil } -func (w *RpcWalletController) SignRawTransaction(tx *wire.MsgTx) (*wire.MsgTx, bool, error) { +func (w *RPCWalletController) SignRawTransaction(tx *wire.MsgTx) (*wire.MsgTx, bool, error) { switch w.backend { case types.BitcoindWalletBackend: return w.Client.SignRawTransactionWithWallet(tx) @@ -221,11 +221,11 @@ func (w *RpcWalletController) SignRawTransaction(tx *wire.MsgTx) (*wire.MsgTx, b } } -func (w *RpcWalletController) SendRawTransaction(tx *wire.MsgTx, allowHighFees bool) (*chainhash.Hash, error) { +func (w *RPCWalletController) SendRawTransaction(tx *wire.MsgTx, allowHighFees bool) (*chainhash.Hash, error) { return w.Client.SendRawTransaction(tx, allowHighFees) } -func (w *RpcWalletController) ListOutputs(onlySpendable bool) ([]Utxo, error) { +func (w *RPCWalletController) ListOutputs(onlySpendable bool) ([]Utxo, error) { utxoResults, err := w.ListUnspent() if err != nil { @@ -258,7 +258,7 @@ func nofitierStateToWalletState(state notifier.TxConfStatus) TxStatus { } } -func (w *RpcWalletController) getTxDetails(req notifier.ConfRequest, msg string) (*notifier.TxConfirmation, TxStatus, error) { +func (w *RPCWalletController) getTxDetails(req notifier.ConfRequest, msg string) (*notifier.TxConfirmation, TxStatus, error) { res, state, err := notifier.ConfDetailsFromTxIndex(w.Client, req, msg) if err != nil { @@ -269,7 +269,7 @@ func (w *RpcWalletController) getTxDetails(req notifier.ConfRequest, msg string) } // Fetch info about transaction from mempool or blockchain, requires node to have enabled transaction index -func (w *RpcWalletController) TxDetails(txHash *chainhash.Hash, pkScript []byte) (*notifier.TxConfirmation, TxStatus, error) { +func (w *RPCWalletController) TxDetails(txHash *chainhash.Hash, pkScript []byte) (*notifier.TxConfirmation, TxStatus, error) { req, err := notifier.NewConfRequest(txHash, pkScript) if err != nil { @@ -291,7 +291,7 @@ func (w *RpcWalletController) TxDetails(txHash *chainhash.Hash, pkScript []byte) // - wallet must be unlocked // - address must be under wallet control // - address must be native segwit address -func (w *RpcWalletController) SignBip322NativeSegwit(msg []byte, address btcutil.Address) (wire.TxWitness, error) { +func (w *RPCWalletController) SignBip322NativeSegwit(msg []byte, address btcutil.Address) (wire.TxWitness, error) { toSpend, err := bip322.GetToSpendTx(msg, address) if err != nil { @@ -327,7 +327,7 @@ func (w *RpcWalletController) SignBip322NativeSegwit(msg []byte, address btcutil return signed.TxIn[0].Witness, nil } -func (w *RpcWalletController) OutputSpent( +func (w *RPCWalletController) OutputSpent( txHash *chainhash.Hash, outputIdx uint32, ) (bool, error) { @@ -342,7 +342,7 @@ func (w *RpcWalletController) OutputSpent( return res == nil, nil } -func (w *RpcWalletController) SignOneInputTaprootSpendingTransaction(request *TaprootSigningRequest) (*TaprootSigningResult, error) { +func (w *RPCWalletController) SignOneInputTaprootSpendingTransaction(request *TaprootSigningRequest) (*TaprootSigningResult, error) { if len(request.TxToSign.TxIn) != 1 { return nil, fmt.Errorf("cannot sign transaction with more than one input") }