From 5a1e6f7e47eec498fefa66e9dcd8b3eab255c705 Mon Sep 17 00:00:00 2001 From: Ivan Kuznetsov Date: Thu, 7 Sep 2017 16:46:55 +0700 Subject: [PATCH] Don't create a wallet when wallet.dat already exists --- cli.go | 11 ++++++++--- wallet.go | 9 +++++++-- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/cli.go b/cli.go index f32e343..8688056 100644 --- a/cli.go +++ b/cli.go @@ -18,9 +18,14 @@ func (cli *CLI) createBlockchain(address string) { } func (cli *CLI) createWallet() { - wallet := NewWallet() - fmt.Printf("Your address: %s\n", wallet.GetAddress()) - wallet.SaveToFile() + wallet, err := NewWallet() + if err == nil { + fmt.Printf("Your address: %s\n", wallet.GetAddress()) + wallet.SaveToFile() + } else { + fmt.Println(err.Error()) + os.Exit(1) + } } func (cli *CLI) getBalance(address string) { diff --git a/wallet.go b/wallet.go index 6752f62..0bb5ee5 100644 --- a/wallet.go +++ b/wallet.go @@ -6,8 +6,10 @@ import ( "crypto/rand" "crypto/sha256" "encoding/gob" + "errors" "io/ioutil" "log" + "os" "golang.org/x/crypto/ripemd160" ) @@ -58,11 +60,14 @@ func (w Wallet) SaveToFile() { } // NewWallet creates and returns a Wallet -func NewWallet() *Wallet { +func NewWallet() (*Wallet, error) { + if _, err := os.Stat(walletFile); !os.IsNotExist(err) { + return nil, errors.New("Wallet already exists") + } private, public := newKeyPair() wallet := Wallet{private, public} - return &wallet + return &wallet, nil } func newKeyPair() ([]byte, []byte) {