diff --git a/internal/handler/wallet/backup.go b/internal/handler/wallet/backup.go index a3c72e64b..8ce97bcf0 100644 --- a/internal/handler/wallet/backup.go +++ b/internal/handler/wallet/backup.go @@ -3,11 +3,11 @@ package wallet import ( "fmt" "io" + "net/http" "os" "github.com/awnumar/memguard" "github.com/go-openapi/runtime/middleware" - "github.com/massalabs/station-massa-wallet/api/server/models" "github.com/massalabs/station-massa-wallet/api/server/restapi/operations" walletapp "github.com/massalabs/station-massa-wallet/pkg/app" "github.com/massalabs/station-massa-wallet/pkg/prompt" @@ -34,10 +34,7 @@ func (w *walletBackupAccount) Handle(params operations.BackupAccountParams) midd if err == walletmanager.AccountNotFoundError { return operations.NewGetAccountNotFound() } else if err != nil { - return operations.NewGetAccountInternalServerError().WithPayload(&models.Error{ - Code: errorGetWallets, - Message: err.Error(), - }) + return newErrorResponse(err.Error(), errorGetWallets, http.StatusInternalServerError) } promptRequest := prompt.PromptRequest{ @@ -47,11 +44,7 @@ func (w *walletBackupAccount) Handle(params operations.BackupAccountParams) midd promptOutput, err := prompt.WakeUpPrompt(w.prompterApp, promptRequest, acc) if err != nil { - return operations.NewBackupAccountUnauthorized().WithPayload( - &models.Error{ - Code: errorCanceledAction, - Message: "Unable to backup account", - }) + return newErrorResponse("Unable to backup account", errorCanceledAction, http.StatusUnauthorized) } // If the user choose to backup the wallet using the yaml file, promptOutput will be a BackupMethod @@ -62,35 +55,25 @@ func (w *walletBackupAccount) Handle(params operations.BackupAccountParams) midd var publicKey string = "" if isYmlBackup { - walletErr := w.saveAccountFile(params.Nickname) - if walletErr != nil { + err = w.saveAccountFile(params.Nickname) + if err != nil { w.prompterApp.EmitEvent(walletapp.PromptResultEvent, - walletapp.EventData{Success: false, CodeMessage: walletErr.CodeErr}) + walletapp.EventData{Success: false, CodeMessage: utils.WailsErrorCode(err)}) - return operations.NewBackupAccountBadRequest().WithPayload( - &models.Error{ - Code: errorSaveAccount, - Message: walletErr.CodeErr, - }) + return newErrorResponse(utils.ErrAccountFile, errorSaveAccount, http.StatusBadRequest) } } else { guardedPassword, _ := promptOutput.(*memguard.LockedBuffer) guardedPrivateKey, err := acc.PrivateKeyTextInClear(guardedPassword) if err != nil { - return operations.NewBackupAccountInternalServerError().WithPayload(&models.Error{ - Code: errorGetWallets, - Message: err.Error(), - }) + return newErrorResponse(err.Error(), errorGetWallets, http.StatusInternalServerError) } defer guardedPrivateKey.Destroy() privateKey = string(guardedPrivateKey.Bytes()) publicKeyBytes, err := acc.PublicKey.MarshalText() if err != nil { - return operations.NewBackupAccountInternalServerError().WithPayload(&models.Error{ - Code: errorGetWallets, - Message: err.Error(), - }) + return newErrorResponse(err.Error(), errorGetWallets, http.StatusInternalServerError) } publicKey = string(publicKeyBytes) @@ -102,60 +85,42 @@ func (w *walletBackupAccount) Handle(params operations.BackupAccountParams) midd } w.prompterApp.EmitEvent(walletapp.PromptResultEvent, - walletapp.EventData{Success: true, CodeMessage: utils.MsgBackupSuccess, Data: data}) + walletapp.EventData{Success: true, Data: data}) return operations.NewBackupAccountNoContent() } -func (w *walletBackupAccount) saveAccountFile(nickname string) *walletmanager.WalletError { +func (w *walletBackupAccount) saveAccountFile(nickname string) error { dstFile, err := w.prompterApp.SelectBackupFilepath(nickname) if err != nil { - return &walletmanager.WalletError{ - Err: err, - CodeErr: utils.ErrAccountFile, - } + return err } if dstFile == "" { - return &walletmanager.WalletError{ - Err: fmt.Errorf("no file selected"), - CodeErr: utils.ActionCanceled, - } + return fmt.Errorf("no file selected: %w", utils.ErrActionCanceled) } // Create the destination file destination, err := os.Create(dstFile) if err != nil { - return &walletmanager.WalletError{ - Err: err, - CodeErr: utils.ErrAccountFile, - } + return err } defer destination.Close() srcFile, err := w.prompterApp.App().WalletManager.AccountPath(nickname) if err != nil { - return &walletmanager.WalletError{ - Err: err, - CodeErr: utils.ErrAccountFile, - } + return err } source, err := os.Open(srcFile) if err != nil { - return &walletmanager.WalletError{ - Err: err, - CodeErr: utils.ErrAccountFile, - } + return err } defer source.Close() _, err = io.Copy(destination, source) if err != nil { - return &walletmanager.WalletError{ - Err: err, - CodeErr: utils.ErrAccountFile, - } + return err } return nil diff --git a/internal/handler/wallet/backup_test.go b/internal/handler/wallet/backup_test.go index 7f7a8d144..9b0e820a5 100644 --- a/internal/handler/wallet/backup_test.go +++ b/internal/handler/wallet/backup_test.go @@ -75,7 +75,7 @@ func Test_walletBackupAccount_Handle(t *testing.T) { result := <-testResult - checkResultChannel(t, result, true, "Backup Success") + checkResultChannel(t, result, true, "") }) t.Run("chose private backup then cancel", func(t *testing.T) { @@ -133,7 +133,7 @@ func Test_walletBackupAccount_Handle(t *testing.T) { assert.Equal(t, "S", string(data.PrivateKey[0])) assert.Equal(t, string(publicKeyBytes), data.PublicKey) - checkResultChannel(t, result, true, "Backup Success") + checkResultChannel(t, result, true, "") }) err = os.Remove(WalletBackupFilepath) diff --git a/internal/handler/wallet/create.go b/internal/handler/wallet/create.go index 60c7d51c6..b193c9c3f 100644 --- a/internal/handler/wallet/create.go +++ b/internal/handler/wallet/create.go @@ -66,7 +66,7 @@ func (w *walletCreate) Handle(params operations.CreateAccountParams) middleware. } w.prompterApp.EmitEvent(walletapp.PromptResultEvent, - walletapp.EventData{Success: true, CodeMessage: utils.MsgAccountCreated}) + walletapp.EventData{Success: true}) infos, err := w.massaClient.GetAccountsInfos([]account.Account{*acc}) if err != nil { diff --git a/internal/handler/wallet/create_test.go b/internal/handler/wallet/create_test.go index 4bee04be5..a156c63fe 100644 --- a/internal/handler/wallet/create_test.go +++ b/internal/handler/wallet/create_test.go @@ -55,7 +55,7 @@ func Test_walletCreate_Handle(t *testing.T) { if len(test.password) > 0 && test.statusCode == http.StatusOK { result := <-testResult - checkResultChannel(t, result, true, "New password created") + checkResultChannel(t, result, true, "") assertWallet(t, prompterApp.App().WalletManager, nickname) } diff --git a/internal/handler/wallet/delete.go b/internal/handler/wallet/delete.go index 2681682ba..f10c2d400 100644 --- a/internal/handler/wallet/delete.go +++ b/internal/handler/wallet/delete.go @@ -78,7 +78,7 @@ func (w *walletDelete) Handle(params operations.DeleteAccountParams) middleware. } w.prompterApp.EmitEvent(walletapp.PromptResultEvent, - walletapp.EventData{Success: true, CodeMessage: utils.MsgAccountDeleted}) + walletapp.EventData{Success: true}) return operations.NewDeleteAccountNoContent() } diff --git a/internal/handler/wallet/delete_test.go b/internal/handler/wallet/delete_test.go index fdd6ecd73..7af4dd137 100644 --- a/internal/handler/wallet/delete_test.go +++ b/internal/handler/wallet/delete_test.go @@ -89,7 +89,7 @@ func Test_walletDelete_Handle(t *testing.T) { result := <-testResult - checkResultChannel(t, result, true, utils.MsgAccountDeleted) + checkResultChannel(t, result, true, "") _, err = prompterApp.App().WalletManager.GetAccount(nickname) assert.Error(t, err, "Wallet should have been deleted") diff --git a/internal/handler/wallet/get.go b/internal/handler/wallet/get.go index bb9eb9de9..4728a65d0 100644 --- a/internal/handler/wallet/get.go +++ b/internal/handler/wallet/get.go @@ -72,7 +72,7 @@ func (w *walletGet) Handle(params operations.GetAccountParams) middleware.Respon defer guardedPrivateKey.Destroy() w.prompterApp.EmitEvent(walletapp.PromptResultEvent, - walletapp.EventData{Success: true, CodeMessage: utils.MsgAccountUnprotected}) + walletapp.EventData{Success: true}) modelWallet.KeyPair, resp = newKeyPairModel(*acc, guardedPrivateKey) if resp != nil { diff --git a/internal/handler/wallet/get_test.go b/internal/handler/wallet/get_test.go index aa40f360b..624d9dee4 100644 --- a/internal/handler/wallet/get_test.go +++ b/internal/handler/wallet/get_test.go @@ -109,7 +109,7 @@ func Test_getWallet_handler(t *testing.T) { result := <-testResult - checkResultChannel(t, result, true, "Unprotect Success") + checkResultChannel(t, result, true, "") }) } diff --git a/internal/handler/wallet/import.go b/internal/handler/wallet/import.go index fc6719a61..3fa789134 100644 --- a/internal/handler/wallet/import.go +++ b/internal/handler/wallet/import.go @@ -9,7 +9,6 @@ import ( walletapp "github.com/massalabs/station-massa-wallet/pkg/app" "github.com/massalabs/station-massa-wallet/pkg/network" "github.com/massalabs/station-massa-wallet/pkg/prompt" - "github.com/massalabs/station-massa-wallet/pkg/utils" "github.com/massalabs/station-massa-wallet/pkg/wallet/account" ) @@ -43,7 +42,7 @@ func (w *walletImport) Handle(_ operations.ImportAccountParams) middleware.Respo acc, _ := promptOutput.(*account.Account) w.prompterApp.EmitEvent(walletapp.PromptResultEvent, - walletapp.EventData{Success: true, CodeMessage: utils.MsgAccountImported}) + walletapp.EventData{Success: true}) infos, err := w.massaClient.GetAccountsInfos([]account.Account{*acc}) if err != nil { diff --git a/internal/handler/wallet/import_test.go b/internal/handler/wallet/import_test.go index f090c24ed..db9ff2b39 100644 --- a/internal/handler/wallet/import_test.go +++ b/internal/handler/wallet/import_test.go @@ -69,39 +69,13 @@ PublicKey: [0, 164, 243, 44, 155, 204, 6, 20, 131, 218, 97, 32, 58, 224, 189, 41 verifyStatusCode(t, resp, http.StatusOK) - checkResultChannel(t, result, true, "Import Success") + checkResultChannel(t, result, true, "") assertWallet(t, prompterApp.App().WalletManager, nickname) os.Remove(filePath) }) - t.Run("import invalid path file", func(t *testing.T) { - walletFile := "InvalidWallet" - - filePath := "importMe.yaml" - // Write wallet file - data := []byte(walletFile) - err = os.WriteFile(filePath, data, 0o644) - assert.NoError(t, err) - defer os.Remove(filePath) - - testResult := make(chan walletapp.EventData) - - // Send filepath to prompter app and wait for result - go func(res chan walletapp.EventData) { - // Send invalid filename to prompter app and wait for result - prompterApp.App().PromptInput <- "invalidFilename" - failRes := <-resChan - - checkResultChannel(t, failRes, false, utils.ErrInvalidFileExtension) - }(testResult) - - resp := importWallet(t, api) - - verifyStatusCode(t, resp, http.StatusUnauthorized) - }) - t.Run("import invalid account file", func(t *testing.T) { walletFile := "InvalidWallet" @@ -184,8 +158,7 @@ PublicKey: [0, 164, 243, 44, 155, 204, 6, 20, 131, 218, 97, 32, 58, 224, 189, 41 password: memguard.NewBufferFromBytes([]byte("aGoodPassword")), wantStatus: http.StatusOK, wantResult: walletapp.EventData{ - Success: true, - CodeMessage: utils.MsgAccountImported, + Success: true, }, }, { diff --git a/internal/handler/wallet/rolls.go b/internal/handler/wallet/rolls.go index 0ab2289e0..195c1c57a 100644 --- a/internal/handler/wallet/rolls.go +++ b/internal/handler/wallet/rolls.go @@ -12,7 +12,6 @@ import ( walletapp "github.com/massalabs/station-massa-wallet/pkg/app" "github.com/massalabs/station-massa-wallet/pkg/network" "github.com/massalabs/station-massa-wallet/pkg/prompt" - "github.com/massalabs/station-massa-wallet/pkg/utils" "github.com/massalabs/station-massa-wallet/pkg/wallet/account" sendOperation "github.com/massalabs/station/pkg/node/sendoperation" "github.com/massalabs/station/pkg/node/sendoperation/buyrolls" @@ -81,7 +80,7 @@ func (t *tradeRolls) Handle(params operations.TradeRollsParams) middleware.Respo } t.prompterApp.EmitEvent(walletapp.PromptResultEvent, - walletapp.EventData{Success: true, CodeMessage: utils.MsgRollTradeSuccess}) + walletapp.EventData{Success: true}) return operations.NewTradeRollsOK().WithPayload( &models.OperationResponse{ diff --git a/internal/handler/wallet/sign.go b/internal/handler/wallet/sign.go index d6dbe8a08..51be67550 100644 --- a/internal/handler/wallet/sign.go +++ b/internal/handler/wallet/sign.go @@ -103,9 +103,10 @@ func (w *walletSign) Handle(params operations.SignParams) middleware.Responder { password, err := w.PromptPassword(acc, promptRequest) if err != nil { msg := fmt.Sprintf("Unable to unprotect wallet: %s", err.Error()) - if errors.Is(err, prompt.ErrWrongPassword) || errors.Is(err, prompt.ErrActionCanceled) { + if errors.Is(err, utils.ErrWrongPassword) || errors.Is(err, utils.ErrActionCanceled) { return newErrorResponse(msg, errorGetWallets, http.StatusUnauthorized) } + return newErrorResponse(msg, errorGetWallets, http.StatusInternalServerError) } @@ -147,7 +148,7 @@ func (w *walletSign) PromptPassword(acc *account.Account, promptRequest *prompt. password, _ := promptOutput.(*memguard.LockedBuffer) w.prompterApp.EmitEvent(walletapp.PromptResultEvent, - walletapp.EventData{Success: true, CodeMessage: utils.MsgAccountUnprotected}) + walletapp.EventData{Success: true}) return password, nil } diff --git a/internal/handler/wallet/sign_message.go b/internal/handler/wallet/sign_message.go index 4dd867f0f..e2aeb590a 100644 --- a/internal/handler/wallet/sign_message.go +++ b/internal/handler/wallet/sign_message.go @@ -1,6 +1,7 @@ package wallet import ( + "errors" "fmt" "net/http" @@ -47,11 +48,12 @@ func (w *walletSignMessage) Handle(params operations.SignMessageParams) middlewa // Use the prompt-based logic to sign the message promptOutput, err := prompt.WakeUpPrompt(w.prompterApp, *promptRequest, acc) if err != nil { - return operations.NewSignMessageUnauthorized().WithPayload( - &models.Error{ - Code: errorCanceledAction, - Message: "Unable to unprotect wallet", - }) + msg := fmt.Sprintf("Unable to unprotect wallet: %s", err.Error()) + if errors.Is(err, utils.ErrWrongPassword) || errors.Is(err, utils.ErrActionCanceled) { + return newErrorResponse(msg, errorGetWallets, http.StatusUnauthorized) + } + + return newErrorResponse(msg, errorGetWallets, http.StatusInternalServerError) } guardedPassword, _ := promptOutput.(*memguard.LockedBuffer) @@ -62,7 +64,7 @@ func (w *walletSignMessage) Handle(params operations.SignMessageParams) middlewa } w.prompterApp.EmitEvent(walletapp.PromptResultEvent, - walletapp.EventData{Success: true, CodeMessage: utils.MsgAccountUnprotected}) + walletapp.EventData{Success: true}) publicKeyBytes, err := acc.PublicKey.MarshalText() if err != nil { diff --git a/internal/handler/wallet/sign_test.go b/internal/handler/wallet/sign_test.go index c7be1dc2a..9aa432466 100644 --- a/internal/handler/wallet/sign_test.go +++ b/internal/handler/wallet/sign_test.go @@ -66,7 +66,7 @@ func Test_walletSign_Handle(t *testing.T) { result := <-testResult - checkResultChannel(t, result, true, utils.MsgAccountUnprotected) + checkResultChannel(t, result, true, "") }) t.Run("sign a plain text message", func(t *testing.T) { @@ -87,7 +87,7 @@ func Test_walletSign_Handle(t *testing.T) { result := <-testResult - checkResultChannel(t, result, true, utils.MsgAccountUnprotected) + checkResultChannel(t, result, true, "") }) // The handler will not return until a the good password is sent or the action is canceled @@ -115,7 +115,7 @@ func Test_walletSign_Handle(t *testing.T) { result := <-testResult - checkResultChannel(t, result, true, utils.MsgAccountUnprotected) + checkResultChannel(t, result, true, "") }) t.Run("invalid password try, then action canceled by user", func(t *testing.T) { @@ -152,7 +152,7 @@ func Test_walletSign_Handle(t *testing.T) { result := <-testResult - checkResultChannel(t, result, true, "Unprotect Success") + checkResultChannel(t, result, true, "") var body models.SignResponse err = json.Unmarshal(resp.Body.Bytes(), &body) diff --git a/internal/handler/wallet/transfer.go b/internal/handler/wallet/transfer.go index cdae72adc..136ceb768 100644 --- a/internal/handler/wallet/transfer.go +++ b/internal/handler/wallet/transfer.go @@ -95,7 +95,7 @@ func (t *transferCoin) Handle(params operations.TransferCoinParams) middleware.R } t.prompterApp.EmitEvent(walletapp.PromptResultEvent, - walletapp.EventData{Success: true, CodeMessage: utils.MsgTransferSuccess}) + walletapp.EventData{Success: true}) return operations.NewTransferCoinOK().WithPayload( &models.OperationResponse{ diff --git a/internal/handler/wallet/update.go b/internal/handler/wallet/update.go index 5154ac0e2..7852ab618 100644 --- a/internal/handler/wallet/update.go +++ b/internal/handler/wallet/update.go @@ -2,13 +2,13 @@ package wallet import ( "fmt" + "net/http" "github.com/go-openapi/runtime/middleware" "github.com/massalabs/station-massa-wallet/api/server/models" "github.com/massalabs/station-massa-wallet/api/server/restapi/operations" "github.com/massalabs/station-massa-wallet/pkg/network" "github.com/massalabs/station-massa-wallet/pkg/prompt" - "github.com/massalabs/station-massa-wallet/pkg/utils" "github.com/massalabs/station-massa-wallet/pkg/wallet/account" "github.com/massalabs/station-massa-wallet/pkg/walletmanager" ) @@ -34,13 +34,9 @@ func (w *walletUpdateAccount) Handle(params operations.UpdateAccountParams) midd return resp } - newAcc, errModify := w.handleUpdateAccount(acc, params.Body.Nickname) - if errModify != nil { - return operations.NewGetAccountInternalServerError().WithPayload( - &models.Error{ - Code: errModify.CodeErr, - Message: errModify.Err.Error(), - }) + newAcc, err := w.handleUpdateAccount(acc, params.Body.Nickname) + if err != nil { + return newErrorResponse(err.Error(), "", http.StatusInternalServerError) } modelWallet, resp := newAccountModel(*newAcc) @@ -63,10 +59,10 @@ func (w *walletUpdateAccount) Handle(params operations.UpdateAccountParams) midd return operations.NewGetAccountOK().WithPayload(modelWallet) } -func (w *walletUpdateAccount) handleUpdateAccount(acc *account.Account, newNickname models.Nickname) (*account.Account, *walletmanager.WalletError) { +func (w *walletUpdateAccount) handleUpdateAccount(acc *account.Account, newNickname models.Nickname) (*account.Account, error) { // check if the nickname does not change if acc.Nickname == string(newNickname) { - return nil, &walletmanager.WalletError{Err: fmt.Errorf("nickname is the same"), CodeErr: utils.ErrSameNickname} + return nil, walletmanager.ErrNicknameNotUnique } // save the old nickname in a variable @@ -82,17 +78,17 @@ func (w *walletUpdateAccount) handleUpdateAccount(acc *account.Account, newNickn acc.PublicKey, ) if err != nil { - return nil, &walletmanager.WalletError{Err: err, CodeErr: utils.ErrInvalidNickname} + return nil, fmt.Errorf("creating new account: %w", err) } err = w.prompterApp.App().WalletManager.DeleteAccount(string(oldNickname)) if err != nil { - return nil, &walletmanager.WalletError{Err: err, CodeErr: utils.WailsErrorCode(err)} + return nil, err } err = w.prompterApp.App().WalletManager.AddAccount(newAcc, true) if err != nil { - return nil, &walletmanager.WalletError{Err: err, CodeErr: utils.WailsErrorCode(err)} + return nil, err } return newAcc, nil diff --git a/pkg/prompt/constants.go b/pkg/prompt/constants.go index e591e1107..bca2312e6 100644 --- a/pkg/prompt/constants.go +++ b/pkg/prompt/constants.go @@ -1,31 +1,14 @@ package prompt import ( - "errors" - "fmt" "time" ) const ( - InvalidAccountFileErr = "invalid account file" - AccountLoadErr = "unable to load account file" - ImportPrivateKeyErr = "unable to import private key" - ActionCanceledErr = "Action canceled by user" - TimeoutErr = "Password prompt reached timeout" - PasswordLengthErr = "password length must be %d characters minimum" - InputTypeErr = "Invalid prompt input type" - AlreadyListeningErr = "prompter is already listening" + InputTypeErr = "Invalid prompt input type" + AlreadyListeningErr = "prompter is already listening" ) const ( - PASSWORD_MIN_LENGTH = 5 - TIMEOUT = 5 * time.Minute -) - -var passwordLengthErrMsg = fmt.Sprintf(PasswordLengthErr, PASSWORD_MIN_LENGTH) - -var ( - ErrWrongPassword = errors.New("wrong password") - ErrActionCanceled = errors.New(ActionCanceledErr) - ErrTimeout = errors.New(TimeoutErr) + TIMEOUT = 5 * time.Minute ) diff --git a/pkg/prompt/createPassword.go b/pkg/prompt/createPassword.go index e3d901570..8f3b18881 100644 --- a/pkg/prompt/createPassword.go +++ b/pkg/prompt/createPassword.go @@ -1,12 +1,9 @@ package prompt import ( - "fmt" "strings" "github.com/awnumar/memguard" - walletapp "github.com/massalabs/station-massa-wallet/pkg/app" - "github.com/massalabs/station-massa-wallet/pkg/utils" ) func handleNewPasswordPrompt(prompterApp WalletPrompterInterface, input interface{}) (*memguard.LockedBuffer, bool, error) { @@ -16,12 +13,6 @@ func handleNewPasswordPrompt(prompterApp WalletPrompterInterface, input interfac } trimmedPassword := strings.TrimSpace(password) - if len(trimmedPassword) < PASSWORD_MIN_LENGTH { - // TODO implement/refactor password strength check - prompterApp.EmitEvent(walletapp.PromptResultEvent, - walletapp.EventData{Success: false, CodeMessage: utils.ErrInvalidPassword}) - return nil, true, fmt.Errorf(passwordLengthErrMsg) - } guardedPassword := memguard.NewBufferFromBytes([]byte(trimmedPassword)) diff --git a/pkg/prompt/import.go b/pkg/prompt/import.go index 98e7864cf..8e1163bb3 100644 --- a/pkg/prompt/import.go +++ b/pkg/prompt/import.go @@ -2,7 +2,6 @@ package prompt import ( "fmt" - "strings" walletapp "github.com/massalabs/station-massa-wallet/pkg/app" "github.com/massalabs/station-massa-wallet/pkg/utils" @@ -24,23 +23,14 @@ func handleImportPrompt(prompterApp WalletPrompterInterface, input interface{}) } func handleImportFile(prompterApp WalletPrompterInterface, filePath string) (*account.Account, bool, error) { - if !strings.HasSuffix(filePath, ".yaml") && !strings.HasSuffix(filePath, ".yml") { - prompterApp.EmitEvent(walletapp.PromptResultEvent, - walletapp.EventData{Success: false, CodeMessage: utils.ErrInvalidFileExtension}) - return nil, false, fmt.Errorf(InvalidAccountFileErr) - } - wallet := prompterApp.App().WalletManager acc, err := wallet.Load(filePath) if err != nil { - msg := fmt.Sprintf("%v: %v", AccountLoadErr, err) - code := utils.WailsErrorCode(err) - fmt.Println("code is: ", code) prompterApp.EmitEvent(walletapp.PromptResultEvent, - walletapp.EventData{Success: false, CodeMessage: code}) + walletapp.EventData{Success: false, CodeMessage: utils.WailsErrorCode(err)}) - return nil, false, fmt.Errorf(msg) + return nil, false, fmt.Errorf("unable to load account file: %w", err) } err = wallet.AddAccount(acc, true) @@ -58,11 +48,10 @@ func handleImportFile(prompterApp WalletPrompterInterface, filePath string) (*ac func handleImportPrivateKey(prompterApp WalletPrompterInterface, walletInfo walletapp.ImportFromPKey) (*account.Account, bool, error) { acc, err := account.NewFromPrivateKey(walletInfo.Password, walletInfo.Nickname, walletInfo.PrivateKey) if err != nil { - errStr := fmt.Sprintf("%v: %v", ImportPrivateKeyErr, err) prompterApp.EmitEvent(walletapp.PromptResultEvent, walletapp.EventData{Success: false, CodeMessage: utils.WailsErrorCode(err)}) - return nil, false, fmt.Errorf(errStr) + return nil, false, fmt.Errorf("unable to import private key: %w", err) } wallet := prompterApp.App().WalletManager diff --git a/pkg/prompt/password.go b/pkg/prompt/password.go index 105fa40f7..72d480c19 100644 --- a/pkg/prompt/password.go +++ b/pkg/prompt/password.go @@ -27,7 +27,7 @@ func handlePasswordPrompt(prompterApp WalletPrompterInterface, input interface{} prompterApp.EmitEvent(walletapp.PromptResultEvent, walletapp.EventData{Success: false, CodeMessage: utils.WrongPassword}) - return nil, true, fmt.Errorf("%w: %s", ErrWrongPassword, msg) + return nil, true, fmt.Errorf("%w: %s", utils.ErrWrongPassword, msg) } return passwordReturned, false, nil diff --git a/pkg/prompt/prompt.go b/pkg/prompt/prompt.go index f9fda1d3e..382203d5e 100644 --- a/pkg/prompt/prompt.go +++ b/pkg/prompt/prompt.go @@ -109,16 +109,16 @@ func WakeUpPrompt( return output, nil case <-prompterApp.App().CtrlChan: - logger.Warn(ActionCanceledErr) + logger.Warn(utils.ErrActionCanceled.Error()) - return nil, ErrActionCanceled + return nil, utils.ErrActionCanceled case <-ctxTimeout.Done(): - logger.Warn(TimeoutErr) + logger.Warn(utils.ErrTimeout.Error()) prompterApp.EmitEvent(walletapp.PromptResultEvent, - walletapp.EventData{Success: false, CodeMessage: utils.ErrTimeout}) + walletapp.EventData{Success: false, CodeMessage: utils.ErrTimeoutMsg}) - return nil, ErrTimeout + return nil, utils.ErrTimeout } } } diff --git a/pkg/utils/constants.go b/pkg/utils/constants.go index ba470789f..161f6e8c3 100644 --- a/pkg/utils/constants.go +++ b/pkg/utils/constants.go @@ -2,19 +2,16 @@ package utils // Error codes const ( - ErrInvalidNickname = "Nickname-0001" - ErrSameNickname = "Nickname-0002" - ErrInvalidPassword = "Password-0001" - ErrInvalidPrivateKey = "PrivateKey-0001" - ErrAccountFile = "AccountFile-0001" // for errors related to folder, read/write file, unmarshal... - ErrNoFile = "NoFile-0001" - ErrInvalidFileExtension = "InvalidFileExtension-0001" // for errors related to file name extension - ErrDuplicateKey = "DuplicateKey-0001" - ErrUnknown = "Unknown-0001" - ErrDuplicateNickname = "DuplicateNickname-001" - ErrTimeout = "Timeout-0001" - ErrNetwork = "Network-0001" - ErrPromptInputType = "InvalidPromptInput-0001" + ErrInvalidNickname = "Nickname-0001" + ErrInvalidPrivateKey = "PrivateKey-0001" + ErrAccountFile = "AccountFile-0001" + ErrNoFile = "NoFile-0001" + ErrDuplicateKey = "DuplicateKey-0001" + ErrUnknown = "Unknown-0001" + ErrDuplicateNickname = "DuplicateNickname-001" + ErrTimeoutMsg = "Timeout-0001" + ErrNetwork = "Network-0001" + ErrPromptInputType = "InvalidPromptInput-0001" ) // Message codes @@ -25,12 +22,5 @@ const ( // Messages const ( - MsgAccountCreated = "New password created" - MsgAccountDeleted = "Delete Success" - MsgAccountUnprotected = "Unprotect Success" - MsgAccountImported = "Import Success" - MsgTransferSuccess = "Transfer Success" - MsgRollTradeSuccess = "Trade rolls Success" - MsgBackupSuccess = "Backup Success" - MsgTransferRequest = "transfer-request" + MsgTransferRequest = "transfer-request" ) diff --git a/pkg/utils/errors.go b/pkg/utils/errors.go index 1fe4b01a4..09530bda5 100644 --- a/pkg/utils/errors.go +++ b/pkg/utils/errors.go @@ -11,6 +11,9 @@ import ( var ( ErrCorrelationIDNotFound = errors.New("Correlation ID not found") ErrCache = errors.New("Error loading cache") + ErrWrongPassword = errors.New("wrong password") + ErrActionCanceled = errors.New("Action canceled by user") + ErrTimeout = errors.New("Password prompt reached timeout") ) func WailsErrorCode(err error) string { @@ -38,5 +41,9 @@ func WailsErrorCode(err error) string { return ErrAccountFile } + if errors.Is(err, ErrActionCanceled) { + return ActionCanceled + } + return ErrUnknown } diff --git a/pkg/walletmanager/wallet.go b/pkg/walletmanager/wallet.go index 38fd1a616..6505a3f4e 100644 --- a/pkg/walletmanager/wallet.go +++ b/pkg/walletmanager/wallet.go @@ -19,11 +19,6 @@ var ( AccountNotFoundError = errors.New("account not found") ) -type WalletError struct { - Err error - CodeErr string // Sentinel error code from utils package, can be used as a translation key. -} - type Wallet struct { accounts map[string]*account.Account // Mapping from nickname to account InvalidAccountNicknames []string // List of invalid account nicknames diff --git a/wails-frontend/src/utils/errors.tsx b/wails-frontend/src/utils/errors.tsx index 2142fc9eb..ba1e91798 100644 --- a/wails-frontend/src/utils/errors.tsx +++ b/wails-frontend/src/utils/errors.tsx @@ -1,8 +1,8 @@ export enum ErrorCode { InvalidNickname = 'Nickname-0001', InvalidPrivateKey = 'PrivateKey-0001', - ErrNoFile = 'NoFile-0001', FilesystemError = 'AccountFile-0001', + ErrNoFile = 'NoFile-0001', DuplicateKey = 'DuplicateKey-0001', UnknownError = 'Unknown-0001', DuplicateNickname = 'DuplicateNickname-001',