From 064d4c3c9998da7c04a9841726b16c34ced7e4fa Mon Sep 17 00:00:00 2001 From: Olanrewaju Collins Date: Wed, 22 Jan 2020 20:21:15 +0100 Subject: [PATCH] multi: fix dcrwallet/errors usage (#92) * multi: fix dcrwallet/errors usage Errors were wrongly formatted and it returned an unreadable error. The fixes it by using the correct error formatting function. * return error for invalid net type * use concrete error type * Add tests for NewMultiWallet * replace 0700 -> os.ModePerm * Change canUseDir condition * Change Build and Test to work on pull requests * Correct NewMultiTest * Revert test changes Co-authored-by: Alawode Oluwandabira <24304808+RogueElement@users.noreply.github.com> --- errors.go | 47 ++++++++++++++++++++++++--------------------- log.go | 19 ++++++------------ multiwallet.go | 23 +++++++++++++++------- spv/sync.go | 2 +- sync.go | 2 +- syncnotification.go | 6 ------ txindex/save.go | 2 +- utils/netparams.go | 9 +++++---- 8 files changed, 55 insertions(+), 55 deletions(-) diff --git a/errors.go b/errors.go index 36911543..74097ff4 100644 --- a/errors.go +++ b/errors.go @@ -4,28 +4,31 @@ import "github.com/decred/dcrwallet/errors/v2" const ( // Error Codes - ErrInsufficientBalance = "insufficient_balance" - ErrInvalid = "invalid" - ErrWalletNotLoaded = "wallet_not_loaded" - ErrWalletNameExist = "wallet_name_exists" - ErrReservedWalletName = "wallet_name_reserved" - ErrWalletIsWatchOnly = "watch_only_wallet" - ErrUnusableSeed = "unusable_seed" - ErrPassphraseRequired = "passphrase_required" - ErrInvalidPassphrase = "invalid_passphrase" - ErrNotConnected = "not_connected" - ErrExist = "exists" - ErrNotExist = "not_exists" - ErrEmptySeed = "empty_seed" - ErrInvalidAddress = "invalid_address" - ErrInvalidAuth = "invalid_auth" - ErrUnavailable = "unavailable" - ErrContextCanceled = "context_canceled" - ErrFailedPrecondition = "failed_precondition" - ErrSyncAlreadyInProgress = "sync_already_in_progress" - ErrNoPeers = "no_peers" - ErrInvalidPeers = "invalid_peers" - ErrListenerAlreadyExist = "listener_already_exist" + ErrInsufficientBalance = "insufficient_balance" + ErrInvalid = "invalid" + ErrWalletDatabaseInUse = "wallet_db_in_use" + ErrWalletNotLoaded = "wallet_not_loaded" + ErrWalletNameExist = "wallet_name_exists" + ErrReservedWalletName = "wallet_name_reserved" + ErrWalletIsWatchOnly = "watch_only_wallet" + ErrUnusableSeed = "unusable_seed" + ErrPassphraseRequired = "passphrase_required" + ErrInvalidPassphrase = "invalid_passphrase" + ErrNotConnected = "not_connected" + ErrExist = "exists" + ErrNotExist = "not_exists" + ErrEmptySeed = "empty_seed" + ErrInvalidAddress = "invalid_address" + ErrInvalidAuth = "invalid_auth" + ErrUnavailable = "unavailable" + ErrContextCanceled = "context_canceled" + ErrFailedPrecondition = "failed_precondition" + ErrSyncAlreadyInProgress = "sync_already_in_progress" + ErrNoPeers = "no_peers" + ErrInvalidPeers = "invalid_peers" + ErrListenerAlreadyExist = "listener_already_exist" + ErrLoggerAlreadyRegistered = "logger_already_registered" + ErrLogRotatorAlreadyInitialized = "log_rotator_already_initialized" ) // todo, should update this method to translate more error kinds. diff --git a/log.go b/log.go index fe0d514e..dda6517e 100644 --- a/log.go +++ b/log.go @@ -6,12 +6,11 @@ package dcrlibwallet import ( - "fmt" "os" - "path/filepath" "github.com/decred/dcrd/addrmgr" "github.com/decred/dcrd/connmgr/v2" + "github.com/decred/dcrwallet/errors" "github.com/decred/dcrwallet/p2p/v2" "github.com/decred/dcrwallet/ticketbuyer/v4" "github.com/decred/dcrwallet/wallet/v3" @@ -89,30 +88,24 @@ var subsystemLoggers = map[string]slog.Logger{ // initLogRotator initializes the logging rotater to write logs to logFile and // create roll files in the same directory. It must be called before the // package-global log rotater variables are used. -func initLogRotator(logFile string) { - logDir, _ := filepath.Split(logFile) - err := os.MkdirAll(logDir, 0700) - if err != nil { - fmt.Fprintf(os.Stderr, "failed to create log directory: %v\n", err) - os.Exit(1) - } +func initLogRotator(logFile string) error { r, err := rotator.New(logFile, 10*1024, false, 3) if err != nil { - fmt.Fprintf(os.Stderr, "failed to create file rotator: %v\n", err) - os.Exit(1) + return errors.Errorf("failed to create file rotator: %v", err) } logRotator = r + return nil } // RegisterLogger should be called before logRotator is initialized. func RegisterLogger(tag string) (slog.Logger, error) { if logRotator != nil { - return nil, fmt.Errorf("cannot register logger after log rotator is initialized") + return nil, errors.E(ErrLogRotatorAlreadyInitialized) } if _, exists := subsystemLoggers[tag]; exists { - return nil, fmt.Errorf("logger already registered for tag: %s", tag) + return nil, errors.E(ErrLoggerAlreadyRegistered) } logger := backendLog.Logger(tag) diff --git a/multiwallet.go b/multiwallet.go index 5a2f6f53..8e55c9ff 100644 --- a/multiwallet.go +++ b/multiwallet.go @@ -37,13 +37,22 @@ type MultiWallet struct { } func NewMultiWallet(rootDir, dbDriver, netType string) (*MultiWallet, error) { - rootDir = filepath.Join(rootDir, netType) - initLogRotator(filepath.Join(rootDir, logFileName)) errors.Separator = ":: " - chainParams := utils.ChainParams(netType) - if chainParams == nil { - return nil, errors.E("unsupported network type: %s", netType) + chainParams, err := utils.ChainParams(netType) + if err != nil { + return nil, err + } + + rootDir = filepath.Join(rootDir, netType) + err = os.MkdirAll(rootDir, os.ModePerm) + if err != nil { + return nil, errors.Errorf("failed to create rootDir: %v", err) + } + + err = initLogRotator(filepath.Join(rootDir, logFileName)) + if err != nil { + return nil, errors.Errorf("failed to init logRotator: %v", err.Error()) } walletsDb, err := storm.Open(filepath.Join(rootDir, walletsDbName)) @@ -51,9 +60,9 @@ func NewMultiWallet(rootDir, dbDriver, netType string) (*MultiWallet, error) { log.Errorf("Error opening wallets database: %s", err.Error()) if err == bolt.ErrTimeout { // timeout error occurs if storm fails to acquire a lock on the database file - return nil, errors.E("wallets database is in use by another process") + return nil, errors.E(ErrWalletDatabaseInUse) } - return nil, errors.E("error opening wallets database: %s", err.Error()) + return nil, errors.Errorf("error opening wallets database: %s", err.Error()) } // init database for saving/reading wallet objects diff --git a/spv/sync.go b/spv/sync.go index c73442e7..dd1f1767 100644 --- a/spv/sync.go +++ b/spv/sync.go @@ -561,7 +561,7 @@ func (s *Syncer) getTransactionsByHashes(ctx context.Context, txHashes []*chainh for walletID, w := range s.wallets { walletFoundTxs, _, err := w.GetTransactionsByHashes(ctx, txHashes) if err != nil && !errors.Is(err, errors.NotExist) { - return nil, nil, errors.E("[%d] Failed to look up transactions for getdata reply to peer: %v", walletID, err) + return nil, nil, errors.Errorf("[%d] Failed to look up transactions for getdata reply to peer: %v", walletID, err) } if len(walletFoundTxs) != 0 { diff --git a/sync.go b/sync.go index 65bcbd25..808ef7be 100644 --- a/sync.go +++ b/sync.go @@ -230,7 +230,7 @@ func (mw *MultiWallet) SpvSync() error { mw.notifySyncCanceled() mw.syncData.syncCanceled <- true } else if err == context.DeadlineExceeded { - mw.notifySyncError(errors.E("SPV synchronization deadline exceeded: %v", err)) + mw.notifySyncError(errors.Errorf("SPV synchronization deadline exceeded: %v", err)) } else { mw.notifySyncError(err) } diff --git a/syncnotification.go b/syncnotification.go index c635ebe3..8fe5f33c 100644 --- a/syncnotification.go +++ b/syncnotification.go @@ -8,12 +8,6 @@ import ( "golang.org/x/sync/errgroup" ) -const ( - SyncStateStart = "start" - SyncStateProgress = "progress" - SyncStateFinish = "finish" -) - func (mw *MultiWallet) spvSyncNotificationCallbacks() *spv.Notifications { return &spv.Notifications{ PeerConnected: func(peerCount int32, addr string) { diff --git a/txindex/save.go b/txindex/save.go index c2dd2330..4de6e22f 100644 --- a/txindex/save.go +++ b/txindex/save.go @@ -17,7 +17,7 @@ func (db *DB) SaveOrUpdate(emptyTxPointer, tx interface{}) (overwritten bool, er txHash := reflect.Indirect(v).FieldByName("Hash").String() err = db.txDB.One("Hash", txHash, emptyTxPointer) if err != nil && err != storm.ErrNotFound { - err = errors.E("error checking if tx was already indexed: %s", err.Error()) + err = errors.Errorf("error checking if tx was already indexed: %s", err.Error()) return } diff --git a/utils/netparams.go b/utils/netparams.go index 78577474..1f173ce0 100644 --- a/utils/netparams.go +++ b/utils/netparams.go @@ -4,6 +4,7 @@ import ( "strings" "github.com/decred/dcrd/chaincfg/v2" + "github.com/decred/dcrwallet/errors" ) var ( @@ -11,13 +12,13 @@ var ( testnetParams = chaincfg.TestNet3Params() ) -func ChainParams(netType string) *chaincfg.Params { +func ChainParams(netType string) (*chaincfg.Params, error) { switch strings.ToLower(netType) { case strings.ToLower(mainnetParams.Name): - return mainnetParams + return mainnetParams, nil case strings.ToLower(testnetParams.Name): - return testnetParams + return testnetParams, nil default: - return nil + return nil, errors.New("invalid net type") } }