accountcmd.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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/logger"
  26. "github.com/ethereum/go-ethereum/logger/glog"
  27. "gopkg.in/urfave/cli.v1"
  28. )
  29. var (
  30. walletCommand = cli.Command{
  31. Name: "wallet",
  32. Usage: "Manage Ethereum presale wallets",
  33. ArgsUsage: "",
  34. Category: "ACCOUNT COMMANDS",
  35. Description: `
  36. geth wallet import /path/to/my/presale.wallet
  37. will prompt for your password and imports your ether presale account.
  38. It can be used non-interactively with the --password option taking a
  39. passwordfile as argument containing the wallet password in plaintext.
  40. `,
  41. Subcommands: []cli.Command{
  42. {
  43. Action: importWallet,
  44. Name: "import",
  45. Usage: "Import Ethereum presale wallet",
  46. ArgsUsage: "<keyFile>",
  47. Description: `
  48. TODO: Please write this
  49. `,
  50. },
  51. },
  52. }
  53. accountCommand = cli.Command{
  54. Action: accountList,
  55. Name: "account",
  56. Usage: "Manage accounts",
  57. ArgsUsage: "",
  58. Category: "ACCOUNT COMMANDS",
  59. Description: `
  60. Manage accounts lets you create new accounts, list all existing accounts,
  61. import a private key into a new account.
  62. ' help' shows a list of subcommands or help for one subcommand.
  63. It supports interactive mode, when you are prompted for password as well as
  64. non-interactive mode where passwords are supplied via a given password file.
  65. Non-interactive mode is only meant for scripted use on test networks or known
  66. safe environments.
  67. Make sure you remember the password you gave when creating a new account (with
  68. either new or import). Without it you are not able to unlock your account.
  69. Note that exporting your key in unencrypted format is NOT supported.
  70. Keys are stored under <DATADIR>/keystore.
  71. It is safe to transfer the entire directory or the individual keys therein
  72. between ethereum nodes by simply copying.
  73. Make sure you backup your keys regularly.
  74. In order to use your account to send transactions, you need to unlock them using
  75. the '--unlock' option. The argument is a space separated list of addresses or
  76. indexes. If used non-interactively with a passwordfile, the file should contain
  77. the respective passwords one per line. If you unlock n accounts and the password
  78. file contains less than n entries, then the last password is meant to apply to
  79. all remaining accounts.
  80. And finally. DO NOT FORGET YOUR PASSWORD.
  81. `,
  82. Subcommands: []cli.Command{
  83. {
  84. Action: accountList,
  85. Name: "list",
  86. Usage: "Print account addresses",
  87. ArgsUsage: " ",
  88. Description: `
  89. TODO: Please write this
  90. `,
  91. },
  92. {
  93. Action: accountCreate,
  94. Name: "new",
  95. Usage: "Create a new account",
  96. ArgsUsage: " ",
  97. Description: `
  98. geth account new
  99. Creates a new account. Prints the address.
  100. The account is saved in encrypted format, you are prompted for a passphrase.
  101. You must remember this passphrase to unlock your account in the future.
  102. For non-interactive use the passphrase can be specified with the --password flag:
  103. geth --password <passwordfile> account new
  104. Note, this is meant to be used for testing only, it is a bad idea to save your
  105. password to file or expose in any other way.
  106. `,
  107. },
  108. {
  109. Action: accountUpdate,
  110. Name: "update",
  111. Usage: "Update an existing account",
  112. ArgsUsage: "<address>",
  113. Description: `
  114. geth account update <address>
  115. Update an existing account.
  116. The account is saved in the newest version in encrypted format, you are prompted
  117. for a passphrase to unlock the account and another to save the updated file.
  118. This same command can therefore be used to migrate an account of a deprecated
  119. format to the newest format or change the password for an account.
  120. For non-interactive use the passphrase can be specified with the --password flag:
  121. geth --password <passwordfile> account update <address>
  122. Since only one password can be given, only format update can be performed,
  123. changing your password is only possible interactively.
  124. `,
  125. },
  126. {
  127. Action: accountImport,
  128. Name: "import",
  129. Usage: "Import a private key into a new account",
  130. ArgsUsage: "<keyFile>",
  131. Description: `
  132. geth account import <keyfile>
  133. Imports an unencrypted private key from <keyfile> and creates a new account.
  134. Prints the address.
  135. The keyfile is assumed to contain an unencrypted private key in hexadecimal format.
  136. The account is saved in encrypted format, you are prompted for a passphrase.
  137. You must remember this passphrase to unlock your account in the future.
  138. For non-interactive use the passphrase can be specified with the -password flag:
  139. geth --password <passwordfile> account import <keyfile>
  140. Note:
  141. As you can directly copy your encrypted accounts to another ethereum instance,
  142. this import mechanism is not needed when you transfer an account between
  143. nodes.
  144. `,
  145. },
  146. },
  147. }
  148. )
  149. func accountList(ctx *cli.Context) error {
  150. stack := utils.MakeNode(ctx, clientIdentifier, gitCommit)
  151. var index int
  152. for _, wallet := range stack.AccountManager().Wallets() {
  153. for _, account := range wallet.Accounts() {
  154. fmt.Printf("Account #%d: {%x} %s\n", index, account.Address, &account.URL)
  155. index++
  156. }
  157. }
  158. return nil
  159. }
  160. // tries unlocking the specified account a few times.
  161. func unlockAccount(ctx *cli.Context, ks *keystore.KeyStore, address string, i int, passwords []string) (accounts.Account, string) {
  162. account, err := utils.MakeAddress(ks, address)
  163. if err != nil {
  164. utils.Fatalf("Could not list accounts: %v", err)
  165. }
  166. for trials := 0; trials < 3; trials++ {
  167. prompt := fmt.Sprintf("Unlocking account %s | Attempt %d/%d", address, trials+1, 3)
  168. password := getPassPhrase(prompt, false, i, passwords)
  169. err = ks.Unlock(account, password)
  170. if err == nil {
  171. glog.V(logger.Info).Infof("Unlocked account %x", account.Address)
  172. return account, password
  173. }
  174. if err, ok := err.(*keystore.AmbiguousAddrError); ok {
  175. glog.V(logger.Info).Infof("Unlocked account %x", account.Address)
  176. return ambiguousAddrRecovery(ks, err, password), password
  177. }
  178. if err != keystore.ErrDecrypt {
  179. // No need to prompt again if the error is not decryption-related.
  180. break
  181. }
  182. }
  183. // All trials expended to unlock account, bail out
  184. utils.Fatalf("Failed to unlock account %s (%v)", address, err)
  185. return accounts.Account{}, ""
  186. }
  187. // getPassPhrase retrieves the passwor associated with an account, either fetched
  188. // from a list of preloaded passphrases, or requested interactively from the user.
  189. func getPassPhrase(prompt string, confirmation bool, i int, passwords []string) string {
  190. // If a list of passwords was supplied, retrieve from them
  191. if len(passwords) > 0 {
  192. if i < len(passwords) {
  193. return passwords[i]
  194. }
  195. return passwords[len(passwords)-1]
  196. }
  197. // Otherwise prompt the user for the password
  198. if prompt != "" {
  199. fmt.Println(prompt)
  200. }
  201. password, err := console.Stdin.PromptPassword("Passphrase: ")
  202. if err != nil {
  203. utils.Fatalf("Failed to read passphrase: %v", err)
  204. }
  205. if confirmation {
  206. confirm, err := console.Stdin.PromptPassword("Repeat passphrase: ")
  207. if err != nil {
  208. utils.Fatalf("Failed to read passphrase confirmation: %v", err)
  209. }
  210. if password != confirm {
  211. utils.Fatalf("Passphrases do not match")
  212. }
  213. }
  214. return password
  215. }
  216. func ambiguousAddrRecovery(ks *keystore.KeyStore, err *keystore.AmbiguousAddrError, auth string) accounts.Account {
  217. fmt.Printf("Multiple key files exist for address %x:\n", err.Addr)
  218. for _, a := range err.Matches {
  219. fmt.Println(" ", a.URL)
  220. }
  221. fmt.Println("Testing your passphrase against all of them...")
  222. var match *accounts.Account
  223. for _, a := range err.Matches {
  224. if err := ks.Unlock(a, auth); err == nil {
  225. match = &a
  226. break
  227. }
  228. }
  229. if match == nil {
  230. utils.Fatalf("None of the listed files could be unlocked.")
  231. }
  232. fmt.Printf("Your passphrase unlocked %s\n", match.URL)
  233. fmt.Println("In order to avoid this warning, you need to remove the following duplicate key files:")
  234. for _, a := range err.Matches {
  235. if a != *match {
  236. fmt.Println(" ", a.URL)
  237. }
  238. }
  239. return *match
  240. }
  241. // accountCreate creates a new account into the keystore defined by the CLI flags.
  242. func accountCreate(ctx *cli.Context) error {
  243. stack := utils.MakeNode(ctx, clientIdentifier, gitCommit)
  244. password := getPassPhrase("Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0, utils.MakePasswordList(ctx))
  245. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  246. account, err := ks.NewAccount(password)
  247. if err != nil {
  248. utils.Fatalf("Failed to create account: %v", err)
  249. }
  250. fmt.Printf("Address: {%x}\n", account.Address)
  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 := utils.MakeNode(ctx, clientIdentifier, gitCommit)
  260. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  261. account, oldPassword := unlockAccount(ctx, ks, ctx.Args().First(), 0, nil)
  262. newPassword := getPassPhrase("Please give a new password. Do not forget this password.", true, 0, nil)
  263. if err := ks.Update(account, oldPassword, newPassword); err != nil {
  264. utils.Fatalf("Could not update the account: %v", err)
  265. }
  266. return nil
  267. }
  268. func importWallet(ctx *cli.Context) error {
  269. keyfile := ctx.Args().First()
  270. if len(keyfile) == 0 {
  271. utils.Fatalf("keyfile must be given as argument")
  272. }
  273. keyJson, err := ioutil.ReadFile(keyfile)
  274. if err != nil {
  275. utils.Fatalf("Could not read wallet file: %v", err)
  276. }
  277. stack := utils.MakeNode(ctx, clientIdentifier, gitCommit)
  278. passphrase := getPassPhrase("", false, 0, utils.MakePasswordList(ctx))
  279. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  280. acct, err := ks.ImportPreSaleKey(keyJson, passphrase)
  281. if err != nil {
  282. utils.Fatalf("%v", err)
  283. }
  284. fmt.Printf("Address: {%x}\n", acct.Address)
  285. return nil
  286. }
  287. func accountImport(ctx *cli.Context) error {
  288. keyfile := ctx.Args().First()
  289. if len(keyfile) == 0 {
  290. utils.Fatalf("keyfile must be given as argument")
  291. }
  292. key, err := crypto.LoadECDSA(keyfile)
  293. if err != nil {
  294. utils.Fatalf("Failed to load the private key: %v", err)
  295. }
  296. stack := utils.MakeNode(ctx, clientIdentifier, gitCommit)
  297. passphrase := getPassPhrase("Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0, utils.MakePasswordList(ctx))
  298. ks := stack.AccountManager().Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
  299. acct, err := ks.ImportECDSA(key, passphrase)
  300. if err != nil {
  301. utils.Fatalf("Could not create the account: %v", err)
  302. }
  303. fmt.Printf("Address: {%x}\n", acct.Address)
  304. return nil
  305. }