accountcmd.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "fmt"
  19. "io/ioutil"
  20. "github.com/ethereum/go-ethereum/accounts"
  21. "github.com/ethereum/go-ethereum/accounts/keystore"
  22. "github.com/ethereum/go-ethereum/cmd/utils"
  23. "github.com/ethereum/go-ethereum/crypto"
  24. "github.com/ethereum/go-ethereum/log"
  25. "gopkg.in/urfave/cli.v1"
  26. )
  27. var (
  28. walletCommand = cli.Command{
  29. Name: "wallet",
  30. Usage: "Manage Ethereum presale wallets",
  31. ArgsUsage: "",
  32. Category: "ACCOUNT COMMANDS",
  33. Description: `
  34. geth wallet import /path/to/my/presale.wallet
  35. will prompt for your password and imports your ether presale account.
  36. It can be used non-interactively with the --password option taking a
  37. passwordfile as argument containing the wallet password in plaintext.`,
  38. Subcommands: []cli.Command{
  39. {
  40. Name: "import",
  41. Usage: "Import Ethereum presale wallet",
  42. ArgsUsage: "<keyFile>",
  43. Action: utils.MigrateFlags(importWallet),
  44. Category: "ACCOUNT COMMANDS",
  45. Flags: []cli.Flag{
  46. utils.DataDirFlag,
  47. utils.KeyStoreDirFlag,
  48. utils.PasswordFileFlag,
  49. utils.LightKDFFlag,
  50. },
  51. Description: `
  52. geth wallet [options] /path/to/my/presale.wallet
  53. will prompt for your password and imports your ether presale account.
  54. It can be used non-interactively with the --password option taking a
  55. passwordfile as argument containing the wallet password in plaintext.`,
  56. },
  57. },
  58. }
  59. accountCommand = cli.Command{
  60. Name: "account",
  61. Usage: "Manage accounts",
  62. Category: "ACCOUNT COMMANDS",
  63. Description: `
  64. Manage accounts, list all existing accounts, import a private key into a new
  65. account, create a new account or update an existing account.
  66. It supports interactive mode, when you are prompted for password as well as
  67. non-interactive mode where passwords are supplied via a given password file.
  68. Non-interactive mode is only meant for scripted use on test networks or known
  69. safe environments.
  70. Make sure you remember the password you gave when creating a new account (with
  71. either new or import). Without it you are not able to unlock your account.
  72. Note that exporting your key in unencrypted format is NOT supported.
  73. Keys are stored under <DATADIR>/keystore.
  74. It is safe to transfer the entire directory or the individual keys therein
  75. between ethereum nodes by simply copying.
  76. Make sure you backup your keys regularly.`,
  77. Subcommands: []cli.Command{
  78. {
  79. Name: "list",
  80. Usage: "Print summary of existing accounts",
  81. Action: utils.MigrateFlags(accountList),
  82. Flags: []cli.Flag{
  83. utils.DataDirFlag,
  84. utils.KeyStoreDirFlag,
  85. },
  86. Description: `
  87. Print a short summary of all accounts`,
  88. },
  89. {
  90. Name: "new",
  91. Usage: "Create a new account",
  92. Action: utils.MigrateFlags(accountCreate),
  93. Flags: []cli.Flag{
  94. utils.DataDirFlag,
  95. utils.KeyStoreDirFlag,
  96. utils.PasswordFileFlag,
  97. utils.LightKDFFlag,
  98. },
  99. Description: `
  100. geth account new
  101. Creates a new account and prints the address.
  102. The account is saved in encrypted format, you are prompted for a password.
  103. You must remember this password to unlock your account in the future.
  104. For non-interactive use the password can be specified with the --password flag:
  105. Note, this is meant to be used for testing only, it is a bad idea to save your
  106. password to file or expose in any other way.
  107. `,
  108. },
  109. {
  110. Name: "update",
  111. Usage: "Update an existing account",
  112. Action: utils.MigrateFlags(accountUpdate),
  113. ArgsUsage: "<address>",
  114. Flags: []cli.Flag{
  115. utils.DataDirFlag,
  116. utils.KeyStoreDirFlag,
  117. utils.LightKDFFlag,
  118. },
  119. Description: `
  120. geth account update <address>
  121. Update an existing account.
  122. The account is saved in the newest version in encrypted format, you are prompted
  123. for a password to unlock the account and another to save the updated file.
  124. This same command can therefore be used to migrate an account of a deprecated
  125. format to the newest format or change the password for an account.
  126. For non-interactive use the password can be specified with the --password flag:
  127. geth account update [options] <address>
  128. Since only one password can be given, only format update can be performed,
  129. changing your password is only possible interactively.
  130. `,
  131. },
  132. {
  133. Name: "import",
  134. Usage: "Import a private key into a new account",
  135. Action: utils.MigrateFlags(accountImport),
  136. Flags: []cli.Flag{
  137. utils.DataDirFlag,
  138. utils.KeyStoreDirFlag,
  139. utils.PasswordFileFlag,
  140. utils.LightKDFFlag,
  141. },
  142. ArgsUsage: "<keyFile>",
  143. Description: `
  144. geth account import <keyfile>
  145. Imports an unencrypted private key from <keyfile> and creates a new account.
  146. Prints the address.
  147. The keyfile is assumed to contain an unencrypted private key in hexadecimal format.
  148. The account is saved in encrypted format, you are prompted for a password.
  149. You must remember this password to unlock your account in the future.
  150. For non-interactive use the password can be specified with the -password flag:
  151. geth account import [options] <keyfile>
  152. Note:
  153. As you can directly copy your encrypted accounts to another ethereum instance,
  154. this import mechanism is not needed when you transfer an account between
  155. nodes.
  156. `,
  157. },
  158. quorumAccountPluginCommands,
  159. },
  160. }
  161. )
  162. func accountList(ctx *cli.Context) error {
  163. stack, _ := makeConfigNode(ctx)
  164. var index int
  165. for _, wallet := range stack.AccountManager().Wallets() {
  166. for _, account := range wallet.Accounts() {
  167. fmt.Printf("Account #%d: {%x} %s\n", index, account.Address, &account.URL)
  168. index++
  169. }
  170. }
  171. return nil
  172. }
  173. // tries unlocking the specified account a few times.
  174. func unlockAccount(ks *keystore.KeyStore, address string, i int, passwords []string) (accounts.Account, string) {
  175. account, err := utils.MakeAddress(ks, address)
  176. if err != nil {
  177. utils.Fatalf("Could not list accounts: %v", err)
  178. }
  179. for trials := 0; trials < 3; trials++ {
  180. prompt := fmt.Sprintf("Unlocking account %s | Attempt %d/%d", address, trials+1, 3)
  181. password := utils.GetPassPhraseWithList(prompt, false, i, passwords)
  182. err = ks.Unlock(account, password)
  183. if err == nil {
  184. log.Info("Unlocked account", "address", account.Address.Hex())
  185. return account, password
  186. }
  187. if err, ok := err.(*keystore.AmbiguousAddrError); ok {
  188. log.Info("Unlocked account", "address", account.Address.Hex())
  189. return ambiguousAddrRecovery(ks, err, password), password
  190. }
  191. if err != keystore.ErrDecrypt {
  192. // No need to prompt again if the error is not decryption-related.
  193. break
  194. }
  195. }
  196. // All trials expended to unlock account, bail out
  197. utils.Fatalf("Failed to unlock account %s (%v)", address, err)
  198. return accounts.Account{}, ""
  199. }
  200. func ambiguousAddrRecovery(ks *keystore.KeyStore, err *keystore.AmbiguousAddrError, auth string) accounts.Account {
  201. fmt.Printf("Multiple key files exist for address %x:\n", err.Addr)
  202. for _, a := range err.Matches {
  203. fmt.Println(" ", a.URL)
  204. }
  205. fmt.Println("Testing your password against all of them...")
  206. var match *accounts.Account
  207. for _, a := range err.Matches {
  208. if err := ks.Unlock(a, auth); err == nil {
  209. match = &a
  210. break
  211. }
  212. }
  213. if match == nil {
  214. utils.Fatalf("None of the listed files could be unlocked.")
  215. }
  216. fmt.Printf("Your password unlocked %s\n", match.URL)
  217. fmt.Println("In order to avoid this warning, you need to remove the following duplicate key files:")
  218. for _, a := range err.Matches {
  219. if a != *match {
  220. fmt.Println(" ", a.URL)
  221. }
  222. }
  223. return *match
  224. }
  225. // accountCreate creates a new account into the keystore defined by the CLI flags.
  226. func accountCreate(ctx *cli.Context) error {
  227. cfg := gethConfig{Node: defaultNodeConfig()}
  228. // Load config file.
  229. if file := ctx.GlobalString(configFileFlag.Name); file != "" {
  230. if err := loadConfig(file, &cfg); err != nil {
  231. utils.Fatalf("%v", err)
  232. }
  233. }
  234. utils.SetNodeConfig(ctx, &cfg.Node)
  235. scryptN, scryptP, keydir, err := cfg.Node.AccountConfig()
  236. if err != nil {
  237. utils.Fatalf("Failed to read configuration: %v", err)
  238. }
  239. password := utils.GetPassPhraseWithList("Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0, utils.MakePasswordList(ctx))
  240. account, err := keystore.StoreKey(keydir, password, scryptN, scryptP)
  241. if err != nil {
  242. utils.Fatalf("Failed to create account: %v", err)
  243. }
  244. fmt.Printf("\nYour new key was generated\n\n")
  245. fmt.Printf("Public address of the key: %s\n", account.Address.Hex())
  246. fmt.Printf("Path of the secret key file: %s\n\n", account.URL.Path)
  247. fmt.Printf("- You can share your public address with anyone. Others need it to interact with you.\n")
  248. fmt.Printf("- You must NEVER share the secret key with anyone! The key controls access to your funds!\n")
  249. fmt.Printf("- You must BACKUP your key file! Without the key, it's impossible to access account funds!\n")
  250. fmt.Printf("- You must REMEMBER your password! Without the password, it's impossible to decrypt the key!\n\n")
  251. return nil
  252. }
  253. // accountUpdate transitions an account from a previous format to the current
  254. // one, also providing the possibility to change the pass-phrase.
  255. func accountUpdate(ctx *cli.Context) error {
  256. if len(ctx.Args()) == 0 {
  257. utils.Fatalf("No accounts specified to update")
  258. }
  259. stack, _ := makeConfigNode(ctx)
  260. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  261. for _, addr := range ctx.Args() {
  262. account, oldPassword := unlockAccount(ks, addr, 0, nil)
  263. newPassword := utils.GetPassPhraseWithList("Please give a new password. Do not forget this password.", true, 0, nil)
  264. if err := ks.Update(account, oldPassword, newPassword); err != nil {
  265. utils.Fatalf("Could not update the account: %v", err)
  266. }
  267. }
  268. return nil
  269. }
  270. func importWallet(ctx *cli.Context) error {
  271. keyfile := ctx.Args().First()
  272. if len(keyfile) == 0 {
  273. utils.Fatalf("keyfile must be given as argument")
  274. }
  275. keyJSON, err := ioutil.ReadFile(keyfile)
  276. if err != nil {
  277. utils.Fatalf("Could not read wallet file: %v", err)
  278. }
  279. stack, _ := makeConfigNode(ctx)
  280. passphrase := utils.GetPassPhraseWithList("", false, 0, utils.MakePasswordList(ctx))
  281. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  282. acct, err := ks.ImportPreSaleKey(keyJSON, passphrase)
  283. if err != nil {
  284. utils.Fatalf("%v", err)
  285. }
  286. fmt.Printf("Address: {%x}\n", acct.Address)
  287. return nil
  288. }
  289. func accountImport(ctx *cli.Context) error {
  290. keyfile := ctx.Args().First()
  291. if len(keyfile) == 0 {
  292. utils.Fatalf("keyfile must be given as argument")
  293. }
  294. key, err := crypto.LoadECDSA(keyfile)
  295. if err != nil {
  296. utils.Fatalf("Failed to load the private key: %v", err)
  297. }
  298. stack, _ := makeConfigNode(ctx)
  299. passphrase := utils.GetPassPhraseWithList("Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0, utils.MakePasswordList(ctx))
  300. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  301. acct, err := ks.ImportECDSA(key, passphrase)
  302. if err != nil {
  303. utils.Fatalf("Could not create the account: %v", err)
  304. }
  305. fmt.Printf("Address: {%x}\n", acct.Address)
  306. return nil
  307. }