Skip to content

Commit

Permalink
batch 2 of fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Lazar955 committed Nov 9, 2024
1 parent 372be76 commit 538c249
Show file tree
Hide file tree
Showing 21 changed files with 86 additions and 87 deletions.
6 changes: 3 additions & 3 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ linters:
- forbidigo
- forcetypeassert
# - gci
- gochecknoinits
# - gochecknoinits
- goconst
- gocritic
# - gocritic
- gocyclo
- goheader
- gomodguard
Expand All @@ -39,7 +39,7 @@ linters:
- makezero
- misspell
- nakedret
- nestif
# - nestif
- nilerr
# - nlreturn # Style wise I personally like this one, todo(lazar): unlax at somepoint, good practice
- noctx
Expand Down
2 changes: 1 addition & 1 deletion btcclient/notifier.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func (c *EmptyHintCache) PurgeConfirmHint(_ ...chainntnfs.ConfRequest) error {
// // 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)
}
}
Expand Down
4 changes: 4 additions & 0 deletions btcclient/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ func (c *Client) getBestBlockHashWithRetry() (*chainhash.Hash, error) {
); err != nil {
c.logger.Debug(
"failed to query the best block hash", zap.Error(err))
return nil, err
}

return blockHash, nil
Expand All @@ -106,6 +107,7 @@ func (c *Client) getBlockHashWithRetry(height uint32) (*chainhash.Hash, error) {
); err != nil {
c.logger.Debug(
"failed to query the block hash", zap.Uint32("height", height), zap.Error(err))
return nil, err
}

return blockHash, nil
Expand All @@ -130,6 +132,7 @@ func (c *Client) getBlockWithRetry(hash *chainhash.Hash) (*wire.MsgBlock, error)
); err != nil {
c.logger.Debug(
"failed to query the block", zap.String("hash", hash.String()), zap.Error(err))
return nil, err
}

return block, nil
Expand All @@ -154,6 +157,7 @@ func (c *Client) getBlockVerboseWithRetry(hash *chainhash.Hash) (*btcjson.GetBlo
); err != nil {
c.logger.Debug(
"failed to query the block verbose", zap.String("hash", hash.String()), zap.Error(err))
return nil, err
}

return blockVerbose, nil
Expand Down
2 changes: 1 addition & 1 deletion btcstaking-tracker/btcslasher/slasher.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ func (bs *BTCSlasher) slashingEnforcer() {
)

// record the metrics of the slashed delegation
bs.metrics.RecordSlashedDelegation(slashRes.Del, slashRes.SlashingTxHash.String())
bs.metrics.RecordSlashedDelegation(slashRes.Del)
}
}
}
Expand Down
1 change: 1 addition & 0 deletions btcstaking-tracker/btcslasher/slasher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import (
"github.com/babylonlabs-io/vigilante/testutil/mocks"
)

