Skip to content

Commit 1959346

Browse files
committed
account update: migrate or change password
* account.Update * KeyStore.Cleanup * fix dir rm for old format deleteKey
1 parent fc17a52 commit 1959346

4 files changed

Lines changed: 149 additions & 25 deletions

File tree

‎accounts/account_manager.go‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import (
3636
"crypto/ecdsa"
3737
crand "crypto/rand"
3838
"errors"
39+
"fmt"
3940
"os"
4041
"sync"
4142
"time"
@@ -158,6 +159,20 @@ func (am *Manager) NewAccount(auth string) (Account, error) {
158159
return Account{Address: key.Address}, nil
159160
}
160161

162+
func (am *Manager) AddressByIndex(index int) (addr string, err error) {
163+
var addrs []common.Address
164+
addrs, err = am.keyStore.GetKeyAddresses()
165+
if err != nil {
166+
return
167+
}
168+
if index < 0 || index >= len(addrs) {
169+
err = fmt.Errorf("index out of range: %d (should be 0-%d)", index, len(addrs)-1)
170+
} else {
171+
addr = addrs[index].Hex()
172+
}
173+
return
174+
}
175+
161176
func (am *Manager) Accounts() ([]Account, error) {
162177
addresses, err := am.keyStore.GetKeyAddresses()
163178
if os.IsNotExist(err) {
@@ -204,6 +219,19 @@ func (am *Manager) Import(path string, keyAuth string) (Account, error) {
204219
return Account{Address: key.Address}, nil
205220
}
206221

222+
func (am *Manager) Update(addr common.Address, authFrom, authTo string) (err error) {
223+
var key *crypto.Key
224+
key, err = am.keyStore.GetKey(addr, authFrom)
225+
226+
if err == nil {
227+
err = am.keyStore.StoreKey(key, authTo)
228+
if err == nil {
229+
am.keyStore.Cleanup(addr)
230+
}
231+
}
232+
return
233+
}
234+
207235
func (am *Manager) ImportPreSaleKey(keyJSON []byte, password string) (acc Account, err error) {
208236
var key *crypto.Key
209237
key, err = crypto.ImportPreSaleKey(am.keyStore, keyJSON, password)

‎cmd/geth/main.go‎

Lines changed: 61 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,33 @@ Note, this is meant to be used for testing only, it is a bad idea to save your
189189
password to file or expose in any other way.
190190
`,
191191
},
192+
{
193+
Action: accountUpdate,
194+
Name: "update",
195+
Usage: "update an existing account",
196+
Description: `
197+
198+
ethereum account update <address>
199+
200+
Update an existing account.
201+
202+
The account is saved in the newest version in encrypted format, you are prompted
203+
for a passphrase to unlock the account and another to save the updated file.
204+
205+
This same command can therefore be used to migrate an account of a deprecated
206+
format to the newest format or change the password for an account.
207+
208+
For non-interactive use the passphrase can be specified with the --password flag:
209+
210+
ethereum --password <passwordfile> account new
211+
212+
Since only one password can be given, only format update can be performed,
213+
changing your password is only possible interactively.
214+
215+
Note that account update has the a side effect that the order of your accounts
216+
changes.
217+
`,
218+
},
192219
{
193220
Action: accountImport,
194221
Name: "import",
@@ -433,27 +460,39 @@ func execJSFiles(ctx *cli.Context) {
433460
ethereum.WaitForShutdown()
434461
}
435462

436-
func unlockAccount(ctx *cli.Context, am *accounts.Manager, account string, i int) {
463+
func unlockAccount(ctx *cli.Context, am *accounts.Manager, addr string, i int) (addrHex, auth string) {
437464
var err error
438465
// Load startup keys. XXX we are going to need a different format
439466

440-
if !((len(account) == 40) || (len(account) == 42)) { // with or without 0x
441-
utils.Fatalf("Invalid account address '%s'", account)
467+
if !((len(addr) == 40) || (len(addr) == 42)) { // with or without 0x
468+
var index int
469+
index, err = strconv.Atoi(addr)
470+
if err != nil {
471+
utils.Fatalf("Invalid account address '%s'", addr)
472+
}
473+
474+
addrHex, err = am.AddressByIndex(index)
475+
if err != nil {
476+
utils.Fatalf("%v", err)
477+
}
478+
} else {
479+
addrHex = addr
442480
}
443481
// Attempt to unlock the account 3 times
444482
attempts := 3
445483
for tries := 0; tries < attempts; tries++ {
446-
msg := fmt.Sprintf("Unlocking account %s | Attempt %d/%d", account, tries+1, attempts)
447-
passphrase := getPassPhrase(ctx, msg, false, i)
448-
err = am.Unlock(common.HexToAddress(account), passphrase)
484+
msg := fmt.Sprintf("Unlocking account %s | Attempt %d/%d", addr, tries+1, attempts)
485+
auth = getPassPhrase(ctx, msg, false, i)
486+
err = am.Unlock(common.HexToAddress(addrHex), auth)
449487
if err == nil {
450488
break
451489
}
452490
}
453491
if err != nil {
454492
utils.Fatalf("Unlock account failed '%v'", err)
455493
}
456-
fmt.Printf("Account '%s' unlocked.\n", account)
494+
fmt.Printf("Account '%s' unlocked.\n", addr)
495+
return
457496
}
458497

459498
func blockRecovery(ctx *cli.Context) {
@@ -578,6 +617,21 @@ func accountCreate(ctx *cli.Context) {
578617
fmt.Printf("Address: %x\n", acct)
579618
}
580619

620+
func accountUpdate(ctx *cli.Context) {
621+
am := utils.MakeAccountManager(ctx)
622+
arg := ctx.Args().First()
623+
if len(arg) == 0 {
624+
utils.Fatalf("account address or index must be given as argument")
625+
}
626+
627+
addr, authFrom := unlockAccount(ctx, am, arg, 0)
628+
authTo := getPassPhrase(ctx, "Please give a new password. Do not forget this password.", true, 0)
629+
err := am.Update(common.HexToAddress(addr), authFrom, authTo)
630+
if err != nil {
631+
utils.Fatalf("Could not update the account: %v", err)
632+
}
633+
}
634+
581635
func importWallet(ctx *cli.Context) {
582636
keyfile := ctx.Args().First()
583637
if len(keyfile) == 0 {

‎crypto/key_store_passphrase.go‎

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -72,16 +72,19 @@ func (ks keyStorePassphrase) GenerateNewKey(rand io.Reader, auth string) (key *K
7272
}
7373

7474
func (ks keyStorePassphrase) GetKey(keyAddr common.Address, auth string) (key *Key, err error) {
75-
keyBytes, keyId, err := decryptKeyFromFile(ks, keyAddr, auth)
76-
if err != nil {
77-
return nil, err
78-
}
79-
key = &Key{
80-
Id: uuid.UUID(keyId),
81-
Address: keyAddr,
82-
PrivateKey: ToECDSA(keyBytes),
75+
keyBytes, keyId, err := decryptKeyFromFile(ks.keysDirPath, keyAddr, auth)
76+
if err == nil {
77+
key = &Key{
78+
Id: uuid.UUID(keyId),
79+
Address: keyAddr,
80+
PrivateKey: ToECDSA(keyBytes),
81+
}
8382
}
84-
return key, err
83+
return
84+
}
85+
86+
func (ks keyStorePassphrase) Cleanup(keyAddr common.Address) (err error) {
87+
return cleanup(ks.keysDirPath, keyAddr)
8588
}
8689

8790
func (ks keyStorePassphrase) GetKeyAddresses() (addresses []common.Address, err error) {
@@ -142,33 +145,33 @@ func (ks keyStorePassphrase) StoreKey(key *Key, auth string) (err error) {
142145

143146
func (ks keyStorePassphrase) DeleteKey(keyAddr common.Address, auth string) (err error) {
144147
// only delete if correct passphrase is given
145-
_, _, err = decryptKeyFromFile(ks, keyAddr, auth)
148+
_, _, err = decryptKeyFromFile(ks.keysDirPath, keyAddr, auth)
146149
if err != nil {
147150
return err
148151
}
149152

150153
return deleteKey(ks.keysDirPath, keyAddr)
151154
}
152155

153-
func decryptKeyFromFile(ks keyStorePassphrase, keyAddr common.Address, auth string) (keyBytes []byte, keyId []byte, err error) {
156+
func decryptKeyFromFile(keysDirPath string, keyAddr common.Address, auth string) (keyBytes []byte, keyId []byte, err error) {
157+
fmt.Printf("%v\n", keyAddr.Hex())
154158
m := make(map[string]interface{})
155-
err = getKey(ks.keysDirPath, keyAddr, &m)
159+
err = getKey(keysDirPath, keyAddr, &m)
156160
if err != nil {
157-
fmt.Printf("get key error: %v\n", err)
158161
return
159162
}
160163

161164
v := reflect.ValueOf(m["version"])
162165
if v.Kind() == reflect.String && v.String() == "1" {
163166
k := new(encryptedKeyJSONV1)
164-
getKey(ks.keysDirPath, keyAddr, &k)
167+
err = getKey(keysDirPath, keyAddr, &k)
165168
if err != nil {
166169
return
167170
}
168171
return decryptKeyV1(k, auth)
169172
} else {
170173
k := new(encryptedKeyJSONV3)
171-
getKey(ks.keysDirPath, keyAddr, &k)
174+
err = getKey(keysDirPath, keyAddr, &k)
172175
if err != nil {
173176
return
174177
}

‎crypto/key_store_plain.go‎

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ type KeyStore interface {
4343
GetKeyAddresses() ([]common.Address, error) // get all addresses
4444
StoreKey(*Key, string) error // store key optionally using auth string
4545
DeleteKey(common.Address, string) error // delete key by addr and auth string
46+
Cleanup(keyAddr common.Address) (err error)
4647
}
4748

4849
type keyStorePlain struct {
@@ -86,6 +87,10 @@ func (ks keyStorePlain) GetKeyAddresses() (addresses []common.Address, err error
8687
return getKeyAddresses(ks.keysDirPath)
8788
}
8889

90+
func (ks keyStorePlain) Cleanup(keyAddr common.Address) (err error) {
91+
return cleanup(ks.keysDirPath, keyAddr)
92+
}
93+
8994
func (ks keyStorePlain) StoreKey(key *Key, auth string) (err error) {
9095
keyJSON, err := json.Marshal(key)
9196
if err != nil {
@@ -100,10 +105,14 @@ func (ks keyStorePlain) DeleteKey(keyAddr common.Address, auth string) (err erro
100105
}
101106

102107
func deleteKey(keysDirPath string, keyAddr common.Address) (err error) {
103-
var keyFilePath string
104-
keyFilePath, err = getKeyFilePath(keysDirPath, keyAddr)
108+
var path string
109+
path, err = getKeyFilePath(keysDirPath, keyAddr)
105110
if err == nil {
106-
err = os.Remove(keyFilePath)
111+
addrHex := hex.EncodeToString(keyAddr[:])
112+
if path == filepath.Join(keysDirPath, addrHex, addrHex) {
113+
path = filepath.Join(keysDirPath, addrHex)
114+
}
115+
err = os.RemoveAll(path)
107116
}
108117
return
109118
}
@@ -122,6 +131,36 @@ func getKeyFilePath(keysDirPath string, keyAddr common.Address) (keyFilePath str
122131
return
123132
}
124133

134+
func cleanup(keysDirPath string, keyAddr common.Address) (err error) {
135+
fileInfos, err := ioutil.ReadDir(keysDirPath)
136+
if err != nil {
137+
return
138+
}
139+
var paths []string
140+
account := hex.EncodeToString(keyAddr[:])
141+
for _, fileInfo := range fileInfos {
142+
path := filepath.Join(keysDirPath, fileInfo.Name())
143+
if len(path) >= 40 {
144+
addr := path[len(path)-40 : len(path)]
145+
if addr == account {
146+
if path == filepath.Join(keysDirPath, addr, addr) {
147+
path = filepath.Join(keysDirPath, addr)
148+
}
149+
paths = append(paths, path)
150+
}
151+
}
152+
}
153+
if len(paths) > 1 {
154+
for i := 0; err == nil && i < len(paths)-1; i++ {
155+
err = os.RemoveAll(paths[i])
156+
if err != nil {
157+
break
158+
}
159+
}
160+
}
161+
return
162+
}
163+
125164
func getKeyFile(keysDirPath string, keyAddr common.Address) (fileContent []byte, err error) {
126165
var keyFilePath string
127166
keyFilePath, err = getKeyFilePath(keysDirPath, keyAddr)

0 commit comments

Comments
 (0)