accountcmd.go 10 KB

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