//nolint:maintidx // Ignoring high maintainability index for this fuzz test
func FuzzSlasher(f *testing.F) {
datagen.AddRandomSeedsToFuzzer(f, 10)

Expand Down
2 changes: 1 addition & 1 deletion btcstaking-tracker/expected_routines.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package btcstaking_tracker
package btcstakingtracker

type IBTCSlasher interface {
// common functions
Expand Down
25 changes: 9 additions & 16 deletions btcstaking-tracker/stakingeventwatcher/stakingeventwatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -415,8 +415,8 @@ func (sew *StakingEventWatcher) watchForSpend(spendEvent *notifier.SpendEvent, t
// As we only care about unbonding transactions, we do not need to take additional actions.
// We start polling babylon for delegation to stop being active, and then delete it from unbondingTracker.
sew.logger.Debugf("Spending tx %s for staking tx %s is not unbonding tx. Info: %v", spendingTxHash, delegationID, err)
proof, err := sew.waitForStakeSpendInclusionProof(quitCtx, spendingTx)
if err != nil {
proof := sew.waitForStakeSpendInclusionProof(quitCtx, spendingTx)
if proof == nil {
sew.logger.Errorf("unbonding tx %s for staking tx %s proof not built", spendingTxHash, delegationID)
return
}
Expand All @@ -425,8 +425,8 @@ func (sew *StakingEventWatcher) watchForSpend(spendEvent *notifier.SpendEvent, t
sew.metrics.DetectedUnbondingTransactionsCounter.Inc()
// We found valid unbonding tx. We need to try to report it to babylon.
// We stop reporting if delegation is no longer active or we succeed.
proof, err := sew.waitForStakeSpendInclusionProof(quitCtx, spendingTx)
if err != nil {
proof := sew.waitForStakeSpendInclusionProof(quitCtx, spendingTx)
if proof == nil {
sew.logger.Errorf("unbonding tx %s for staking tx %s proof not built", spendingTxHash, delegationID)
return
}
Expand Down Expand Up @@ -471,7 +471,7 @@ func (sew *StakingEventWatcher) buildSpendingTxProof(spendingTx *wire.MsgTx) (*b
func (sew *StakingEventWatcher) waitForStakeSpendInclusionProof(
ctx context.Context,
spendingTx *wire.MsgTx,
) (*btcstakingtypes.InclusionProof, error) {
) *btcstakingtypes.InclusionProof {
var (
proof *btcstakingtypes.InclusionProof
err error
Expand All @@ -498,7 +498,7 @@ func (sew *StakingEventWatcher) waitForStakeSpendInclusionProof(
}),
)

return proof, nil
return proof
}

func (sew *StakingEventWatcher) handleUnbondedDelegations() {
Expand Down Expand Up @@ -564,12 +564,7 @@ func (sew *StakingEventWatcher) handlerVerifiedDelegations() {
select {
case <-ticker.C:
sew.logger.Debug("Checking for new staking txs")

if err := sew.checkBtcForStakingTx(); err != nil {
sew.logger.Errorf("error checking verified delegations: %v", err)
continue
}

sew.checkBtcForStakingTx()
case <-sew.quit:
sew.logger.Debug("verified delegations loop quit")
return
Expand All @@ -579,10 +574,10 @@ func (sew *StakingEventWatcher) handlerVerifiedDelegations() {

// checkBtcForStakingTx gets a snapshot of current Delegations in cache
// checks if staking tx is in BTC, generates a proof and invokes sending of MsgAddBTCDelegationInclusionProof
func (sew *StakingEventWatcher) checkBtcForStakingTx() error {
func (sew *StakingEventWatcher) checkBtcForStakingTx() {
delegations := sew.pendingTracker.GetDelegations()
if delegations == nil {
return nil
return
}

for _, del := range delegations {
Expand Down Expand Up @@ -612,8 +607,6 @@ func (sew *StakingEventWatcher) checkBtcForStakingTx() error {

go sew.activateBtcDelegation(txHash, proof)
}

return nil
}

// activateBtcDelegation invokes bbn client and send MsgAddBTCDelegationInclusionProof
Expand Down
2 changes: 1 addition & 1 deletion btcstaking-tracker/tracker.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package btcstaking_tracker
package btcstakingtracker

import (
"fmt"
Expand Down
37 changes: 22 additions & 15 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,22 +112,29 @@ func DefaultConfig() *Config {

// New returns a fully parsed Config object from a given file directory
func New(configFile string) (Config, error) {
if _, err := os.Stat(configFile); err == nil { // the given file exists, parse it
viper.SetConfigFile(configFile)
if err := viper.ReadInConfig(); err != nil {
return Config{}, err
if _, err := os.Stat(configFile); err != nil {
if errors.Is(err, os.ErrNotExist) {
// The given config file does not exist
return Config{}, fmt.Errorf("no config file found at %s", configFile)
}
var cfg Config
if err := viper.Unmarshal(&cfg); err != nil {
return Config{}, err
}
if err := cfg.Validate(); err != nil {
return Config{}, err
}
return cfg, err
} else if errors.Is(err, os.ErrNotExist) { // the given config file does not exist, return error
return Config{}, fmt.Errorf("no config file found at %s", configFile)
} else { // other errors
// Other errors
return Config{}, err
}

// File exists, so parse it
viper.SetConfigFile(configFile)
if err := viper.ReadInConfig(); err != nil {
return Config{}, err
}

var cfg Config
if err := viper.Unmarshal(&cfg); err != nil {
return Config{}, err
}

if err := cfg.Validate(); err != nil {
return Config{}, err
}

return cfg, nil
}
2 changes: 1 addition & 1 deletion metrics/btcstaking_tracker.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ func newSlasherMetrics(registry *prometheus.Registry) *SlasherMetrics {
return metrics
}

func (sm *SlasherMetrics) RecordSlashedDelegation(del *types.BTCDelegationResponse, txHashStr string) {
func (sm *SlasherMetrics) RecordSlashedDelegation(del *types.BTCDelegationResponse) {
// refresh time of the slashed delegation gauge for each (fp, del) pair
for _, pk := range del.FpBtcPkList {
sm.SlashedDelegationGaugeVec.WithLabelValues(
Expand Down
1 change: 0 additions & 1 deletion metrics/reporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,5 +88,4 @@ func (sm *ReporterMetrics) RecordMetrics() {
sm.SecondsSinceLastCheckpointGauge.Inc()
}
}()

}
2 changes: 1 addition & 1 deletion monitor/btcscanner/btc_scanner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func FuzzBootStrap(f *testing.F) {
confirmedBlocks := chainIndexedBlocks[:numBlocks-uint64(k)]
mockBtcClient.EXPECT().GetBestBlock().Return(bestHeight, nil)
for i := 0; i < int(numBlocks); i++ {
mockBtcClient.EXPECT().GetBlockByHeight(gomock.Eq(uint32(chainIndexedBlocks[i].Height))).
mockBtcClient.EXPECT().GetBlockByHeight(gomock.Eq(chainIndexedBlocks[i].Height)).
Return(chainIndexedBlocks[i], nil, nil).AnyTimes()
}

Expand Down
4 changes: 1 addition & 3 deletions reporter/block_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,7 @@ func (r *Reporter) processNewBlock(ib *types.IndexedBlock) error {
}

// Process checkpoints
if _, _, err := r.ProcessCheckpoints(signer, headersToProcess); err != nil {
r.logger.Warnf("Failed to submit checkpoints: %v", err)
}
_, _ = r.ProcessCheckpoints(signer, headersToProcess)

return nil
}
5 changes: 1 addition & 4 deletions reporter/bootstrapping.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,7 @@ func (r *Reporter) bootstrap() error {

// fetch k+w blocks from cache and submit checkpoints
ibs = r.btcCache.GetAllBlocks()
_, _, err = r.ProcessCheckpoints(signer, ibs)
if err != nil {
r.logger.Warnf("Failed to submit checkpoints: %v", err)
}
_, _ = r.ProcessCheckpoints(signer, ibs)

r.logger.Info("Successfully finished bootstrapping")

Expand Down
18 changes: 7 additions & 11 deletions reporter/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ import (
"github.com/babylonlabs-io/vigilante/retrywrap"
"strconv"

pv "github.com/cosmos/relayer/v2/relayer/provider"

"github.com/avast/retry-go/v4"
btcctypes "github.com/babylonlabs-io/babylon/x/btccheckpoint/types"
btclctypes "github.com/babylonlabs-io/babylon/x/btclightclient/types"
Expand Down Expand Up @@ -152,12 +150,10 @@ func (r *Reporter) extractCheckpoints(ib *types.IndexedBlock) int {
return numCkptSegs
}

func (r *Reporter) matchAndSubmitCheckpoints(signer string) (int, error) {
func (r *Reporter) matchAndSubmitCheckpoints(signer string) int {
var (
res *pv.RelayerTxResponse
proofs []*btcctypes.BTCSpvProof
msgInsertBTCSpvProof *btcctypes.MsgInsertBTCSpvProof
err error
)

// get matched ckpt parts from the ckptCache
Expand All @@ -167,7 +163,7 @@ func (r *Reporter) matchAndSubmitCheckpoints(signer string) (int, error) {

if numMatchedCkpts == 0 {
r.logger.Debug("Found no matched pair of checkpoint segments in this match attempt")
return numMatchedCkpts, nil
return numMatchedCkpts
}

// for each matched checkpoint, wrap to MsgInsertBTCSpvProof and send to Babylon
Expand All @@ -189,7 +185,7 @@ func (r *Reporter) matchAndSubmitCheckpoints(signer string) (int, error) {
msgInsertBTCSpvProof = types.MustNewMsgInsertBTCSpvProof(signer, proofs)

// submit the checkpoint to Babylon
res, err = r.babylonClient.InsertBTCSpvProof(context.Background(), msgInsertBTCSpvProof)
res, err := r.babylonClient.InsertBTCSpvProof(context.Background(), msgInsertBTCSpvProof)
if err != nil {
r.logger.Errorf("Failed to submit MsgInsertBTCSpvProof with error %v", err)
r.metrics.FailedCheckpointsCounter.Inc()
Expand All @@ -208,12 +204,12 @@ func (r *Reporter) matchAndSubmitCheckpoints(signer string) (int, error) {
).SetToCurrentTime()
}

return numMatchedCkpts, nil
return numMatchedCkpts
}

// ProcessCheckpoints tries to extract checkpoint segments from a list of blocks, find matched checkpoint segments, and report matched checkpoints
// It returns the number of extracted checkpoint segments, and the number of matched checkpoints
func (r *Reporter) ProcessCheckpoints(signer string, ibs []*types.IndexedBlock) (int, int, error) {
func (r *Reporter) ProcessCheckpoints(signer string, ibs []*types.IndexedBlock) (int, int) {
var numCkptSegs int

// extract ckpt segments from the blocks
Expand All @@ -226,7 +222,7 @@ func (r *Reporter) ProcessCheckpoints(signer string, ibs []*types.IndexedBlock)
}

// match and submit checkpoint segments
numMatchedCkpts, err := r.matchAndSubmitCheckpoints(signer)
numMatchedCkpts := r.matchAndSubmitCheckpoints(signer)

return numCkptSegs, numMatchedCkpts, err
return numCkptSegs, numMatchedCkpts
}
11 changes: 5 additions & 6 deletions reporter/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import (
)

func newMockReporter(t *testing.T, ctrl *gomock.Controller) (
*mocks.MockBTCClient, *reporter.MockBabylonClient, *reporter.Reporter) {
*reporter.MockBabylonClient, *reporter.Reporter) {
cfg := config.DefaultConfig()
logger, err := cfg.CreateLogger()
require.NoError(t, err)
Expand All @@ -47,7 +47,7 @@ func newMockReporter(t *testing.T, ctrl *gomock.Controller) (
)
require.NoError(t, err)

return mockBTCClient, mockBabylonClient, r
return mockBabylonClient, r
}

// FuzzProcessHeaders fuzz tests ProcessHeaders()
Expand All @@ -70,7 +70,7 @@ func FuzzProcessHeaders(f *testing.F) {
ibs = append(ibs, types.NewIndexedBlockFromMsgBlock(r.Uint32(), block))
}

_, mockBabylonClient, mockReporter := newMockReporter(t, ctrl)
mockBabylonClient, mockReporter := newMockReporter(t, ctrl)

// a random number of blocks exists on chain
numBlocksOnChain := r.Intn(int(numBlocks))
Expand Down Expand Up @@ -101,7 +101,7 @@ func FuzzProcessCheckpoints(f *testing.F) {
defer ctrl.Finish()
r := rand.New(rand.NewSource(seed))

_, mockBabylonClient, mockReporter := newMockReporter(t, ctrl)
mockBabylonClient, mockReporter := newMockReporter(t, ctrl)
// inserting SPV proofs is always successful
mockBabylonClient.EXPECT().InsertBTCSpvProof(gomock.Any(), gomock.Any()).Return(&pv.RelayerTxResponse{Code: 0}, nil).AnyTimes()

Expand All @@ -117,9 +117,8 @@ func FuzzProcessCheckpoints(f *testing.F) {
}
}

numCkptSegs, numMatchedCkpts, err := mockReporter.ProcessCheckpoints("", ibs)
numCkptSegs, numMatchedCkpts := mockReporter.ProcessCheckpoints("", ibs)
require.Equal(t, numCkptSegsExpected, numCkptSegs)
require.Equal(t, numMatchedCkptsExpected, numMatchedCkpts)
require.NoError(t, err)
})
}
Loading

0 comments on commit 538c249

Please sign in to comment.