accountcmd.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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/console"
  24. "github.com/ethereum/go-ethereum/crypto"
  25. "github.com/ethereum/go-ethereum/log"
  26. "gopkg.in/urfave/cli.v1"
  27. )
  28. var (
  29. walletCommand = cli.Command{
  30. Name: "wallet",
  31. Usage: "Manage Ethereum presale wallets",
  32. ArgsUsage: "",
  33. Category: "ACCOUNT COMMANDS",
  34. Description: `
  35. geth wallet import /path/to/my/presale.wallet
  36. will prompt for your password and imports your ether presale account.
  37. It can be used non-interactively with the --password option taking a
  38. passwordfile as argument containing the wallet password in plaintext.`,
  39. Subcommands: []cli.Command{
  40. {
  41. Name: "import",
  42. Usage: "Import Ethereum presale wallet",
  43. ArgsUsage: "<keyFile>",
  44. Action: utils.MigrateFlags(importWallet),
  45. Category: "ACCOUNT COMMANDS",
  46. Flags: []cli.Flag{
  47. utils.DataDirFlag,
  48. utils.KeyStoreDirFlag,
  49. utils.PasswordFileFlag,
  50. utils.LightKDFFlag,
  51. },
  52. Description: `
  53. geth wallet [options] /path/to/my/presale.wallet
  54. will prompt for your password and imports your ether presale account.
  55. It can be used non-interactively with the --password option taking a
  56. passwordfile as argument containing the wallet password in plaintext.`,
  57. },
  58. },
  59. }
  60. accountCommand = cli.Command{
  61. Name: "account",
  62. Usage: "Manage accounts",
  63. Category: "ACCOUNT COMMANDS",
  64. Description: `
  65. Manage accounts, list all existing accounts, import a private key into a new
  66. account, create a new account or update an existing account.
  67. It supports interactive mode, when you are prompted for password as well as
  68. non-interactive mode where passwords are supplied via a given password file.
  69. Non-interactive mode is only meant for scripted use on test networks or known
  70. safe environments.
  71. Make sure you remember the password you gave when creating a new account (with
  72. either new or import). Without it you are not able to unlock your account.
  73. Note that exporting your key in unencrypted format is NOT supported.
  74. Keys are stored under <DATADIR>/keystore.
  75. It is safe to transfer the entire directory or the individual keys therein
  76. between ethereum nodes by simply copying.
  77. Make sure you backup your keys regularly.`,
  78. Subcommands: []cli.Command{
  79. {
  80. Name: "list",
  81. Usage: "Print summary of existing accounts",
  82. Action: utils.MigrateFlags(accountList),
  83. Flags: []cli.Flag{
  84. utils.DataDirFlag,
  85. utils.KeyStoreDirFlag,
  86. },
  87. Description: `
  88. Print a short summary of all accounts`,
  89. },
  90. {
  91. Name: "new",
  92. Usage: "Create a new account",
  93. Action: utils.MigrateFlags(accountCreate),
  94. Flags: []cli.Flag{
  95. utils.DataDirFlag,
  96. utils.KeyStoreDirFlag,
  97. utils.PasswordFileFlag,
  98. utils.LightKDFFlag,
  99. },
  100. Description: `
  101. geth account new
  102. Creates a new account and prints the address.
  103. The account is saved in encrypted format, you are prompted for a passphrase.
  104. You must remember this passphrase to unlock your account in the future.
  105. For non-interactive use the passphrase can be specified with the --password flag:
  106. Note, this is meant to be used for testing only, it is a bad idea to save your
  107. password to file or expose in any other way.
  108. `,
  109. },
  110. {
  111. Name: "update",
  112. Usage: "Update an existing account",
  113. Action: utils.MigrateFlags(accountUpdate),
  114. ArgsUsage: "<address>",
  115. Flags: []cli.Flag{
  116. utils.DataDirFlag,
  117. utils.KeyStoreDirFlag,
  118. utils.LightKDFFlag,
  119. },
  120. Description: `
  121. geth account update <address>
  122. Update an existing account.
  123. The account is saved in the newest version in encrypted format, you are prompted
  124. for a passphrase to unlock the account and another to save the updated file.
  125. This same command can therefore be used to migrate an account of a deprecated
  126. format to the newest format or change the password for an account.
  127. For non-interactive use the passphrase can be specified with the --password flag:
  128. geth account update [options] <address>
  129. Since only one password can be given, only format update can be performed,
  130. changing your password is only possible interactively.
  131. `,
  132. },
  133. {
  134. Name: "import",
  135. Usage: "Import a private key into a new account",
  136. Action: utils.MigrateFlags(accountImport),
  137. Flags: []cli.Flag{
  138. utils.DataDirFlag,
  139. utils.KeyStoreDirFlag,
  140. utils.PasswordFileFlag,
  141. utils.LightKDFFlag,
  142. },
  143. ArgsUsage: "<keyFile>",
  144. Description: `
  145. geth account import <keyfile>
  146. Imports an unencrypted private key from <keyfile> and creates a new account.
  147. Prints the address.
  148. The keyfile is assumed to contain an unencrypted private key in hexadecimal format.
  149. The account is saved in encrypted format, you are prompted for a passphrase.
  150. You must remember this passphrase to unlock your account in the future.
  151. For non-interactive use the passphrase can be specified with the -password flag:
  152. geth account import [options] <keyfile>
  153. Note:
  154. As you can directly copy your encrypted accounts to another ethereum instance,
  155. this import mechanism is not needed when you transfer an account between
  156. nodes.
  157. `,
  158. },
  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(ctx *cli.Context, 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 := getPassPhrase(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. // getPassPhrase retrieves the password associated with an account, either fetched
  201. // from a list of preloaded passphrases, or requested interactively from the user.
  202. func getPassPhrase(prompt string, confirmation bool, i int, passwords []string) string {
  203. // If a list of passwords was supplied, retrieve from them
  204. if len(passwords) > 0 {
  205. if i < len(passwords) {
  206. return passwords[i]
  207. }
  208. return passwords[len(passwords)-1]
  209. }
  210. // Otherwise prompt the user for the password
  211. if prompt != "" {
  212. fmt.Println(prompt)
  213. }
  214. password, err := console.Stdin.PromptPassword("Passphrase: ")
  215. if err != nil {
  216. utils.Fatalf("Failed to read passphrase: %v", err)
  217. }
  218. if confirmation {
  219. confirm, err := console.Stdin.PromptPassword("Repeat passphrase: ")
  220. if err != nil {
  221. utils.Fatalf("Failed to read passphrase confirmation: %v", err)
  222. }
  223. if password != confirm {
  224. utils.Fatalf("Passphrases do not match")
  225. }
  226. }
  227. return password
  228. }
  229. func ambiguousAddrRecovery(ks *keystore.KeyStore, err *keystore.AmbiguousAddrError, auth string) accounts.Account {
  230. fmt.Printf("Multiple key files exist for address %x:\n", err.Addr)
  231. for _, a := range err.Matches {
  232. fmt.Println(" ", a.URL)
  233. }
  234. fmt.Println("Testing your passphrase against all of them...")
  235. var match *accounts.Account
  236. for _, a := range err.Matches {
  237. if err := ks.Unlock(a, auth); err == nil {
  238. match = &a
  239. break
  240. }
  241. }
  242. if match == nil {
  243. utils.Fatalf("None of the listed files could be unlocked.")
  244. }
  245. fmt.Printf("Your passphrase unlocked %s\n", match.URL)
  246. fmt.Println("In order to avoid this warning, you need to remove the following duplicate key files:")
  247. for _, a := range err.Matches {
  248. if a != *match {
  249. fmt.Println(" ", a.URL)
  250. }
  251. }
  252. return *match
  253. }
  254. // accountCreate creates a new account into the keystore defined by the CLI flags.
  255. func accountCreate(ctx *cli.Context) error {
  256. cfg := gethConfig{Node: defaultNodeConfig()}
  257. // Load config file.
  258. if file := ctx.GlobalString(configFileFlag.Name); file != "" {
  259. if err := loadConfig(file, &cfg); err != nil {
  260. utils.Fatalf("%v", err)
  261. }
  262. }
  263. utils.SetNodeConfig(ctx, &cfg.Node)
  264. scryptN, scryptP, keydir, err := cfg.Node.AccountConfig()
  265. if err != nil {
  266. utils.Fatalf("Failed to read configuration: %v", err)
  267. }
  268. password := getPassPhrase("Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0, utils.MakePasswordList(ctx))
  269. address, err := keystore.StoreKey(keydir, password, scryptN, scryptP)
  270. if err != nil {
  271. utils.Fatalf("Failed to create account: %v", err)
  272. }
  273. fmt.Printf("Address: {%x}\n", address)
  274. return nil
  275. }
  276. // accountUpdate transitions an account from a previous format to the current
  277. // one, also providing the possibility to change the pass-phrase.
  278. func accountUpdate(ctx *cli.Context) error {
  279. if len(ctx.Args()) == 0 {
  280. utils.Fatalf("No accounts specified to update")
  281. }
  282. stack, _ := makeConfigNode(ctx)
  283. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  284. for _, addr := range ctx.Args() {
  285. account, oldPassword := unlockAccount(ctx, ks, addr, 0, nil)
  286. newPassword := getPassPhrase("Please give a new password. Do not forget this password.", true, 0, nil)
  287. if err := ks.Update(account, oldPassword, newPassword); err != nil {
  288. utils.Fatalf("Could not update the account: %v", err)
  289. }
  290. }
  291. return nil
  292. }
  293. func importWallet(ctx *cli.Context) error {
  294. keyfile := ctx.Args().First()
  295. if len(keyfile) == 0 {
  296. utils.Fatalf("keyfile must be given as argument")
  297. }
  298. keyJSON, err := ioutil.ReadFile(keyfile)
  299. if err != nil {
  300. utils.Fatalf("Could not read wallet file: %v", err)
  301. }
  302. stack, _ := makeConfigNode(ctx)
  303. passphrase := getPassPhrase("", false, 0, utils.MakePasswordList(ctx))
  304. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  305. acct, err := ks.ImportPreSaleKey(keyJSON, passphrase)
  306. if err != nil {
  307. utils.Fatalf("%v", err)
  308. }
  309. fmt.Printf("Address: {%x}\n", acct.Address)
  310. return nil
  311. }
  312. func accountImport(ctx *cli.Context) error {
  313. keyfile := ctx.Args().First()
  314. if len(keyfile) == 0 {
  315. utils.Fatalf("keyfile must be given as argument")
  316. }
  317. key, err := crypto.LoadECDSA(keyfile)
  318. if err != nil {
  319. utils.Fatalf("Failed to load the private key: %v", err)
  320. }
  321. stack, _ := makeConfigNode(ctx)
  322. passphrase := getPassPhrase("Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0, utils.MakePasswordList(ctx))
  323. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  324. acct, err := ks.ImportECDSA(key, passphrase)
  325. if err != nil {
  326. utils.Fatalf("Could not create the account: %v", err)
  327. }
  328. fmt.Printf("Address: {%x}\n", acct.Address)
  329. return nil
  330. }