Skip to content

Commit

Permalink
chore: Replace logrus with zap as logger (ethereum-optimism#164)
Browse files Browse the repository at this point in the history
  • Loading branch information
gitferry authored Dec 5, 2023
1 parent b04de0e commit eebea03
Show file tree
Hide file tree
Showing 30 changed files with 544 additions and 534 deletions.
8 changes: 3 additions & 5 deletions clientcontroller/babylon.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import (
sdkquery "github.com/cosmos/cosmos-sdk/types/query"
sttypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/cosmos/relayer/v2/relayer/provider"
"github.com/sirupsen/logrus"
"go.uber.org/zap"

"github.com/babylonchain/btc-validator/config"
"github.com/babylonchain/btc-validator/types"
Expand All @@ -36,13 +36,13 @@ type BabylonController struct {
bbnClient *bbnclient.Client
cfg *config.BBNConfig
btcParams *chaincfg.Params
logger *logrus.Logger
logger *zap.Logger
}

func NewBabylonController(
cfg *config.BBNConfig,
btcParams *chaincfg.Params,
logger *logrus.Logger,
logger *zap.Logger,
) (*BabylonController, error) {

bbnConfig := config.BBNConfigToBabylonConfig(cfg)
Expand Down Expand Up @@ -683,7 +683,6 @@ func (bc *BabylonController) CreateBTCDelegation(
return nil, err
}

bc.logger.Infof("successfully submitted a BTC delegation, code: %v, height: %v, tx hash: %s", res.Code, res.Height, res.TxHash)
return &types.TxResponse{TxHash: res.TxHash}, nil
}

Expand All @@ -709,7 +708,6 @@ func (bc *BabylonController) CreateBTCUndelegation(
return nil, err
}

bc.logger.Infof("successfully submitted a BTC undelegation, code: %v, height: %v, tx hash: %s", res.Code, res.Height, res.TxHash)
return res, nil
}

Expand Down
7 changes: 4 additions & 3 deletions clientcontroller/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ package clientcontroller

import (
"fmt"
"github.com/btcsuite/btcd/chaincfg"
"math/big"

"github.com/btcsuite/btcd/chaincfg"
"go.uber.org/zap"

"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/sirupsen/logrus"

"github.com/babylonchain/btc-validator/config"
"github.com/babylonchain/btc-validator/types"
Expand Down Expand Up @@ -97,7 +98,7 @@ type CovenantAPIs interface {
QueryUnbondingDelegations(limit uint64) ([]*types.Delegation, error)
}

func NewClientController(chainName string, bbnConfig *config.BBNConfig, netParams *chaincfg.Params, logger *logrus.Logger) (ClientController, error) {
func NewClientController(chainName string, bbnConfig *config.BBNConfig, netParams *chaincfg.Params, logger *zap.Logger) (ClientController, error) {
var (
cc ClientController
err error
Expand Down
32 changes: 12 additions & 20 deletions covenant/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,19 @@ package config

import (
"fmt"
"github.com/sirupsen/logrus"
"io"
"os"
"path/filepath"
"time"

"github.com/babylonchain/btc-validator/config"
"go.uber.org/zap"

"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg"
"github.com/jessevdk/go-flags"

"github.com/babylonchain/btc-validator/config"
"github.com/babylonchain/btc-validator/log"
)

const (
Expand Down Expand Up @@ -57,7 +60,7 @@ type Config struct {
// 2. Pre-parse the command line to check for an alternative config file
// 3. Load configuration file overwriting defaults with any specified options
// 4. Parse CLI options and overwrite/add any specified options
func LoadConfig(filePath string) (*Config, *logrus.Logger, error) {
func LoadConfig(filePath string) (*Config, *zap.Logger, error) {
// Pre-parse the command line options to pick up an alternative config
// file.
preCfg := DefaultConfig()
Expand Down Expand Up @@ -86,18 +89,11 @@ func LoadConfig(filePath string) (*Config, *logrus.Logger, error) {
configFileError = err
}

cfgLogger := logrus.New()
cfgLogger.Out = os.Stdout
// Make sure everything we just loaded makes sense.
if err := cfg.Validate(); err != nil {
return nil, nil, err
}

logRuslLevel, err := logrus.ParseLevel(cfg.LogLevel)
if err != nil {
return nil, nil, err
}

// At this point we know config is valid, create logger which also log to file
logFilePath := filepath.Join(cfg.CovenantDir, defaultLogFilename)
f, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
Expand All @@ -106,20 +102,21 @@ func LoadConfig(filePath string) (*Config, *logrus.Logger, error) {
}
mw := io.MultiWriter(os.Stdout, f)

cfgLogger.SetOutput(mw)
cfgLogger.SetLevel(logRuslLevel)
cfgLogger, err := log.NewRootLogger("console", cfg.LogLevel, mw)
if err != nil {
return nil, nil, err
}

// Warn about missing config file only after all other configuration is
// done. This prevents the warning on help messages and invalid
// options. Note this should go directly before the return.
if configFileError != nil {
cfgLogger.Warnf("%v", configFileError)
if cfg.DumpCfg {
cfgLogger.Infof("Writing configuration file to %s", filePath)
cfgLogger.Info("Writing configuration file", zap.String("path", filePath))
fileParser := flags.NewParser(&cfg, flags.Default)
err := flags.NewIniParser(fileParser).WriteFile(filePath, flags.IniIncludeComments|flags.IniIncludeDefaults)
if err != nil {
cfgLogger.Warnf("Error writing configuration file: %v", err)
cfgLogger.Error("Error writing configuration file", zap.Error(err))
return nil, nil, err
}
}
Expand Down Expand Up @@ -161,11 +158,6 @@ func (cfg *Config) Validate() error {
return fmt.Errorf("unsupported Bitcoin network: %s", cfg.BitcoinNetwork)
}

_, err = logrus.ParseLevel(cfg.LogLevel)
if err != nil {
return err
}

return nil
}

Expand Down
74 changes: 31 additions & 43 deletions covenant/covenant.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,21 @@ package covenant

import (
"fmt"
"github.com/babylonchain/btc-validator/keyring"
"strings"
"sync"
"time"

"go.uber.org/zap"

"github.com/babylonchain/btc-validator/keyring"

"github.com/avast/retry-go/v4"
"github.com/babylonchain/babylon/btcstaking"
asig "github.com/babylonchain/babylon/crypto/schnorr-adaptor-signature"
bbntypes "github.com/babylonchain/babylon/types"
bstypes "github.com/babylonchain/babylon/x/btcstaking/types"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcutil"
"github.com/sirupsen/logrus"

"github.com/babylonchain/btc-validator/clientcontroller"
covcfg "github.com/babylonchain/btc-validator/covenant/config"
Expand Down Expand Up @@ -43,7 +45,7 @@ type CovenantEmulator struct {

config *covcfg.Config
params *types.StakingParams
logger *logrus.Logger
logger *zap.Logger

// input is used to pass passphrase to the keyring
input *strings.Reader
Expand All @@ -54,7 +56,7 @@ func NewCovenantEmulator(
config *covcfg.Config,
cc clientcontroller.ClientController,
passphrase string,
logger *logrus.Logger,
logger *zap.Logger,
) (*CovenantEmulator, error) {
input := strings.NewReader("")
kr, err := keyring.CreateKeyring(
Expand Down Expand Up @@ -185,13 +187,7 @@ func (ce *CovenantEmulator) AddCovenantSignature(btcDel *types.Delegation) (*Add
// 4. submit covenant sigs
res, err := ce.cc.SubmitCovenantSigs(ce.pk, stakingMsgTx.TxHash().String(), covSigs)

delPkHex := bbntypes.NewBIP340PubKeyFromBTCPK(btcDel.BtcPk).MarshalHex()
if err != nil {
ce.logger.WithFields(logrus.Fields{
"err": err,
"validator_pks": btcDel.ValBtcPks,
"delegator_pk": delPkHex,
}).Error("failed to submit Covenant signature")
return nil, err
}

Expand Down Expand Up @@ -326,13 +322,7 @@ func (ce *CovenantEmulator) AddCovenantUnbondingSignatures(del *types.Delegation
covSlashingSigs,
)

delPkHex := bbntypes.NewBIP340PubKeyFromBTCPK(del.BtcPk).MarshalHex()

if err != nil {
ce.logger.WithFields(logrus.Fields{
"err": err,
"delegator_pk": delPkHex,
}).Error("failed to submit covenant signatures")
return nil, err
}

Expand Down Expand Up @@ -365,55 +355,52 @@ func (ce *CovenantEmulator) covenantSigSubmissionLoop() {
case <-covenantSigTicker.C:
// 0. Update slashing address in case it is changed upon governance proposal
if err := ce.UpdateParams(); err != nil {
ce.logger.WithFields(logrus.Fields{
"err": err,
}).Error("failed to get staking params")
ce.logger.Debug("failed to get staking params", zap.Error(err))
continue
}

// 1. Get all pending delegations first, these are more important than the unbonding ones
dels, err := ce.cc.QueryPendingDelegations(limit)
if err != nil {
ce.logger.WithFields(logrus.Fields{
"err": err,
}).Error("failed to get pending delegations")
ce.logger.Debug("failed to get pending delegations", zap.Error(err))
continue
}
if len(dels) == 0 {
ce.logger.WithFields(logrus.Fields{}).Debug("no pending delegations are found")
ce.logger.Debug("no pending delegations are found")
}

for _, d := range dels {
_, err := ce.AddCovenantSignature(d)
if err != nil {
ce.logger.WithFields(logrus.Fields{
"err": err,
"del_btc_pk": d.BtcPk,
}).Error("failed to submit Covenant sig to the Bitcoin delegation")
delPkHex := bbntypes.NewBIP340PubKeyFromBTCPK(d.BtcPk).MarshalHex()
ce.logger.Error(
"failed to submit covenant signatures to the BTC delegation",
zap.String("del_btc_pk", delPkHex),
zap.Error(err),
)
}
}

// 2. Get all unbonding delegations
unbondingDels, err := ce.cc.QueryUnbondingDelegations(limit)

if err != nil {
ce.logger.WithFields(logrus.Fields{
"err": err,
}).Error("failed to get pending delegations")
ce.logger.Debug("failed to get unbonding delegations", zap.Error(err))
continue
}

if len(unbondingDels) == 0 {
ce.logger.WithFields(logrus.Fields{}).Debug("no unbonding delegations are found")
ce.logger.Debug("no unbonding delegations are found")
}

for _, d := range unbondingDels {
_, err := ce.AddCovenantUnbondingSignatures(d)
if err != nil {
ce.logger.WithFields(logrus.Fields{
"err": err,
"del_btc_pk": d.BtcPk,
}).Error("failed to submit Covenant sig to the Bitcoin undelegation")
delPkHex := bbntypes.NewBIP340PubKeyFromBTCPK(d.BtcPk).MarshalHex()
ce.logger.Error(
"failed to submit covenant signatures to the BTC undelegation",
zap.String("del_btc_pk", delPkHex),
zap.Error(err),
)
}
}

Expand Down Expand Up @@ -458,11 +445,12 @@ func (ce *CovenantEmulator) getParamsWithRetry() (*types.StakingParams, error) {
}
return nil
}, RtyAtt, RtyDel, RtyErr, retry.OnRetry(func(n uint, err error) {
ce.logger.WithFields(logrus.Fields{
"attempt": n + 1,
"max_attempts": RtyAttNum,
"error": err,
}).Debug("failed to query the consumer chain for the staking params")
ce.logger.Debug(
"failed to query the consumer chain for the staking params",
zap.Uint("attempt", n+1),
zap.Uint("max_attempts", RtyAttNum),
zap.Error(err),
)
})); err != nil {
return nil, err
}
Expand All @@ -473,7 +461,7 @@ func (ce *CovenantEmulator) getParamsWithRetry() (*types.StakingParams, error) {
func (ce *CovenantEmulator) Start() error {
var startErr error
ce.startOnce.Do(func() {
ce.logger.Infof("Starting Covenant Emulator")
ce.logger.Info("Starting Covenant Emulator")

ce.wg.Add(1)
go ce.covenantSigSubmissionLoop()
Expand All @@ -485,7 +473,7 @@ func (ce *CovenantEmulator) Start() error {
func (ce *CovenantEmulator) Stop() error {
var stopErr error
ce.stopOnce.Do(func() {
ce.logger.Infof("Stopping Covenant Emulator")
ce.logger.Info("Stopping Covenant Emulator")

// Always stop the submission loop first to not generate additional events and actions
ce.logger.Debug("Stopping submission loop")
Expand Down
4 changes: 2 additions & 2 deletions covenant/covenant_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import (
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/wire"
"github.com/golang/mock/gomock"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
"go.uber.org/zap"

"github.com/babylonchain/btc-validator/covenant"
covcfg "github.com/babylonchain/btc-validator/covenant/config"
Expand Down Expand Up @@ -52,7 +52,7 @@ func FuzzAddCovenantSig(f *testing.F) {
require.NoError(t, err)

// create and start covenant emulator
ce, err := covenant.NewCovenantEmulator(&covenantConfig, mockClientController, passphrase, logrus.New())
ce, err := covenant.NewCovenantEmulator(&covenantConfig, mockClientController, passphrase, zap.NewNop())
require.NoError(t, err)

err = ce.UpdateParams()
Expand Down
8 changes: 4 additions & 4 deletions covenant/service/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"sync/atomic"

"github.com/lightningnetwork/lnd/signal"
"github.com/sirupsen/logrus"
"go.uber.org/zap"

"github.com/babylonchain/btc-validator/covenant"
)
Expand All @@ -16,15 +16,15 @@ type CovenantServer struct {

ce *covenant.CovenantEmulator

logger *logrus.Logger
logger *zap.Logger

interceptor signal.Interceptor

quit chan struct{}
}

// NewCovenantServer creates a new server with the given config.
func NewCovenantServer(l *logrus.Logger, ce *covenant.CovenantEmulator, sig signal.Interceptor) *CovenantServer {
func NewCovenantServer(l *zap.Logger, ce *covenant.CovenantEmulator, sig signal.Interceptor) *CovenantServer {
return &CovenantServer{
logger: l,
ce: ce,
Expand All @@ -49,7 +49,7 @@ func (s *CovenantServer) RunUntilShutdown() error {
return fmt.Errorf("failed to start covenant emulator: %w", err)
}

s.logger.Infof("Covenant Emulator Daemon is fully active!")
s.logger.Info("Covenant Emulator Daemon is fully active!")

// Wait for shutdown signal from either a graceful server stop or from
// the interrupt handler.
Expand Down
Loading

0 comments on commit eebea03

Please sign in to comment.