Skip to content

Commit

Permalink
multi: fix dcrwallet/errors usage (#92)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>
  • Loading branch information
2 people authored and itswisdomagain committed Jan 22, 2020
1 parent d4d67d9 commit 064d4c3
Showing 8 changed files with 55 additions and 55 deletions.
47 changes: 25 additions & 22 deletions errors.go
Original file line number Diff line number Diff line change
@@ -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.
19 changes: 6 additions & 13 deletions log.go
Original file line number Diff line number Diff line change
@@ -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)
23 changes: 16 additions & 7 deletions multiwallet.go
Original file line number Diff line number Diff line change
@@ -37,23 +37,32 @@ 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))
if err != nil {
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
2 changes: 1 addition & 1 deletion spv/sync.go
Original file line number Diff line number Diff line change
@@ -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 {
2 changes: 1 addition & 1 deletion sync.go
Original file line number Diff line number Diff line change
@@ -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)
}
6 changes: 0 additions & 6 deletions syncnotification.go
Original file line number Diff line number Diff line change
@@ -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) {
2 changes: 1 addition & 1 deletion txindex/save.go
Original file line number Diff line number Diff line change
@@ -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
}

9 changes: 5 additions & 4 deletions utils/netparams.go
Original file line number Diff line number Diff line change
@@ -4,20 +4,21 @@ import (
"strings"

"github.com/decred/dcrd/chaincfg/v2"
"github.com/decred/dcrwallet/errors"
)

var (
mainnetParams = chaincfg.MainNetParams()
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")
}
}

0 comments on commit 064d4c3

Please sign in to comment.